From 49ee0794b5d912db1f95dce6eb52d781dc210db5 Mon Sep 17 00:00:00 2001 From: "Matt A. Tobin" Date: Fri, 2 Feb 2018 03:35:06 -0500 Subject: Add Pale Moon --- .../palemoon/components/BrowserComponents.manifest | 46 + .../palemoon/components/about/AboutRedirector.cpp | 188 + .../palemoon/components/about/AboutRedirector.h | 32 + application/palemoon/components/about/moz.build | 19 + application/palemoon/components/build/Makefile.in | 8 + application/palemoon/components/build/moz.build | 36 + .../palemoon/components/build/nsBrowserCompsCID.h | 43 + application/palemoon/components/build/nsModule.cpp | 126 + .../certerror/content/aboutCertError.css | 17 + .../certerror/content/aboutCertError.xhtml | 247 + application/palemoon/components/certerror/jar.mn | 7 + .../palemoon/components/certerror/moz.build | 8 + .../components/dirprovider/DirectoryProvider.cpp | 318 ++ .../components/dirprovider/DirectoryProvider.h | 51 + .../palemoon/components/dirprovider/moz.build | 19 + application/palemoon/components/distribution.js | 355 ++ .../components/downloads/BrowserDownloads.manifest | 4 + .../components/downloads/DownloadsCommon.jsm | 2401 ++++++++++ .../components/downloads/DownloadsLogger.jsm | 76 + .../components/downloads/DownloadsStartup.js | 278 ++ .../components/downloads/DownloadsTaskbar.jsm | 177 + .../palemoon/components/downloads/DownloadsUI.js | 151 + .../downloads/content/allDownloadsViewOverlay.css | 56 + .../downloads/content/allDownloadsViewOverlay.js | 1609 +++++++ .../downloads/content/allDownloadsViewOverlay.xul | 119 + .../downloads/content/contentAreaDownloadsView.css | 11 + .../downloads/content/contentAreaDownloadsView.js | 15 + .../downloads/content/contentAreaDownloadsView.xul | 45 + .../components/downloads/content/download.css | 45 + .../components/downloads/content/download.xml | 188 + .../components/downloads/content/downloads.css | 132 + .../components/downloads/content/downloads.js | 1813 ++++++++ .../downloads/content/downloadsOverlay.xul | 142 + .../components/downloads/content/indicator.js | 594 +++ .../downloads/content/indicatorOverlay.xul | 60 + application/palemoon/components/downloads/jar.mn | 18 + .../palemoon/components/downloads/moz.build | 19 + .../components/feeds/BrowserFeeds.manifest | 28 + .../palemoon/components/feeds/FeedConverter.js | 591 +++ .../palemoon/components/feeds/FeedWriter.js | 1421 ++++++ .../components/feeds/WebContentConverter.js | 932 ++++ .../components/feeds/content/subscribe.css | 7 + .../palemoon/components/feeds/content/subscribe.js | 23 + .../components/feeds/content/subscribe.xhtml | 65 + .../components/feeds/content/subscribe.xml | 40 + application/palemoon/components/feeds/jar.mn | 9 + application/palemoon/components/feeds/moz.build | 39 + .../palemoon/components/feeds/nsFeedSniffer.cpp | 363 ++ .../palemoon/components/feeds/nsFeedSniffer.h | 37 + .../components/feeds/nsIFeedResultService.idl | 66 + .../feeds/nsIWebContentConverterRegistrar.idl | 117 + .../palemoon/components/fuel/fuelApplication.js | 818 ++++ .../components/fuel/fuelApplication.manifest | 3 + .../palemoon/components/fuel/fuelIApplication.idl | 347 ++ application/palemoon/components/fuel/moz.build | 20 + .../migration/BrowserProfileMigrators.manifest | 14 + .../components/migration/ChromeProfileMigrator.js | 463 ++ .../components/migration/FirefoxProfileMigrator.js | 117 + .../components/migration/IEProfileMigrator.js | 521 +++ .../components/migration/MigrationUtils.jsm | 644 +++ .../components/migration/ProfileMigrator.js | 21 + .../components/migration/SafariProfileMigrator.js | 416 ++ .../components/migration/content/migration.js | 474 ++ .../components/migration/content/migration.xul | 96 + application/palemoon/components/migration/jar.mn | 7 + .../palemoon/components/migration/moz.build | 53 + .../migration/nsIBrowserProfileMigrator.idl | 63 + .../components/migration/nsIEHistoryEnumerator.cpp | 139 + .../components/migration/nsIEHistoryEnumerator.h | 37 + application/palemoon/components/moz.build | 44 + .../palemoon/components/nsBrowserContentHandler.js | 812 ++++ application/palemoon/components/nsBrowserGlue.js | 1961 ++++++++ application/palemoon/components/nsIBrowserGlue.idl | 47 + .../palemoon/components/nsIBrowserHandler.idl | 20 + .../components/places/BrowserPlaces.manifest | 2 + .../components/places/PlacesProtocolHandler.js | 49 + .../palemoon/components/places/PlacesUIUtils.jsm | 1337 ++++++ .../places/content/bookmarkProperties.js | 658 +++ .../places/content/bookmarkProperties.xul | 43 + .../components/places/content/bookmarksPanel.js | 25 + .../components/places/content/bookmarksPanel.xul | 55 + .../places/content/browserPlacesViews.js | 1744 ++++++++ .../components/places/content/controller.js | 1895 ++++++++ .../places/content/downloadsViewOverlay.xul | 47 + .../places/content/editBookmarkOverlay.js | 1039 +++++ .../places/content/editBookmarkOverlay.xul | 228 + .../components/places/content/history-panel.js | 91 + .../components/places/content/history-panel.xul | 95 + .../palemoon/components/places/content/menu.xml | 488 ++ .../components/places/content/moveBookmarks.js | 54 + .../components/places/content/moveBookmarks.xul | 53 + .../components/places/content/organizer.css | 7 + .../palemoon/components/places/content/places.css | 16 + .../palemoon/components/places/content/places.js | 1562 +++++++ .../palemoon/components/places/content/places.xul | 478 ++ .../components/places/content/placesOverlay.xul | 248 + .../components/places/content/sidebarUtils.js | 108 + .../palemoon/components/places/content/tree.xml | 789 ++++ .../palemoon/components/places/content/treeView.js | 1765 ++++++++ application/palemoon/components/places/jar.mn | 34 + application/palemoon/components/places/moz.build | 14 + .../components/preferences/aboutPermissions.css | 11 + .../components/preferences/aboutPermissions.js | 1348 ++++++ .../components/preferences/aboutPermissions.xml | 113 + .../components/preferences/aboutPermissions.xul | 397 ++ .../palemoon/components/preferences/advanced.js | 754 ++++ .../palemoon/components/preferences/advanced.xul | 458 ++ .../components/preferences/applicationManager.js | 102 + .../components/preferences/applicationManager.xul | 59 + .../components/preferences/applications.js | 1891 ++++++++ .../components/preferences/applications.xul | 99 + .../palemoon/components/preferences/colors.xul | 102 + .../palemoon/components/preferences/connection.js | 200 + .../palemoon/components/preferences/connection.xul | 164 + .../palemoon/components/preferences/content.js | 209 + .../palemoon/components/preferences/content.xul | 176 + .../palemoon/components/preferences/cookies.js | 914 ++++ .../palemoon/components/preferences/cookies.xul | 113 + .../palemoon/components/preferences/fonts.js | 144 + .../palemoon/components/preferences/fonts.xul | 279 ++ .../palemoon/components/preferences/handlers.css | 25 + .../palemoon/components/preferences/handlers.xml | 81 + application/palemoon/components/preferences/jar.mn | 47 + .../palemoon/components/preferences/languages.js | 304 ++ .../palemoon/components/preferences/languages.xul | 98 + .../palemoon/components/preferences/main.js | 473 ++ .../palemoon/components/preferences/main.xul | 187 + .../palemoon/components/preferences/moz.build | 14 + .../palemoon/components/preferences/permissions.js | 361 ++ .../components/preferences/permissions.xul | 83 + .../components/preferences/preferences.xul | 92 + .../palemoon/components/preferences/privacy.js | 551 +++ .../palemoon/components/preferences/privacy.xul | 285 ++ .../palemoon/components/preferences/sanitize.js | 12 + .../palemoon/components/preferences/sanitize.xul | 108 + .../palemoon/components/preferences/security.js | 268 ++ .../palemoon/components/preferences/security.xul | 165 + .../components/preferences/selectBookmark.js | 83 + .../components/preferences/selectBookmark.xul | 44 + .../palemoon/components/preferences/sync.js | 192 + .../palemoon/components/preferences/sync.xul | 178 + .../palemoon/components/preferences/tabs.js | 142 + .../palemoon/components/preferences/tabs.xul | 101 + .../content/aboutPrivateBrowsing.xhtml | 156 + .../palemoon/components/privatebrowsing/jar.mn | 6 + .../palemoon/components/privatebrowsing/moz.build | 7 + .../components/search/content/engineManager.js | 491 ++ .../components/search/content/engineManager.xul | 93 + .../palemoon/components/search/content/search.xml | 842 ++++ .../search/content/searchbarBindings.css | 13 + application/palemoon/components/search/jar.mn | 9 + application/palemoon/components/search/moz.build | 8 + .../components/sessionstore/DocumentUtils.jsm | 230 + .../components/sessionstore/SessionStorage.jsm | 165 + .../components/sessionstore/SessionStore.jsm | 4733 ++++++++++++++++++++ .../components/sessionstore/XPathGenerator.jsm | 97 + .../components/sessionstore/_SessionFile.jsm | 311 ++ .../sessionstore/content/aboutSessionRestore.js | 317 ++ .../sessionstore/content/aboutSessionRestore.xhtml | 94 + .../sessionstore/content/content-sessionStore.js | 40 + .../palemoon/components/sessionstore/jar.mn | 8 + .../palemoon/components/sessionstore/moz.build | 31 + .../components/sessionstore/nsISessionStartup.idl | 59 + .../components/sessionstore/nsISessionStore.idl | 206 + .../components/sessionstore/nsSessionStartup.js | 291 ++ .../components/sessionstore/nsSessionStore.js | 37 + .../sessionstore/nsSessionStore.manifest | 18 + application/palemoon/components/shell/Makefile.in | 11 + .../shell/content/setDesktopBackground.js | 213 + .../shell/content/setDesktopBackground.xul | 84 + application/palemoon/components/shell/jar.mn | 7 + application/palemoon/components/shell/moz.build | 48 + .../components/shell/nsGNOMEShellService.cpp | 664 +++ .../components/shell/nsGNOMEShellService.h | 36 + .../components/shell/nsIMacShellService.idl | 15 + .../palemoon/components/shell/nsIShellService.idl | 112 + .../components/shell/nsIWindowsShellService.idl | 17 + .../components/shell/nsMacShellService.cpp | 470 ++ .../palemoon/components/shell/nsMacShellService.h | 34 + .../components/shell/nsSetDefaultBrowser.js | 31 + .../components/shell/nsSetDefaultBrowser.manifest | 3 + .../palemoon/components/shell/nsShellService.h | 10 + .../components/shell/nsWindowsShellService.cpp | 1198 +++++ .../components/shell/nsWindowsShellService.h | 37 + .../palemoon/components/statusbar/Downloads.jsm | 674 +++ .../palemoon/components/statusbar/Progress.jsm | 183 + .../palemoon/components/statusbar/Status.jsm | 464 ++ .../palemoon/components/statusbar/Status4Evar.jsm | 279 ++ .../palemoon/components/statusbar/Toolbars.jsm | 221 + .../components/statusbar/content/overlay.css | 15 + .../components/statusbar/content/overlay.js | 16 + .../components/statusbar/content/overlay.xul | 82 + .../components/statusbar/content/prefs.css | 11 + .../palemoon/components/statusbar/content/prefs.js | 274 ++ .../components/statusbar/content/prefs.xml | 704 +++ .../components/statusbar/content/prefs.xul | 297 ++ .../components/statusbar/content/tabbrowser.xml | 218 + application/palemoon/components/statusbar/jar.mn | 15 + .../palemoon/components/statusbar/moz.build | 24 + .../palemoon/components/statusbar/status4evar.idl | 57 + .../palemoon/components/statusbar/status4evar.js | 695 +++ .../components/statusbar/status4evar.manifest | 3 + 202 files changed, 60183 insertions(+) create mode 100644 application/palemoon/components/BrowserComponents.manifest create mode 100644 application/palemoon/components/about/AboutRedirector.cpp create mode 100644 application/palemoon/components/about/AboutRedirector.h create mode 100644 application/palemoon/components/about/moz.build create mode 100644 application/palemoon/components/build/Makefile.in create mode 100644 application/palemoon/components/build/moz.build create mode 100644 application/palemoon/components/build/nsBrowserCompsCID.h create mode 100644 application/palemoon/components/build/nsModule.cpp create mode 100644 application/palemoon/components/certerror/content/aboutCertError.css create mode 100644 application/palemoon/components/certerror/content/aboutCertError.xhtml create mode 100644 application/palemoon/components/certerror/jar.mn create mode 100644 application/palemoon/components/certerror/moz.build create mode 100644 application/palemoon/components/dirprovider/DirectoryProvider.cpp create mode 100644 application/palemoon/components/dirprovider/DirectoryProvider.h create mode 100644 application/palemoon/components/dirprovider/moz.build create mode 100644 application/palemoon/components/distribution.js create mode 100644 application/palemoon/components/downloads/BrowserDownloads.manifest create mode 100644 application/palemoon/components/downloads/DownloadsCommon.jsm create mode 100644 application/palemoon/components/downloads/DownloadsLogger.jsm create mode 100644 application/palemoon/components/downloads/DownloadsStartup.js create mode 100644 application/palemoon/components/downloads/DownloadsTaskbar.jsm create mode 100644 application/palemoon/components/downloads/DownloadsUI.js create mode 100644 application/palemoon/components/downloads/content/allDownloadsViewOverlay.css create mode 100644 application/palemoon/components/downloads/content/allDownloadsViewOverlay.js create mode 100644 application/palemoon/components/downloads/content/allDownloadsViewOverlay.xul create mode 100644 application/palemoon/components/downloads/content/contentAreaDownloadsView.css create mode 100644 application/palemoon/components/downloads/content/contentAreaDownloadsView.js create mode 100644 application/palemoon/components/downloads/content/contentAreaDownloadsView.xul create mode 100644 application/palemoon/components/downloads/content/download.css create mode 100644 application/palemoon/components/downloads/content/download.xml create mode 100644 application/palemoon/components/downloads/content/downloads.css create mode 100644 application/palemoon/components/downloads/content/downloads.js create mode 100644 application/palemoon/components/downloads/content/downloadsOverlay.xul create mode 100644 application/palemoon/components/downloads/content/indicator.js create mode 100644 application/palemoon/components/downloads/content/indicatorOverlay.xul create mode 100644 application/palemoon/components/downloads/jar.mn create mode 100644 application/palemoon/components/downloads/moz.build create mode 100644 application/palemoon/components/feeds/BrowserFeeds.manifest create mode 100644 application/palemoon/components/feeds/FeedConverter.js create mode 100644 application/palemoon/components/feeds/FeedWriter.js create mode 100644 application/palemoon/components/feeds/WebContentConverter.js create mode 100644 application/palemoon/components/feeds/content/subscribe.css create mode 100644 application/palemoon/components/feeds/content/subscribe.js create mode 100644 application/palemoon/components/feeds/content/subscribe.xhtml create mode 100644 application/palemoon/components/feeds/content/subscribe.xml create mode 100644 application/palemoon/components/feeds/jar.mn create mode 100644 application/palemoon/components/feeds/moz.build create mode 100644 application/palemoon/components/feeds/nsFeedSniffer.cpp create mode 100644 application/palemoon/components/feeds/nsFeedSniffer.h create mode 100644 application/palemoon/components/feeds/nsIFeedResultService.idl create mode 100644 application/palemoon/components/feeds/nsIWebContentConverterRegistrar.idl create mode 100644 application/palemoon/components/fuel/fuelApplication.js create mode 100644 application/palemoon/components/fuel/fuelApplication.manifest create mode 100644 application/palemoon/components/fuel/fuelIApplication.idl create mode 100644 application/palemoon/components/fuel/moz.build create mode 100644 application/palemoon/components/migration/BrowserProfileMigrators.manifest create mode 100644 application/palemoon/components/migration/ChromeProfileMigrator.js create mode 100644 application/palemoon/components/migration/FirefoxProfileMigrator.js create mode 100644 application/palemoon/components/migration/IEProfileMigrator.js create mode 100644 application/palemoon/components/migration/MigrationUtils.jsm create mode 100644 application/palemoon/components/migration/ProfileMigrator.js create mode 100644 application/palemoon/components/migration/SafariProfileMigrator.js create mode 100644 application/palemoon/components/migration/content/migration.js create mode 100644 application/palemoon/components/migration/content/migration.xul create mode 100644 application/palemoon/components/migration/jar.mn create mode 100644 application/palemoon/components/migration/moz.build create mode 100644 application/palemoon/components/migration/nsIBrowserProfileMigrator.idl create mode 100644 application/palemoon/components/migration/nsIEHistoryEnumerator.cpp create mode 100644 application/palemoon/components/migration/nsIEHistoryEnumerator.h create mode 100644 application/palemoon/components/moz.build create mode 100644 application/palemoon/components/nsBrowserContentHandler.js create mode 100644 application/palemoon/components/nsBrowserGlue.js create mode 100644 application/palemoon/components/nsIBrowserGlue.idl create mode 100644 application/palemoon/components/nsIBrowserHandler.idl create mode 100644 application/palemoon/components/places/BrowserPlaces.manifest create mode 100644 application/palemoon/components/places/PlacesProtocolHandler.js create mode 100644 application/palemoon/components/places/PlacesUIUtils.jsm create mode 100644 application/palemoon/components/places/content/bookmarkProperties.js create mode 100644 application/palemoon/components/places/content/bookmarkProperties.xul create mode 100644 application/palemoon/components/places/content/bookmarksPanel.js create mode 100644 application/palemoon/components/places/content/bookmarksPanel.xul create mode 100644 application/palemoon/components/places/content/browserPlacesViews.js create mode 100644 application/palemoon/components/places/content/controller.js create mode 100644 application/palemoon/components/places/content/downloadsViewOverlay.xul create mode 100644 application/palemoon/components/places/content/editBookmarkOverlay.js create mode 100644 application/palemoon/components/places/content/editBookmarkOverlay.xul create mode 100644 application/palemoon/components/places/content/history-panel.js create mode 100644 application/palemoon/components/places/content/history-panel.xul create mode 100644 application/palemoon/components/places/content/menu.xml create mode 100644 application/palemoon/components/places/content/moveBookmarks.js create mode 100644 application/palemoon/components/places/content/moveBookmarks.xul create mode 100644 application/palemoon/components/places/content/organizer.css create mode 100644 application/palemoon/components/places/content/places.css create mode 100644 application/palemoon/components/places/content/places.js create mode 100644 application/palemoon/components/places/content/places.xul create mode 100644 application/palemoon/components/places/content/placesOverlay.xul create mode 100644 application/palemoon/components/places/content/sidebarUtils.js create mode 100644 application/palemoon/components/places/content/tree.xml create mode 100644 application/palemoon/components/places/content/treeView.js create mode 100644 application/palemoon/components/places/jar.mn create mode 100644 application/palemoon/components/places/moz.build create mode 100644 application/palemoon/components/preferences/aboutPermissions.css create mode 100644 application/palemoon/components/preferences/aboutPermissions.js create mode 100644 application/palemoon/components/preferences/aboutPermissions.xml create mode 100644 application/palemoon/components/preferences/aboutPermissions.xul create mode 100644 application/palemoon/components/preferences/advanced.js create mode 100644 application/palemoon/components/preferences/advanced.xul create mode 100644 application/palemoon/components/preferences/applicationManager.js create mode 100644 application/palemoon/components/preferences/applicationManager.xul create mode 100644 application/palemoon/components/preferences/applications.js create mode 100644 application/palemoon/components/preferences/applications.xul create mode 100644 application/palemoon/components/preferences/colors.xul create mode 100644 application/palemoon/components/preferences/connection.js create mode 100644 application/palemoon/components/preferences/connection.xul create mode 100644 application/palemoon/components/preferences/content.js create mode 100644 application/palemoon/components/preferences/content.xul create mode 100644 application/palemoon/components/preferences/cookies.js create mode 100644 application/palemoon/components/preferences/cookies.xul create mode 100644 application/palemoon/components/preferences/fonts.js create mode 100644 application/palemoon/components/preferences/fonts.xul create mode 100644 application/palemoon/components/preferences/handlers.css create mode 100644 application/palemoon/components/preferences/handlers.xml create mode 100644 application/palemoon/components/preferences/jar.mn create mode 100644 application/palemoon/components/preferences/languages.js create mode 100644 application/palemoon/components/preferences/languages.xul create mode 100644 application/palemoon/components/preferences/main.js create mode 100644 application/palemoon/components/preferences/main.xul create mode 100644 application/palemoon/components/preferences/moz.build create mode 100644 application/palemoon/components/preferences/permissions.js create mode 100644 application/palemoon/components/preferences/permissions.xul create mode 100644 application/palemoon/components/preferences/preferences.xul create mode 100644 application/palemoon/components/preferences/privacy.js create mode 100644 application/palemoon/components/preferences/privacy.xul create mode 100644 application/palemoon/components/preferences/sanitize.js create mode 100644 application/palemoon/components/preferences/sanitize.xul create mode 100644 application/palemoon/components/preferences/security.js create mode 100644 application/palemoon/components/preferences/security.xul create mode 100644 application/palemoon/components/preferences/selectBookmark.js create mode 100644 application/palemoon/components/preferences/selectBookmark.xul create mode 100644 application/palemoon/components/preferences/sync.js create mode 100644 application/palemoon/components/preferences/sync.xul create mode 100644 application/palemoon/components/preferences/tabs.js create mode 100644 application/palemoon/components/preferences/tabs.xul create mode 100644 application/palemoon/components/privatebrowsing/content/aboutPrivateBrowsing.xhtml create mode 100644 application/palemoon/components/privatebrowsing/jar.mn create mode 100644 application/palemoon/components/privatebrowsing/moz.build create mode 100644 application/palemoon/components/search/content/engineManager.js create mode 100644 application/palemoon/components/search/content/engineManager.xul create mode 100644 application/palemoon/components/search/content/search.xml create mode 100644 application/palemoon/components/search/content/searchbarBindings.css create mode 100644 application/palemoon/components/search/jar.mn create mode 100644 application/palemoon/components/search/moz.build create mode 100644 application/palemoon/components/sessionstore/DocumentUtils.jsm create mode 100644 application/palemoon/components/sessionstore/SessionStorage.jsm create mode 100644 application/palemoon/components/sessionstore/SessionStore.jsm create mode 100644 application/palemoon/components/sessionstore/XPathGenerator.jsm create mode 100644 application/palemoon/components/sessionstore/_SessionFile.jsm create mode 100644 application/palemoon/components/sessionstore/content/aboutSessionRestore.js create mode 100644 application/palemoon/components/sessionstore/content/aboutSessionRestore.xhtml create mode 100644 application/palemoon/components/sessionstore/content/content-sessionStore.js create mode 100644 application/palemoon/components/sessionstore/jar.mn create mode 100644 application/palemoon/components/sessionstore/moz.build create mode 100644 application/palemoon/components/sessionstore/nsISessionStartup.idl create mode 100644 application/palemoon/components/sessionstore/nsISessionStore.idl create mode 100644 application/palemoon/components/sessionstore/nsSessionStartup.js create mode 100644 application/palemoon/components/sessionstore/nsSessionStore.js create mode 100644 application/palemoon/components/sessionstore/nsSessionStore.manifest create mode 100644 application/palemoon/components/shell/Makefile.in create mode 100644 application/palemoon/components/shell/content/setDesktopBackground.js create mode 100644 application/palemoon/components/shell/content/setDesktopBackground.xul create mode 100644 application/palemoon/components/shell/jar.mn create mode 100644 application/palemoon/components/shell/moz.build create mode 100644 application/palemoon/components/shell/nsGNOMEShellService.cpp create mode 100644 application/palemoon/components/shell/nsGNOMEShellService.h create mode 100644 application/palemoon/components/shell/nsIMacShellService.idl create mode 100644 application/palemoon/components/shell/nsIShellService.idl create mode 100644 application/palemoon/components/shell/nsIWindowsShellService.idl create mode 100644 application/palemoon/components/shell/nsMacShellService.cpp create mode 100644 application/palemoon/components/shell/nsMacShellService.h create mode 100644 application/palemoon/components/shell/nsSetDefaultBrowser.js create mode 100644 application/palemoon/components/shell/nsSetDefaultBrowser.manifest create mode 100644 application/palemoon/components/shell/nsShellService.h create mode 100644 application/palemoon/components/shell/nsWindowsShellService.cpp create mode 100644 application/palemoon/components/shell/nsWindowsShellService.h create mode 100644 application/palemoon/components/statusbar/Downloads.jsm create mode 100644 application/palemoon/components/statusbar/Progress.jsm create mode 100644 application/palemoon/components/statusbar/Status.jsm create mode 100644 application/palemoon/components/statusbar/Status4Evar.jsm create mode 100644 application/palemoon/components/statusbar/Toolbars.jsm create mode 100644 application/palemoon/components/statusbar/content/overlay.css create mode 100644 application/palemoon/components/statusbar/content/overlay.js create mode 100644 application/palemoon/components/statusbar/content/overlay.xul create mode 100644 application/palemoon/components/statusbar/content/prefs.css create mode 100644 application/palemoon/components/statusbar/content/prefs.js create mode 100644 application/palemoon/components/statusbar/content/prefs.xml create mode 100644 application/palemoon/components/statusbar/content/prefs.xul create mode 100644 application/palemoon/components/statusbar/content/tabbrowser.xml create mode 100644 application/palemoon/components/statusbar/jar.mn create mode 100644 application/palemoon/components/statusbar/moz.build create mode 100644 application/palemoon/components/statusbar/status4evar.idl create mode 100644 application/palemoon/components/statusbar/status4evar.js create mode 100644 application/palemoon/components/statusbar/status4evar.manifest (limited to 'application/palemoon/components') diff --git a/application/palemoon/components/BrowserComponents.manifest b/application/palemoon/components/BrowserComponents.manifest new file mode 100644 index 000000000..1e4bff59a --- /dev/null +++ b/application/palemoon/components/BrowserComponents.manifest @@ -0,0 +1,46 @@ +# nsBrowserContentHandler.js +component {5d0ce354-df01-421a-83fb-7ead0990c24e} nsBrowserContentHandler.js application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/browser/clh;1 {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +component {47cd0651-b1be-4a0f-b5c4-10e5a573ef71} nsBrowserContentHandler.js application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/browser/final-clh;1 {47cd0651-b1be-4a0f-b5c4-10e5a573ef71} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=text/html {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=application/vnd.mozilla.xul+xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=image/svg+xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=text/rdf {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=text/xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=application/xhtml+xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=text/css {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=text/plain {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=image/gif {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=image/jpeg {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=image/jpg {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=image/png {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=image/bmp {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=image/x-icon {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=image/vnd.microsoft.icon {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=image/webp {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +contract @mozilla.org/uriloader/content-handler;1?type=application/http-index-format {5d0ce354-df01-421a-83fb-7ead0990c24e} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +category command-line-handler m-browser @mozilla.org/browser/clh;1 application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +category command-line-handler x-default @mozilla.org/browser/final-clh;1 application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +category command-line-validator b-browser @mozilla.org/browser/clh;1 application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} + +# nsBrowserGlue.js + +# WebappRT doesn't need these instructions, and they don't necessarily work +# with it, but it does use a GRE directory that the GRE shares with Firefox, +# so in order to prevent the instructions from being processed for WebappRT, +# we need to restrict them to the applications that depend on them, i.e.: +# +# b2g: {3c2e2abc-06d4-11e1-ac3b-374f68613e61} +# browser: {8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} +# mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110} +# mobile/xul: {a23983c0-fd0e-11dc-95ff-0800200c9a66} +# +# In theory we should do this for all these instructions, but in practice it is +# sufficient to do it for the app-startup one, and the file is simpler that way. + +component {eab9012e-5f74-4cbc-b2b5-a590235513cc} nsBrowserGlue.js +contract @mozilla.org/browser/browserglue;1 {eab9012e-5f74-4cbc-b2b5-a590235513cc} +category app-startup nsBrowserGlue service,@mozilla.org/browser/browserglue;1 application={3c2e2abc-06d4-11e1-ac3b-374f68613e61} application={8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66} +component {d8903bf6-68d5-4e97-bcd1-e4d3012f721a} nsBrowserGlue.js +contract @mozilla.org/content-permission/prompt;1 {d8903bf6-68d5-4e97-bcd1-e4d3012f721a} diff --git a/application/palemoon/components/about/AboutRedirector.cpp b/application/palemoon/components/about/AboutRedirector.cpp new file mode 100644 index 000000000..d927b7936 --- /dev/null +++ b/application/palemoon/components/about/AboutRedirector.cpp @@ -0,0 +1,188 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// See also: docshell/base/nsAboutRedirector.cpp + +#include "AboutRedirector.h" +#include "nsNetUtil.h" +#include "nsIScriptSecurityManager.h" +#include "mozilla/ArrayUtils.h" +#include "nsDOMString.h" + + +namespace mozilla { +namespace browser { + +NS_IMPL_ISUPPORTS(AboutRedirector, nsIAboutModule) + +struct RedirEntry { + const char* id; + const char* url; + uint32_t flags; + const char* idbOriginPostfix; +}; + +/* + Entries which do not have URI_SAFE_FOR_UNTRUSTED_CONTENT will run with chrome + privileges. This is potentially dangerous. Please use + URI_SAFE_FOR_UNTRUSTED_CONTENT in the third argument to each map item below + unless your about: page really needs chrome privileges. Security review is + required before adding new map entries without + URI_SAFE_FOR_UNTRUSTED_CONTENT. +*/ +static RedirEntry kRedirMap[] = { + { "certerror", "chrome://browser/content/certerror/aboutCertError.xhtml", + nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT | + nsIAboutModule::ALLOW_SCRIPT | + nsIAboutModule::HIDE_FROM_ABOUTABOUT }, + { "feeds", "chrome://browser/content/feeds/subscribe.xhtml", + nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT | + nsIAboutModule::ALLOW_SCRIPT | + nsIAboutModule::HIDE_FROM_ABOUTABOUT }, + { "privatebrowsing", "chrome://browser/content/aboutPrivateBrowsing.xhtml", + nsIAboutModule::ALLOW_SCRIPT }, + { "rights", +#ifdef MOZ_OFFICIAL_BRANDING + "chrome://global/content/aboutRights.xhtml", +#else + "chrome://global/content/aboutRights-unbranded.xhtml", +#endif + nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT | + nsIAboutModule::MAKE_LINKABLE | + nsIAboutModule::ALLOW_SCRIPT }, + { "palemoon", "chrome://global/content/palemoon.xhtml", + nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT | + nsIAboutModule::HIDE_FROM_ABOUTABOUT }, + { "logopage", "chrome://global/content/logopage.xhtml", + nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT | + nsIAboutModule::HIDE_FROM_ABOUTABOUT }, + { "robots", "chrome://browser/content/aboutRobots.xhtml", + nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT | + nsIAboutModule::ALLOW_SCRIPT }, + { "sessionrestore", "chrome://browser/content/aboutSessionRestore.xhtml", + nsIAboutModule::ALLOW_SCRIPT }, +#ifdef MOZ_SERVICES_SYNC + { "sync-progress", "chrome://browser/content/sync/progress.xhtml", + nsIAboutModule::ALLOW_SCRIPT }, + { "sync-tabs", "chrome://browser/content/sync/aboutSyncTabs.xul", + nsIAboutModule::ALLOW_SCRIPT }, +#endif + { "home", "chrome://browser/content/abouthome/aboutHome.xhtml", + nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT | + nsIAboutModule::MAKE_LINKABLE | + nsIAboutModule::ALLOW_SCRIPT }, + { "newtab", "chrome://browser/content/newtab/newTab.xul", + nsIAboutModule::ALLOW_SCRIPT }, + { "permissions", "chrome://browser/content/preferences/aboutPermissions.xul", + nsIAboutModule::ALLOW_SCRIPT }, + { "downloads", "chrome://browser/content/downloads/contentAreaDownloadsView.xul", + nsIAboutModule::ALLOW_SCRIPT }, +}; +static const int kRedirTotal = ArrayLength(kRedirMap); + +static nsAutoCString +GetAboutModuleName(nsIURI *aURI) +{ + nsAutoCString path; + aURI->GetPath(path); + + int32_t f = path.FindChar('#'); + if (f >= 0) + path.SetLength(f); + + f = path.FindChar('?'); + if (f >= 0) + path.SetLength(f); + + ToLowerCase(path); + return path; +} + +NS_IMETHODIMP +AboutRedirector::NewChannel(nsIURI* aURI, + nsILoadInfo* aLoadInfo, + nsIChannel** result) +{ + NS_ENSURE_ARG_POINTER(aURI); + NS_ASSERTION(result, "must not be null"); + + nsAutoCString path = GetAboutModuleName(aURI); + + nsresult rv; + nsCOMPtr ioService = do_GetIOService(&rv); + NS_ENSURE_SUCCESS(rv, rv); + + for (int i = 0; i < kRedirTotal; i++) { + if (!strcmp(path.get(), kRedirMap[i].id)) { + nsCOMPtr tempChannel; + rv = ioService->NewChannel(nsDependentCString(kRedirMap[i].url), + nullptr, nullptr, getter_AddRefs(tempChannel)); + NS_ENSURE_SUCCESS(rv, rv); + + tempChannel->SetOriginalURI(aURI); + + NS_ADDREF(*result = tempChannel); + return rv; + } + } + + return NS_ERROR_ILLEGAL_VALUE; +} + +NS_IMETHODIMP +AboutRedirector::GetURIFlags(nsIURI *aURI, uint32_t *result) +{ + NS_ENSURE_ARG_POINTER(aURI); + + nsAutoCString name = GetAboutModuleName(aURI); + + for (int i = 0; i < kRedirTotal; i++) { + if (name.Equals(kRedirMap[i].id)) { + *result = kRedirMap[i].flags; + return NS_OK; + } + } + + return NS_ERROR_ILLEGAL_VALUE; +} + +NS_IMETHODIMP +AboutRedirector::GetIndexedDBOriginPostfix(nsIURI *aURI, nsAString &result) +{ + NS_ENSURE_ARG_POINTER(aURI); + + nsAutoCString name = GetAboutModuleName(aURI); + + for (int i = 0; i < kRedirTotal; i++) { + if (name.Equals(kRedirMap[i].id)) { + const char* postfix = kRedirMap[i].idbOriginPostfix; + if (!postfix) { + break; + } + + result.AssignASCII(postfix); + return NS_OK; + } + } + + SetDOMStringToNull(result); + return NS_ERROR_ILLEGAL_VALUE; +} + + +nsresult +AboutRedirector::Create(nsISupports *aOuter, REFNSIID aIID, void **result) +{ + AboutRedirector* about = new AboutRedirector(); + if (about == nullptr) + return NS_ERROR_OUT_OF_MEMORY; + NS_ADDREF(about); + nsresult rv = about->QueryInterface(aIID, result); + NS_RELEASE(about); + return rv; +} + +} // namespace browser +} // namespace mozilla diff --git a/application/palemoon/components/about/AboutRedirector.h b/application/palemoon/components/about/AboutRedirector.h new file mode 100644 index 000000000..8feeb7491 --- /dev/null +++ b/application/palemoon/components/about/AboutRedirector.h @@ -0,0 +1,32 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef AboutRedirector_h__ +#define AboutRedirector_h__ + +#include "nsIAboutModule.h" + +namespace mozilla { +namespace browser { + +class AboutRedirector : public nsIAboutModule +{ +public: + NS_DECL_ISUPPORTS + NS_DECL_NSIABOUTMODULE + + AboutRedirector() {} + + static nsresult + Create(nsISupports *aOuter, REFNSIID aIID, void **aResult); + +protected: + virtual ~AboutRedirector() {} +}; + +} // namespace browser +} // namespace mozilla + +#endif // AboutRedirector_h__ diff --git a/application/palemoon/components/about/moz.build b/application/palemoon/components/about/moz.build new file mode 100644 index 000000000..95a8451ba --- /dev/null +++ b/application/palemoon/components/about/moz.build @@ -0,0 +1,19 @@ +# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +EXPORTS.mozilla.browser += [ + 'AboutRedirector.h', +] + +SOURCES += [ + 'AboutRedirector.cpp', +] + +FINAL_LIBRARY = 'browsercomps' + +LOCAL_INCLUDES += [ + '../build', +] diff --git a/application/palemoon/components/build/Makefile.in b/application/palemoon/components/build/Makefile.in new file mode 100644 index 000000000..2387227ab --- /dev/null +++ b/application/palemoon/components/build/Makefile.in @@ -0,0 +1,8 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +include $(topsrcdir)/config/rules.mk + +# Ensure that we don't embed a manifest referencing the CRT. +EMBED_MANIFEST_AT = diff --git a/application/palemoon/components/build/moz.build b/application/palemoon/components/build/moz.build new file mode 100644 index 000000000..f8073907e --- /dev/null +++ b/application/palemoon/components/build/moz.build @@ -0,0 +1,36 @@ +# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +EXPORTS += [ + 'nsBrowserCompsCID.h', +] + +SOURCES += [ + 'nsModule.cpp', +] + +XPCOMBinaryComponent('browsercomps') + +LOCAL_INCLUDES += [ + '../about', + '../dirprovider', + '../feeds', + '../migration', + '../shell', +] + +if CONFIG['OS_ARCH'] == 'WINNT': + OS_LIBS += [ + 'ole32', + 'shell32', + 'shlwapi', + 'version', + ] + +# Mac: Need to link with CoreFoundation for Mac Migrators (PList reading code) +# GTK2: Need to link with glib for GNOME shell service +if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('cocoa', 'gtk2', 'gtk3'): + OS_LIBS += CONFIG['TK_LIBS'] diff --git a/application/palemoon/components/build/nsBrowserCompsCID.h b/application/palemoon/components/build/nsBrowserCompsCID.h new file mode 100644 index 000000000..e325e43d4 --- /dev/null +++ b/application/palemoon/components/build/nsBrowserCompsCID.h @@ -0,0 +1,43 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +///////////////////////////////////////////////////////////////////////////// + +#ifdef XP_WIN +#define NS_WINIEHISTORYENUMERATOR_CID \ +{ 0x93480624, 0x806e, 0x4756, { 0xb7, 0xcb, 0x0f, 0xb7, 0xdd, 0x74, 0x6a, 0x8f } } + +#define NS_IEHISTORYENUMERATOR_CONTRACTID \ + "@mozilla.org/profile/migrator/iehistoryenumerator;1" +#endif + +#define NS_SHELLSERVICE_CID \ +{ 0x63c7b9f4, 0xcc8, 0x43f8, { 0xb6, 0x66, 0xa, 0x66, 0x16, 0x55, 0xcb, 0x73 } } + +#define NS_SHELLSERVICE_CONTRACTID \ + "@mozilla.org/browser/shell-service;1" + +#define NS_RDF_FORWARDPROXY_INFER_DATASOURCE_CID \ +{ 0x7a024bcf, 0xedd5, 0x4d9a, { 0x86, 0x14, 0xd4, 0x4b, 0xe1, 0xda, 0xda, 0xd3 } } + +#define NS_FEEDSNIFFER_CID \ +{ 0x6893e69, 0x71d8, 0x4b23, { 0x81, 0xeb, 0x80, 0x31, 0x4d, 0xaf, 0x3e, 0x66 } } + +#define NS_FEEDSNIFFER_CONTRACTID \ + "@mozilla.org/browser/feeds/sniffer;1" + +#define NS_ABOUTFEEDS_CID \ +{ 0x12ff56ec, 0x58be, 0x402c, { 0xb0, 0x57, 0x1, 0xf9, 0x61, 0xde, 0x96, 0x9b } } + +// 136e2c4d-c5a4-477c-b131-d93d7d704f64 +#define NS_PRIVATE_BROWSING_SERVICE_WRAPPER_CID \ +{ 0x136e2c4d, 0xc5a4, 0x477c, { 0xb1, 0x31, 0xd9, 0x3d, 0x7d, 0x70, 0x4f, 0x64 } } + +// 7e4bb6ad-2fc4-4dc6-89ef-23e8e5ccf980 +#define NS_BROWSER_ABOUT_REDIRECTOR_CID \ +{ 0x7e4bb6ad, 0x2fc4, 0x4dc6, { 0x89, 0xef, 0x23, 0xe8, 0xe5, 0xcc, 0xf9, 0x80 } } + +// {6DEB193C-F87D-4078-BC78-5E64655B4D62} +#define NS_BROWSERDIRECTORYPROVIDER_CID \ +{ 0x6deb193c, 0xf87d, 0x4078, { 0xbc, 0x78, 0x5e, 0x64, 0x65, 0x5b, 0x4d, 0x62 } } diff --git a/application/palemoon/components/build/nsModule.cpp b/application/palemoon/components/build/nsModule.cpp new file mode 100644 index 000000000..d5b79b455 --- /dev/null +++ b/application/palemoon/components/build/nsModule.cpp @@ -0,0 +1,126 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "mozilla/ModuleUtils.h" + +#include "nsBrowserCompsCID.h" +#include "DirectoryProvider.h" + +#if defined(XP_WIN) +#include "nsWindowsShellService.h" +#elif defined(XP_MACOSX) +#include "nsMacShellService.h" +#elif defined(MOZ_WIDGET_GTK) +#include "nsGNOMEShellService.h" +#endif + +#if defined(XP_WIN) +#include "nsIEHistoryEnumerator.h" +#endif + +#include "rdf.h" +#include "nsFeedSniffer.h" +#include "AboutRedirector.h" +#include "nsIAboutModule.h" + +#include "nsNetCID.h" + +using namespace mozilla::browser; + +///////////////////////////////////////////////////////////////////////////// + +NS_GENERIC_FACTORY_CONSTRUCTOR(DirectoryProvider) +#if defined(XP_WIN) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsWindowsShellService) +#elif defined(XP_MACOSX) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsMacShellService) +#elif defined(MOZ_WIDGET_GTK) +NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsGNOMEShellService, Init) +#endif + +#if defined(XP_WIN) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsIEHistoryEnumerator) +#endif + +NS_GENERIC_FACTORY_CONSTRUCTOR(nsFeedSniffer) + +NS_DEFINE_NAMED_CID(NS_BROWSERDIRECTORYPROVIDER_CID); +#if defined(XP_WIN) +NS_DEFINE_NAMED_CID(NS_SHELLSERVICE_CID); +#elif defined(MOZ_WIDGET_GTK) +NS_DEFINE_NAMED_CID(NS_SHELLSERVICE_CID); +#endif +NS_DEFINE_NAMED_CID(NS_FEEDSNIFFER_CID); +NS_DEFINE_NAMED_CID(NS_BROWSER_ABOUT_REDIRECTOR_CID); +#if defined(XP_WIN) +NS_DEFINE_NAMED_CID(NS_WINIEHISTORYENUMERATOR_CID); +#elif defined(XP_MACOSX) +NS_DEFINE_NAMED_CID(NS_SHELLSERVICE_CID); +#endif + +static const mozilla::Module::CIDEntry kBrowserCIDs[] = { + { &kNS_BROWSERDIRECTORYPROVIDER_CID, false, nullptr, DirectoryProviderConstructor }, +#if defined(XP_WIN) + { &kNS_SHELLSERVICE_CID, false, nullptr, nsWindowsShellServiceConstructor }, +#elif defined(MOZ_WIDGET_GTK) + { &kNS_SHELLSERVICE_CID, false, nullptr, nsGNOMEShellServiceConstructor }, +#endif + { &kNS_FEEDSNIFFER_CID, false, nullptr, nsFeedSnifferConstructor }, + { &kNS_BROWSER_ABOUT_REDIRECTOR_CID, false, nullptr, AboutRedirector::Create }, +#if defined(XP_WIN) + { &kNS_WINIEHISTORYENUMERATOR_CID, false, nullptr, nsIEHistoryEnumeratorConstructor }, +#elif defined(XP_MACOSX) + { &kNS_SHELLSERVICE_CID, false, nullptr, nsMacShellServiceConstructor }, +#endif + { nullptr } +}; + +static const mozilla::Module::ContractIDEntry kBrowserContracts[] = { + { NS_BROWSERDIRECTORYPROVIDER_CONTRACTID, &kNS_BROWSERDIRECTORYPROVIDER_CID }, +#if defined(XP_WIN) + { NS_SHELLSERVICE_CONTRACTID, &kNS_SHELLSERVICE_CID }, +#elif defined(MOZ_WIDGET_GTK) + { NS_SHELLSERVICE_CONTRACTID, &kNS_SHELLSERVICE_CID }, +#endif + { NS_FEEDSNIFFER_CONTRACTID, &kNS_FEEDSNIFFER_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "certerror", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "socialerror", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "feeds", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "privatebrowsing", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "rights", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "palemoon", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "logopage", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "robots", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "sessionrestore", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, +#ifdef MOZ_SERVICES_SYNC + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "sync-tabs", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "sync-progress", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, +#endif + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "home", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "newtab", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "permissions", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, + { NS_ABOUT_MODULE_CONTRACTID_PREFIX "downloads", &kNS_BROWSER_ABOUT_REDIRECTOR_CID }, +#if defined(XP_WIN) + { NS_IEHISTORYENUMERATOR_CONTRACTID, &kNS_WINIEHISTORYENUMERATOR_CID }, +#elif defined(XP_MACOSX) + { NS_SHELLSERVICE_CONTRACTID, &kNS_SHELLSERVICE_CID }, +#endif + { nullptr } +}; + +static const mozilla::Module::CategoryEntry kBrowserCategories[] = { + { XPCOM_DIRECTORY_PROVIDER_CATEGORY, "browser-directory-provider", NS_BROWSERDIRECTORYPROVIDER_CONTRACTID }, + { NS_CONTENT_SNIFFER_CATEGORY, "Feed Sniffer", NS_FEEDSNIFFER_CONTRACTID }, + { nullptr } +}; + +static const mozilla::Module kBrowserModule = { + mozilla::Module::kVersion, + kBrowserCIDs, + kBrowserContracts, + kBrowserCategories +}; + +NSMODULE_DEFN(nsBrowserCompsModule) = &kBrowserModule; diff --git a/application/palemoon/components/certerror/content/aboutCertError.css b/application/palemoon/components/certerror/content/aboutCertError.css new file mode 100644 index 000000000..059d8123e --- /dev/null +++ b/application/palemoon/components/certerror/content/aboutCertError.css @@ -0,0 +1,17 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* Logical CSS rules belong here, but presentation & theming rules + should live in the CSS of the appropriate theme */ + +#technicalContentText { + overflow: auto; + white-space: pre-wrap; +} + +.expander[hidden], +.expander[hidden] + *, +.expander[collapsed] + * { + display: none; +} diff --git a/application/palemoon/components/certerror/content/aboutCertError.xhtml b/application/palemoon/components/certerror/content/aboutCertError.xhtml new file mode 100644 index 000000000..c8a7e44f0 --- /dev/null +++ b/application/palemoon/components/certerror/content/aboutCertError.xhtml @@ -0,0 +1,247 @@ + + + + %htmlDTD; + + %globalDTD; + + %certerrorDTD; +]> + + + + + &certerror.pagetitle; + + + + + + + + + + + +
+ + +
+

&certerror.longpagetitle;

+
+ + +
+
+

&certerror.introPara1;

+

&certerror.introPara2;

+
+ +
+

&certerror.whatShouldIDo.heading;

+
+

&certerror.whatShouldIDo.content;

+ +
+
+ + +

+ +

+

+ +

+ +

+
+

&certerror.expert.content;

+

&certerror.expert.contentPara2;

+ +
+
+
+ + + + + + diff --git a/application/palemoon/components/certerror/jar.mn b/application/palemoon/components/certerror/jar.mn new file mode 100644 index 000000000..64aecae92 --- /dev/null +++ b/application/palemoon/components/certerror/jar.mn @@ -0,0 +1,7 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +browser.jar: + content/browser/certerror/aboutCertError.xhtml (content/aboutCertError.xhtml) + content/browser/certerror/aboutCertError.css (content/aboutCertError.css) diff --git a/application/palemoon/components/certerror/moz.build b/application/palemoon/components/certerror/moz.build new file mode 100644 index 000000000..35f6d454a --- /dev/null +++ b/application/palemoon/components/certerror/moz.build @@ -0,0 +1,8 @@ +# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +JAR_MANIFESTS += ['jar.mn'] \ No newline at end of file diff --git a/application/palemoon/components/dirprovider/DirectoryProvider.cpp b/application/palemoon/components/dirprovider/DirectoryProvider.cpp new file mode 100644 index 000000000..4d3993b7f --- /dev/null +++ b/application/palemoon/components/dirprovider/DirectoryProvider.cpp @@ -0,0 +1,318 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsIDirectoryService.h" +#include "DirectoryProvider.h" + +#include "nsIFile.h" +#include "nsISimpleEnumerator.h" +#include "nsIPrefService.h" +#include "nsIPrefBranch.h" + +#include "nsArrayEnumerator.h" +#include "nsEnumeratorUtils.h" +#include "nsAppDirectoryServiceDefs.h" +#include "nsDirectoryServiceDefs.h" +#include "nsCategoryManagerUtils.h" +#include "nsComponentManagerUtils.h" +#include "nsCOMArray.h" +#include "nsDirectoryServiceUtils.h" +#include "mozilla/ModuleUtils.h" +#include "nsServiceManagerUtils.h" +#include "nsStringAPI.h" +#include "nsXULAppAPI.h" +#include "nsIPrefLocalizedString.h" + +namespace mozilla { +namespace browser { + +NS_IMPL_ISUPPORTS(DirectoryProvider, + nsIDirectoryServiceProvider, + nsIDirectoryServiceProvider2) + +NS_IMETHODIMP +DirectoryProvider::GetFile(const char *aKey, bool *aPersist, nsIFile* *aResult) +{ + nsresult rv; + + *aResult = nullptr; + + // NOTE: This function can be reentrant through the NS_GetSpecialDirectory + // call, so be careful not to cause infinite recursion. + + nsCOMPtr file; + + char const* leafName = nullptr; + + if (!strcmp(aKey, NS_APP_BOOKMARKS_50_FILE)) { + leafName = "bookmarks.html"; + + nsCOMPtr prefs(do_GetService(NS_PREFSERVICE_CONTRACTID)); + if (prefs) { + nsCString path; + rv = prefs->GetCharPref("browser.bookmarks.file", getter_Copies(path)); + if (NS_SUCCEEDED(rv)) { + NS_NewNativeLocalFile(path, true, getter_AddRefs(file)); + } + } + } + else { + return NS_ERROR_FAILURE; + } + + nsDependentCString leafstr(leafName); + + nsCOMPtr parentDir; + if (file) { + rv = file->GetParent(getter_AddRefs(parentDir)); + if (NS_FAILED(rv)) + return rv; + } + else { + rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(parentDir)); + if (NS_FAILED(rv)) + return rv; + + rv = parentDir->Clone(getter_AddRefs(file)); + if (NS_FAILED(rv)) + return rv; + + file->AppendNative(leafstr); + } + + *aPersist = true; + NS_ADDREF(*aResult = file); + + return NS_OK; +} + +static void +AppendFileKey(const char *key, nsIProperties* aDirSvc, + nsCOMArray &array) +{ + nsCOMPtr file; + nsresult rv = aDirSvc->Get(key, NS_GET_IID(nsIFile), getter_AddRefs(file)); + if (NS_FAILED(rv)) + return; + + bool exists; + rv = file->Exists(&exists); + if (NS_FAILED(rv) || !exists) + return; + + array.AppendObject(file); +} + +// Appends the distribution-specific search engine directories to the +// array. The directory structure is as follows: + +// appdir/ +// \- distribution/ +// \- searchplugins/ +// |- common/ +// \- locale/ +// |- / +// ... +// \- / + +// common engines are loaded for all locales. If there is no locale +// directory for the current locale, there is a pref: +// "distribution.searchplugins.defaultLocale" +// which specifies a default locale to use. + +static void +AppendDistroSearchDirs(nsIProperties* aDirSvc, nsCOMArray &array) +{ + nsCOMPtr searchPlugins; + nsresult rv = aDirSvc->Get(XRE_APP_DISTRIBUTION_DIR, + NS_GET_IID(nsIFile), + getter_AddRefs(searchPlugins)); + if (NS_FAILED(rv)) + return; + searchPlugins->AppendNative(NS_LITERAL_CSTRING("searchplugins")); + + bool exists; + rv = searchPlugins->Exists(&exists); + if (NS_FAILED(rv) || !exists) + return; + + nsCOMPtr commonPlugins; + rv = searchPlugins->Clone(getter_AddRefs(commonPlugins)); + if (NS_SUCCEEDED(rv)) { + commonPlugins->AppendNative(NS_LITERAL_CSTRING("common")); + rv = commonPlugins->Exists(&exists); + if (NS_SUCCEEDED(rv) && exists) + array.AppendObject(commonPlugins); + } + + nsCOMPtr prefs(do_GetService(NS_PREFSERVICE_CONTRACTID)); + if (prefs) { + + nsCOMPtr localePlugins; + rv = searchPlugins->Clone(getter_AddRefs(localePlugins)); + if (NS_FAILED(rv)) + return; + + localePlugins->AppendNative(NS_LITERAL_CSTRING("locale")); + + nsCString locale; + nsCOMPtr prefString; + rv = prefs->GetComplexValue("general.useragent.locale", + NS_GET_IID(nsIPrefLocalizedString), + getter_AddRefs(prefString)); + if (NS_SUCCEEDED(rv)) { + nsAutoString wLocale; + prefString->GetData(getter_Copies(wLocale)); + CopyUTF16toUTF8(wLocale, locale); + } else { + rv = prefs->GetCharPref("general.useragent.locale", getter_Copies(locale)); + } + + if (NS_SUCCEEDED(rv)) { + + nsCOMPtr curLocalePlugins; + rv = localePlugins->Clone(getter_AddRefs(curLocalePlugins)); + if (NS_SUCCEEDED(rv)) { + + curLocalePlugins->AppendNative(locale); + rv = curLocalePlugins->Exists(&exists); + if (NS_SUCCEEDED(rv) && exists) { + array.AppendObject(curLocalePlugins); + return; // all done + } + } + } + + // we didn't append the locale dir - try the default one + nsCString defLocale; + rv = prefs->GetCharPref("distribution.searchplugins.defaultLocale", + getter_Copies(defLocale)); + if (NS_SUCCEEDED(rv)) { + + nsCOMPtr defLocalePlugins; + rv = localePlugins->Clone(getter_AddRefs(defLocalePlugins)); + if (NS_SUCCEEDED(rv)) { + + defLocalePlugins->AppendNative(defLocale); + rv = defLocalePlugins->Exists(&exists); + if (NS_SUCCEEDED(rv) && exists) + array.AppendObject(defLocalePlugins); + } + } + } +} + +NS_IMETHODIMP +DirectoryProvider::GetFiles(const char *aKey, nsISimpleEnumerator* *aResult) +{ + nsresult rv; + + if (!strcmp(aKey, NS_APP_SEARCH_DIR_LIST)) { + nsCOMPtr dirSvc + (do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID)); + if (!dirSvc) + return NS_ERROR_FAILURE; + + nsCOMArray baseFiles; + + /** + * We want to preserve the following order, since the search service loads + * engines in first-loaded-wins order. + * - extension search plugin locations (prepended below using + * NS_NewUnionEnumerator) + * - distro search plugin locations + * - user search plugin locations (profile) + * - app search plugin location (shipped engines) + */ + AppendDistroSearchDirs(dirSvc, baseFiles); + AppendFileKey(NS_APP_USER_SEARCH_DIR, dirSvc, baseFiles); + AppendFileKey(NS_APP_SEARCH_DIR, dirSvc, baseFiles); + + nsCOMPtr baseEnum; + rv = NS_NewArrayEnumerator(getter_AddRefs(baseEnum), baseFiles); + if (NS_FAILED(rv)) + return rv; + + nsCOMPtr list; + rv = dirSvc->Get(XRE_EXTENSIONS_DIR_LIST, + NS_GET_IID(nsISimpleEnumerator), getter_AddRefs(list)); + if (NS_FAILED(rv)) + return rv; + + static char const *const kAppendSPlugins[] = {"searchplugins", nullptr}; + + nsCOMPtr extEnum = + new AppendingEnumerator(list, kAppendSPlugins); + if (!extEnum) + return NS_ERROR_OUT_OF_MEMORY; + + return NS_NewUnionEnumerator(aResult, extEnum, baseEnum); + } + + return NS_ERROR_FAILURE; +} + +NS_IMPL_ISUPPORTS(DirectoryProvider::AppendingEnumerator, nsISimpleEnumerator) + +NS_IMETHODIMP +DirectoryProvider::AppendingEnumerator::HasMoreElements(bool *aResult) +{ + *aResult = mNext ? true : false; + return NS_OK; +} + +NS_IMETHODIMP +DirectoryProvider::AppendingEnumerator::GetNext(nsISupports* *aResult) +{ + if (aResult) + NS_ADDREF(*aResult = mNext); + + mNext = nullptr; + + nsresult rv; + + // Ignore all errors + + bool more; + while (NS_SUCCEEDED(mBase->HasMoreElements(&more)) && more) { + nsCOMPtr nextbasesupp; + mBase->GetNext(getter_AddRefs(nextbasesupp)); + + nsCOMPtr nextbase(do_QueryInterface(nextbasesupp)); + if (!nextbase) + continue; + + nextbase->Clone(getter_AddRefs(mNext)); + if (!mNext) + continue; + + char const *const * i = mAppendList; + while (*i) { + mNext->AppendNative(nsDependentCString(*i)); + ++i; + } + + bool exists; + rv = mNext->Exists(&exists); + if (NS_SUCCEEDED(rv) && exists) + break; + + mNext = nullptr; + } + + return NS_OK; +} + +DirectoryProvider::AppendingEnumerator::AppendingEnumerator + (nsISimpleEnumerator* aBase, + char const *const *aAppendList) : + mBase(aBase), + mAppendList(aAppendList) +{ + // Initialize mNext to begin. + GetNext(nullptr); +} + +} // namespace browser +} // namespace mozilla diff --git a/application/palemoon/components/dirprovider/DirectoryProvider.h b/application/palemoon/components/dirprovider/DirectoryProvider.h new file mode 100644 index 000000000..43fa85ab9 --- /dev/null +++ b/application/palemoon/components/dirprovider/DirectoryProvider.h @@ -0,0 +1,51 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef DirectoryProvider_h__ +#define DirectoryProvider_h__ + +#include "nsIDirectoryService.h" +#include "nsComponentManagerUtils.h" +#include "nsISimpleEnumerator.h" +#include "nsIFile.h" +#include "mozilla/Attributes.h" + +#define NS_BROWSERDIRECTORYPROVIDER_CONTRACTID \ + "@mozilla.org/browser/directory-provider;1" + +namespace mozilla { +namespace browser { + +class DirectoryProvider final : public nsIDirectoryServiceProvider2 +{ +public: + NS_DECL_ISUPPORTS + NS_DECL_NSIDIRECTORYSERVICEPROVIDER + NS_DECL_NSIDIRECTORYSERVICEPROVIDER2 + +private: + ~DirectoryProvider() {} + + class AppendingEnumerator final : public nsISimpleEnumerator + { + public: + NS_DECL_ISUPPORTS + NS_DECL_NSISIMPLEENUMERATOR + + AppendingEnumerator(nsISimpleEnumerator* aBase, + char const *const *aAppendList); + + private: + ~AppendingEnumerator() {} + + nsCOMPtr mBase; + char const *const *const mAppendList; + nsCOMPtr mNext; + }; +}; + +} // namespace browser +} // namespace mozilla + +#endif // DirectoryProvider_h__ diff --git a/application/palemoon/components/dirprovider/moz.build b/application/palemoon/components/dirprovider/moz.build new file mode 100644 index 000000000..e51e63449 --- /dev/null +++ b/application/palemoon/components/dirprovider/moz.build @@ -0,0 +1,19 @@ +# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +EXPORTS.mozilla.browser += [ + 'DirectoryProvider.h', +] + +SOURCES += [ + 'DirectoryProvider.cpp', +] + +FINAL_LIBRARY = 'browsercomps' + +LOCAL_INCLUDES += [ + '../build' +] diff --git a/application/palemoon/components/distribution.js b/application/palemoon/components/distribution.js new file mode 100644 index 000000000..b44b5bed3 --- /dev/null +++ b/application/palemoon/components/distribution.js @@ -0,0 +1,355 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +this.EXPORTED_SYMBOLS = [ "DistributionCustomizer" ]; + +const Ci = Components.interfaces; +const Cc = Components.classes; +const Cr = Components.results; +const Cu = Components.utils; + +const DISTRIBUTION_CUSTOMIZATION_COMPLETE_TOPIC = + "distribution-customization-complete"; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", + "resource://gre/modules/PlacesUtils.jsm"); + +this.DistributionCustomizer = function DistributionCustomizer() { + let dirSvc = Cc["@mozilla.org/file/directory_service;1"]. + getService(Ci.nsIProperties); + let iniFile = dirSvc.get("XREExeF", Ci.nsIFile); + iniFile.leafName = "distribution"; + iniFile.append("distribution.ini"); + if (iniFile.exists()) + this._iniFile = iniFile; +} + +DistributionCustomizer.prototype = { + _iniFile: null, + + get _ini() { + let ini = Cc["@mozilla.org/xpcom/ini-parser-factory;1"]. + getService(Ci.nsIINIParserFactory). + createINIParser(this._iniFile); + this.__defineGetter__("_ini", function() ini); + return this._ini; + }, + + get _locale() { + let locale; + try { + locale = this._prefs.getCharPref("general.useragent.locale"); + } + catch (e) { + locale = "en-US"; + } + this.__defineGetter__("_locale", function() locale); + return this._locale; + }, + + get _prefSvc() { + let svc = Cc["@mozilla.org/preferences-service;1"]. + getService(Ci.nsIPrefService); + this.__defineGetter__("_prefSvc", function() svc); + return this._prefSvc; + }, + + get _prefs() { + let branch = this._prefSvc.getBranch(null); + this.__defineGetter__("_prefs", function() branch); + return this._prefs; + }, + + get _ioSvc() { + let svc = Cc["@mozilla.org/network/io-service;1"]. + getService(Ci.nsIIOService); + this.__defineGetter__("_ioSvc", function() svc); + return this._ioSvc; + }, + + _makeURI: function DIST__makeURI(spec) { + return this._ioSvc.newURI(spec, null, null); + }, + + _parseBookmarksSection: + function DIST_parseBookmarksSection(parentId, section) { + let keys = []; + for (let i in enumerate(this._ini.getKeys(section))) + keys.push(i); + keys.sort(); + + let items = {}; + let defaultItemId = -1; + let maxItemId = -1; + + for (let i = 0; i < keys.length; i++) { + let m = /^item\.(\d+)\.(\w+)\.?(\w*)/.exec(keys[i]); + if (m) { + let [foo, iid, iprop, ilocale] = m; + iid = parseInt(iid); + + if (ilocale) + continue; + + if (!items[iid]) + items[iid] = {}; + if (keys.indexOf(keys[i] + "." + this._locale) >= 0) { + items[iid][iprop] = this._ini.getString(section, keys[i] + "." + + this._locale); + } else { + items[iid][iprop] = this._ini.getString(section, keys[i]); + } + + if (iprop == "type" && items[iid]["type"] == "default") + defaultItemId = iid; + + if (maxItemId < iid) + maxItemId = iid; + } else { + dump("Key did not match: " + keys[i] + "\n"); + } + } + + let prependIndex = 0; + for (let iid = 0; iid <= maxItemId; iid++) { + if (!items[iid]) + continue; + + let index = PlacesUtils.bookmarks.DEFAULT_INDEX; + let newId; + + switch (items[iid]["type"]) { + case "default": + break; + + case "folder": + if (iid < defaultItemId) + index = prependIndex++; + + newId = PlacesUtils.bookmarks.createFolder(parentId, + items[iid]["title"], + index); + + this._parseBookmarksSection(newId, "BookmarksFolder-" + + items[iid]["folderId"]); + + if (items[iid]["description"]) + PlacesUtils.annotations.setItemAnnotation(newId, + "bookmarkProperties/description", + items[iid]["description"], 0, + PlacesUtils.annotations.EXPIRE_NEVER); + + break; + + case "separator": + if (iid < defaultItemId) + index = prependIndex++; + PlacesUtils.bookmarks.insertSeparator(parentId, index); + break; + + case "livemark": + if (iid < defaultItemId) + index = prependIndex++; + + // Don't bother updating the livemark contents on creation. + PlacesUtils.livemarks.addLivemark({ title: items[iid]["title"] + , parentId: parentId + , index: index + , feedURI: this._makeURI(items[iid]["feedLink"]) + , siteURI: this._makeURI(items[iid]["siteLink"]) + }).then(null, Cu.reportError); + break; + + case "bookmark": + default: + if (iid < defaultItemId) + index = prependIndex++; + + newId = PlacesUtils.bookmarks.insertBookmark(parentId, + this._makeURI(items[iid]["link"]), + index, items[iid]["title"]); + + if (items[iid]["description"]) + PlacesUtils.annotations.setItemAnnotation(newId, + "bookmarkProperties/description", + items[iid]["description"], 0, + PlacesUtils.annotations.EXPIRE_NEVER); + + break; + } + } + }, + + _customizationsApplied: false, + applyCustomizations: function DIST_applyCustomizations() { + this._customizationsApplied = true; + if (!this._iniFile) + return this._checkCustomizationComplete(); + + // nsPrefService loads very early. Reload prefs so we can set + // distribution defaults during the prefservice:after-app-defaults + // notification (see applyPrefDefaults below) + this._prefSvc.QueryInterface(Ci.nsIObserver); + this._prefSvc.observe(null, "reload-default-prefs", null); + }, + + _bookmarksApplied: false, + applyBookmarks: function DIST_applyBookmarks() { + this._bookmarksApplied = true; + if (!this._iniFile) + return this._checkCustomizationComplete(); + + let sections = enumToObject(this._ini.getSections()); + + // The global section, and several of its fields, is required + // (we also check here to be consistent with applyPrefDefaults below) + if (!sections["Global"]) + return this._checkCustomizationComplete(); + let globalPrefs = enumToObject(this._ini.getKeys("Global")); + if (!(globalPrefs["id"] && globalPrefs["version"] && globalPrefs["about"])) + return this._checkCustomizationComplete(); + + let bmProcessedPref; + try { + bmProcessedPref = this._ini.getString("Global", + "bookmarks.initialized.pref"); + } + catch (e) { + bmProcessedPref = "distribution." + + this._ini.getString("Global", "id") + ".bookmarksProcessed"; + } + + let bmProcessed = false; + try { + bmProcessed = this._prefs.getBoolPref(bmProcessedPref); + } + catch (e) {} + + if (!bmProcessed) { + if (sections["BookmarksMenu"]) + this._parseBookmarksSection(PlacesUtils.bookmarksMenuFolderId, + "BookmarksMenu"); + if (sections["BookmarksToolbar"]) + this._parseBookmarksSection(PlacesUtils.toolbarFolderId, + "BookmarksToolbar"); + this._prefs.setBoolPref(bmProcessedPref, true); + } + return this._checkCustomizationComplete(); + }, + + _prefDefaultsApplied: false, + applyPrefDefaults: function DIST_applyPrefDefaults() { + this._prefDefaultsApplied = true; + if (!this._iniFile) + return this._checkCustomizationComplete(); + + let sections = enumToObject(this._ini.getSections()); + + // The global section, and several of its fields, is required + if (!sections["Global"]) + return this._checkCustomizationComplete(); + let globalPrefs = enumToObject(this._ini.getKeys("Global")); + if (!(globalPrefs["id"] && globalPrefs["version"] && globalPrefs["about"])) + return this._checkCustomizationComplete(); + + let defaults = this._prefSvc.getDefaultBranch(null); + + // Global really contains info we set as prefs. They're only + // separate because they are "special" (read: required) + + defaults.setCharPref("distribution.id", this._ini.getString("Global", "id")); + defaults.setCharPref("distribution.version", + this._ini.getString("Global", "version")); + + let partnerAbout = Cc["@mozilla.org/supports-string;1"]. + createInstance(Ci.nsISupportsString); + try { + if (globalPrefs["about." + this._locale]) { + partnerAbout.data = this._ini.getString("Global", "about." + this._locale); + } else { + partnerAbout.data = this._ini.getString("Global", "about"); + } + defaults.setComplexValue("distribution.about", + Ci.nsISupportsString, partnerAbout); + } catch (e) { + /* ignore bad prefs due to bug 895473 and move on */ + Cu.reportError(e); + } + + if (sections["Preferences"]) { + for (let key in enumerate(this._ini.getKeys("Preferences"))) { + try { + let value = eval(this._ini.getString("Preferences", key)); + switch (typeof value) { + case "boolean": + defaults.setBoolPref(key, value); + break; + case "number": + defaults.setIntPref(key, value); + break; + case "string": + defaults.setCharPref(key, value); + break; + case "undefined": + defaults.setCharPref(key, value); + break; + } + } catch (e) { /* ignore bad prefs and move on */ } + } + } + + // We eval() the localizable prefs as well (even though they'll + // always get set as a string) to keep the INI format consistent: + // string prefs always need to be in quotes + + let localizedStr = Cc["@mozilla.org/pref-localizedstring;1"]. + createInstance(Ci.nsIPrefLocalizedString); + + if (sections["LocalizablePreferences"]) { + for (let key in enumerate(this._ini.getKeys("LocalizablePreferences"))) { + try { + let value = eval(this._ini.getString("LocalizablePreferences", key)); + value = value.replace("%LOCALE%", this._locale, "g"); + localizedStr.data = "data:text/plain," + key + "=" + value; + defaults.setComplexValue(key, Ci.nsIPrefLocalizedString, localizedStr); + } catch (e) { /* ignore bad prefs and move on */ } + } + } + + if (sections["LocalizablePreferences-" + this._locale]) { + for (let key in enumerate(this._ini.getKeys("LocalizablePreferences-" + this._locale))) { + try { + let value = eval(this._ini.getString("LocalizablePreferences-" + this._locale, key)); + localizedStr.data = "data:text/plain," + key + "=" + value; + defaults.setComplexValue(key, Ci.nsIPrefLocalizedString, localizedStr); + } catch (e) { /* ignore bad prefs and move on */ } + } + } + + return this._checkCustomizationComplete(); + }, + + _checkCustomizationComplete: function DIST__checkCustomizationComplete() { + let prefDefaultsApplied = this._prefDefaultsApplied || !this._iniFile; + if (this._customizationsApplied && this._bookmarksApplied && + prefDefaultsApplied) { + let os = Cc["@mozilla.org/observer-service;1"]. + getService(Ci.nsIObserverService); + os.notifyObservers(null, DISTRIBUTION_CUSTOMIZATION_COMPLETE_TOPIC, null); + } + } +}; + +function enumerate(UTF8Enumerator) { + while (UTF8Enumerator.hasMore()) + yield UTF8Enumerator.getNext(); +} + +function enumToObject(UTF8Enumerator) { + let ret = {}; + for (let i in enumerate(UTF8Enumerator)) + ret[i] = 1; + return ret; +} diff --git a/application/palemoon/components/downloads/BrowserDownloads.manifest b/application/palemoon/components/downloads/BrowserDownloads.manifest new file mode 100644 index 000000000..1881ca1d7 --- /dev/null +++ b/application/palemoon/components/downloads/BrowserDownloads.manifest @@ -0,0 +1,4 @@ +component {49507fe5-2cee-4824-b6a3-e999150ce9b8} DownloadsStartup.js +contract @mozilla.org/browser/downloadsstartup;1 {49507fe5-2cee-4824-b6a3-e999150ce9b8} +category profile-after-change DownloadsStartup @mozilla.org/browser/downloadsstartup;1 +component {4d99321e-d156-455b-81f7-e7aa2308134f} DownloadsUI.js diff --git a/application/palemoon/components/downloads/DownloadsCommon.jsm b/application/palemoon/components/downloads/DownloadsCommon.jsm new file mode 100644 index 000000000..b90baaf9c --- /dev/null +++ b/application/palemoon/components/downloads/DownloadsCommon.jsm @@ -0,0 +1,2401 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +this.EXPORTED_SYMBOLS = [ + "DownloadsCommon", +]; + +/** + * Handles the Downloads panel shared methods and data access. + * + * This file includes the following constructors and global objects: + * + * DownloadsCommon + * This object is exposed directly to the consumers of this JavaScript module, + * and provides shared methods for all the instances of the user interface. + * + * DownloadsData + * Retrieves the list of past and completed downloads from the underlying + * Download Manager data, and provides asynchronous notifications allowing + * to build a consistent view of the available data. + * + * DownloadsDataItem + * Represents a single item in the list of downloads. This object either wraps + * an existing nsIDownload from the Download Manager, or provides the same + * information read directly from the downloads database, with the possibility + * of querying the nsIDownload lazily, for performance reasons. + * + * DownloadsIndicatorData + * This object registers itself with DownloadsData as a view, and transforms the + * notifications it receives into overall status data, that is then broadcast to + * the registered download status indicators. + */ + +//////////////////////////////////////////////////////////////////////////////// +//// Globals + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PluralForm", + "resource://gre/modules/PluralForm.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Downloads", + "resource://gre/modules/Downloads.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "DownloadUIHelper", + "resource://gre/modules/DownloadUIHelper.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "DownloadUtils", + "resource://gre/modules/DownloadUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OS", + "resource://gre/modules/osfile.jsm") +XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", + "resource://gre/modules/PlacesUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "RecentWindow", + "resource:///modules/RecentWindow.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", + "resource://gre/modules/PlacesUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Promise", + "resource://gre/modules/Promise.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "DownloadsLogger", + "resource:///modules/DownloadsLogger.jsm"); + +const nsIDM = Ci.nsIDownloadManager; + +const kDownloadsStringBundleUrl = + "chrome://browser/locale/downloads/downloads.properties"; + +const kPrefBdmScanWhenDone = "browser.download.manager.scanWhenDone"; +const kPrefBdmAlertOnExeOpen = "browser.download.manager.alertOnEXEOpen"; + +const kDownloadsStringsRequiringFormatting = { + sizeWithUnits: true, + shortTimeLeftSeconds: true, + shortTimeLeftMinutes: true, + shortTimeLeftHours: true, + shortTimeLeftDays: true, + statusSeparator: true, + statusSeparatorBeforeNumber: true, + fileExecutableSecurityWarning: true +}; + +const kDownloadsStringsRequiringPluralForm = { + otherDownloads2: true +}; + +XPCOMUtils.defineLazyGetter(this, "DownloadsLocalFileCtor", function () { + return Components.Constructor("@mozilla.org/file/local;1", + "nsILocalFile", "initWithPath"); +}); + +const kPartialDownloadSuffix = ".part"; + +const kPrefBranch = Services.prefs.getBranch("browser.download."); + +let PrefObserver = { + QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, + Ci.nsISupportsWeakReference]), + getPref: function PO_getPref(name) { + try { + switch (typeof this.prefs[name]) { + case "boolean": + return kPrefBranch.getBoolPref(name); + } + } catch (ex) { } + return this.prefs[name]; + }, + observe: function PO_observe(aSubject, aTopic, aData) { + if (this.prefs.hasOwnProperty(aData)) { + return this[aData] = this.getPref(aData); + } + }, + register: function PO_register(prefs) { + this.prefs = prefs; + kPrefBranch.addObserver("", this, true); + for (let key in prefs) { + let name = key; + XPCOMUtils.defineLazyGetter(this, name, function () { + return PrefObserver.getPref(name); + }); + } + }, +}; + +PrefObserver.register({ + // prefName: defaultValue + debug: false, + animateNotifications: true +}); + + +//////////////////////////////////////////////////////////////////////////////// +//// DownloadsCommon + +/** + * This object is exposed directly to the consumers of this JavaScript module, + * and provides shared methods for all the instances of the user interface. + */ +this.DownloadsCommon = { + log: function DC_log(...aMessageArgs) { + delete this.log; + this.log = function DC_log(...aMessageArgs) { + if (!PrefObserver.debug) { + return; + } + DownloadsLogger.log.apply(DownloadsLogger, aMessageArgs); + } + this.log.apply(this, aMessageArgs); + }, + + error: function DC_error(...aMessageArgs) { + delete this.error; + this.error = function DC_error(...aMessageArgs) { + if (!PrefObserver.debug) { + return; + } + DownloadsLogger.reportError.apply(DownloadsLogger, aMessageArgs); + } + this.error.apply(this, aMessageArgs); + }, + /** + * Returns an object whose keys are the string names from the downloads string + * bundle, and whose values are either the translated strings or functions + * returning formatted strings. + */ + get strings() + { + let strings = {}; + let sb = Services.strings.createBundle(kDownloadsStringBundleUrl); + let enumerator = sb.getSimpleEnumeration(); + while (enumerator.hasMoreElements()) { + let string = enumerator.getNext().QueryInterface(Ci.nsIPropertyElement); + let stringName = string.key; + if (stringName in kDownloadsStringsRequiringFormatting) { + strings[stringName] = function () { + // Convert "arguments" to a real array before calling into XPCOM. + return sb.formatStringFromName(stringName, + Array.slice(arguments, 0), + arguments.length); + }; + } else if (stringName in kDownloadsStringsRequiringPluralForm) { + strings[stringName] = function (aCount) { + // Convert "arguments" to a real array before calling into XPCOM. + let formattedString = sb.formatStringFromName(stringName, + Array.slice(arguments, 0), + arguments.length); + return PluralForm.get(aCount, formattedString); + }; + } else { + strings[stringName] = string.value; + } + } + delete this.strings; + return this.strings = strings; + }, + + /** + * Generates a very short string representing the given time left. + * + * @param aSeconds + * Value to be formatted. It represents the number of seconds, it must + * be positive but does not need to be an integer. + * + * @return Formatted string, for example "30s" or "2h". The returned value is + * maximum three characters long, at least in English. + */ + formatTimeLeft: function DC_formatTimeLeft(aSeconds) + { + // Decide what text to show for the time + let seconds = Math.round(aSeconds); + if (!seconds) { + return ""; + } else if (seconds <= 30) { + return DownloadsCommon.strings["shortTimeLeftSeconds"](seconds); + } + let minutes = Math.round(aSeconds / 60); + if (minutes < 60) { + return DownloadsCommon.strings["shortTimeLeftMinutes"](minutes); + } + let hours = Math.round(minutes / 60); + if (hours < 48) { // two days + return DownloadsCommon.strings["shortTimeLeftHours"](hours); + } + let days = Math.round(hours / 24); + return DownloadsCommon.strings["shortTimeLeftDays"](Math.min(days, 99)); + }, + + /** + * Indicates whether we should show the full Download Manager window interface + * instead of the simplified panel interface. The behavior of downloads + * across browsing session is consistent with the selected interface. + */ + get useToolkitUI() + { + /* Toolkit UI is currently incompatible. + * FIXME: Either fix the toolkitUI (make DBConnection work) or remove + * the unused code altogether + */ + //try { + // return Services.prefs.getBoolPref("browser.download.useToolkitUI"); + //} catch (ex) { } + return false; + }, + + /** + * Indicates whether we should show visual notification on the indicator + * when a download event is triggered. + */ + get animateNotifications() + { + return PrefObserver.animateNotifications; + }, + + /** + * Get access to one of the DownloadsData or PrivateDownloadsData objects, + * depending on the privacy status of the window in question. + * + * @param aWindow + * The browser window which owns the download button. + */ + getData: function DC_getData(aWindow) { + if (PrivateBrowsingUtils.isWindowPrivate(aWindow)) { + return PrivateDownloadsData; + } else { + return DownloadsData; + } + }, + + /** + * Initializes the data link for both the private and non-private downloads + * data objects. + * + * @param aDownloadManagerService + * Reference to the service implementing nsIDownloadManager. We need + * this because getService isn't available for us when this method is + * called, and we must ensure to register our listeners before the + * getService call for the Download Manager returns. + */ + initializeAllDataLinks: function DC_initializeAllDataLinks(aDownloadManagerService) { + DownloadsData.initializeDataLink(aDownloadManagerService); + PrivateDownloadsData.initializeDataLink(aDownloadManagerService); + }, + + /** + * Terminates the data link for both the private and non-private downloads + * data objects. + */ + terminateAllDataLinks: function DC_terminateAllDataLinks() { + DownloadsData.terminateDataLink(); + PrivateDownloadsData.terminateDataLink(); + }, + + /** + * Reloads the specified kind of downloads from the non-private store. + * This method must only be called when Private Browsing Mode is disabled. + * + * @param aActiveOnly + * True to load only active downloads from the database. + */ + ensureAllPersistentDataLoaded: + function DC_ensureAllPersistentDataLoaded(aActiveOnly) { + DownloadsData.ensurePersistentDataLoaded(aActiveOnly); + }, + + /** + * Get access to one of the DownloadsIndicatorData or + * PrivateDownloadsIndicatorData objects, depending on the privacy status of + * the window in question. + */ + getIndicatorData: function DC_getIndicatorData(aWindow) { + if (PrivateBrowsingUtils.isWindowPrivate(aWindow)) { + return PrivateDownloadsIndicatorData; + } else { + return DownloadsIndicatorData; + } + }, + + /** + * Returns a reference to the DownloadsSummaryData singleton - creating one + * in the process if one hasn't been instantiated yet. + * + * @param aWindow + * The browser window which owns the download button. + * @param aNumToExclude + * The number of items on the top of the downloads list to exclude + * from the summary. + */ + getSummary: function DC_getSummary(aWindow, aNumToExclude) + { + if (PrivateBrowsingUtils.isWindowPrivate(aWindow)) { + if (this._privateSummary) { + return this._privateSummary; + } + return this._privateSummary = new DownloadsSummaryData(true, aNumToExclude); + } else { + if (this._summary) { + return this._summary; + } + return this._summary = new DownloadsSummaryData(false, aNumToExclude); + } + }, + _summary: null, + _privateSummary: null, + + /** + * Returns the legacy state integer value for the provided Download object. + */ + stateOfDownload(download) { + // Collapse state using the correct priority. + if (!download.stopped) { + return nsIDM.DOWNLOAD_DOWNLOADING; + } + if (download.succeeded) { + return nsIDM.DOWNLOAD_FINISHED; + } + if (download.error) { + if (download.error.becauseBlockedByParentalControls) { + return nsIDM.DOWNLOAD_BLOCKED_PARENTAL; + } + if (download.error.becauseBlockedByReputationCheck) { + return nsIDM.DOWNLOAD_DIRTY; + } + return nsIDM.DOWNLOAD_FAILED; + } + if (download.canceled) { + if (download.hasPartialData) { + return nsIDM.DOWNLOAD_PAUSED; + } + return nsIDM.DOWNLOAD_CANCELED; + } + return nsIDM.DOWNLOAD_NOTSTARTED; + }, + + /** + * Given an iterable collection of DownloadDataItems, generates and returns + * statistics about that collection. + * + * @param aDataItems An iterable collection of DownloadDataItems. + * + * @return Object whose properties are the generated statistics. Currently, + * we return the following properties: + * + * numActive : The total number of downloads. + * numPaused : The total number of paused downloads. + * numScanning : The total number of downloads being scanned. + * numDownloading : The total number of downloads being downloaded. + * totalSize : The total size of all downloads once completed. + * totalTransferred: The total amount of transferred data for these + * downloads. + * slowestSpeed : The slowest download rate. + * rawTimeLeft : The estimated time left for the downloads to + * complete. + * percentComplete : The percentage of bytes successfully downloaded. + */ + summarizeDownloads: function DC_summarizeDownloads(aDataItems) + { + let summary = { + numActive: 0, + numPaused: 0, + numScanning: 0, + numDownloading: 0, + totalSize: 0, + totalTransferred: 0, + // slowestSpeed is Infinity so that we can use Math.min to + // find the slowest speed. We'll set this to 0 afterwards if + // it's still at Infinity by the time we're done iterating all + // dataItems. + slowestSpeed: Infinity, + rawTimeLeft: -1, + percentComplete: -1 + } + + for (let dataItem of aDataItems) { + summary.numActive++; + switch (dataItem.state) { + case nsIDM.DOWNLOAD_PAUSED: + summary.numPaused++; + break; + case nsIDM.DOWNLOAD_SCANNING: + summary.numScanning++; + break; + case nsIDM.DOWNLOAD_DOWNLOADING: + summary.numDownloading++; + if (dataItem.maxBytes > 0 && dataItem.speed > 0) { + let sizeLeft = dataItem.maxBytes - dataItem.currBytes; + summary.rawTimeLeft = Math.max(summary.rawTimeLeft, + sizeLeft / dataItem.speed); + summary.slowestSpeed = Math.min(summary.slowestSpeed, + dataItem.speed); + } + break; + } + // Only add to total values if we actually know the download size. + if (dataItem.maxBytes > 0 && + dataItem.state != nsIDM.DOWNLOAD_CANCELED && + dataItem.state != nsIDM.DOWNLOAD_FAILED) { + summary.totalSize += dataItem.maxBytes; + summary.totalTransferred += dataItem.currBytes; + } + } + + if (summary.numActive != 0 && summary.totalSize != 0 && + summary.numActive != summary.numScanning) { + summary.percentComplete = (summary.totalTransferred / + summary.totalSize) * 100; + } + + if (summary.slowestSpeed == Infinity) { + summary.slowestSpeed = 0; + } + + return summary; + }, + + /** + * If necessary, smooths the estimated number of seconds remaining for one + * or more downloads to complete. + * + * @param aSeconds + * Current raw estimate on number of seconds left for one or more + * downloads. This is a floating point value to help get sub-second + * accuracy for current and future estimates. + */ + smoothSeconds: function DC_smoothSeconds(aSeconds, aLastSeconds) + { + // We apply an algorithm similar to the DownloadUtils.getTimeLeft function, + // though tailored to a single time estimation for all downloads. We never + // apply something if the new value is less than half the previous value. + let shouldApplySmoothing = aLastSeconds >= 0 && + aSeconds > aLastSeconds / 2; + if (shouldApplySmoothing) { + // Apply hysteresis to favor downward over upward swings. Trust only 30% + // of the new value if lower, and 10% if higher (exponential smoothing). + let diff = aSeconds - aLastSeconds; + aSeconds = aLastSeconds + (diff < 0 ? .3 : .1) * diff; + + // If the new time is similar, reuse something close to the last time + // left, but subtract a little to provide forward progress. + diff = aSeconds - aLastSeconds; + let diffPercent = diff / aLastSeconds * 100; + if (Math.abs(diff) < 5 || Math.abs(diffPercent) < 5) { + aSeconds = aLastSeconds - (diff < 0 ? .4 : .2); + } + } + + // In the last few seconds of downloading, we are always subtracting and + // never adding to the time left. Ensure that we never fall below one + // second left until all downloads are actually finished. + return aLastSeconds = Math.max(aSeconds, 1); + }, + + /** + * Opens a downloaded file. + * If you've a dataItem, you should call dataItem.openLocalFile. + * @param aFile + * the downloaded file to be opened. + * @param aMimeInfo + * the mime type info object. May be null. + * @param aOwnerWindow + * the window with which this action is associated. + */ + openDownloadedFile: function DC_openDownloadedFile(aFile, aMimeInfo, aOwnerWindow) { + if (!(aFile instanceof Ci.nsIFile)) + throw new Error("aFile must be a nsIFile object"); + if (aMimeInfo && !(aMimeInfo instanceof Ci.nsIMIMEInfo)) + throw new Error("Invalid value passed for aMimeInfo"); + if (!(aOwnerWindow instanceof Ci.nsIDOMWindow)) + throw new Error("aOwnerWindow must be a dom-window object"); + + // Confirm opening executable files if required. + if (aFile.isExecutable()) { + let showAlert = true; + try { + showAlert = Services.prefs.getBoolPref(kPrefBdmAlertOnExeOpen); + } catch (ex) { } + + // On Vista and above, we rely on native security prompting for + // downloaded content unless it's disabled. + if (DownloadsCommon.isWinVistaOrHigher) { + try { + if (Services.prefs.getBoolPref(kPrefBdmScanWhenDone)) { + showAlert = false; + } + } catch (ex) { } + } + + if (showAlert) { + let name = aFile.leafName; + let message = + DownloadsCommon.strings.fileExecutableSecurityWarning(name, name); + let title = + DownloadsCommon.strings.fileExecutableSecurityWarningTitle; + let dontAsk = + DownloadsCommon.strings.fileExecutableSecurityWarningDontAsk; + + let checkbox = { value: false }; + let open = Services.prompt.confirmCheck(aOwnerWindow, title, message, + dontAsk, checkbox); + if (!open) { + return; + } + + Services.prefs.setBoolPref(kPrefBdmAlertOnExeOpen, + !checkbox.value); + } + } + + // Actually open the file. + try { + if (aMimeInfo && aMimeInfo.preferredAction == aMimeInfo.useHelperApp) { + aMimeInfo.launchWithFile(aFile); + return; + } + } + catch(ex) { } + + // If either we don't have the mime info, or the preferred action failed, + // attempt to launch the file directly. + try { + aFile.launch(); + } + catch(ex) { + // If launch fails, try sending it through the system's external "file:" + // URL handler. + Cc["@mozilla.org/uriloader/external-protocol-service;1"] + .getService(Ci.nsIExternalProtocolService) + .loadUrl(NetUtil.newURI(aFile)); + } + }, + + /** + * Show a downloaded file in the system file manager. + * If you have a dataItem, use dataItem.showLocalFile. + * + * @param aFile + * a downloaded file. + */ + showDownloadedFile: function DC_showDownloadedFile(aFile) { + if (!(aFile instanceof Ci.nsIFile)) + throw new Error("aFile must be a nsIFile object"); + try { + // Show the directory containing the file and select the file. + aFile.reveal(); + } catch (ex) { + // If reveal fails for some reason (e.g., it's not implemented on unix + // or the file doesn't exist), try using the parent if we have it. + let parent = aFile.parent; + if (parent) { + try { + // Open the parent directory to show where the file should be. + parent.launch(); + } catch (ex) { + // If launch also fails (probably because it's not implemented), let + // the OS handler try to open the parent. + Cc["@mozilla.org/uriloader/external-protocol-service;1"] + .getService(Ci.nsIExternalProtocolService) + .loadUrl(NetUtil.newURI(parent)); + } + } + } + } +}; + +/** + * Returns true if we are executing on Windows Vista or a later version. + */ +XPCOMUtils.defineLazyGetter(DownloadsCommon, "isWinVistaOrHigher", function () { + let os = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS; + if (os != "WINNT") { + return false; + } + let sysInfo = Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2); + return parseFloat(sysInfo.getProperty("version")) >= 6; +}); + +/** + * Returns true to indicate that we should hook the panel to the JavaScript API + * for downloads instead of the nsIDownloadManager back-end. + * This is kept for compatibility/leftovers and should be removed later. + */ +XPCOMUtils.defineLazyGetter(DownloadsCommon, "useJSTransfer", function () { + return true; +}); + +//////////////////////////////////////////////////////////////////////////////// +//// DownloadsData + +/** + * Retrieves the list of past and completed downloads from the underlying + * Download Manager data, and provides asynchronous notifications allowing to + * build a consistent view of the available data. + * + * This object responds to real-time changes in the underlying Download Manager + * data. For example, the deletion of one or more downloads is notified through + * the nsIObserver interface, while any state or progress change is notified + * through the nsIDownloadProgressListener interface. + * + * Note that using this object does not automatically start the Download Manager + * service. Consumers will see an empty list of downloads until the service is + * actually started. This is useful to display a neutral progress indicator in + * the main browser window until the autostart timeout elapses. + * + * Note that DownloadsData and PrivateDownloadsData are two equivalent singleton + * objects, one accessing non-private downloads, and the other accessing private + * ones. + */ +function DownloadsDataCtor(aPrivate) { + this._isPrivate = aPrivate; + + // This Object contains all the available DownloadsDataItem objects, indexed by + // their globally unique identifier. The identifiers of downloads that have + // been removed from the Download Manager data are still present, however the + // associated objects are replaced with the value "null". This is required to + // prevent race conditions when populating the list asynchronously. + this.dataItems = {}; + + // Array of view objects that should be notified when the available download + // data changes. + this._views = []; + + // Maps Download objects to DownloadDataItem objects. + this._downloadToDataItemMap = new Map(); +} + +DownloadsDataCtor.prototype = { + /** + * Starts receiving events for current downloads. + */ + initializeDataLink() { + if (!this._dataLinkInitialized) { + let promiseList = Downloads.getList(this._isPrivate ? Downloads.PRIVATE + : Downloads.PUBLIC); + promiseList.then(list => list.addView(this)).then(null, Cu.reportError); + this._dataLinkInitialized = true; + } + }, + _dataLinkInitialized: false, + + /** + * Stops receiving events for current downloads and cancels any pending read. + */ + terminateDataLink: function DD_terminateDataLink() + { + Cu.reportError("terminateDataLink not applicable with JS Transfers"); + return; + }, + + /** + * True if there are finished downloads that can be removed from the list. + */ + get canRemoveFinished() + { + for (let [, dataItem] of Iterator(this.dataItems)) { + if (dataItem && !dataItem.inProgress) { + return true; + } + } + return false; + }, + + /** + * Asks the back-end to remove finished downloads from the list. + */ + removeFinished: function DD_removeFinished() + { + let promiseList = Downloads.getList(this._isPrivate ? Downloads.PRIVATE + : Downloads.PUBLIC); + promiseList.then(list => list.removeFinished()) + .then(null, Cu.reportError); + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Integration with the asynchronous Downloads back-end + + onDownloadAdded: function (aDownload) + { + let dataItem = new DownloadsDataItem(aDownload); + this._downloadToDataItemMap.set(aDownload, dataItem); + this.dataItems[dataItem.downloadGuid] = dataItem; + + for (let view of this._views) { + view.onDataItemAdded(dataItem, true); + } + + this._updateDataItemState(dataItem); + }, + + onDownloadChanged: function (aDownload) + { + let dataItem = this._downloadToDataItemMap.get(aDownload); + if (!dataItem) { + Cu.reportError("Download doesn't exist."); + return; + } + + this._updateDataItemState(dataItem); + }, + + onDownloadRemoved: function (aDownload) + { + let dataItem = this._downloadToDataItemMap.get(aDownload); + if (!dataItem) { + Cu.reportError("Download doesn't exist."); + return; + } + + this._downloadToDataItemMap.delete(aDownload); + this.dataItems[dataItem.downloadGuid] = null; + for (let view of this._views) { + view.onDataItemRemoved(dataItem); + } + }, + + /** + * Updates the given data item and sends related notifications. + */ + _updateDataItemState: function (aDataItem) + { + let oldState = aDataItem.state; + let wasInProgress = aDataItem.inProgress; + let wasDone = aDataItem.done; + + aDataItem.updateFromJSDownload(); + + if (wasInProgress && !aDataItem.inProgress) { + aDataItem.endTime = Date.now(); + } + + if (oldState != aDataItem.state) { + for (let view of this._views) { + try { + view.getViewItem(aDataItem).onStateChange(oldState); + } catch (ex) { + Cu.reportError(ex); + } + } + + // This state transition code should actually be located in a Downloads + // API module (bug 941009). Moreover, the fact that state is stored as + // annotations should be ideally hidden behind methods of + // nsIDownloadHistory (bug 830415). + if (!this._isPrivate && !aDataItem.inProgress) { + try { + let downloadMetaData = { state: aDataItem.state, + endTime: aDataItem.endTime }; + if (aDataItem.done) { + downloadMetaData.fileSize = aDataItem.maxBytes; + } + + // RRR: Annotation service throws here. commented out for now. + /*PlacesUtils.annotations.setPageAnnotation( + NetUtil.newURI(aDataItem.uri), "downloads/metaData", + JSON.stringify(downloadMetaData), 0, + PlacesUtils.annotations.EXPIRE_WITH_HISTORY);*/ + } catch (ex) { + Cu.reportError(ex); + } + } + } + + if (!aDataItem.newDownloadNotified) { + aDataItem.newDownloadNotified = true; + this._notifyDownloadEvent("start"); + } + + if (!wasDone && aDataItem.done) { + this._notifyDownloadEvent("finish"); + } + + for (let view of this._views) { + view.getViewItem(aDataItem).onProgressChange(); + } + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Registration of views + + /** + * Adds an object to be notified when the available download data changes. + * The specified object is initialized with the currently available downloads. + * + * @param aView + * DownloadsView object to be added. This reference must be passed to + * removeView before termination. + */ + addView: function DD_addView(aView) + { + this._views.push(aView); + this._updateView(aView); + }, + + /** + * Removes an object previously added using addView. + * + * @param aView + * DownloadsView object to be removed. + */ + removeView: function DD_removeView(aView) + { + let index = this._views.indexOf(aView); + if (index != -1) { + this._views.splice(index, 1); + } + }, + + /** + * Ensures that the currently loaded data is added to the specified view. + * + * @param aView + * DownloadsView object to be initialized. + */ + _updateView: function DD_updateView(aView) + { + // Indicate to the view that a batch loading operation is in progress. + aView.onDataLoadStarting(); + + // Sort backwards by start time, ensuring that the most recent + // downloads are added first regardless of their state. + let loadedItemsArray = [dataItem + for each (dataItem in this.dataItems) + if (dataItem)]; + loadedItemsArray.sort(function(a, b) b.startTime - a.startTime); + loadedItemsArray.forEach( + function (dataItem) aView.onDataItemAdded(dataItem, false) + ); + + // Notify the view that all data is available unless loading is in progress. + if (!this._pendingStatement) { + aView.onDataLoadCompleted(); + } + }, + + ////////////////////////////////////////////////////////////////////////////// + //// In-memory downloads data store + + /** + * Clears the loaded data. + */ + clear: function DD_clear() + { + this._terminateDataAccess(); + this.dataItems = {}; + }, + + /** + * Returns the data item associated with the provided source object. The + * source can be a download object that we received from the Download Manager + * because of a real-time notification, or a row from the downloads database, + * during the asynchronous data load. + * + * In case we receive download status notifications while we are still + * populating the list of downloads from the database, we want the real-time + * status to take precedence over the state that is read from the database, + * which might be older. This is achieved by creating the download item if + * it's not already in the list, but never updating the returned object using + * the data from the database, if the object already exists. + * + * @param aSource + * Object containing the data with which the item should be initialized + * if it doesn't already exist in the list. This should implement + * either nsIDownload or mozIStorageRow. If the item exists, this + * argument is only used to retrieve the download identifier. + * @param aMayReuseGUID + * If false, indicates that the download should not be added if a + * download with the same identifier was removed in the meantime. This + * ensures that, while loading the list asynchronously, downloads that + * have been removed in the meantime do no reappear inadvertently. + * + * @return New or existing data item, or null if the item was deleted from the + * list of available downloads. + */ + _getOrAddDataItem: function DD_getOrAddDataItem(aSource, aMayReuseGUID) + { + let downloadGuid = (aSource instanceof Ci.nsIDownload) + ? aSource.guid + : aSource.getResultByName("guid"); + if (downloadGuid in this.dataItems) { + let existingItem = this.dataItems[downloadGuid]; + if (existingItem || !aMayReuseGUID) { + // Returns null if the download was removed and we can't reuse the item. + return existingItem; + } + } + DownloadsCommon.log("Creating a new DownloadsDataItem with downloadGuid =", + downloadGuid); + let dataItem = new DownloadsDataItem(aSource); + this.dataItems[downloadGuid] = dataItem; + + // Create the view items before returning. + let addToStartOfList = aSource instanceof Ci.nsIDownload; + this._views.forEach( + function (view) view.onDataItemAdded(dataItem, addToStartOfList) + ); + return dataItem; + }, + + /** + * Removes the data item with the specified identifier. + * + * This method can be called at most once per download identifier. + */ + _removeDataItem: function DD_removeDataItem(aDownloadId) + { + if (aDownloadId in this.dataItems) { + let dataItem = this.dataItems[aDownloadId]; + this.dataItems[aDownloadId] = null; + this._views.forEach( + function (view) view.onDataItemRemoved(dataItem) + ); + } + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Persistent data loading + + /** + * Represents an executing statement, allowing its cancellation. + */ + _pendingStatement: null, + + /** + * Indicates which kind of items from the persistent downloads database have + * been fully loaded in memory and are available to the views. This can + * assume the value of one of the kLoad constants. + */ + _loadState: 0, + + /** No downloads have been fully loaded yet. */ + get kLoadNone() 0, + /** All the active downloads in the database are loaded in memory. */ + get kLoadActive() 1, + /** All the downloads in the database are loaded in memory. */ + get kLoadAll() 2, + + /** + * Reloads the specified kind of downloads from the persistent database. This + * method must only be called when Private Browsing Mode is disabled. + * + * @param aActiveOnly + * True to load only active downloads from the database. + */ + ensurePersistentDataLoaded: + function DD_ensurePersistentDataLoaded(aActiveOnly) + { + if (this == PrivateDownloadsData) { + Cu.reportError("ensurePersistentDataLoaded should not be called on PrivateDownloadsData"); + return; + } + + if (this._pendingStatement) { + // We are already in the process of reloading all downloads. + return; + } + + if (aActiveOnly) { + if (this._loadState == this.kLoadNone) { + DownloadsCommon.log("Loading only active downloads from the persistence database"); + // Indicate to the views that a batch loading operation is in progress. + this._views.forEach( + function (view) view.onDataLoadStarting() + ); + + // Reload the list using the Download Manager service. The list is + // returned in no particular order. + let downloads = Services.downloads.activeDownloads; + while (downloads.hasMoreElements()) { + let download = downloads.getNext().QueryInterface(Ci.nsIDownload); + this._getOrAddDataItem(download, true); + } + this._loadState = this.kLoadActive; + + // Indicate to the views that the batch loading operation is complete. + this._views.forEach( + function (view) view.onDataLoadCompleted() + ); + DownloadsCommon.log("Active downloads done loading."); + } + } else { + if (this._loadState != this.kLoadAll) { + // Load only the relevant columns from the downloads database. The + // columns are read in the _initFromDataRow method of DownloadsDataItem. + // Order by descending download identifier so that the most recent + // downloads are notified first to the listening views. + DownloadsCommon.log("Loading all downloads from the persistence database."); + let dbConnection = Services.downloads.DBConnection; + let statement = dbConnection.createAsyncStatement( + "SELECT guid, target, name, source, referrer, state, " + + "startTime, endTime, currBytes, maxBytes " + + "FROM moz_downloads " + + "ORDER BY startTime DESC" + ); + try { + this._pendingStatement = statement.executeAsync(this); + } finally { + statement.finalize(); + } + } + } + }, + + /** + * Cancels any pending data access and ensures views are notified. + */ + _terminateDataAccess: function DD_terminateDataAccess() + { + if (this._pendingStatement) { + this._pendingStatement.cancel(); + this._pendingStatement = null; + } + + // Close all the views on the current data. Create a copy of the array + // because some views might unregister while processing this event. + Array.slice(this._views, 0).forEach( + function (view) view.onDataInvalidated() + ); + }, + + ////////////////////////////////////////////////////////////////////////////// + //// mozIStorageStatementCallback + + handleResult: function DD_handleResult(aResultSet) + { + for (let row = aResultSet.getNextRow(); + row; + row = aResultSet.getNextRow()) { + // Add the download to the list and initialize it with the data we read, + // unless we already received a notification providing more reliable + // information for this download. + this._getOrAddDataItem(row, false); + } + }, + + handleError: function DD_handleError(aError) + { + DownloadsCommon.error("Database statement execution error (", + aError.result, "): ", aError.message); + }, + + handleCompletion: function DD_handleCompletion(aReason) + { + DownloadsCommon.log("Loading all downloads from database completed with reason:", + aReason); + this._pendingStatement = null; + + // To ensure that we don't inadvertently delete more downloads from the + // database than needed on shutdown, we should update the load state only if + // the operation completed successfully. + if (aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) { + this._loadState = this.kLoadAll; + } + + // Indicate to the views that the batch loading operation is complete, even + // if the lookup failed or was canceled. The only possible glitch happens + // in case the database backend changes while loading data, when the views + // would open and immediately close. This case is rare enough not to need a + // special treatment. + this._views.forEach( + function (view) view.onDataLoadCompleted() + ); + }, + + ////////////////////////////////////////////////////////////////////////////// + //// nsIObserver + + observe: function DD_observe(aSubject, aTopic, aData) + { + switch (aTopic) { + case "download-manager-remove-download-guid": + // If a single download was removed, remove the corresponding data item. + if (aSubject) { + let downloadGuid = aSubject.QueryInterface(Ci.nsISupportsCString).data; + DownloadsCommon.log("A single download with id", + downloadGuid, "was removed."); + this._removeDataItem(downloadGuid); + break; + } + + // Multiple downloads have been removed. Iterate over known downloads + // and remove those that don't exist anymore. + DownloadsCommon.log("Multiple downloads were removed."); + for each (let dataItem in this.dataItems) { + if (dataItem) { + // Bug 449811 - We have to bind to the dataItem because Javascript + // doesn't do fresh let-bindings per loop iteration. + let dataItemBinding = dataItem; + Services.downloads.getDownloadByGUID(dataItemBinding.downloadGuid, + function(aStatus, aResult) { + if (aStatus == Components.results.NS_ERROR_NOT_AVAILABLE) { + DownloadsCommon.log("Removing download with id", + dataItemBinding.downloadGuid); + this._removeDataItem(dataItemBinding.downloadGuid); + } + }.bind(this)); + } + } + break; + } + }, + + ////////////////////////////////////////////////////////////////////////////// + //// nsIDownloadProgressListener + + onDownloadStateChange: function DD_onDownloadStateChange(aOldState, aDownload) + { + if (aDownload.isPrivate != this._isPrivate) { + // Ignore the downloads with a privacy status other than what we are + // tracking. + return; + } + + // When a new download is added, it may have the same identifier of a + // download that we previously deleted during this session, and we also + // want to provide a visible indication that the download started. + let isNew = aOldState == nsIDM.DOWNLOAD_NOTSTARTED || + aOldState == nsIDM.DOWNLOAD_QUEUED; + + let dataItem = this._getOrAddDataItem(aDownload, isNew); + if (!dataItem) { + return; + } + + let wasInProgress = dataItem.inProgress; + + DownloadsCommon.log("A download changed its state to:", aDownload.state); + dataItem.state = aDownload.state; + dataItem.referrer = aDownload.referrer && aDownload.referrer.spec; + dataItem.resumable = aDownload.resumable; + dataItem.startTime = Math.round(aDownload.startTime / 1000); + dataItem.currBytes = aDownload.amountTransferred; + dataItem.maxBytes = aDownload.size; + + if (wasInProgress && !dataItem.inProgress) { + dataItem.endTime = Date.now(); + } + + // When a download is retried, we create a different download object from + // the database with the same ID as before. This means that the nsIDownload + // that the dataItem holds might now need updating. + // + // We only overwrite this in the event that _download exists, because if it + // doesn't, that means that no caller ever tried to get the nsIDownload, + // which means it was never retrieved and doesn't need to be overwritten. + if (dataItem._download) { + dataItem._download = aDownload; + } + + for (let view of this._views) { + try { + view.getViewItem(dataItem).onStateChange(aOldState); + } catch (ex) { + Cu.reportError(ex); + } + } + + if (isNew && !dataItem.newDownloadNotified) { + dataItem.newDownloadNotified = true; + this._notifyDownloadEvent("start"); + } + + // This is a final state of which we are only notified once. + if (dataItem.done) { + this._notifyDownloadEvent("finish"); + } + + // TODO Bug 830415: this isn't the right place to set these annotation. + // It should be set it in places' nsIDownloadHistory implementation. + if (!this._isPrivate && !dataItem.inProgress) { + let downloadMetaData = { state: dataItem.state, + endTime: dataItem.endTime }; + if (dataItem.done) + downloadMetaData.fileSize = dataItem.maxBytes; + + try { + PlacesUtils.annotations.setPageAnnotation( + NetUtil.newURI(dataItem.uri), "downloads/metaData", JSON.stringify(downloadMetaData), 0, + PlacesUtils.annotations.EXPIRE_WITH_HISTORY); + } + catch(ex) { + Cu.reportError(ex); + } + } + }, + + onProgressChange: function DD_onProgressChange(aWebProgress, aRequest, + aCurSelfProgress, + aMaxSelfProgress, + aCurTotalProgress, + aMaxTotalProgress, aDownload) + { + if (aDownload.isPrivate != this._isPrivate) { + // Ignore the downloads with a privacy status other than what we are + // tracking. + return; + } + + let dataItem = this._getOrAddDataItem(aDownload, false); + if (!dataItem) { + return; + } + + dataItem.currBytes = aDownload.amountTransferred; + dataItem.maxBytes = aDownload.size; + dataItem.speed = aDownload.speed; + dataItem.percentComplete = aDownload.percentComplete; + + this._views.forEach( + function (view) view.getViewItem(dataItem).onProgressChange() + ); + }, + + onStateChange: function () { }, + + onSecurityChange: function () { }, + + ////////////////////////////////////////////////////////////////////////////// + //// Notifications sent to the most recent browser window only + + /** + * Set to true after the first download causes the downloads panel to be + * displayed. + */ + get panelHasShownBefore() { + try { + return Services.prefs.getBoolPref("browser.download.panel.shown"); + } catch (ex) { } + return false; + }, + + set panelHasShownBefore(aValue) { + Services.prefs.setBoolPref("browser.download.panel.shown", aValue); + return aValue; + }, + + /** + * Displays a new or finished download notification in the most recent browser + * window, if one is currently available with the required privacy type. + * + * @param aType + * Set to "start" for new downloads, "finish" for completed downloads. + */ + _notifyDownloadEvent: function DD_notifyDownloadEvent(aType) + { + DownloadsCommon.log("Attempting to notify that a new download has started or finished."); + if (DownloadsCommon.useToolkitUI) { + DownloadsCommon.log("Cancelling notification - we're using the toolkit downloads manager."); + return; + } + + // Show the panel in the most recent browser window, if present. + let browserWin = RecentWindow.getMostRecentBrowserWindow({ private: this._isPrivate }); + if (!browserWin) { + return; + } + + if (this.panelHasShownBefore) { + // For new downloads after the first one, don't show the panel + // automatically, but provide a visible notification in the topmost + // browser window, if the status indicator is already visible. + DownloadsCommon.log("Showing new download notification."); + browserWin.DownloadsIndicatorView.showEventNotification(aType); + return; + } + this.panelHasShownBefore = true; + browserWin.DownloadsPanel.showPanel(); + } +}; + +XPCOMUtils.defineLazyGetter(this, "PrivateDownloadsData", function() { + return new DownloadsDataCtor(true); +}); + +XPCOMUtils.defineLazyGetter(this, "DownloadsData", function() { + return new DownloadsDataCtor(false); +}); + +//////////////////////////////////////////////////////////////////////////////// +//// DownloadsDataItem + +/** + * Represents a single item in the list of downloads. This object either wraps + * an existing nsIDownload from the Download Manager, or provides the same + * information read directly from the downloads database, with the possibility + * of querying the nsIDownload lazily, for performance reasons. + * + * @param aSource + * Object containing the data with which the item should be initialized. + * This should implement either nsIDownload or mozIStorageRow. If the + * JavaScript API for downloads is enabled, this is a Download object. + */ +function DownloadsDataItem(aSource) +{ + this._initFromJSDownload(aSource); +} + +DownloadsDataItem.prototype = { + /** + * The JavaScript API does not need identifiers for Download objects, so they + * are generated sequentially for the corresponding DownloadDataItem. + */ + get _autoIncrementId() ++DownloadsDataItem.prototype.__lastId, + __lastId: 0, + + /** + * Initializes this object from the JavaScript API for downloads. + * + * The endTime property is initialized to the current date and time. + * + * @param aDownload + * The Download object with the current state. + */ + _initFromJSDownload: function (aDownload) + { + this._download = aDownload; + + this.downloadGuid = "id:" + this._autoIncrementId; + this.file = aDownload.target.path; + this.target = OS.Path.basename(aDownload.target.path); + this.uri = aDownload.source.url; + this.endTime = Date.now(); + + this.updateFromJSDownload(); + }, + + /** + * Updates this object from the JavaScript API for downloads. + */ + updateFromJSDownload: function () + { + // Collapse state using the correct priority. + if (this._download.succeeded) { + this.state = nsIDM.DOWNLOAD_FINISHED; + } else if (this._download.error && + this._download.error.becauseBlockedByParentalControls) { + this.state = nsIDM.DOWNLOAD_BLOCKED_PARENTAL; + } else if (this._download.error) { + this.state = nsIDM.DOWNLOAD_FAILED; + } else if (this._download.canceled && this._download.hasPartialData) { + this.state = nsIDM.DOWNLOAD_PAUSED; + } else if (this._download.canceled) { + this.state = nsIDM.DOWNLOAD_CANCELED; + } else if (this._download.stopped) { + this.state = nsIDM.DOWNLOAD_NOTSTARTED; + } else { + this.state = nsIDM.DOWNLOAD_DOWNLOADING; + } + + this.referrer = this._download.source.referrer; + this.startTime = this._download.startTime; + this.currBytes = this._download.currentBytes; + this.resumable = this._download.hasPartialData; + this.speed = this._download.speed; + + if (this._download.succeeded) { + // If the download succeeded, show the final size if available, otherwise + // use the last known number of bytes transferred. The final size on disk + // will be available when bug 941063 is resolved. + this.maxBytes = this._download.hasProgress ? + this._download.totalBytes : + this._download.currentBytes; + this.percentComplete = 100; + } else if (this._download.hasProgress) { + // If the final size and progress are known, use them. + this.maxBytes = this._download.totalBytes; + this.percentComplete = this._download.progress; + } else { + // The download final size and progress percentage is unknown. + this.maxBytes = -1; + this.percentComplete = -1; + } + }, + + /** + * Initializes this object from a download object of the Download Manager. + * + * The endTime property is initialized to the current date and time. + * + * @param aDownload + * The nsIDownload with the current state. + */ + _initFromDownload: function DDI_initFromDownload(aDownload) + { + this._download = aDownload; + + // Fetch all the download properties eagerly. + this.downloadGuid = aDownload.guid; + this.file = aDownload.target.spec; + this.target = aDownload.displayName; + this.uri = aDownload.source.spec; + this.referrer = aDownload.referrer && aDownload.referrer.spec; + this.state = aDownload.state; + this.startTime = Math.round(aDownload.startTime / 1000); + this.endTime = Date.now(); + this.currBytes = aDownload.amountTransferred; + this.maxBytes = aDownload.size; + this.resumable = aDownload.resumable; + this.speed = aDownload.speed; + this.percentComplete = aDownload.percentComplete; + }, + + /** + * Initializes this object from a data row in the downloads database, without + * querying the associated nsIDownload object, to improve performance when + * loading the list of downloads asynchronously. + * + * When this object is initialized in this way, accessing the "download" + * property loads the underlying nsIDownload object synchronously, and should + * be avoided unless the object is really required. + * + * @param aStorageRow + * The mozIStorageRow from the downloads database. + */ + _initFromDataRow: function DDI_initFromDataRow(aStorageRow) + { + // Get the download properties from the data row. + this._download = null; + this.downloadGuid = aStorageRow.getResultByName("guid"); + this.file = aStorageRow.getResultByName("target"); + this.target = aStorageRow.getResultByName("name"); + this.uri = aStorageRow.getResultByName("source"); + this.referrer = aStorageRow.getResultByName("referrer"); + this.state = aStorageRow.getResultByName("state"); + this.startTime = Math.round(aStorageRow.getResultByName("startTime") / 1000); + this.endTime = Math.round(aStorageRow.getResultByName("endTime") / 1000); + this.currBytes = aStorageRow.getResultByName("currBytes"); + this.maxBytes = aStorageRow.getResultByName("maxBytes"); + + // Now we have to determine if the download is resumable, but don't want to + // access the underlying download object unnecessarily. The only case where + // the property is relevant is when we are currently downloading data, and + // in this case the download object is already loaded in memory or will be + // loaded very soon in any case. In all the other cases, including a paused + // download, we assume that the download is resumable. The property will be + // updated as soon as the underlying download state changes. + + // We'll start by assuming we're resumable, and then if we're downloading, + // update resumable property in case we were wrong. + this.resumable = true; + + if (this.state == nsIDM.DOWNLOAD_DOWNLOADING) { + this.getDownload(function(aDownload) { + this.resumable = aDownload.resumable; + }.bind(this)); + } + + // Compute the other properties without accessing the download object. + this.speed = 0; + this.percentComplete = this.maxBytes <= 0 + ? -1 + : Math.round(this.currBytes / this.maxBytes * 100); + }, + + /** + * Asynchronous getter for the download object corresponding to this data item. + * + * @param aCallback + * A callback function which will be called when the download object is + * available. It should accept one argument which will be the download + * object. + */ + getDownload: function DDI_getDownload(aCallback) { + if (this._download) { + // Return the download object asynchronously to the caller + let download = this._download; + Services.tm.mainThread.dispatch(function () aCallback(download), + Ci.nsIThread.DISPATCH_NORMAL); + } else { + Services.downloads.getDownloadByGUID(this.downloadGuid, + function(aStatus, aResult) { + if (!Components.isSuccessCode(aStatus)) { + Cu.reportError( + new Components.Exception("Cannot retrieve download for GUID: " + + this.downloadGuid)); + } else { + this._download = aResult; + aCallback(aResult); + } + }.bind(this)); + } + }, + + /** + * Indicates whether the download is proceeding normally, and not finished + * yet. This includes paused downloads. When this property is true, the + * "progress" property represents the current progress of the download. + */ + get inProgress() + { + return [ + nsIDM.DOWNLOAD_NOTSTARTED, + nsIDM.DOWNLOAD_QUEUED, + nsIDM.DOWNLOAD_DOWNLOADING, + nsIDM.DOWNLOAD_PAUSED, + nsIDM.DOWNLOAD_SCANNING, + ].indexOf(this.state) != -1; + }, + + /** + * This is true during the initial phases of a download, before the actual + * download of data bytes starts. + */ + get starting() + { + return this.state == nsIDM.DOWNLOAD_NOTSTARTED || + this.state == nsIDM.DOWNLOAD_QUEUED; + }, + + /** + * Indicates whether the download is paused. + */ + get paused() + { + return this.state == nsIDM.DOWNLOAD_PAUSED; + }, + + /** + * Indicates whether the download is in a final state, either because it + * completed successfully or because it was blocked. + */ + get done() + { + return [ + nsIDM.DOWNLOAD_FINISHED, + nsIDM.DOWNLOAD_BLOCKED_PARENTAL, + nsIDM.DOWNLOAD_BLOCKED_POLICY, + nsIDM.DOWNLOAD_DIRTY, + ].indexOf(this.state) != -1; + }, + + /** + * Indicates whether the download is finished and can be opened. + */ + get openable() + { + return this.state == nsIDM.DOWNLOAD_FINISHED; + }, + + /** + * Indicates whether the download stopped because of an error, and can be + * resumed manually. + */ + get canRetry() + { + return this.state == nsIDM.DOWNLOAD_CANCELED || + this.state == nsIDM.DOWNLOAD_FAILED; + }, + + /** + * Returns the nsILocalFile for the download target. + * + * @throws if the native path is not valid. This can happen if the same + * profile is used on different platforms, for example if a native + * Windows path is stored and then the item is accessed on a Mac. + */ + get localFile() + { + return this._getFile(this.file); + }, + + /** + * Returns the nsILocalFile for the partially downloaded target. + * + * @throws if the native path is not valid. This can happen if the same + * profile is used on different platforms, for example if a native + * Windows path is stored and then the item is accessed on a Mac. + */ + get partFile() + { + return this._getFile(this.file + kPartialDownloadSuffix); + }, + + /** + * Returns an nsILocalFile for aFilename. aFilename might be a file URL or + * a native path. + * + * @param aFilename the filename of the file to retrieve. + * @return an nsILocalFile for the file. + * @throws if the native path is not valid. This can happen if the same + * profile is used on different platforms, for example if a native + * Windows path is stored and then the item is accessed on a Mac. + * @note This function makes no guarantees about the file's existence - + * callers should check that the returned file exists. + */ + _getFile: function DDI__getFile(aFilename) + { + // The download database may contain targets stored as file URLs or native + // paths. This can still be true for previously stored items, even if new + // items are stored using their file URL. See also bug 239948 comment 12. + if (aFilename.startsWith("file:")) { + // Assume the file URL we obtained from the downloads database or from the + // "spec" property of the target has the UTF-8 charset. + let fileUrl = NetUtil.newURI(aFilename).QueryInterface(Ci.nsIFileURL); + return fileUrl.file.clone().QueryInterface(Ci.nsILocalFile); + } else { + // The downloads database contains a native path. Try to create a local + // file, though this may throw an exception if the path is invalid. + return new DownloadsLocalFileCtor(aFilename); + } + }, + + /** + * Open the target file for this download. + * + * @param aOwnerWindow + * The window with which the required action is associated. + * @throws if the file cannot be opened. + */ + openLocalFile: function DDI_openLocalFile(aOwnerWindow) { + this._download.launch().then(null, Cu.reportError); + return; + }, + + /** + * Show the downloaded file in the system file manager. + */ + showLocalFile: function DDI_showLocalFile() { + DownloadsCommon.showDownloadedFile(this.localFile); + }, + + /** + * Resumes the download if paused, pauses it if active. + * @throws if the download is not resumable or if has already done. + */ + togglePauseResume: function DDI_togglePauseResume() { + if (this._download.stopped) { + this._download.start(); + } else { + this._download.cancel(); + } + return; + }, + + /** + * Attempts to retry the download. + * @throws if we cannot. + */ + retry: function DDI_retry() { + this._download.start(); + return; + }, + + /** + * Support function that deletes the local file for a download. This is + * used in cases where the Download Manager service doesn't delete the file + * from disk when cancelling. See bug 732924. + */ + _ensureLocalFileRemoved: function DDI__ensureLocalFileRemoved() + { + try { + let localFile = this.localFile; + if (localFile.exists()) { + localFile.remove(false); + } + } catch (ex) { } + }, + + /** + * Cancels the download. + * @throws if the download is already done. + */ + cancel: function() { + this._download.cancel(); + this._download.removePartialData().then(null, Cu.reportError); + return; + }, + + /** + * Remove the download. + */ + remove: function DDI_remove() { + let promiseList = this._download.source.isPrivate + ? Downloads.getList(Downloads.PUBLIC) + : Downloads.getList(Downloads.PRIVATE); + promiseList.then(list => list.remove(this._download)) + .then(() => this._download.finalize(true)) + .then(null, Cu.reportError); + return; + } +}; + +//////////////////////////////////////////////////////////////////////////////// +//// DownloadsViewPrototype + +/** + * A prototype for an object that registers itself with DownloadsData as soon + * as a view is registered with it. + */ +const DownloadsViewPrototype = { + ////////////////////////////////////////////////////////////////////////////// + //// Registration of views + + /** + * Array of view objects that should be notified when the available status + * data changes. + * + * SUBCLASSES MUST OVERRIDE THIS PROPERTY. + */ + _views: null, + + /** + * Determines whether this view object is over the private or non-private + * downloads. + * + * SUBCLASSES MUST OVERRIDE THIS PROPERTY. + */ + _isPrivate: false, + + /** + * Adds an object to be notified when the available status data changes. + * The specified object is initialized with the currently available status. + * + * @param aView + * View object to be added. This reference must be + * passed to removeView before termination. + */ + addView: function DVP_addView(aView) + { + // Start receiving events when the first of our views is registered. + if (this._views.length == 0) { + if (this._isPrivate) { + PrivateDownloadsData.addView(this); + } else { + DownloadsData.addView(this); + } + } + + this._views.push(aView); + this.refreshView(aView); + }, + + /** + * Updates the properties of an object previously added using addView. + * + * @param aView + * View object to be updated. + */ + refreshView: function DVP_refreshView(aView) + { + // Update immediately even if we are still loading data asynchronously. + // Subclasses must provide these two functions! + this._refreshProperties(); + this._updateView(aView); + }, + + /** + * Removes an object previously added using addView. + * + * @param aView + * View object to be removed. + */ + removeView: function DVP_removeView(aView) + { + let index = this._views.indexOf(aView); + if (index != -1) { + this._views.splice(index, 1); + } + + // Stop receiving events when the last of our views is unregistered. + if (this._views.length == 0) { + if (this._isPrivate) { + PrivateDownloadsData.removeView(this); + } else { + DownloadsData.removeView(this); + } + } + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Callback functions from DownloadsData + + /** + * Indicates whether we are still loading downloads data asynchronously. + */ + _loading: false, + + /** + * Called before multiple downloads are about to be loaded. + */ + onDataLoadStarting: function DVP_onDataLoadStarting() + { + this._loading = true; + }, + + /** + * Called after data loading finished. + */ + onDataLoadCompleted: function DVP_onDataLoadCompleted() + { + this._loading = false; + }, + + /** + * Called when the downloads database becomes unavailable (for example, we + * entered Private Browsing Mode and the database backend changed). + * References to existing data should be discarded. + * + * @note Subclasses should override this. + */ + onDataInvalidated: function DVP_onDataInvalidated() + { + throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + }, + + /** + * Called when a new download data item is available, either during the + * asynchronous data load or when a new download is started. + * + * @param aDataItem + * DownloadsDataItem object that was just added. + * @param aNewest + * When true, indicates that this item is the most recent and should be + * added in the topmost position. This happens when a new download is + * started. When false, indicates that the item is the least recent + * with regard to the items that have been already added. The latter + * generally happens during the asynchronous data load. + * + * @note Subclasses should override this. + */ + onDataItemAdded: function DVP_onDataItemAdded(aDataItem, aNewest) + { + throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + }, + + /** + * Called when a data item is removed, ensures that the widget associated with + * the view item is removed from the user interface. + * + * @param aDataItem + * DownloadsDataItem object that is being removed. + * + * @note Subclasses should override this. + */ + onDataItemRemoved: function DVP_onDataItemRemoved(aDataItem) + { + throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + }, + + /** + * Returns the view item associated with the provided data item for this view. + * + * @param aDataItem + * DownloadsDataItem object for which the view item is requested. + * + * @return Object that can be used to notify item status events. + * + * @note Subclasses should override this. + */ + getViewItem: function DID_getViewItem(aDataItem) + { + throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + }, + + /** + * Private function used to refresh the internal properties being sent to + * each registered view. + * + * @note Subclasses should override this. + */ + _refreshProperties: function DID_refreshProperties() + { + throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + }, + + /** + * Private function used to refresh an individual view. + * + * @note Subclasses should override this. + */ + _updateView: function DID_updateView() + { + throw Components.results.NS_ERROR_NOT_IMPLEMENTED; + } +}; + +//////////////////////////////////////////////////////////////////////////////// +//// DownloadsIndicatorData + +/** + * This object registers itself with DownloadsData as a view, and transforms the + * notifications it receives into overall status data, that is then broadcast to + * the registered download status indicators. + * + * Note that using this object does not automatically start the Download Manager + * service. Consumers will see an empty list of downloads until the service is + * actually started. This is useful to display a neutral progress indicator in + * the main browser window until the autostart timeout elapses. + */ +function DownloadsIndicatorDataCtor(aPrivate) { + this._isPrivate = aPrivate; + this._views = []; +} +DownloadsIndicatorDataCtor.prototype = { + __proto__: DownloadsViewPrototype, + + /** + * Removes an object previously added using addView. + * + * @param aView + * DownloadsIndicatorView object to be removed. + */ + removeView: function DID_removeView(aView) + { + DownloadsViewPrototype.removeView.call(this, aView); + + if (this._views.length == 0) { + this._itemCount = 0; + } + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Callback functions from DownloadsData + + /** + * Called after data loading finished. + */ + onDataLoadCompleted: function DID_onDataLoadCompleted() + { + DownloadsViewPrototype.onDataLoadCompleted.call(this); + this._updateViews(); + }, + + /** + * Called when the downloads database becomes unavailable (for example, we + * entered Private Browsing Mode and the database backend changed). + * References to existing data should be discarded. + */ + onDataInvalidated: function DID_onDataInvalidated() + { + this._itemCount = 0; + }, + + /** + * Called when a new download data item is available, either during the + * asynchronous data load or when a new download is started. + * + * @param aDataItem + * DownloadsDataItem object that was just added. + * @param aNewest + * When true, indicates that this item is the most recent and should be + * added in the topmost position. This happens when a new download is + * started. When false, indicates that the item is the least recent + * with regard to the items that have been already added. The latter + * generally happens during the asynchronous data load. + */ + onDataItemAdded: function DID_onDataItemAdded(aDataItem, aNewest) + { + this._itemCount++; + this._updateViews(); + }, + + /** + * Called when a data item is removed, ensures that the widget associated with + * the view item is removed from the user interface. + * + * @param aDataItem + * DownloadsDataItem object that is being removed. + */ + onDataItemRemoved: function DID_onDataItemRemoved(aDataItem) + { + this._itemCount--; + this._updateViews(); + }, + + /** + * Returns the view item associated with the provided data item for this view. + * + * @param aDataItem + * DownloadsDataItem object for which the view item is requested. + * + * @return Object that can be used to notify item status events. + */ + getViewItem: function DID_getViewItem(aDataItem) + { + let data = this._isPrivate ? PrivateDownloadsIndicatorData + : DownloadsIndicatorData; + return Object.freeze({ + onStateChange: function DIVI_onStateChange(aOldState) + { + if (aDataItem.state == nsIDM.DOWNLOAD_FINISHED || + aDataItem.state == nsIDM.DOWNLOAD_FAILED) { + data.attention = true; + } + + // Since the state of a download changed, reset the estimated time left. + data._lastRawTimeLeft = -1; + data._lastTimeLeft = -1; + + data._updateViews(); + }, + onProgressChange: function DIVI_onProgressChange() + { + data._updateViews(); + } + }); + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Propagation of properties to our views + + // The following properties are updated by _refreshProperties and are then + // propagated to the views. See _refreshProperties for details. + _hasDownloads: false, + _counter: "", + _percentComplete: -1, + _paused: false, + + /** + * Indicates whether the download indicators should be highlighted. + */ + set attention(aValue) + { + this._attention = aValue; + this._updateViews(); + return aValue; + }, + _attention: false, + + /** + * Indicates whether the user is interacting with downloads, thus the + * attention indication should not be shown even if requested. + */ + set attentionSuppressed(aValue) + { + this._attentionSuppressed = aValue; + this._attention = false; + this._updateViews(); + return aValue; + }, + _attentionSuppressed: false, + + /** + * Computes aggregate values and propagates the changes to our views. + */ + _updateViews: function DID_updateViews() + { + // Do not update the status indicators during batch loads of download items. + if (this._loading) { + return; + } + + this._refreshProperties(); + this._views.forEach(this._updateView, this); + }, + + /** + * Updates the specified view with the current aggregate values. + * + * @param aView + * DownloadsIndicatorView object to be updated. + */ + _updateView: function DID_updateView(aView) + { + aView.hasDownloads = this._hasDownloads; + aView.counter = this._counter; + aView.percentComplete = this._percentComplete; + aView.paused = this._paused; + aView.attention = this._attention && !this._attentionSuppressed; + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Property updating based on current download status + + /** + * Number of download items that are available to be displayed. + */ + _itemCount: 0, + + /** + * Floating point value indicating the last number of seconds estimated until + * the longest download will finish. We need to store this value so that we + * don't continuously apply smoothing if the actual download state has not + * changed. This is set to -1 if the previous value is unknown. + */ + _lastRawTimeLeft: -1, + + /** + * Last number of seconds estimated until all in-progress downloads with a + * known size and speed will finish. This value is stored to allow smoothing + * in case of small variations. This is set to -1 if the previous value is + * unknown. + */ + _lastTimeLeft: -1, + + /** + * A generator function for the dataItems that this summary is currently + * interested in. This generator is passed off to summarizeDownloads in order + * to generate statistics about the dataItems we care about - in this case, + * it's all dataItems for active downloads. + */ + _activeDataItems: function DID_activeDataItems() + { + let dataItems = this._isPrivate ? PrivateDownloadsData.dataItems + : DownloadsData.dataItems; + for each (let dataItem in dataItems) { + if (dataItem && dataItem.inProgress) { + yield dataItem; + } + } + }, + + /** + * Computes aggregate values based on the current state of downloads. + */ + _refreshProperties: function DID_refreshProperties() + { + let summary = + DownloadsCommon.summarizeDownloads(this._activeDataItems()); + + // Determine if the indicator should be shown or get attention. + this._hasDownloads = (this._itemCount > 0); + + // If all downloads are paused, show the progress indicator as paused. + this._paused = summary.numActive > 0 && + summary.numActive == summary.numPaused; + + this._percentComplete = summary.percentComplete; + + // Display the estimated time left, if present. + if (summary.rawTimeLeft == -1) { + // There are no downloads with a known time left. + this._lastRawTimeLeft = -1; + this._lastTimeLeft = -1; + this._counter = ""; + } else { + // Compute the new time left only if state actually changed. + if (this._lastRawTimeLeft != summary.rawTimeLeft) { + this._lastRawTimeLeft = summary.rawTimeLeft; + this._lastTimeLeft = DownloadsCommon.smoothSeconds(summary.rawTimeLeft, + this._lastTimeLeft); + } + this._counter = DownloadsCommon.formatTimeLeft(this._lastTimeLeft); + } + } +}; + +XPCOMUtils.defineLazyGetter(this, "PrivateDownloadsIndicatorData", function() { + return new DownloadsIndicatorDataCtor(true); +}); + +XPCOMUtils.defineLazyGetter(this, "DownloadsIndicatorData", function() { + return new DownloadsIndicatorDataCtor(false); +}); + +//////////////////////////////////////////////////////////////////////////////// +//// DownloadsSummaryData + +/** + * DownloadsSummaryData is a view for DownloadsData that produces a summary + * of all downloads after a certain exclusion point aNumToExclude. For example, + * if there were 5 downloads in progress, and a DownloadsSummaryData was + * constructed with aNumToExclude equal to 3, then that DownloadsSummaryData + * would produce a summary of the last 2 downloads. + * + * @param aIsPrivate + * True if the browser window which owns the download button is a private + * window. + * @param aNumToExclude + * The number of items to exclude from the summary, starting from the + * top of the list. + */ +function DownloadsSummaryData(aIsPrivate, aNumToExclude) { + this._numToExclude = aNumToExclude; + // Since we can have multiple instances of DownloadsSummaryData, we + // override these values from the prototype so that each instance can be + // completely separated from one another. + this._loading = false; + + this._dataItems = []; + + // Floating point value indicating the last number of seconds estimated until + // the longest download will finish. We need to store this value so that we + // don't continuously apply smoothing if the actual download state has not + // changed. This is set to -1 if the previous value is unknown. + this._lastRawTimeLeft = -1; + + // Last number of seconds estimated until all in-progress downloads with a + // known size and speed will finish. This value is stored to allow smoothing + // in case of small variations. This is set to -1 if the previous value is + // unknown. + this._lastTimeLeft = -1; + + // The following properties are updated by _refreshProperties and are then + // propagated to the views. + this._showingProgress = false; + this._details = ""; + this._description = ""; + this._numActive = 0; + this._percentComplete = -1; + + this._isPrivate = aIsPrivate; + this._views = []; +} + +DownloadsSummaryData.prototype = { + __proto__: DownloadsViewPrototype, + + /** + * Removes an object previously added using addView. + * + * @param aView + * DownloadsSummary view to be removed. + */ + removeView: function DSD_removeView(aView) + { + DownloadsViewPrototype.removeView.call(this, aView); + + if (this._views.length == 0) { + // Clear out our collection of DownloadDataItems. If we ever have + // another view registered with us, this will get re-populated. + this._dataItems = []; + } + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Callback functions from DownloadsData - see the documentation in + //// DownloadsViewPrototype for more information on what these functions + //// are used for. + + onDataLoadCompleted: function DSD_onDataLoadCompleted() + { + DownloadsViewPrototype.onDataLoadCompleted.call(this); + this._updateViews(); + }, + + onDataInvalidated: function DSD_onDataInvalidated() + { + this._dataItems = []; + }, + + onDataItemAdded: function DSD_onDataItemAdded(aDataItem, aNewest) + { + if (aNewest) { + this._dataItems.unshift(aDataItem); + } else { + this._dataItems.push(aDataItem); + } + + this._updateViews(); + }, + + onDataItemRemoved: function DSD_onDataItemRemoved(aDataItem) + { + let itemIndex = this._dataItems.indexOf(aDataItem); + this._dataItems.splice(itemIndex, 1); + this._updateViews(); + }, + + getViewItem: function DSD_getViewItem(aDataItem) + { + let self = this; + return Object.freeze({ + onStateChange: function DIVI_onStateChange(aOldState) + { + // Since the state of a download changed, reset the estimated time left. + self._lastRawTimeLeft = -1; + self._lastTimeLeft = -1; + self._updateViews(); + }, + onProgressChange: function DIVI_onProgressChange() + { + self._updateViews(); + } + }); + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Propagation of properties to our views + + /** + * Computes aggregate values and propagates the changes to our views. + */ + _updateViews: function DSD_updateViews() + { + // Do not update the status indicators during batch loads of download items. + if (this._loading) { + return; + } + + this._refreshProperties(); + this._views.forEach(this._updateView, this); + }, + + /** + * Updates the specified view with the current aggregate values. + * + * @param aView + * DownloadsIndicatorView object to be updated. + */ + _updateView: function DSD_updateView(aView) + { + aView.showingProgress = this._showingProgress; + aView.percentComplete = this._percentComplete; + aView.description = this._description; + aView.details = this._details; + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Property updating based on current download status + + /** + * A generator function for the dataItems that this summary is currently + * interested in. This generator is passed off to summarizeDownloads in order + * to generate statistics about the dataItems we care about - in this case, + * it's the dataItems in this._dataItems after the first few to exclude, + * which was set when constructing this DownloadsSummaryData instance. + */ + _dataItemsForSummary: function DSD_dataItemsForSummary() + { + if (this._dataItems.length > 0) { + for (let i = this._numToExclude; i < this._dataItems.length; ++i) { + yield this._dataItems[i]; + } + } + }, + + /** + * Computes aggregate values based on the current state of downloads. + */ + _refreshProperties: function DSD_refreshProperties() + { + // Pre-load summary with default values. + let summary = + DownloadsCommon.summarizeDownloads(this._dataItemsForSummary()); + + this._description = DownloadsCommon.strings + .otherDownloads2(summary.numActive); + this._percentComplete = summary.percentComplete; + + // If all downloads are paused, show the progress indicator as paused. + this._showingProgress = summary.numDownloading > 0 || + summary.numPaused > 0; + + // Display the estimated time left, if present. + if (summary.rawTimeLeft == -1) { + // There are no downloads with a known time left. + this._lastRawTimeLeft = -1; + this._lastTimeLeft = -1; + this._details = ""; + } else { + // Compute the new time left only if state actually changed. + if (this._lastRawTimeLeft != summary.rawTimeLeft) { + this._lastRawTimeLeft = summary.rawTimeLeft; + this._lastTimeLeft = DownloadsCommon.smoothSeconds(summary.rawTimeLeft, + this._lastTimeLeft); + } + [this._details] = DownloadUtils.getDownloadStatusNoRate( + summary.totalTransferred, summary.totalSize, summary.slowestSpeed, + this._lastTimeLeft); + } + } +} diff --git a/application/palemoon/components/downloads/DownloadsLogger.jsm b/application/palemoon/components/downloads/DownloadsLogger.jsm new file mode 100644 index 000000000..1218539c9 --- /dev/null +++ b/application/palemoon/components/downloads/DownloadsLogger.jsm @@ -0,0 +1,76 @@ +/* -*- Mode: js2; js2-basic-offset: 2; indent-tabs-mode: nil; -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/** + * The contents of this file were copied almost entirely from + * toolkit/identity/LogUtils.jsm. Until we've got a more generalized logging + * mechanism for toolkit, I think this is going to be how we roll. + */ + +"use strict"; + +this.EXPORTED_SYMBOLS = ["DownloadsLogger"]; +const PREF_DEBUG = "browser.download.debug"; + +const Cu = Components.utils; +const Ci = Components.interfaces; +const Cc = Components.classes; +const Cr = Components.results; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); + +this.DownloadsLogger = { + _generateLogMessage: function _generateLogMessage(args) { + // create a string representation of a list of arbitrary things + let strings = []; + + for (let arg of args) { + if (typeof arg === 'string') { + strings.push(arg); + } else if (arg === undefined) { + strings.push('undefined'); + } else if (arg === null) { + strings.push('null'); + } else { + try { + strings.push(JSON.stringify(arg, null, 2)); + } catch(err) { + strings.push("<>"); + } + } + }; + return 'Downloads: ' + strings.join(' '); + }, + + /** + * log() - utility function to print a list of arbitrary things + * + * Enable with about:config pref browser.download.debug + */ + log: function DL_log(...args) { + let output = this._generateLogMessage(args); + dump(output + "\n"); + + // Additionally, make the output visible in the Error Console + Services.console.logStringMessage(output); + }, + + /** + * reportError() - report an error through component utils as well as + * our log function + */ + reportError: function DL_reportError(...aArgs) { + // Report the error in the browser + let output = this._generateLogMessage(aArgs); + Cu.reportError(output); + dump("ERROR:" + output + "\n"); + for (let frame = Components.stack.caller; frame; frame = frame.caller) { + dump("\t" + frame + "\n"); + } + } + +}; diff --git a/application/palemoon/components/downloads/DownloadsStartup.js b/application/palemoon/components/downloads/DownloadsStartup.js new file mode 100644 index 000000000..e1dd207ef --- /dev/null +++ b/application/palemoon/components/downloads/DownloadsStartup.js @@ -0,0 +1,278 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/** + * This component listens to notifications for startup, shutdown and session + * restore, controlling which downloads should be loaded from the database. + * + * To avoid affecting startup performance, this component monitors the current + * session restore state, but defers the actual downloads data manipulation + * until the Download Manager service is loaded. + */ + +"use strict"; + +//////////////////////////////////////////////////////////////////////////////// +//// Globals + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "DownloadsCommon", + "resource:///modules/DownloadsCommon.jsm"); +XPCOMUtils.defineLazyServiceGetter(this, "gSessionStartup", + "@mozilla.org/browser/sessionstartup;1", + "nsISessionStartup"); + +const kObservedTopics = [ + "sessionstore-windows-restored", + "sessionstore-browser-state-restored", + "download-manager-initialized", + "download-manager-change-retention", + "last-pb-context-exited", + "browser-lastwindow-close-granted", + "quit-application", + "profile-change-teardown", +]; + +/** + * CID of our implementation of nsIDownloadManagerUI. + */ +const kDownloadsUICid = Components.ID("{4d99321e-d156-455b-81f7-e7aa2308134f}"); + +/** + * Contract ID of the service implementing nsIDownloadManagerUI. + */ +const kDownloadsUIContractId = "@mozilla.org/download-manager-ui;1"; + +/** + * CID of the JavaScript implementation of nsITransfer. + */ +const kTransferCid = Components.ID("{1b4c85df-cbdd-4bb6-b04e-613caece083c}"); + +/** + * Contract ID of the service implementing nsITransfer. + */ +const kTransferContractId = "@mozilla.org/transfer;1"; + +//////////////////////////////////////////////////////////////////////////////// +//// DownloadsStartup + +function DownloadsStartup() { } + +DownloadsStartup.prototype = { + classID: Components.ID("{49507fe5-2cee-4824-b6a3-e999150ce9b8}"), + + _xpcom_factory: XPCOMUtils.generateSingletonFactory(DownloadsStartup), + + ////////////////////////////////////////////////////////////////////////////// + //// nsISupports + + QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, + Ci.nsISupportsWeakReference]), + + ////////////////////////////////////////////////////////////////////////////// + //// nsIObserver + + observe: function DS_observe(aSubject, aTopic, aData) + { + switch (aTopic) { + case "profile-after-change": + // Override Toolkit's nsIDownloadManagerUI implementation with our own. + // This must be done at application startup and not in the manifest to + // ensure that our implementation overrides the original one. + Components.manager.QueryInterface(Ci.nsIComponentRegistrar) + .registerFactory(kDownloadsUICid, "", + kDownloadsUIContractId, null); + + Components.manager.QueryInterface(Ci.nsIComponentRegistrar) + .registerFactory(kTransferCid, "", + kTransferContractId, null); + break; + + case "sessionstore-windows-restored": + case "sessionstore-browser-state-restored": + // Unless there is no saved session, there is a chance that we are + // starting up after a restart or a crash. We should check the disk + // database to see if there are completed downloads to recover and show + // in the panel, in addition to in-progress downloads. + if (gSessionStartup.sessionType != Ci.nsISessionStartup.NO_SESSION) { + this._restoringSession = true; + } + this._ensureDataLoaded(); + break; + + case "download-manager-initialized": + // Don't initialize the JavaScript data and user interface layer if we + // are initializing the Download Manager service during shutdown. + if (this._shuttingDown) { + break; + } + + // Start receiving events for active and new downloads before we return + // from this observer function. We can't defer the execution of this + // step, to ensure that we don't lose events raised in the meantime. + DownloadsCommon.initializeAllDataLinks( + aSubject.QueryInterface(Ci.nsIDownloadManager)); + + this._downloadsServiceInitialized = true; + + // Since this notification is generated during the getService call and + // we need to get the Download Manager service ourselves, we must post + // the handler on the event queue to be executed later. + Services.tm.mainThread.dispatch(this._ensureDataLoaded.bind(this), + Ci.nsIThread.DISPATCH_NORMAL); + break; + + case "download-manager-change-retention": + // If we're using the Downloads Panel, we override the retention + // preference to always retain downloads on completion. + if (!DownloadsCommon.useToolkitUI) { + aSubject.QueryInterface(Ci.nsISupportsPRInt32).data = 2; + } + break; + + case "browser-lastwindow-close-granted": + // When using the panel interface, downloads that are already completed + // should be removed when the last full browser window is closed. This + // event is invoked only if the application is not shutting down yet. + // If the Download Manager service is not initialized, we don't want to + // initialize it just to clean up completed downloads, because they can + // be present only in case there was a browser crash or restart. + if (this._downloadsServiceInitialized && + !DownloadsCommon.useToolkitUI) { + Services.downloads.cleanUp(); + } + break; + + case "last-pb-context-exited": + // Similar to the above notification, but for private downloads. + if (this._downloadsServiceInitialized && + !DownloadsCommon.useToolkitUI) { + Services.downloads.cleanUpPrivate(); + } + break; + + case "quit-application": + // When the application is shutting down, we must free all resources in + // addition to cleaning up completed downloads. If the Download Manager + // service is not initialized, we don't want to initialize it just to + // clean up completed downloads, because they can be present only in + // case there was a browser crash or restart. + this._shuttingDown = true; + if (!this._downloadsServiceInitialized) { + break; + } + + DownloadsCommon.terminateAllDataLinks(); + + // When using the panel interface, downloads that are already completed + // should be removed when quitting the application. + if (!DownloadsCommon.useToolkitUI && aData != "restart") { + this._cleanupOnShutdown = true; + } + break; + + case "profile-change-teardown": + // If we need to clean up, we must do it synchronously after all the + // "quit-application" listeners are invoked, so that the Download + // Manager service has a chance to pause or cancel in-progress downloads + // before we remove completed downloads from the list. Note that, since + // "quit-application" was invoked, we've already exited Private Browsing + // Mode, thus we are always working on the disk database. + if (this._cleanupOnShutdown) { + Services.downloads.cleanUp(); + } + + if (!DownloadsCommon.useToolkitUI) { + // If we got this far, that means that we finished our first session + // with the Downloads Panel without crashing. This means that we don't + // have to force displaying only active downloads on the next startup + // now. + this._firstSessionCompleted = true; + } + break; + } + }, + + ////////////////////////////////////////////////////////////////////////////// + //// Private + + /** + * Indicates whether we're restoring a previous session. This is used by + * _recoverAllDownloads to determine whether or not we should load and + * display all downloads data, or restrict it to only the active downloads. + */ + _restoringSession: false, + + /** + * Indicates whether the Download Manager service has been initialized. This + * flag is required because we want to avoid accessing the service immediately + * at browser startup. The service will start when the user first requests a + * download, or some time after browser startup. + */ + _downloadsServiceInitialized: false, + + /** + * True while we are processing the "quit-application" event, and later. + */ + _shuttingDown: false, + + /** + * True during shutdown if we need to remove completed downloads. + */ + _cleanupOnShutdown: false, + + /** + * True if we should display all downloads, as opposed to just active + * downloads. We decide to display all downloads if we're restoring a session, + * or if we're using the Downloads Panel anytime after the first session with + * it has completed. + */ + get _recoverAllDownloads() { + return this._restoringSession || + (!DownloadsCommon.useToolkitUI && this._firstSessionCompleted); + }, + + /** + * True if we've ever completed a session with the Downloads Panel enabled. + */ + get _firstSessionCompleted() { + return Services.prefs + .getBoolPref("browser.download.panel.firstSessionCompleted"); + }, + + set _firstSessionCompleted(aValue) { + Services.prefs.setBoolPref("browser.download.panel.firstSessionCompleted", + aValue); + return aValue; + }, + + /** + * Ensures that persistent download data is reloaded at the appropriate time. + */ + _ensureDataLoaded: function DS_ensureDataLoaded() + { + if (!this._downloadsServiceInitialized) { + return; + } + + // If the previous session has been already restored, then we ensure that + // all the downloads are loaded. Otherwise, we only ensure that the active + // downloads from the previous session are loaded. + DownloadsCommon.ensureAllPersistentDataLoaded(!this._recoverAllDownloads); + } +}; + +//////////////////////////////////////////////////////////////////////////////// +//// Module + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([DownloadsStartup]); diff --git a/application/palemoon/components/downloads/DownloadsTaskbar.jsm b/application/palemoon/components/downloads/DownloadsTaskbar.jsm new file mode 100644 index 000000000..cf915abb5 --- /dev/null +++ b/application/palemoon/components/downloads/DownloadsTaskbar.jsm @@ -0,0 +1,177 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/** + * Handles the download progress indicator in the taskbar. + */ + +"use strict"; + +this.EXPORTED_SYMBOLS = [ + "DownloadsTaskbar", +]; + +//////////////////////////////////////////////////////////////////////////////// +//// Globals + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "Downloads", + "resource://gre/modules/Downloads.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "RecentWindow", + "resource:///modules/RecentWindow.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Services", + "resource://gre/modules/Services.jsm"); + +XPCOMUtils.defineLazyGetter(this, "gWinTaskbar", function () { + if (!("@mozilla.org/windows-taskbar;1" in Cc)) { + return null; + } + let winTaskbar = Cc["@mozilla.org/windows-taskbar;1"] + .getService(Ci.nsIWinTaskbar); + return winTaskbar.available && winTaskbar; +}); + +XPCOMUtils.defineLazyGetter(this, "gMacTaskbarProgress", function () { + return ("@mozilla.org/widget/macdocksupport;1" in Cc) && + Cc["@mozilla.org/widget/macdocksupport;1"] + .getService(Ci.nsITaskbarProgress); +}); + +//////////////////////////////////////////////////////////////////////////////// +//// DownloadsTaskbar + +/** + * Handles the download progress indicator in the taskbar. + */ +this.DownloadsTaskbar = { + /** + * Underlying DownloadSummary providing the aggregate download information, or + * null if the indicator has never been initialized. + */ + _summary: null, + + /** + * nsITaskbarProgress object to which download information is dispatched. + * This can be null if the indicator has never been initialized or if the + * indicator is currently hidden on Windows. + */ + _taskbarProgress: null, + + /** + * This method is called after a new browser window is opened, and ensures + * that the download progress indicator is displayed in the taskbar. + * + * On Windows, the indicator is attached to the first browser window that + * calls this method. When the window is closed, the indicator is moved to + * another browser window, if available, in no particular order. When there + * are no browser windows visible, the indicator is hidden. + * + * On Mac OS X, the indicator is initialized globally when this method is + * called for the first time. Subsequent calls have no effect. + * + * @param aBrowserWindow + * nsIDOMWindow object of the newly opened browser window to which the + * indicator may be attached. + */ + registerIndicator(aBrowserWindow) { + if (!this._taskbarProgress) { + if (gMacTaskbarProgress) { + // On Mac OS X, we have to register the global indicator only once. + this._taskbarProgress = gMacTaskbarProgress; + // Free the XPCOM reference on shutdown, to prevent detecting a leak. + Services.obs.addObserver(() => { + this._taskbarProgress = null; + gMacTaskbarProgress = null; + }, "quit-application-granted", false); + } else if (gWinTaskbar) { + // On Windows, the indicator is currently hidden because we have no + // previous browser window, thus we should attach the indicator now. + this._attachIndicator(aBrowserWindow); + } else { + // The taskbar indicator is not available on this platform. + return; + } + } + + // Ensure that the DownloadSummary object will be created asynchronously. + if (!this._summary) { + Downloads.getSummary(Downloads.ALL).then(summary => { + // In case the method is re-entered, we simply ignore redundant + // invocations of the callback, instead of keeping separate state. + if (this._summary) { + return; + } + this._summary = summary; + return this._summary.addView(this); + }).then(null, Cu.reportError); + } + }, + + /** + * On Windows, attaches the taskbar indicator to the specified browser window. + */ + _attachIndicator(aWindow) { + // Activate the indicator on the specified window. + let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .QueryInterface(Ci.nsIDocShellTreeItem).treeOwner + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIXULWindow).docShell; + this._taskbarProgress = gWinTaskbar.getTaskbarProgress(docShell); + + // If the DownloadSummary object has already been created, we should update + // the state of the new indicator, otherwise it will be updated as soon as + // the DownloadSummary view is registered. + if (this._summary) { + this.onSummaryChanged(); + } + + aWindow.addEventListener("unload", () => { + // Locate another browser window, excluding the one being closed. + let browserWindow = RecentWindow.getMostRecentBrowserWindow(); + if (browserWindow) { + // Move the progress indicator to the other browser window. + this._attachIndicator(browserWindow); + } else { + // The last browser window has been closed. We remove the reference to + // the taskbar progress object so that the indicator will be registered + // again on the next browser window that is opened. + this._taskbarProgress = null; + } + }, false); + }, + + ////////////////////////////////////////////////////////////////////////////// + //// DownloadSummary view + + onSummaryChanged() { + // If the last browser window has been closed, we have no indicator any more. + if (!this._taskbarProgress) { + return; + } + + if (this._summary.allHaveStopped || this._summary.progressTotalBytes == 0) { + this._taskbarProgress.setProgressState( + Ci.nsITaskbarProgress.STATE_NO_PROGRESS, 0, 0); + } else { + // For a brief moment before completion, some download components may + // report more transferred bytes than the total number of bytes. Thus, + // ensure that we never break the expectations of the progress indicator. + let progressCurrentBytes = Math.min(this._summary.progressTotalBytes, + this._summary.progressCurrentBytes); + this._taskbarProgress.setProgressState( + Ci.nsITaskbarProgress.STATE_NORMAL, + progressCurrentBytes, + this._summary.progressTotalBytes); + } + }, +}; diff --git a/application/palemoon/components/downloads/DownloadsUI.js b/application/palemoon/components/downloads/DownloadsUI.js new file mode 100644 index 000000000..afdbda834 --- /dev/null +++ b/application/palemoon/components/downloads/DownloadsUI.js @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/** + * This component implements the nsIDownloadManagerUI interface and opens the + * downloads panel in the most recent browser window when requested. + * + * If a specific preference is set, this component transparently forwards all + * calls to the original implementation in Toolkit, that shows the window UI. + */ + +"use strict"; + +//////////////////////////////////////////////////////////////////////////////// +//// Globals + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "DownloadsCommon", + "resource:///modules/DownloadsCommon.jsm"); +XPCOMUtils.defineLazyServiceGetter(this, "gBrowserGlue", + "@mozilla.org/browser/browserglue;1", + "nsIBrowserGlue"); +XPCOMUtils.defineLazyModuleGetter(this, "RecentWindow", + "resource:///modules/RecentWindow.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); + +//////////////////////////////////////////////////////////////////////////////// +//// DownloadsUI + +function DownloadsUI() +{ + XPCOMUtils.defineLazyGetter(this, "_toolkitUI", function () { + // Create Toolkit's nsIDownloadManagerUI implementation. + return Components.classesByID["{7dfdf0d1-aff6-4a34-bad1-d0fe74601642}"] + .getService(Ci.nsIDownloadManagerUI); + }); +} + +DownloadsUI.prototype = { + classID: Components.ID("{4d99321e-d156-455b-81f7-e7aa2308134f}"), + + _xpcom_factory: XPCOMUtils.generateSingletonFactory(DownloadsUI), + + ////////////////////////////////////////////////////////////////////////////// + //// nsISupports + + QueryInterface: XPCOMUtils.generateQI([Ci.nsIDownloadManagerUI]), + + ////////////////////////////////////////////////////////////////////////////// + //// nsIDownloadManagerUI + + show: function DUI_show(aWindowContext, aDownload, aReason, aUsePrivateUI) + { + if (DownloadsCommon.useToolkitUI && !PrivateBrowsingUtils.isWindowPrivate(aWindowContext)) { + this._toolkitUI.show(aWindowContext, aDownload, aReason, aUsePrivateUI); + return; + } + + if (!aReason) { + aReason = Ci.nsIDownloadManagerUI.REASON_USER_INTERACTED; + } + + if (aReason == Ci.nsIDownloadManagerUI.REASON_NEW_DOWNLOAD) { + const kMinimized = Ci.nsIDOMChromeWindow.STATE_MINIMIZED; + let browserWin = gBrowserGlue.getMostRecentBrowserWindow(); + + if (!browserWin || browserWin.windowState == kMinimized) { + this._showDownloadManagerUI(aWindowContext, aUsePrivateUI); + } + else { + // If the indicator is visible, then new download notifications are + // already handled by the panel service. + browserWin.DownloadsButton.checkIsVisible(function(isVisible) { + if (!isVisible) { + this._showDownloadManagerUI(aWindowContext, aUsePrivateUI); + } + }.bind(this)); + } + } else { + this._showDownloadManagerUI(aWindowContext, aUsePrivateUI); + } + }, + + get visible() + { + // If we're still using the toolkit downloads manager, delegate the call + // to it. Otherwise, return true for now, until we decide on how we want + // to indicate that a new download has started if a browser window is + // not available or minimized. + return DownloadsCommon.useToolkitUI ? this._toolkitUI.visible : true; + }, + + getAttention: function DUI_getAttention() + { + if (DownloadsCommon.useToolkitUI) { + this._toolkitUI.getAttention(); + } + }, + + /** + * Helper function that opens the download manager UI. + */ + _showDownloadManagerUI: + function DUI_showDownloadManagerUI(aWindowContext, aUsePrivateUI) + { + // If we weren't given a window context, try to find a browser window + // to use as our parent - and if that doesn't work, error out and give up. + let parentWindow = aWindowContext; + if (!parentWindow) { + parentWindow = RecentWindow.getMostRecentBrowserWindow({ private: !!aUsePrivateUI }); + if (!parentWindow) { + Components.utils.reportError( + "Couldn't find a browser window to open the Places Downloads View " + + "from."); + return; + } + } + + // If window is private then show it in a tab. + if (PrivateBrowsingUtils.isWindowPrivate(parentWindow)) { + parentWindow.openUILinkIn("about:downloads", "tab"); + return; + } else { + let organizer = Services.wm.getMostRecentWindow("Places:Organizer"); + if (!organizer) { + parentWindow.openDialog("chrome://browser/content/places/places.xul", + "", "chrome,toolbar=yes,dialog=no,resizable", + "Downloads"); + } else { + organizer.PlacesOrganizer.selectLeftPaneQuery("Downloads"); + organizer.focus(); + } + } + } +}; + +//////////////////////////////////////////////////////////////////////////////// +//// Module + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([DownloadsUI]); diff --git a/application/palemoon/components/downloads/content/allDownloadsViewOverlay.css b/application/palemoon/components/downloads/content/allDownloadsViewOverlay.css new file mode 100644 index 000000000..c062ae464 --- /dev/null +++ b/application/palemoon/components/downloads/content/allDownloadsViewOverlay.css @@ -0,0 +1,56 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/** + * The downloads richlistbox may list thousands of items, and it turns out + * XBL binding attachment, and even more so detachment, is a performance hog. + * This hack makes sure we don't apply any binding to inactive items (inactive + * items are history downloads that haven't been in the visible area). + * We can do this because the richlistbox implementation does not interact + * much with the richlistitem binding. However, this may turn out to have + * some side effects (see bug 828111 for the details). + * + * We might be able to do away with this workaround once bug 653881 is fixed. + */ +richlistitem.download { + -moz-binding: none; +} + +richlistitem.download[active] { + -moz-binding: url('chrome://browser/content/downloads/download.xml#download-full-ui'); +} + +richlistitem.download[active]:-moz-any([state="-1"],/* Starting (initial) */ + [state="0"], /* Downloading */ + [state="4"], /* Paused */ + [state="5"], /* Starting (queued) */ + [state="7"]) /* Scanning */ +{ + -moz-binding: url('chrome://browser/content/downloads/download.xml#download-in-progress-full-ui'); +} + +.download-state:not( [state="0"] /* Downloading */) + .downloadPauseMenuItem, +.download-state:not( [state="4"] /* Paused */) + .downloadResumeMenuItem, +.download-state:not(:-moz-any([state="2"], /* Failed */ + [state="4"]) /* Paused */) + .downloadCancelMenuItem, +.download-state[state]:not(:-moz-any([state="1"], /* Finished */ + [state="2"], /* Failed */ + [state="3"], /* Canceled */ + [state="6"], /* Blocked (parental) */ + [state="8"], /* Blocked (dirty) */ + [state="9"]) /* Blocked (policy) */) + .downloadRemoveFromHistoryMenuItem, +.download-state:not(:-moz-any([state="-1"],/* Starting (initial) */ + [state="0"], /* Downloading */ + [state="1"], /* Finished */ + [state="4"], /* Paused */ + [state="5"]) /* Starting (queued) */) + .downloadShowMenuItem, +.download-state[state="7"] /* Scanning */ .downloadCommandsSeparator +{ + display: none; +} diff --git a/application/palemoon/components/downloads/content/allDownloadsViewOverlay.js b/application/palemoon/components/downloads/content/allDownloadsViewOverlay.js new file mode 100644 index 000000000..e1d0e75d4 --- /dev/null +++ b/application/palemoon/components/downloads/content/allDownloadsViewOverlay.js @@ -0,0 +1,1609 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/** + * THE PLACES VIEW IMPLEMENTED IN THIS FILE HAS A VERY PARTICULAR USE CASE. + * IT IS HIGHLY RECOMMENDED NOT TO EXTEND IT FOR ANY OTHER USE CASES OR RELY + * ON IT AS AN API. + */ + +let Cu = Components.utils; +let Ci = Components.interfaces; +let Cc = Components.classes; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/NetUtil.jsm"); +Cu.import("resource://gre/modules/DownloadUtils.jsm"); +Cu.import("resource:///modules/DownloadsCommon.jsm"); +Cu.import("resource://gre/modules/PlacesUtils.jsm"); +Cu.import("resource://gre/modules/osfile.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "RecentWindow", + "resource:///modules/RecentWindow.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", + "resource://gre/modules/FileUtils.jsm"); + +const nsIDM = Ci.nsIDownloadManager; + +const DESTINATION_FILE_URI_ANNO = "downloads/destinationFileURI"; +const DOWNLOAD_META_DATA_ANNO = "downloads/metaData"; + +const DOWNLOAD_VIEW_SUPPORTED_COMMANDS = + ["cmd_delete", "cmd_copy", "cmd_paste", "cmd_selectAll", + "downloadsCmd_pauseResume", "downloadsCmd_cancel", + "downloadsCmd_open", "downloadsCmd_show", "downloadsCmd_retry", + "downloadsCmd_openReferrer", "downloadsCmd_clearDownloads"]; + +const NOT_AVAILABLE = Number.MAX_VALUE; + +/** + * Download a URL. + * + * @param aURL + * the url to download (nsIURI object) + * @param [optional] aFileName + * the destination file name + */ +function DownloadURL(aURL, aFileName) { + // For private browsing, try to get document out of the most recent browser + // window, or provide our own if there's no browser window. + let browserWin = RecentWindow.getMostRecentBrowserWindow(); + let initiatingDoc = browserWin ? browserWin.document : document; + saveURL(aURL, aFileName, null, true, true, undefined, initiatingDoc); +} + +/** + * A download element shell is responsible for handling the commands and the + * displayed data for a single download view element. The download element + * could represent either a past download (for which we get data from places) or + * a "session" download (using a data-item object. See DownloadsCommon.jsm), or both. + * + * Once initialized with either a data item or a places node, the created richlistitem + * can be accessed through the |element| getter, and can then be inserted/removed from + * a richlistbox. + * + * The shell doesn't take care of inserting the item, or removing it when it's no longer + * valid. That's the caller (a DownloadsPlacesView object) responsibility. + * + * The caller is also responsible for "passing over" notification from both the + * download-view and the places-result-observer, in the following manner: + * - The DownloadsPlacesView object implements getViewItem of the download-view + * pseudo interface. It returns this object (therefore we implement + * onStateChangea and onProgressChange here). + * - The DownloadsPlacesView object adds itself as a places result observer and + * calls this object's placesNodeIconChanged, placesNodeTitleChanged and + * placeNodeAnnotationChanged from its callbacks. + * + * @param [optional] aDataItem + * The data item of a the session download. Required if aPlacesNode is not set + * @param [optional] aPlacesNode + * The places node for a past download. Required if aDataItem is not set. + * @param [optional] aAnnotations + * Map containing annotations values, to speed up the initial loading. + */ +function DownloadElementShell(aDataItem, aPlacesNode, aAnnotations) { + this._element = document.createElement("richlistitem"); + this._element._shell = this; + + this._element.classList.add("download"); + this._element.classList.add("download-state"); + + if (aAnnotations) + this._annotations = aAnnotations; + if (aDataItem) + this.dataItem = aDataItem; + if (aPlacesNode) + this.placesNode = aPlacesNode; +} + +DownloadElementShell.prototype = { + // The richlistitem for the download + get element() this._element, + + /** + * Manages the "active" state of the shell. By default all the shells + * without a dataItem are inactive, thus their UI is not updated. They must + * be activated when entering the visible area. Session downloads are + * always active since they always have a dataItem. + */ + ensureActive: function DES_ensureActive() { + if (!this._active) { + this._active = true; + this._element.setAttribute("active", true); + this._updateUI(); + } + }, + get active() !!this._active, + + // The data item for the download + _dataItem: null, + get dataItem() this._dataItem, + + set dataItem(aValue) { + if (this._dataItem != aValue) { + if (!aValue && !this._placesNode) + throw new Error("Should always have either a dataItem or a placesNode"); + + this._dataItem = aValue; + if (!this.active) + this.ensureActive(); + else + this._updateUI(); + } + return aValue; + }, + + _placesNode: null, + get placesNode() this._placesNode, + set placesNode(aValue) { + if (this._placesNode != aValue) { + if (!aValue && !this._dataItem) + throw new Error("Should always have either a dataItem or a placesNode"); + + // Preserve the annotations map if this is the first loading and we got + // cached values. + if (this._placesNode || !this._annotations) { + this._annotations = new Map(); + } + + this._placesNode = aValue; + + // We don't need to update the UI if we had a data item, because + // the places information isn't used in this case. + if (!this._dataItem && this.active) + this._updateUI(); + } + return aValue; + }, + + // The download uri (as a string) + get downloadURI() { + if (this._dataItem) + return this._dataItem.uri; + if (this._placesNode) + return this._placesNode.uri; + throw new Error("Unexpected download element state"); + }, + + get _downloadURIObj() { + if (!("__downloadURIObj" in this)) + this.__downloadURIObj = NetUtil.newURI(this.downloadURI); + return this.__downloadURIObj; + }, + + _getIcon: function DES__getIcon() { + let metaData = this.getDownloadMetaData(); + if ("filePath" in metaData) + return "moz-icon://" + metaData.filePath + "?size=32"; + + if (this._placesNode) { + // Try to extract an extension from the uri. + let ext = this._downloadURIObj.QueryInterface(Ci.nsIURL).fileExtension; + if (ext) + return "moz-icon://." + ext + "?size=32"; + return this._placesNode.icon || "moz-icon://.unknown?size=32"; + } + if (this._dataItem) + throw new Error("Session-download items should always have a target file uri"); + + throw new Error("Unexpected download element state"); + }, + + // Helper for getting a places annotation set for the download. + _getAnnotation: function DES__getAnnotation(aAnnotation, aDefaultValue) { + let value; + if (this._annotations.has(aAnnotation)) + value = this._annotations.get(aAnnotation); + + // If the value is cached, or we know it doesn't exist, avoid a database + // lookup. + if (value === undefined) { + try { + value = PlacesUtils.annotations.getPageAnnotation( + this._downloadURIObj, aAnnotation); + } + catch(ex) { + value = NOT_AVAILABLE; + } + } + + if (value === NOT_AVAILABLE) { + if (aDefaultValue === undefined) { + throw new Error("Could not get required annotation '" + aAnnotation + + "' for download with url '" + this.downloadURI + "'"); + } + value = aDefaultValue; + } + + this._annotations.set(aAnnotation, value); + return value; + }, + + _fetchTargetFileInfo: function DES__fetchTargetFileInfo(aUpdateMetaDataAndStatusUI = false) { + if (this._targetFileInfoFetched) + throw new Error("_fetchTargetFileInfo should not be called if the information was already fetched"); + if (!this.active) + throw new Error("Trying to _fetchTargetFileInfo on an inactive download shell"); + + let path = this.getDownloadMetaData().filePath; + + // In previous version, the target file annotations were not set, + // so we cannot tell where is the file. + if (path === undefined) { + this._targetFileInfoFetched = true; + this._targetFileExists = false; + if (aUpdateMetaDataAndStatusUI) { + this._metaData = null; + this._updateDownloadStatusUI(); + } + // Here we don't need to update the download commands, + // as the state is unknown as it was. + return; + } + + OS.File.stat(path).then( + function onSuccess(fileInfo) { + this._targetFileInfoFetched = true; + this._targetFileExists = true; + this._targetFileSize = fileInfo.size; + if (aUpdateMetaDataAndStatusUI) { + this._metaData = null; + this._updateDownloadStatusUI(); + } + if (this._element.selected) + goUpdateDownloadCommands(); + }.bind(this), + + function onFailure(reason) { + if (reason instanceof OS.File.Error && reason.becauseNoSuchFile) { + this._targetFileInfoFetched = true; + this._targetFileExists = false; + } + else { + Cu.reportError("Could not fetch info for target file (reason: " + + reason + ")"); + } + + if (aUpdateMetaDataAndStatusUI) { + this._metaData = null; + this._updateDownloadStatusUI(); + } + + if (this._element.selected) + goUpdateDownloadCommands(); + }.bind(this) + ); + }, + + _getAnnotatedMetaData: function DES__getAnnotatedMetaData() + JSON.parse(this._getAnnotation(DOWNLOAD_META_DATA_ANNO)), + + _extractFilePathAndNameFromFileURI: + function DES__extractFilePathAndNameFromFileURI(aFileURI) { + let file = Cc["@mozilla.org/network/protocol;1?name=file"] + .getService(Ci.nsIFileProtocolHandler) + .getFileFromURLSpec(aFileURI); + return [file.path, file.leafName]; + }, + + /** + * Retrieve the meta data object for the download. The following fields + * may be set. + * + * - state - any download state defined in nsIDownloadManager. If this field + * is not set, the download state is unknown. + * - endTime: the end time of the download. + * - filePath: the downloaded file path on the file system, when it + * was downloaded. The file may not exist. This is set for session + * downloads that have a local file set, and for history downloads done + * after the landing of bug 591289. + * - fileName: the downloaded file name on the file system. Set if filePath + * is set. + * - displayName: the user-facing label for the download. This is always + * set. If available, it's set to the downloaded file name. If not, + * the places title for the download uri is used. As a last resort, + * we fallback to the download uri. + * - fileSize (only set for downloads which completed successfully): + * the downloaded file size. For downloads done after the landing of + * bug 826991, this value is "static" - that is, it does not necessarily + * mean that the file is in place and has this size. + */ + getDownloadMetaData: function DES_getDownloadMetaData() { + if (!this._metaData) { + if (this._dataItem) { + let s = DownloadsCommon.strings; + let referrer = this._dataItem.referrer || this._dataItem.uri; + let [displayHost, fullHost] = DownloadUtils.getURIHost(referrer); + this._metaData = { + state: this._dataItem.state, + endTime: this._dataItem.endTime, + fileName: this._dataItem.target, + displayName: this._dataItem.target, + extendedDisplayName: s.statusSeparator(this._dataItem.target, displayHost), + extendedDisplayNameTip: s.statusSeparator(this._dataItem.target, fullHost) + }; + if (this._dataItem.done) + this._metaData.fileSize = this._dataItem.maxBytes; + if (this._dataItem.localFile) + this._metaData.filePath = this._dataItem.localFile.path; + } + else { + try { + this._metaData = this._getAnnotatedMetaData(); + } + catch(ex) { + this._metaData = { }; + if (this._targetFileInfoFetched && this._targetFileExists) { + this._metaData.state = this._targetFileSize > 0 ? + nsIDM.DOWNLOAD_FINISHED : nsIDM.DOWNLOAD_FAILED; + this._metaData.fileSize = this._targetFileSize; + } + + // This is actually the start-time, but it's the best we can get. + this._metaData.endTime = this._placesNode.time / 1000; + } + + try { + let targetFileURI = this._getAnnotation(DESTINATION_FILE_URI_ANNO); + [this._metaData.filePath, this._metaData.fileName] = + this._extractFilePathAndNameFromFileURI(targetFileURI); + this._metaData.displayName = this._metaData.fileName; + } + catch(ex) { + this._metaData.displayName = this._placesNode.title || this.downloadURI; + } + } + } + return this._metaData; + }, + + // The status text for the download + _getStatusText: function DES__getStatusText() { + let s = DownloadsCommon.strings; + if (this._dataItem && this._dataItem.inProgress) { + if (this._dataItem.paused) { + let transfer = + DownloadUtils.getTransferTotal(this._dataItem.currBytes, + this._dataItem.maxBytes); + + // We use the same XUL label to display both the state and the amount + // transferred, for example "Paused - 1.1 MB". + return s.statusSeparatorBeforeNumber(s.statePaused, transfer); + } + if (this._dataItem.state == nsIDM.DOWNLOAD_DOWNLOADING) { + let [status, newEstimatedSecondsLeft] = + DownloadUtils.getDownloadStatus(this.dataItem.currBytes, + this.dataItem.maxBytes, + this.dataItem.speed, + this._lastEstimatedSecondsLeft || Infinity); + this._lastEstimatedSecondsLeft = newEstimatedSecondsLeft; + return status; + } + if (this._dataItem.starting) { + return s.stateStarting; + } + if (this._dataItem.state == nsIDM.DOWNLOAD_SCANNING) { + return s.stateScanning; + } + + throw new Error("_getStatusText called with a bogus download state"); + } + + // This is a not-in-progress or history download. + let stateLabel = ""; + let state = this.getDownloadMetaData().state; + switch (state) { + case nsIDM.DOWNLOAD_FAILED: + stateLabel = s.stateFailed; + break; + case nsIDM.DOWNLOAD_CANCELED: + stateLabel = s.stateCanceled; + break; + case nsIDM.DOWNLOAD_BLOCKED_PARENTAL: + stateLabel = s.stateBlockedParentalControls; + break; + case nsIDM.DOWNLOAD_BLOCKED_POLICY: + stateLabel = s.stateBlockedPolicy; + break; + case nsIDM.DOWNLOAD_DIRTY: + stateLabel = s.stateDirty; + break; + case nsIDM.DOWNLOAD_FINISHED:{ + // For completed downloads, show the file size (e.g. "1.5 MB") + let metaData = this.getDownloadMetaData(); + if ("fileSize" in metaData) { + let [size, unit] = DownloadUtils.convertByteUnits(metaData.fileSize); + stateLabel = s.sizeWithUnits(size, unit); + break; + } + // Fallback to default unknown state. + } + default: + stateLabel = s.sizeUnknown; + break; + } + + // TODO (bug 829201): history downloads should get the referrer from Places. + let referrer = this._dataItem && this._dataItem.referrer || + this.downloadURI; + let [displayHost, fullHost] = DownloadUtils.getURIHost(referrer); + + let date = new Date(this.getDownloadMetaData().endTime); + let [displayDate, fullDate] = DownloadUtils.getReadableDates(date); + + // We use the same XUL label to display the state, the host name, and the + // end time. + let firstPart = s.statusSeparator(stateLabel, displayHost); + return s.statusSeparator(firstPart, displayDate); + }, + + // The progressmeter element for the download + get _progressElement() { + if (!("__progressElement" in this)) { + this.__progressElement = + document.getAnonymousElementByAttribute(this._element, "anonid", + "progressmeter"); + } + return this.__progressElement; + }, + + // Updates the download state attribute (and by that hide/unhide the + // appropriate buttons and context menu items), the status text label, + // and the progress meter. + _updateDownloadStatusUI: function DES__updateDownloadStatusUI() { + if (!this.active) + throw new Error("_updateDownloadStatusUI called for an inactive item."); + + let state = this.getDownloadMetaData().state; + if (state !== undefined) + this._element.setAttribute("state", state); + + this._element.setAttribute("status", this._getStatusText()); + + // For past-downloads, we're done. For session-downloads, we may also need + // to update the progress-meter. + if (!this._dataItem) + return; + + // Copied from updateProgress in downloads.js. + if (this._dataItem.starting) { + // Before the download starts, the progress meter has its initial value. + this._element.setAttribute("progressmode", "normal"); + this._element.setAttribute("progress", "0"); + } + else if (this._dataItem.state == nsIDM.DOWNLOAD_SCANNING || + this._dataItem.percentComplete == -1) { + // We might not know the progress of a running download, and we don't know + // the remaining time during the malware scanning phase. + this._element.setAttribute("progressmode", "undetermined"); + } + else { + // This is a running download of which we know the progress. + this._element.setAttribute("progressmode", "normal"); + this._element.setAttribute("progress", this._dataItem.percentComplete); + } + + // Dispatch the ValueChange event for accessibility, if possible. + if (this._progressElement) { + let event = document.createEvent("Events"); + event.initEvent("ValueChange", true, true); + this._progressElement.dispatchEvent(event); + } + }, + + _updateDisplayNameAndIcon: function DES__updateDisplayNameAndIcon() { + let metaData = this.getDownloadMetaData(); + this._element.setAttribute("displayName", metaData.displayName); + if ("extendedDisplayName" in metaData) + this._element.setAttribute("extendedDisplayName", metaData.extendedDisplayName); + if ("extendedDisplayNameTip" in metaData) + this._element.setAttribute("extendedDisplayNameTip", metaData.extendedDisplayNameTip); + this._element.setAttribute("image", this._getIcon()); + }, + + _updateUI: function DES__updateUI() { + if (!this.active) + throw new Error("Trying to _updateUI on an inactive download shell"); + + this._metaData = null; + this._targetFileInfoFetched = false; + + this._updateDisplayNameAndIcon(); + + // For history downloads done in past releases, the downloads/metaData + // annotation is not set, and therefore we cannot tell the download + // state without the target file information. + if (this._dataItem || this.getDownloadMetaData().state !== undefined) + this._updateDownloadStatusUI(); + else + this._fetchTargetFileInfo(true); + }, + + placesNodeIconChanged: function DES_placesNodeIconChanged() { + if (!this._dataItem) + this._element.setAttribute("image", this._getIcon()); + }, + + placesNodeTitleChanged: function DES_placesNodeTitleChanged() { + // If there's a file path, we use the leaf name for the title. + if (!this._dataItem && this.active && !this.getDownloadMetaData().filePath) { + this._metaData = null; + this._updateDisplayNameAndIcon(); + } + }, + + placesNodeAnnotationChanged: function DES_placesNodeAnnotationChanged(aAnnoName) { + this._annotations.delete(aAnnoName); + if (!this._dataItem && this.active) { + if (aAnnoName == DOWNLOAD_META_DATA_ANNO) { + let metaData = this.getDownloadMetaData(); + let annotatedMetaData = this._getAnnotatedMetaData(); + metaData.endTime = annotatedMetaData.endTime; + if ("fileSize" in annotatedMetaData) + metaData.fileSize = annotatedMetaData.fileSize; + else + delete metaData.fileSize; + + if (metaData.state != annotatedMetaData.state) { + metaData.state = annotatedMetaData.state; + if (this._element.selected) + goUpdateDownloadCommands(); + } + + this._updateDownloadStatusUI(); + } + else if (aAnnoName == DESTINATION_FILE_URI_ANNO) { + let metaData = this.getDownloadMetaData(); + let targetFileURI = this._getAnnotation(DESTINATION_FILE_URI_ANNO); + [metaData.filePath, metaData.fileName] = + this._extractFilePathAndNameFromFileURI(targetFileURI); + metaData.displayName = metaData.fileName; + this._updateDisplayNameAndIcon(); + + if (this._targetFileInfoFetched) { + // This will also update the download commands if necessary. + this._targetFileInfoFetched = false; + this._fetchTargetFileInfo(); + } + } + } + }, + + /* DownloadView */ + onStateChange: function DES_onStateChange(aOldState) { + let metaData = this.getDownloadMetaData(); + metaData.state = this.dataItem.state; + if (aOldState != nsIDM.DOWNLOAD_FINISHED && aOldState != metaData.state) { + // See comment in DVI_onStateChange in downloads.js (the panel-view) + this._element.setAttribute("image", this._getIcon() + "&state=normal"); + metaData.fileSize = this._dataItem.maxBytes; + if (this._targetFileInfoFetched) { + this._targetFileInfoFetched = false; + this._fetchTargetFileInfo(); + } + } + + this._updateDownloadStatusUI(); + if (this._element.selected) + goUpdateDownloadCommands(); + else + goUpdateCommand("downloadsCmd_clearDownloads"); + }, + + /* DownloadView */ + onProgressChange: function DES_onProgressChange() { + this._updateDownloadStatusUI(); + }, + + /* nsIController */ + isCommandEnabled: function DES_isCommandEnabled(aCommand) { + // The only valid command for inactive elements is cmd_delete. + if (!this.active && aCommand != "cmd_delete") + return false; + switch (aCommand) { + case "downloadsCmd_open": { + // We cannot open a session download file unless it's done ("openable"). + // If it's finished, we need to make sure the file was not removed, + // as we do for past downloads. + if (this._dataItem && !this._dataItem.openable) + return false; + + if (this._targetFileInfoFetched) + return this._targetFileExists; + + // If the target file information is not yet fetched, + // temporarily assume that the file is in place. + return this.getDownloadMetaData().state == nsIDM.DOWNLOAD_FINISHED; + } + case "downloadsCmd_show": { + // TODO: Bug 827010 - Handle part-file asynchronously. + if (this._dataItem && + this._dataItem.partFile && this._dataItem.partFile.exists()) + return true; + + if (this._targetFileInfoFetched) + return this._targetFileExists; + + // If the target file information is not yet fetched, + // temporarily assume that the file is in place. + return this.getDownloadMetaData().state == nsIDM.DOWNLOAD_FINISHED; + } + case "downloadsCmd_pauseResume": + return this._dataItem && this._dataItem.inProgress && this._dataItem.resumable; + case "downloadsCmd_retry": + // An history download can always be retried. + return !this._dataItem || this._dataItem.canRetry; + case "downloadsCmd_openReferrer": + return this._dataItem && !!this._dataItem.referrer; + case "cmd_delete": + // The behavior in this case is somewhat unexpected, so we disallow that. + if (this._placesNode && this._dataItem && this._dataItem.inProgress) + return false; + return true; + case "downloadsCmd_cancel": + return this._dataItem != null; + } + return false; + }, + + _retryAsHistoryDownload: function DES__retryAsHistoryDownload() { + // In future we may try to download into the same original target uri, when + // we have it. Though that requires verifying the path is still valid and + // may surprise the user if he wants to be requested every time. + DownloadURL(this.downloadURI, this.getDownloadMetaData().fileName); + }, + + /* nsIController */ + doCommand: function DES_doCommand(aCommand) { + switch (aCommand) { + case "downloadsCmd_open": { + let file = this._dataItem ? + this.dataItem.localFile : + new FileUtils.File(this.getDownloadMetaData().filePath); + + DownloadsCommon.openDownloadedFile(file, null, window); + break; + } + case "downloadsCmd_show": { + if (this._dataItem) { + this._dataItem.showLocalFile(); + } + else { + let file = new FileUtils.File(this.getDownloadMetaData().filePath); + DownloadsCommon.showDownloadedFile(file); + } + break; + } + case "downloadsCmd_openReferrer": { + openURL(this._dataItem.referrer); + break; + } + case "downloadsCmd_cancel": { + this._dataItem.cancel(); + break; + } + case "cmd_delete": { + if (this._dataItem) + Downloads.getList(Downloads.ALL) + .then(list => list.remove(this._dataItem._download)) + .then(() => this._dataItem._download.finalize(true)) + .catch(Cu.reportError); + if (this._placesNode) + PlacesUtils.bhistory.removePage(this._downloadURIObj); + break; + } + case "downloadsCmd_retry": { + if (this._dataItem) + this._dataItem.retry(); + else + this._retryAsHistoryDownload(); + break; + } + case "downloadsCmd_pauseResume": { + this._dataItem.togglePauseResume(); + break; + } + } + }, + + // Returns whether or not the download handled by this shell should + // show up in the search results for the given term. Both the display + // name for the download and the url are searched. + matchesSearchTerm: function DES_matchesSearchTerm(aTerm) { + if (!aTerm) + return true; + aTerm = aTerm.toLowerCase(); + return this.getDownloadMetaData().displayName.toLowerCase().includes(aTerm) || + this.downloadURI.toLowerCase().includes(aTerm); + }, + + // Handles return keypress on the element (the keypress listener is + // set in the DownloadsPlacesView object). + doDefaultCommand: function DES_doDefaultCommand() { + function getDefaultCommandForState(aState) { + switch (aState) { + case nsIDM.DOWNLOAD_FINISHED: + return "downloadsCmd_open"; + case nsIDM.DOWNLOAD_PAUSED: + return "downloadsCmd_pauseResume"; + case nsIDM.DOWNLOAD_NOTSTARTED: + case nsIDM.DOWNLOAD_QUEUED: + return "downloadsCmd_cancel"; + case nsIDM.DOWNLOAD_FAILED: + case nsIDM.DOWNLOAD_CANCELED: + return "downloadsCmd_retry"; + case nsIDM.DOWNLOAD_SCANNING: + return "downloadsCmd_show"; + case nsIDM.DOWNLOAD_BLOCKED_PARENTAL: + case nsIDM.DOWNLOAD_DIRTY: + case nsIDM.DOWNLOAD_BLOCKED_POLICY: + return "downloadsCmd_openReferrer"; + } + return ""; + } + let command = getDefaultCommandForState(this.getDownloadMetaData().state); + if (command && this.isCommandEnabled(command)) + this.doCommand(command); + }, + + /** + * At the first time an item is selected, we don't yet have + * the target file information. Thus the call to goUpdateDownloadCommands + * in DPV_onSelect would result in best-guess enabled/disabled result. + * That way we let the user perform command immediately. However, once + * we have the target file information, we can update the commands + * appropriately (_fetchTargetFileInfo() calls goUpdateDownloadCommands). + */ + onSelect: function DES_onSelect() { + if (!this.active) + return; + if (!this._targetFileInfoFetched) + this._fetchTargetFileInfo(); + } +}; + +/** + * A Downloads Places View is a places view designed to show a places query + * for history downloads alongside the current "session"-downloads. + * + * As we don't use the places controller, some methods implemented by other + * places views are not implemented by this view. + * + * A richlistitem in this view can represent either a past download or a session + * download, or both. Session downloads are shown first in the view, and as long + * as they exist they "collapses" their history "counterpart" (So we don't show two + * items for every download). + */ +function DownloadsPlacesView(aRichListBox, aActive = true) { + this._richlistbox = aRichListBox; + this._richlistbox._placesView = this; + window.controllers.insertControllerAt(0, this); + + // Map download URLs to download element shells regardless of their type + this._downloadElementsShellsForURI = new Map(); + + // Map download data items to their element shells. + this._viewItemsForDataItems = new WeakMap(); + + // Points to the last session download element. We keep track of this + // in order to keep all session downloads above past downloads. + this._lastSessionDownloadElement = null; + + this._searchTerm = ""; + + this._active = aActive; + + // Register as a downloads view. The places data will be initialized by + // the places setter. + this._initiallySelectedElement = null; + this._downloadsData = DownloadsCommon.getData(window.opener || window); + this._downloadsData.addView(this); + + // Get the Download button out of the attention state since we're about to + // view all downloads. + DownloadsCommon.getIndicatorData(window).attention = false; + + // Make sure to unregister the view if the window is closed. + window.addEventListener("unload", function() { + window.controllers.removeController(this); + this._downloadsData.removeView(this); + this.result = null; + }.bind(this), true); + // Resizing the window may change items visibility. + window.addEventListener("resize", function() { + this._ensureVisibleElementsAreActive(); + }.bind(this), true); +} + +DownloadsPlacesView.prototype = { + get associatedElement() this._richlistbox, + + get active() this._active, + set active(val) { + this._active = val; + if (this._active) + this._ensureVisibleElementsAreActive(); + return this._active; + }, + + _forEachDownloadElementShellForURI: + function DPV__forEachDownloadElementShellForURI(aURI, aCallback) { + if (this._downloadElementsShellsForURI.has(aURI)) { + let downloadElementShells = this._downloadElementsShellsForURI.get(aURI); + for (let des of downloadElementShells) { + aCallback(des); + } + } + }, + + _getAnnotationsFor: function DPV_getAnnotationsFor(aURI) { + if (!this._cachedAnnotations) { + this._cachedAnnotations = new Map(); + for (let name of [ DESTINATION_FILE_URI_ANNO, + DOWNLOAD_META_DATA_ANNO ]) { + let results = PlacesUtils.annotations.getAnnotationsWithName(name); + for (let result of results) { + let url = result.uri.spec; + if (!this._cachedAnnotations.has(url)) + this._cachedAnnotations.set(url, new Map()); + let m = this._cachedAnnotations.get(url); + m.set(result.annotationName, result.annotationValue); + } + } + } + + let annotations = this._cachedAnnotations.get(aURI); + if (!annotations) { + // There are no annotations for this entry, that means it is quite old. + // Make up a fake annotations entry with default values. + annotations = new Map(); + annotations.set(DESTINATION_FILE_URI_ANNO, NOT_AVAILABLE); + } + // The meta-data annotation has been added recently, so it's likely missing. + if (!annotations.has(DOWNLOAD_META_DATA_ANNO)) { + annotations.set(DOWNLOAD_META_DATA_ANNO, NOT_AVAILABLE); + } + return annotations; + }, + + /** + * Given a data item for a session download, or a places node for a past + * download, updates the view as necessary. + * 1. If the given data is a places node, we check whether there are any + * elements for the same download url. If there are, then we just reset + * their places node. Otherwise we add a new download element. + * 2. If the given data is a data item, we first check if there's a history + * download in the list that is not associated with a data item. If we + * found one, we use it for the data item as well and reposition it + * alongside the other session downloads. If we don't, then we go ahead + * and create a new element for the download. + * + * @param aDataItem + * The data item of a session download. Set to null for history + * downloads data. + * @param [optional] aPlacesNode + * The places node for a history download. Required if there's no data + * item. + * @param [optional] aNewest + * @see onDataItemAdded. Ignored for history downloads. + * @param [optional] aDocumentFragment + * To speed up the appending of multiple elements to the end of the + * list which are coming in a single batch (i.e. invalidateContainer), + * a document fragment may be passed to which the new elements would + * be appended. It's the caller's job to ensure the fragment is merged + * to the richlistbox at the end. + */ + _addDownloadData: + function DPV_addDownloadData(aDataItem, aPlacesNode, aNewest = false, + aDocumentFragment = null) { + let downloadURI = aPlacesNode ? aPlacesNode.uri : aDataItem.uri; + let shellsForURI = this._downloadElementsShellsForURI.get(downloadURI); + if (!shellsForURI) { + shellsForURI = new Set(); + this._downloadElementsShellsForURI.set(downloadURI, shellsForURI); + } + + let newOrUpdatedShell = null; + + // Trivial: if there are no shells for this download URI, we always + // need to create one. + let shouldCreateShell = shellsForURI.size == 0; + + // However, if we do have shells for this download uri, there are + // few options: + // 1) There's only one shell and it's for a history download (it has + // no data item). In this case, we update this shell and move it + // if necessary + // 2) There are multiple shells, indicating multiple downloads for + // the same download uri are running. In this case we create + // another shell for the download (so we have one shell for each data + // item). + // + // Note: If a cancelled session download is already in the list, and the + // download is retired, onDataItemAdded is called again for the same + // data item. Thus, we also check that we make sure we don't have a view item + // already. + if (!shouldCreateShell && + aDataItem && this.getViewItem(aDataItem) == null) { + // If there's a past-download-only shell for this download-uri with no + // associated data item, use it for the new data item. Otherwise, go ahead + // and create another shell. + shouldCreateShell = true; + for (let shell of shellsForURI) { + if (!shell.dataItem) { + shouldCreateShell = false; + shell.dataItem = aDataItem; + newOrUpdatedShell = shell; + this._viewItemsForDataItems.set(aDataItem, shell); + break; + } + } + } + + if (shouldCreateShell) { + // Bug 836271: The annotations for a url should be cached only when the + // places node is available, i.e. when we know we we'd be notified for + // annotation changes. + // Otherwise we may cache NOT_AVILABLE values first for a given session + // download, and later use these NOT_AVILABLE values when a history + // download for the same URL is added. + let cachedAnnotations = aPlacesNode ? this._getAnnotationsFor(downloadURI) : null; + let shell = new DownloadElementShell(aDataItem, aPlacesNode, cachedAnnotations); + newOrUpdatedShell = shell; + shellsForURI.add(shell); + if (aDataItem) + this._viewItemsForDataItems.set(aDataItem, shell); + } + else if (aPlacesNode) { + for (let shell of shellsForURI) { + if (shell.placesNode != aPlacesNode) + shell.placesNode = aPlacesNode; + } + } + + if (newOrUpdatedShell) { + if (aNewest) { + this._richlistbox.insertBefore(newOrUpdatedShell.element, + this._richlistbox.firstChild); + if (!this._lastSessionDownloadElement) { + this._lastSessionDownloadElement = newOrUpdatedShell.element; + } + // Some operations like retrying an history download move an element to + // the top of the richlistbox, along with other session downloads. + // More generally, if a new download is added, should be made visible. + this._richlistbox.ensureElementIsVisible(newOrUpdatedShell.element); + } + else if (aDataItem) { + let before = this._lastSessionDownloadElement ? + this._lastSessionDownloadElement.nextSibling : this._richlistbox.firstChild; + this._richlistbox.insertBefore(newOrUpdatedShell.element, before); + this._lastSessionDownloadElement = newOrUpdatedShell.element; + } + else { + let appendTo = aDocumentFragment || this._richlistbox; + appendTo.appendChild(newOrUpdatedShell.element); + } + + if (this.searchTerm) { + newOrUpdatedShell.element.hidden = + !newOrUpdatedShell.element._shell.matchesSearchTerm(this.searchTerm); + } + } + + // If aDocumentFragment is defined this is a batch change, so it's up to + // the caller to append the fragment and activate the visible shells. + if (!aDocumentFragment) { + this._ensureVisibleElementsAreActive(); + goUpdateCommand("downloadsCmd_clearDownloads"); + } + }, + + _removeElement: function DPV__removeElement(aElement) { + // If the element was selected exclusively, select its next + // sibling first, if not, try for previous sibling, if any. + if ((aElement.nextSibling || aElement.previousSibling) && + this._richlistbox.selectedItems && + this._richlistbox.selectedItems.length == 1 && + this._richlistbox.selectedItems[0] == aElement) { + this._richlistbox.selectItem(aElement.nextSibling || + aElement.previousSibling); + } + + if (this._lastSessionDownloadElement == aElement) + this._lastSessionDownloadElement = aElement.previousSibling; + + this._richlistbox.removeItemFromSelection(aElement); + this._richlistbox.removeChild(aElement); + this._ensureVisibleElementsAreActive(); + goUpdateCommand("downloadsCmd_clearDownloads"); + }, + + _removeHistoryDownloadFromView: + function DPV__removeHistoryDownloadFromView(aPlacesNode) { + let downloadURI = aPlacesNode.uri; + let shellsForURI = this._downloadElementsShellsForURI.get(downloadURI); + if (shellsForURI) { + for (let shell of shellsForURI) { + if (shell.dataItem) { + shell.placesNode = null; + } + else { + this._removeElement(shell.element); + shellsForURI.delete(shell); + if (shellsForURI.size == 0) + this._downloadElementsShellsForURI.delete(downloadURI); + } + } + } + }, + + _removeSessionDownloadFromView: + function DPV__removeSessionDownloadFromView(aDataItem) { + let shells = this._downloadElementsShellsForURI.get(aDataItem.uri); + if (shells.size == 0) + throw new Error("Should have had at leaat one shell for this uri"); + + let shell = this.getViewItem(aDataItem); + if (!shells.has(shell)) + throw new Error("Missing download element shell in shells list for url"); + + // If there's more than one item for this download uri, we can let the + // view item for this this particular data item go away. + // If there's only one item for this download uri, we should only + // keep it if it is associated with a history download. + if (shells.size > 1 || !shell.placesNode) { + this._removeElement(shell.element); + shells.delete(shell); + if (shells.size == 0) + this._downloadElementsShellsForURI.delete(aDataItem.uri); + } + else { + shell.dataItem = null; + // Move it below the session-download items; + if (this._lastSessionDownloadElement == shell.element) { + this._lastSessionDownloadElement = shell.element.previousSibling; + } + else { + let before = this._lastSessionDownloadElement ? + this._lastSessionDownloadElement.nextSibling : this._richlistbox.firstChild; + this._richlistbox.insertBefore(shell.element, before); + } + } + }, + + _ensureVisibleElementsAreActive: + function DPV__ensureVisibleElementsAreActive() { + if (!this.active || this._ensureVisibleTimer || !this._richlistbox.firstChild) + return; + + this._ensureVisibleTimer = setTimeout(function() { + delete this._ensureVisibleTimer; + if (!this._richlistbox.firstChild) + return; + + let rlbRect = this._richlistbox.getBoundingClientRect(); + let winUtils = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils); + let nodes = winUtils.nodesFromRect(rlbRect.left, rlbRect.top, + 0, rlbRect.width, rlbRect.height, 0, + true, false); + // nodesFromRect returns nodes in z-index order, and for the same z-index + // sorts them in inverted DOM order, thus starting from the one that would + // be on top. + let firstVisibleNode, lastVisibleNode; + for (let node of nodes) { + if (node.localName === "richlistitem" && node._shell) { + node._shell.ensureActive(); + // The first visible node is the last match. + firstVisibleNode = node; + // While the last visible node is the first match. + if (!lastVisibleNode) + lastVisibleNode = node; + } + } + + // Also activate the first invisible nodes in both boundaries (that is, + // above and below the visible area) to ensure proper keyboard navigation + // in both directions. + let nodeBelowVisibleArea = lastVisibleNode && lastVisibleNode.nextSibling; + if (nodeBelowVisibleArea && nodeBelowVisibleArea._shell) + nodeBelowVisibleArea._shell.ensureActive(); + + let nodeABoveVisibleArea = + firstVisibleNode && firstVisibleNode.previousSibling; + if (nodeABoveVisibleArea && nodeABoveVisibleArea._shell) + nodeABoveVisibleArea._shell.ensureActive(); + }.bind(this), 10); + }, + + _place: "", + get place() this._place, + set place(val) { + // Don't reload everything if we don't have to. + if (this._place == val) { + // XXXmano: places.js relies on this behavior (see Bug 822203). + this.searchTerm = ""; + return val; + } + + this._place = val; + + let history = PlacesUtils.history; + let queries = { }, options = { }; + history.queryStringToQueries(val, queries, { }, options); + if (!queries.value.length) + queries.value = [history.getNewQuery()]; + + let result = history.executeQueries(queries.value, queries.value.length, + options.value); + result.addObserver(this, false); + return val; + }, + + _result: null, + get result() this._result, + set result(val) { + if (this._result == val) + return val; + + if (this._result) { + this._result.removeObserver(this); + this._resultNode.containerOpen = false; + } + + if (val) { + this._result = val; + this._resultNode = val.root; + this._resultNode.containerOpen = true; + this._ensureInitialSelection(); + } + else { + delete this._resultNode; + delete this._result; + } + + return val; + }, + + get selectedNodes() { + let placesNodes = []; + let selectedElements = this._richlistbox.selectedItems; + for (let elt of selectedElements) { + if (elt._shell.placesNode) + placesNodes.push(elt._shell.placesNode); + } + return placesNodes; + }, + + get selectedNode() { + let selectedNodes = this.selectedNodes; + return selectedNodes.length == 1 ? selectedNodes[0] : null; + }, + + get hasSelection() this.selectedNodes.length > 0, + + containerStateChanged: + function DPV_containerStateChanged(aNode, aOldState, aNewState) { + this.invalidateContainer(aNode) + }, + + invalidateContainer: + function DPV_invalidateContainer(aContainer) { + if (aContainer != this._resultNode) + throw new Error("Unexpected container node"); + if (!aContainer.containerOpen) + throw new Error("Root container for the downloads query cannot be closed"); + + let suppressOnSelect = this._richlistbox.suppressOnSelect; + this._richlistbox.suppressOnSelect = true; + try { + // Remove the invalidated history downloads from the list and unset the + // places node for data downloads. + // Loop backwards since _removeHistoryDownloadFromView may removeChild(). + for (let i = this._richlistbox.childNodes.length - 1; i >= 0; --i) { + let element = this._richlistbox.childNodes[i]; + if (element._shell.placesNode) + this._removeHistoryDownloadFromView(element._shell.placesNode); + } + } + finally { + this._richlistbox.suppressOnSelect = suppressOnSelect; + } + + if (aContainer.childCount > 0) { + let elementsToAppendFragment = document.createDocumentFragment(); + for (let i = 0; i < aContainer.childCount; i++) { + try { + this._addDownloadData(null, aContainer.getChild(i), false, + elementsToAppendFragment); + } + catch(ex) { + Cu.reportError(ex); + } + } + + // _addDownloadData may not add new elements if there were already + // data items in place. + if (elementsToAppendFragment.firstChild) { + this._appendDownloadsFragment(elementsToAppendFragment); + this._ensureVisibleElementsAreActive(); + } + } + + goUpdateDownloadCommands(); + }, + + _appendDownloadsFragment: function DPV__appendDownloadsFragment(aDOMFragment) { + // Workaround multiple reflows hang by removing the richlistbox + // and adding it back when we're done. + + // Hack for bug 836283: reset xbl fields to their old values after the + // binding is reattached to avoid breaking the selection state + let xblFields = new Map(); + for (let [key, value] in Iterator(this._richlistbox)) { + xblFields.set(key, value); + } + + let parentNode = this._richlistbox.parentNode; + let nextSibling = this._richlistbox.nextSibling; + parentNode.removeChild(this._richlistbox); + this._richlistbox.appendChild(aDOMFragment); + parentNode.insertBefore(this._richlistbox, nextSibling); + + for (let [key, value] of xblFields) { + this._richlistbox[key] = value; + } + }, + + nodeInserted: function DPV_nodeInserted(aParent, aPlacesNode) { + this._addDownloadData(null, aPlacesNode); + }, + + nodeRemoved: function DPV_nodeRemoved(aParent, aPlacesNode, aOldIndex) { + this._removeHistoryDownloadFromView(aPlacesNode); + }, + + nodeIconChanged: function DPV_nodeIconChanged(aNode) { + this._forEachDownloadElementShellForURI(aNode.uri, function(aDownloadElementShell) { + aDownloadElementShell.placesNodeIconChanged(); + }); + }, + + nodeAnnotationChanged: function DPV_nodeAnnotationChanged(aNode, aAnnoName) { + this._forEachDownloadElementShellForURI(aNode.uri, function(aDownloadElementShell) { + aDownloadElementShell.placesNodeAnnotationChanged(aAnnoName); + }); + }, + + nodeTitleChanged: function DPV_nodeTitleChanged(aNode, aNewTitle) { + this._forEachDownloadElementShellForURI(aNode.uri, function(aDownloadElementShell) { + aDownloadElementShell.placesNodeTitleChanged(); + }); + }, + + nodeKeywordChanged: function() {}, + nodeDateAddedChanged: function() {}, + nodeLastModifiedChanged: function() {}, + nodeHistoryDetailsChanged: function() {}, + nodeTagsChanged: function() {}, + sortingChanged: function() {}, + nodeMoved: function() {}, + nodeURIChanged: function() {}, + batching: function() {}, + + get controller() this._richlistbox.controller, + + get searchTerm() this._searchTerm, + set searchTerm(aValue) { + if (this._searchTerm != aValue) { + for (let element of this._richlistbox.childNodes) { + element.hidden = !element._shell.matchesSearchTerm(aValue); + } + this._ensureVisibleElementsAreActive(); + } + return this._searchTerm = aValue; + }, + + /** + * When the view loads, we want to select the first item. + * However, because session downloads, for which the data is loaded + * asynchronously, always come first in the list, and because the list + * may (or may not) already contain history downloads at that point, it + * turns out that by the time we can select the first item, the user may + * have already started using the view. + * To make things even more complicated, in other cases, the places data + * may be loaded after the session downloads data. Thus we cannot rely on + * the order in which the data comes in. + * We work around this by attempting to select the first element twice, + * once after the places data is loaded and once when the session downloads + * data is done loading. However, if the selection has changed in-between, + * we assume the user has already started using the view and give up. + */ + _ensureInitialSelection: function DPV__ensureInitialSelection() { + // Either they're both null, or the selection has not changed in between. + if (this._richlistbox.selectedItem == this._initiallySelectedElement) { + let firstDownloadElement = this._richlistbox.firstChild; + if (firstDownloadElement != this._initiallySelectedElement) { + // We may be called before _ensureVisibleElementsAreActive, + // or before the download binding is attached. Therefore, ensure the + // first item is activated, and pass the item to the richlistbox + // setters only at a point we know for sure the binding is attached. + firstDownloadElement._shell.ensureActive(); + Services.tm.mainThread.dispatch(function() { + this._richlistbox.selectedItem = firstDownloadElement; + this._richlistbox.currentItem = firstDownloadElement; + this._initiallySelectedElement = firstDownloadElement; + }.bind(this), Ci.nsIThread.DISPATCH_NORMAL); + } + } + }, + + onDataLoadStarting: function() { }, + onDataLoadCompleted: function DPV_onDataLoadCompleted() { + this._ensureInitialSelection(); + }, + + onDataItemAdded: function DPV_onDataItemAdded(aDataItem, aNewest) { + this._addDownloadData(aDataItem, null, aNewest); + }, + + onDataItemRemoved: function DPV_onDataItemRemoved(aDataItem) { + this._removeSessionDownloadFromView(aDataItem); + }, + + getViewItem: function(aDataItem) + this._viewItemsForDataItems.get(aDataItem, null), + + supportsCommand: function DPV_supportsCommand(aCommand) { + if (DOWNLOAD_VIEW_SUPPORTED_COMMANDS.indexOf(aCommand) != -1) { + // The clear-downloads command may be performed by the toolbar-button, + // which can be focused on OS X. Thus enable this command even if the + // richlistbox is not focused. + // For other commands, be prudent and disable them unless the richlistview + // is focused. It's important to make the decision here rather than in + // isCommandEnabled. Otherwise our controller may "steal" commands from + // other controls in the window (see goUpdateCommand & + // getControllerForCommand). + if (document.activeElement == this._richlistbox || + aCommand == "downloadsCmd_clearDownloads") { + return true; + } + } + return false; + }, + + isCommandEnabled: function DPV_isCommandEnabled(aCommand) { + switch (aCommand) { + case "cmd_copy": + return this._richlistbox.selectedItems.length > 0; + case "cmd_selectAll": + return true; + case "cmd_paste": + return this._canDownloadClipboardURL(); + case "downloadsCmd_clearDownloads": + return this._canClearDownloads(); + default: + return Array.every(this._richlistbox.selectedItems, function(element) { + return element._shell.isCommandEnabled(aCommand); + }); + } + }, + + _canClearDownloads: function DPV__canClearDownloads() { + // Downloads can be cleared if there's at least one removable download in + // the list (either a history download or a completed session download). + // Because history downloads are always removable and are listed after the + // session downloads, check from bottom to top. + for (let elt = this._richlistbox.lastChild; elt; elt = elt.previousSibling) { + if (elt._shell.placesNode || !elt._shell.dataItem.inProgress) + return true; + } + return false; + }, + + _copySelectedDownloadsToClipboard: + function DPV__copySelectedDownloadsToClipboard() { + let selectedElements = this._richlistbox.selectedItems; + let urls = [e._shell.downloadURI for each (e in selectedElements)]; + + Cc["@mozilla.org/widget/clipboardhelper;1"]. + getService(Ci.nsIClipboardHelper).copyString(urls.join("\n"), document); + }, + + _getURLFromClipboardData: function DPV__getURLFromClipboardData() { + let trans = Cc["@mozilla.org/widget/transferable;1"]. + createInstance(Ci.nsITransferable); + trans.init(null); + + let flavors = ["text/x-moz-url", "text/unicode"]; + flavors.forEach(trans.addDataFlavor); + + Services.clipboard.getData(trans, Services.clipboard.kGlobalClipboard); + + // Getting the data or creating the nsIURI might fail. + try { + let data = {}; + trans.getAnyTransferData({}, data, {}); + let [url, name] = data.value.QueryInterface(Ci.nsISupportsString) + .data.split("\n"); + if (url) + return [NetUtil.newURI(url, null, null).spec, name]; + } + catch(ex) { } + + return ["", ""]; + }, + + _canDownloadClipboardURL: function DPV__canDownloadClipboardURL() { + let [url, name] = this._getURLFromClipboardData(); + return url != ""; + }, + + _downloadURLFromClipboard: function DPV__downloadURLFromClipboard() { + let [url, name] = this._getURLFromClipboardData(); + DownloadURL(url, name); + }, + + doCommand: function DPV_doCommand(aCommand) { + switch (aCommand) { + case "cmd_copy": + this._copySelectedDownloadsToClipboard(); + break; + case "cmd_selectAll": + this._richlistbox.selectAll(); + break; + case "cmd_paste": + this._downloadURLFromClipboard(); + break; + case "downloadsCmd_clearDownloads": + this._downloadsData.removeFinished(); + if (this.result) { + Cc["@mozilla.org/browser/download-history;1"] + .getService(Ci.nsIDownloadHistory) + .removeAllDownloads(); + } + // There may be no selection or focus change as a result + // of these change, and we want the command updated immediately. + goUpdateCommand("downloadsCmd_clearDownloads"); + break; + default: { + // Slicing the array to get a freezed list of selected items. Otherwise, + // the selectedItems array is live and doCommand may alter the selection + // while we are trying to do one particular action, like removing items + // from history. + let selectedElements = this._richlistbox.selectedItems.slice(); + for (let element of selectedElements) { + element._shell.doCommand(aCommand); + } + } + } + }, + + onEvent: function() { }, + + onContextMenu: function DPV_onContextMenu(aEvent) + { + let element = this._richlistbox.selectedItem; + if (!element || !element._shell) + return false; + + // Set the state attribute so that only the appropriate items are displayed. + let contextMenu = document.getElementById("downloadsContextMenu"); + let state = element._shell.getDownloadMetaData().state; + if (state !== undefined) + contextMenu.setAttribute("state", state); + else + contextMenu.removeAttribute("state"); + + return true; + }, + + onKeyPress: function DPV_onKeyPress(aEvent) { + let selectedElements = this._richlistbox.selectedItems; + if (aEvent.keyCode == KeyEvent.DOM_VK_RETURN) { + // In the content tree, opening bookmarks by pressing return is only + // supported when a single item is selected. To be consistent, do the + // same here. + if (selectedElements.length == 1) { + let element = selectedElements[0]; + if (element._shell) + element._shell.doDefaultCommand(); + } + } + else if (aEvent.charCode == " ".charCodeAt(0)) { + // Pause/Resume every selected download + for (let element of selectedElements) { + if (element._shell.isCommandEnabled("downloadsCmd_pauseResume")) + element._shell.doCommand("downloadsCmd_pauseResume"); + } + } + }, + + onDoubleClick: function DPV_onDoubleClick(aEvent) { + if (aEvent.button != 0) + return; + + let selectedElements = this._richlistbox.selectedItems; + if (selectedElements.length != 1) + return; + + let element = selectedElements[0]; + if (element._shell) + element._shell.doDefaultCommand(); + }, + + onScroll: function DPV_onScroll() { + this._ensureVisibleElementsAreActive(); + }, + + onSelect: function DPV_onSelect() { + goUpdateDownloadCommands(); + + let selectedElements = this._richlistbox.selectedItems; + for (let elt of selectedElements) { + if (elt._shell) + elt._shell.onSelect(); + } + }, + + onDragStart: function DPV_onDragStart(aEvent) { + // TODO Bug 831358: Support d&d for multiple selection. + // For now, we just drag the first element. + let selectedItem = this._richlistbox.selectedItem; + if (!selectedItem) + return; + + let metaData = selectedItem._shell.getDownloadMetaData(); + if (!("filePath" in metaData)) + return; + let file = new FileUtils.File(metaData.filePath); + if (!file.exists()) + return; + + let dt = aEvent.dataTransfer; + dt.mozSetDataAt("application/x-moz-file", file, 0); + let url = Services.io.newFileURI(file).spec; + dt.setData("text/uri-list", url); + dt.setData("text/plain", url); + dt.effectAllowed = "copyMove"; + dt.addElement(selectedItem); + }, + + onDragOver: function DPV_onDragOver(aEvent) { + let types = aEvent.dataTransfer.types; + if (types.contains("text/uri-list") || + types.contains("text/x-moz-url") || + types.contains("text/plain")) { + aEvent.preventDefault(); + } + }, + + onDrop: function DPV_onDrop(aEvent) { + let dt = aEvent.dataTransfer; + // If dragged item is from our source, do not try to + // redownload already downloaded file. + if (dt.mozGetDataAt("application/x-moz-file", 0)) + return; + + let name = { }; + let url = Services.droppedLinkHandler.dropLink(aEvent, name); + if (url) + DownloadURL(url, name.value); + } +}; + +for (let methodName of ["load", "applyFilter", "selectNode", "selectItems"]) { + DownloadsPlacesView.prototype[methodName] = function() { + throw new Error("|" + methodName + "| is not implemented by the downloads view."); + } +} + +function goUpdateDownloadCommands() { + for (let command of DOWNLOAD_VIEW_SUPPORTED_COMMANDS) { + goUpdateCommand(command); + } +} diff --git a/application/palemoon/components/downloads/content/allDownloadsViewOverlay.xul b/application/palemoon/components/downloads/content/allDownloadsViewOverlay.xul new file mode 100644 index 000000000..4e9bfd15b --- /dev/null +++ b/application/palemoon/components/downloads/content/allDownloadsViewOverlay.xul @@ -0,0 +1,119 @@ + + +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + + + + + +%downloadsDTD; +]> + + + + + + +
+
+ + + +
+

+

+

+
+
+
+ + diff --git a/application/palemoon/components/feeds/content/subscribe.xml b/application/palemoon/components/feeds/content/subscribe.xml new file mode 100644 index 000000000..949bcfd7e --- /dev/null +++ b/application/palemoon/components/feeds/content/subscribe.xml @@ -0,0 +1,40 @@ + + + + + %feedDTD; +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/application/palemoon/components/feeds/jar.mn b/application/palemoon/components/feeds/jar.mn new file mode 100644 index 000000000..2fae7efae --- /dev/null +++ b/application/palemoon/components/feeds/jar.mn @@ -0,0 +1,9 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +browser.jar: + content/browser/feeds/subscribe.xhtml (content/subscribe.xhtml) + content/browser/feeds/subscribe.js (content/subscribe.js) + content/browser/feeds/subscribe.xml (content/subscribe.xml) + content/browser/feeds/subscribe.css (content/subscribe.css) diff --git a/application/palemoon/components/feeds/moz.build b/application/palemoon/components/feeds/moz.build new file mode 100644 index 000000000..1dea0ce77 --- /dev/null +++ b/application/palemoon/components/feeds/moz.build @@ -0,0 +1,39 @@ +# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +JAR_MANIFESTS += ['jar.mn'] + +XPIDL_SOURCES += [ + 'nsIFeedResultService.idl', + 'nsIWebContentConverterRegistrar.idl', +] + +XPIDL_MODULE = 'browser-feeds' + +SOURCES += [ + 'nsFeedSniffer.cpp', +] + +EXTRA_COMPONENTS += [ + 'BrowserFeeds.manifest', + 'FeedConverter.js', +] + +EXTRA_PP_COMPONENTS += [ + 'FeedWriter.js', + 'WebContentConverter.js', +] + +FINAL_LIBRARY = 'browsercomps' + +for var in ('MOZ_APP_NAME', 'MOZ_MACBUNDLE_NAME'): + DEFINES[var] = CONFIG[var] + +LOCAL_INCLUDES += [ + '../build', +] + +FAIL_ON_WARNINGS = True diff --git a/application/palemoon/components/feeds/nsFeedSniffer.cpp b/application/palemoon/components/feeds/nsFeedSniffer.cpp new file mode 100644 index 000000000..61cc77bdd --- /dev/null +++ b/application/palemoon/components/feeds/nsFeedSniffer.cpp @@ -0,0 +1,363 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsFeedSniffer.h" + + +#include "nsNetCID.h" +#include "nsXPCOM.h" +#include "nsCOMPtr.h" +#include "nsStringStream.h" + +#include "nsBrowserCompsCID.h" + +#include "nsICategoryManager.h" +#include "nsIServiceManager.h" +#include "nsComponentManagerUtils.h" +#include "nsServiceManagerUtils.h" + +#include "nsIStreamConverterService.h" +#include "nsIStreamConverter.h" + +#include "nsIStreamListener.h" + +#include "nsIHttpChannel.h" +#include "nsIMIMEHeaderParam.h" + +#include "nsMimeTypes.h" +#include "nsIURI.h" +#include + +#define TYPE_ATOM "application/atom+xml" +#define TYPE_RSS "application/rss+xml" +#define TYPE_MAYBE_FEED "application/vnd.mozilla.maybe.feed" + +#define NS_RDF "http://www.w3.org/1999/02/22-rdf-syntax-ns#" +#define NS_RSS "http://purl.org/rss/1.0/" + +#define MAX_BYTES 512u + +NS_IMPL_ISUPPORTS(nsFeedSniffer, + nsIContentSniffer, + nsIStreamListener, + nsIRequestObserver) + +nsresult +nsFeedSniffer::ConvertEncodedData(nsIRequest* request, + const uint8_t* data, + uint32_t length) +{ + nsresult rv = NS_OK; + + mDecodedData = ""; + nsCOMPtr httpChannel(do_QueryInterface(request)); + if (!httpChannel) + return NS_ERROR_NO_INTERFACE; + + nsAutoCString contentEncoding; + httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("Content-Encoding"), + contentEncoding); + if (!contentEncoding.IsEmpty()) { + nsCOMPtr converterService(do_GetService(NS_STREAMCONVERTERSERVICE_CONTRACTID)); + if (converterService) { + ToLowerCase(contentEncoding); + + nsCOMPtr converter; + rv = converterService->AsyncConvertData(contentEncoding.get(), + "uncompressed", this, nullptr, + getter_AddRefs(converter)); + NS_ENSURE_SUCCESS(rv, rv); + + converter->OnStartRequest(request, nullptr); + + nsCOMPtr rawStream = + do_CreateInstance(NS_STRINGINPUTSTREAM_CONTRACTID); + if (!rawStream) + return NS_ERROR_FAILURE; + + rv = rawStream->SetData((const char*)data, length); + NS_ENSURE_SUCCESS(rv, rv); + + rv = converter->OnDataAvailable(request, nullptr, rawStream, 0, length); + NS_ENSURE_SUCCESS(rv, rv); + + converter->OnStopRequest(request, nullptr, NS_OK); + } + } + return rv; +} + +template +static bool +StringBeginsWithLowercaseLiteral(nsAString& aString, + const char (&aSubstring)[N]) +{ + return StringHead(aString, N).LowerCaseEqualsLiteral(aSubstring); +} + +bool +HasAttachmentDisposition(nsIHttpChannel* httpChannel) +{ + if (!httpChannel) + return false; + + uint32_t disp; + nsresult rv = httpChannel->GetContentDisposition(&disp); + + if (NS_SUCCEEDED(rv) && disp == nsIChannel::DISPOSITION_ATTACHMENT) + return true; + + return false; +} + +/** + * @return the first occurrence of a character within a string buffer, + * or nullptr if not found + */ +static const char* +FindChar(char c, const char *begin, const char *end) +{ + for (; begin < end; ++begin) { + if (*begin == c) + return begin; + } + return nullptr; +} + +/** + * + * Determine if a substring is the "documentElement" in the document. + * + * All of our sniffed substrings: = end) + return false; + + // Check to see if the character following the '<' is either '?' or '!' + // (processing instruction or doctype or comment)... these are valid nodes + // to have in the prologue. + if (*start != '?' && *start != '!') + return false; + + // Now advance the iterator until the '>' (We do this because we don't want + // to sniff indicator substrings that are embedded within other nodes, e.g. + // comments: + start = FindChar('>', start, end); + if (!start) + return false; + + ++start; + } + return true; +} + +/** + * Determines whether or not a string exists as the root element in an XML data + * string buffer. + * @param dataString + * The data being sniffed + * @param substring + * The substring being tested for existence and root-ness. + * @returns true if the substring exists and is the documentElement, false + * otherwise. + */ +static bool +ContainsTopLevelSubstring(nsACString& dataString, const char *substring) +{ + int32_t offset = dataString.Find(substring); + if (offset == -1) + return false; + + const char *begin = dataString.BeginReading(); + + // Only do the validation when we find the substring. + return IsDocumentElement(begin, begin + offset); +} + +NS_IMETHODIMP +nsFeedSniffer::GetMIMETypeFromContent(nsIRequest* request, + const uint8_t* data, + uint32_t length, + nsACString& sniffedType) +{ + nsCOMPtr channel(do_QueryInterface(request)); + if (!channel) + return NS_ERROR_NO_INTERFACE; + + // Check that this is a GET request, since you can't subscribe to a POST... + nsAutoCString method; + channel->GetRequestMethod(method); + if (!method.EqualsLiteral("GET")) { + sniffedType.Truncate(); + return NS_OK; + } + + // We need to find out if this is a load of a view-source document. In this + // case we do not want to override the content type, since the source display + // does not need to be converted from feed format to XUL. More importantly, + // we don't want to change the content type from something + // nsContentDLF::CreateInstance knows about (e.g. application/xml, text/html + // etc) to something that only the application fe knows about (maybe.feed) + // thus deactivating syntax highlighting. + nsCOMPtr originalURI; + channel->GetOriginalURI(getter_AddRefs(originalURI)); + + nsAutoCString scheme; + originalURI->GetScheme(scheme); + if (scheme.EqualsLiteral("view-source")) { + sniffedType.Truncate(); + return NS_OK; + } + + // Check the Content-Type to see if it is set correctly. If it is set to + // something specific that we think is a reliable indication of a feed, don't + // bother sniffing since we assume the site maintainer knows what they're + // doing. + nsAutoCString contentType; + channel->GetContentType(contentType); + bool noSniff = contentType.EqualsLiteral(TYPE_RSS) || + contentType.EqualsLiteral(TYPE_ATOM); + + // Check to see if this was a feed request from the location bar or from + // the feed: protocol. This is also a reliable indication. + // The value of the header doesn't matter. + if (!noSniff) { + nsAutoCString sniffHeader; + nsresult foundHeader = + channel->GetRequestHeader(NS_LITERAL_CSTRING("X-Moz-Is-Feed"), + sniffHeader); + noSniff = NS_SUCCEEDED(foundHeader); + } + + if (noSniff) { + // check for an attachment after we have a likely feed. + if(HasAttachmentDisposition(channel)) { + sniffedType.Truncate(); + return NS_OK; + } + + // set the feed header as a response header, since we have good metadata + // telling us that the feed is supposed to be RSS or Atom + channel->SetResponseHeader(NS_LITERAL_CSTRING("X-Moz-Is-Feed"), + NS_LITERAL_CSTRING("1"), false); + sniffedType.AssignLiteral(TYPE_MAYBE_FEED); + return NS_OK; + } + + // Don't sniff arbitrary types. Limit sniffing to situations that + // we think can reasonably arise. + if (!contentType.EqualsLiteral(TEXT_HTML) && + !contentType.EqualsLiteral(APPLICATION_OCTET_STREAM) && + // Same criterion as XMLHttpRequest. Should we be checking for "+xml" + // and check for text/xml and application/xml by hand instead? + contentType.Find("xml") == -1) { + sniffedType.Truncate(); + return NS_OK; + } + + // Now we need to potentially decompress data served with + // Content-Encoding: gzip + nsresult rv = ConvertEncodedData(request, data, length); + if (NS_FAILED(rv)) + return rv; + + // We cap the number of bytes to scan at MAX_BYTES to prevent picking up + // false positives by accidentally reading document content, e.g. a "how to + // make a feed" page. + const char* testData; + if (mDecodedData.IsEmpty()) { + testData = (const char*)data; + length = std::min(length, MAX_BYTES); + } else { + testData = mDecodedData.get(); + length = std::min(mDecodedData.Length(), MAX_BYTES); + } + + // The strategy here is based on that described in: + // http://blogs.msdn.com/rssteam/articles/PublishersGuide.aspx + // for interoperarbility purposes. + + // Thus begins the actual sniffing. + nsDependentCSubstring dataString((const char*)testData, length); + + bool isFeed = false; + + // RSS 0.91/0.92/2.0 + isFeed = ContainsTopLevelSubstring(dataString, "(closure); + decodedData->Append(rawSegment, count); + *writeCount = count; + return NS_OK; +} + +NS_IMETHODIMP +nsFeedSniffer::OnDataAvailable(nsIRequest* request, nsISupports* context, + nsIInputStream* stream, uint64_t offset, + uint32_t count) +{ + uint32_t read; + return stream->ReadSegments(AppendSegmentToString, &mDecodedData, count, + &read); +} + +NS_IMETHODIMP +nsFeedSniffer::OnStopRequest(nsIRequest* request, nsISupports* context, + nsresult status) +{ + return NS_OK; +} diff --git a/application/palemoon/components/feeds/nsFeedSniffer.h b/application/palemoon/components/feeds/nsFeedSniffer.h new file mode 100644 index 000000000..57e10d954 --- /dev/null +++ b/application/palemoon/components/feeds/nsFeedSniffer.h @@ -0,0 +1,37 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + + +#include "nsIContentSniffer.h" +#include "nsIStreamListener.h" +#include "nsStringAPI.h" +#include "mozilla/Attributes.h" + +class nsFeedSniffer final : public nsIContentSniffer, + nsIStreamListener +{ +public: + NS_DECL_ISUPPORTS + NS_DECL_NSICONTENTSNIFFER + NS_DECL_NSIREQUESTOBSERVER + NS_DECL_NSISTREAMLISTENER + + static NS_METHOD AppendSegmentToString(nsIInputStream* inputStream, + void* closure, + const char* rawSegment, + uint32_t toOffset, + uint32_t count, + uint32_t* writeCount); + +protected: + ~nsFeedSniffer() {} + + nsresult ConvertEncodedData(nsIRequest* request, const uint8_t* data, + uint32_t length); + +private: + nsCString mDecodedData; +}; + diff --git a/application/palemoon/components/feeds/nsIFeedResultService.idl b/application/palemoon/components/feeds/nsIFeedResultService.idl new file mode 100644 index 000000000..cb0f332d1 --- /dev/null +++ b/application/palemoon/components/feeds/nsIFeedResultService.idl @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsISupports.idl" +interface nsIURI; +interface nsIRequest; +interface nsIFeedResult; + +/** + * nsIFeedResultService provides a globally-accessible object for retrieving + * the results of feed processing. + */ +[scriptable, uuid(950a829e-c20e-4dc3-b447-f8b753ae54da)] +interface nsIFeedResultService : nsISupports +{ + /** + * When set to true, forces the preview page to be displayed, regardless + * of the user's preferences. + */ + attribute boolean forcePreviewPage; + + /** + * Adds a URI to the user's specified external feed handler, or live + * bookmarks. + * @param uri + * The uri of the feed to add. + * @param title + * The title of the feed to add. + * @param subtitle + * The subtitle of the feed to add. + * @param feedType + * The nsIFeed type of the feed. See nsIFeed.idl + */ + void addToClientReader(in AUTF8String uri, + in AString title, + in AString subtitle, + in unsigned long feedType); + + /** + * Registers a Feed Result object with a globally accessible service + * so that it can be accessed by a singleton method outside the usual + * flow of control in document loading. + * + * @param feedResult + * An object implementing nsIFeedResult representing the feed. + */ + void addFeedResult(in nsIFeedResult feedResult); + + /** + * Gets a Feed Handler object registered using addFeedResult. + * + * @param uri + * The URI of the feed a handler is being requested for + */ + nsIFeedResult getFeedResult(in nsIURI uri); + + /** + * Unregisters a Feed Handler object registered using addFeedResult. + * @param uri + * The feed URI the handler was registered under. This must be + * the same *instance* the feed was registered under. + */ + void removeFeedResult(in nsIURI uri); +}; diff --git a/application/palemoon/components/feeds/nsIWebContentConverterRegistrar.idl b/application/palemoon/components/feeds/nsIWebContentConverterRegistrar.idl new file mode 100644 index 000000000..08ce2f4ae --- /dev/null +++ b/application/palemoon/components/feeds/nsIWebContentConverterRegistrar.idl @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsIMIMEInfo.idl" +#include "nsIWebContentHandlerRegistrar.idl" + +interface nsIRequest; + +[scriptable, uuid(eb361098-5158-4b21-8f98-50b445f1f0b2)] +interface nsIWebContentHandlerInfo : nsIHandlerApp +{ + /** + * The content type handled by the handler + */ + readonly attribute AString contentType; + + /** + * The uri of the handler, with an embedded %s where the URI of the loaded + * document will be encoded. + */ + readonly attribute AString uri; + + /** + * Gets the service URL Spec, with the loading document URI encoded in it. + * @param uri + * The URI of the document being loaded + * @returns The URI of the service with the loading document URI encoded in + * it. + */ + AString getHandlerURI(in AString uri); +}; + +[scriptable, uuid(de7cc06e-e778-45cb-b7db-7a114e1e75b1)] +interface nsIWebContentConverterService : nsIWebContentHandlerRegistrar +{ + /** + * Specifies the handler to be used to automatically handle all links of a + * certain content type from now on. + * @param contentType + * The content type to automatically load with the specified handler + * @param handler + * A web service handler. If this is null, no automatic action is + * performed and the user must choose. + * @throws NS_ERROR_NOT_AVAILABLE if the service refered to by |handler| is + * not already registered. + */ + void setAutoHandler(in AString contentType, in nsIWebContentHandlerInfo handler); + + /** + * Gets the auto handler specified for a particular content type + * @param contentType + * The content type to look up an auto handler for. + * @returns The web service handler that will automatically handle all + * documents of the specified type. null if there is no automatic + * handler. (Handlers may be registered, just none of them specified + * as "automatic"). + */ + nsIWebContentHandlerInfo getAutoHandler(in AString contentType); + + /** + * Gets a web handler for the specified service URI + * @param contentType + * The content type of the service being located + * @param uri + * The service URI of the handler to locate. + * @returns A web service handler that uses the specified uri. + */ + nsIWebContentHandlerInfo getWebContentHandlerByURI(in AString contentType, + in AString uri); + + /** + * Loads the preferred handler when content of a registered type is about + * to be loaded. + * @param request + * The nsIRequest for the load of the content + */ + void loadPreferredHandler(in nsIRequest request); + + /** + * Removes a registered protocol handler + * @param protocol + * The protocol scheme to remove a service handler for + * @param uri + * The uri of the service handler to remove + */ + void removeProtocolHandler(in AString protocol, in AString uri); + + /** + * Removes a registered content handler + * @param contentType + * The content type to remove a service handler for + * @param uri + * The uri of the service handler to remove + */ + void removeContentHandler(in AString contentType, in AString uri); + + /** + * Gets the list of content handlers for a particular type. + * @param contentType + * The content type to get handlers for + * @returns An array of nsIWebContentHandlerInfo objects + */ + void getContentHandlers(in AString contentType, + [optional] out unsigned long count, + [retval,array,size_is(count)] out nsIWebContentHandlerInfo handlers); + + /** + * Resets the list of available content handlers to the default set from + * the distribution. + * @param contentType + * The content type to reset handlers for + */ + void resetHandlersForType(in AString contentType); +}; + diff --git a/application/palemoon/components/fuel/fuelApplication.js b/application/palemoon/components/fuel/fuelApplication.js new file mode 100644 index 000000000..89d568ae1 --- /dev/null +++ b/application/palemoon/components/fuel/fuelApplication.js @@ -0,0 +1,818 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +const Ci = Components.interfaces; +const Cc = Components.classes; + +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); + +const APPLICATION_CID = Components.ID("fe74cf80-aa2d-11db-abbd-0800200c9a66"); +const APPLICATION_CONTRACTID = "@mozilla.org/fuel/application;1"; + +//================================================= +// Singleton that holds services and utilities +var Utilities = { + get bookmarks() { + let bookmarks = Cc["@mozilla.org/browser/nav-bookmarks-service;1"]. + getService(Ci.nsINavBookmarksService); + this.__defineGetter__("bookmarks", function() bookmarks); + return this.bookmarks; + }, + + get bookmarksObserver() { + let bookmarksObserver = new BookmarksObserver(); + this.__defineGetter__("bookmarksObserver", function() bookmarksObserver); + return this.bookmarksObserver; + }, + + get annotations() { + let annotations = Cc["@mozilla.org/browser/annotation-service;1"]. + getService(Ci.nsIAnnotationService); + this.__defineGetter__("annotations", function() annotations); + return this.annotations; + }, + + get history() { + let history = Cc["@mozilla.org/browser/nav-history-service;1"]. + getService(Ci.nsINavHistoryService); + this.__defineGetter__("history", function() history); + return this.history; + }, + + get windowMediator() { + let windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"]. + getService(Ci.nsIWindowMediator); + this.__defineGetter__("windowMediator", function() windowMediator); + return this.windowMediator; + }, + + makeURI: function fuelutil_makeURI(aSpec) { + if (!aSpec) + return null; + var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); + return ios.newURI(aSpec, null, null); + }, + + free: function fuelutil_free() { + delete this.bookmarks; + delete this.bookmarksObserver; + delete this.annotations; + delete this.history; + delete this.windowMediator; + } +}; + + +//================================================= +// Window implementation + +var fuelWindowMap = new WeakMap(); +function getWindow(aWindow) { + let fuelWindow = fuelWindowMap.get(aWindow); + if (!fuelWindow) { + fuelWindow = new Window(aWindow); + fuelWindowMap.set(aWindow, fuelWindow); + } + return fuelWindow; +} + +// Don't call new Window() directly; use getWindow instead. +function Window(aWindow) { + this._window = aWindow; + this._events = new Events(); + + this._watch("TabOpen"); + this._watch("TabMove"); + this._watch("TabClose"); + this._watch("TabSelect"); +} + +Window.prototype = { + get events() { + return this._events; + }, + + get _tabbrowser() { + return this._window.getBrowser(); + }, + + /* + * Helper used to setup event handlers on the XBL element. Note that the events + * are actually dispatched to tabs, so we capture them. + */ + _watch: function win_watch(aType) { + this._tabbrowser.tabContainer.addEventListener(aType, this, + /* useCapture = */ true); + }, + + handleEvent: function win_handleEvent(aEvent) { + this._events.dispatch(aEvent.type, getBrowserTab(this, aEvent.originalTarget.linkedBrowser)); + }, + + get tabs() { + var tabs = []; + var browsers = this._tabbrowser.browsers; + for (var i=0; i getWindow(Utilities.windowMediator.getMostRecentWindow("navigator:browser")), + enumerable: true, + configurable: true + }); + +}; + +// set the proto, defined in extApplication.js +ApplicationPrototype.prototype = extApplication.prototype; + +Application.prototype = new ApplicationPrototype(); + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([Application]); + diff --git a/application/palemoon/components/fuel/fuelApplication.manifest b/application/palemoon/components/fuel/fuelApplication.manifest new file mode 100644 index 000000000..67e6d0fe6 --- /dev/null +++ b/application/palemoon/components/fuel/fuelApplication.manifest @@ -0,0 +1,3 @@ +component {fe74cf80-aa2d-11db-abbd-0800200c9a66} fuelApplication.js +contract @mozilla.org/fuel/application;1 {fe74cf80-aa2d-11db-abbd-0800200c9a66} +category JavaScript-global-privileged-property Application @mozilla.org/fuel/application;1 diff --git a/application/palemoon/components/fuel/fuelIApplication.idl b/application/palemoon/components/fuel/fuelIApplication.idl new file mode 100644 index 000000000..69b51b0f5 --- /dev/null +++ b/application/palemoon/components/fuel/fuelIApplication.idl @@ -0,0 +1,347 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsISupports.idl" +#include "extIApplication.idl" + +interface nsIVariant; +interface nsIURI; +interface nsIDOMHTMLDocument; + +interface fuelIBookmarkFolder; +interface fuelIBrowserTab; + +/** + * Interface representing a collection of annotations associated + * with a bookmark or bookmark folder. + */ +[scriptable, uuid(335c9292-91a1-4ca0-ad0b-07d5f63ed6cd)] +interface fuelIAnnotations : nsISupports +{ + /** + * Array of the annotation names associated with the owning item + */ + readonly attribute nsIVariant names; + + /** + * Determines if an annotation exists with the given name. + * @param aName + * The name of the annotation + * @returns true if an annotation exists with the given name, + * false otherwise. + */ + boolean has(in AString aName); + + /** + * Gets the value of an annotation with the given name. + * @param aName + * The name of the annotation + * @returns A variant containing the value of the annotation. Supports + * string, boolean and number. + */ + nsIVariant get(in AString aName); + + /** + * Sets the value of an annotation with the given name. + * @param aName + * The name of the annotation + * @param aValue + * The new value of the annotation. Supports string, boolean + * and number + * @param aExpiration + * The expiration policy for the annotation. + * See nsIAnnotationService. + */ + void set(in AString aName, in nsIVariant aValue, in int32_t aExpiration); + + /** + * Removes the named annotation from the owner item. + * @param aName + * The name of annotation. + */ + void remove(in AString aName); +}; + + +/** + * Interface representing a bookmark item. + */ +[scriptable, uuid(808585b6-7568-4b26-8c62-545221bf2b8c)] +interface fuelIBookmark : nsISupports +{ + /** + * The id of the bookmark. + */ + readonly attribute long long id; + + /** + * The title of the bookmark. + */ + attribute AString title; + + /** + * The uri of the bookmark. + */ + attribute nsIURI uri; + + /** + * The description of the bookmark. + */ + attribute AString description; + + /** + * The keyword associated with the bookmark. + */ + attribute AString keyword; + + /** + * The type of the bookmark. + * values: "bookmark", "separator" + */ + readonly attribute AString type; + + /** + * The parent folder of the bookmark. + */ + attribute fuelIBookmarkFolder parent; + + /** + * The annotations object for the bookmark. + */ + readonly attribute fuelIAnnotations annotations; + + /** + * The events object for the bookmark. + * supports: "remove", "change", "visit", "move" + */ + readonly attribute extIEvents events; + + /** + * Removes the item from the parent folder. Used to + * delete a bookmark or separator + */ + void remove(); +}; + + +/** + * Interface representing a bookmark folder. Folders + * can hold bookmarks, separators and other folders. + */ +[scriptable, uuid(9f42fe20-52de-4a55-8632-a459c7716aa0)] +interface fuelIBookmarkFolder : nsISupports +{ + /** + * The id of the folder. + */ + readonly attribute long long id; + + /** + * The title of the folder. + */ + attribute AString title; + + /** + * The description of the folder. + */ + attribute AString description; + + /** + * The type of the folder. + * values: "folder" + */ + readonly attribute AString type; + + /** + * The parent folder of the folder. + */ + attribute fuelIBookmarkFolder parent; + + /** + * The annotations object for the folder. + */ + readonly attribute fuelIAnnotations annotations; + + /** + * The events object for the folder. + * supports: "add", "addchild", "remove", "removechild", "change", "move" + */ + readonly attribute extIEvents events; + + /** + * Array of all bookmarks, separators and folders contained + * in this folder. + */ + readonly attribute nsIVariant children; + + /** + * Adds a new child bookmark to this folder. + * @param aTitle + * The title of bookmark. + * @param aURI + * The uri of bookmark. + */ + fuelIBookmark addBookmark(in AString aTitle, in nsIURI aURI); + + /** + * Adds a new child separator to this folder. + */ + fuelIBookmark addSeparator(); + + /** + * Adds a new child folder to this folder. + * @param aTitle + * The title of folder. + */ + fuelIBookmarkFolder addFolder(in AString aTitle); + + /** + * Removes the folder from the parent folder. + */ + void remove(); +}; + +/** + * Interface representing a container for bookmark roots. Roots + * are the top level parents for the various types of bookmarks in the system. + */ +[scriptable, uuid(c9a80870-eb3c-11dc-95ff-0800200c9a66)] +interface fuelIBookmarkRoots : nsISupports +{ + /** + * The folder for the 'bookmarks menu' root. + */ + readonly attribute fuelIBookmarkFolder menu; + + /** + * The folder for the 'personal toolbar' root. + */ + readonly attribute fuelIBookmarkFolder toolbar; + + /** + * The folder for the 'tags' root. + */ + readonly attribute fuelIBookmarkFolder tags; + + /** + * The folder for the 'unfiled bookmarks' root. + */ + readonly attribute fuelIBookmarkFolder unfiled; +}; + +/** + * Interface representing a browser window. + */ +[scriptable, uuid(207edb28-eb5e-424e-a862-b0e97C8de866)] +interface fuelIWindow : nsISupports +{ + /** + * A collection of browser tabs within the browser window. + */ + readonly attribute nsIVariant tabs; + + /** + * The currently-active tab within the browser window. + */ + readonly attribute fuelIBrowserTab activeTab; + + /** + * Open a new browser tab, pointing to the specified URI. + * @param aURI + * The uri to open the browser tab to + */ + fuelIBrowserTab open(in nsIURI aURI); + + /** + * The events object for the browser window. + * supports: "TabOpen", "TabClose", "TabMove", "TabSelect" + */ + readonly attribute extIEvents events; +}; + +/** + * Interface representing a browser tab. + */ +[scriptable, uuid(3073ceff-777c-41ce-9ace-ab37268147c1)] +interface fuelIBrowserTab : nsISupports +{ + /** + * The current uri of this tab. + */ + readonly attribute nsIURI uri; + + /** + * The current index of this tab in the browser window. + */ + readonly attribute int32_t index; + + /** + * The browser window that is holding the tab. + */ + readonly attribute fuelIWindow window; + + /** + * The content document of the browser tab. + */ + readonly attribute nsIDOMHTMLDocument document; + + /** + * The events object for the browser tab. + * supports: "load" + */ + readonly attribute extIEvents events; + + /** + * Load a new URI into this browser tab. + * @param aURI + * The uri to load into the browser tab + */ + void load(in nsIURI aURI); + + /** + * Give focus to this browser tab, and bring it to the front. + */ + void focus(); + + /** + * Close the browser tab. This may not actually close the tab + * as script may abort the close operation. + */ + void close(); + + /** + * Moves this browser tab before another browser tab within the window. + * @param aBefore + * The tab before which the target tab will be moved + */ + void moveBefore(in fuelIBrowserTab aBefore); + + /** + * Move this browser tab to the last tab within the window. + */ + void moveToEnd(); +}; + +/** + * Interface for managing and accessing the applications systems + */ +[scriptable, uuid(fe74cf80-aa2d-11db-abbd-0800200c9a66)] +interface fuelIApplication : extIApplication +{ + /** + * The root bookmarks object for the application. + * Contains all the bookmark roots in the system. + */ + readonly attribute fuelIBookmarkRoots bookmarks; + + /** + * An array of browser windows within the application. + */ + readonly attribute nsIVariant windows; + + /** + * The currently active browser window. + */ + readonly attribute fuelIWindow activeWindow; +}; diff --git a/application/palemoon/components/fuel/moz.build b/application/palemoon/components/fuel/moz.build new file mode 100644 index 000000000..e78eda088 --- /dev/null +++ b/application/palemoon/components/fuel/moz.build @@ -0,0 +1,20 @@ +# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +XPIDL_SOURCES += [ + 'fuelIApplication.idl', +] + +XPIDL_MODULE = 'fuel' + +EXTRA_COMPONENTS += [ + 'fuelApplication.manifest', +] + +EXTRA_PP_COMPONENTS += [ + 'fuelApplication.js', +] + diff --git a/application/palemoon/components/migration/BrowserProfileMigrators.manifest b/application/palemoon/components/migration/BrowserProfileMigrators.manifest new file mode 100644 index 000000000..d7fec75e3 --- /dev/null +++ b/application/palemoon/components/migration/BrowserProfileMigrators.manifest @@ -0,0 +1,14 @@ +component {6F8BB968-C14F-4D6F-9733-6C6737B35DCE} ProfileMigrator.js +contract @mozilla.org/toolkit/profile-migrator;1 {6F8BB968-C14F-4D6F-9733-6C6737B35DCE} +component {4cec1de4-1671-4fc3-a53e-6c539dc77a26} ChromeProfileMigrator.js +contract @mozilla.org/profile/migrator;1?app=browser&type=chrome {4cec1de4-1671-4fc3-a53e-6c539dc77a26} +component {91185366-ba97-4438-acba-48deaca63386} FirefoxProfileMigrator.js +contract @mozilla.org/profile/migrator;1?app=browser&type=firefox {91185366-ba97-4438-acba-48deaca63386} +#ifdef HAS_IE_MIGRATOR +component {3d2532e3-4932-4774-b7ba-968f5899d3a4} IEProfileMigrator.js +contract @mozilla.org/profile/migrator;1?app=browser&type=ie {3d2532e3-4932-4774-b7ba-968f5899d3a4} +#endif +#ifdef HAS_SAFARI_MIGRATOR +component {4b609ecf-60b2-4655-9df4-dc149e474da1} SafariProfileMigrator.js +contract @mozilla.org/profile/migrator;1?app=browser&type=safari {4b609ecf-60b2-4655-9df4-dc149e474da1} +#endif diff --git a/application/palemoon/components/migration/ChromeProfileMigrator.js b/application/palemoon/components/migration/ChromeProfileMigrator.js new file mode 100644 index 000000000..61955fbb4 --- /dev/null +++ b/application/palemoon/components/migration/ChromeProfileMigrator.js @@ -0,0 +1,463 @@ +/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- + * vim: sw=2 ts=2 sts=2 et */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; +const Cr = Components.results; + +const FILE_INPUT_STREAM_CID = "@mozilla.org/network/file-input-stream;1"; + +const S100NS_FROM1601TO1970 = 0x19DB1DED53E8000; +const S100NS_PER_MS = 10; + +const AUTH_TYPE = { + SCHEME_HTML: 0, + SCHEME_BASIC: 1, + SCHEME_DIGEST: 2 +}; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/NetUtil.jsm"); +Cu.import("resource://gre/modules/FileUtils.jsm"); +Cu.import("resource:///modules/MigrationUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", + "resource://gre/modules/PlacesUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OSCrypto", + "resource://gre/modules/OSCrypto.jsm"); + +/** + * Convert Chrome time format to Date object + * + * @param aTime + * Chrome time + * @return converted Date object + * @note Google Chrome uses FILETIME / 10 as time. + * FILETIME is based on same structure of Windows. + */ +function chromeTimeToDate(aTime) +{ + return new Date((aTime * S100NS_PER_MS - S100NS_FROM1601TO1970 ) / 10000); +} + +/** + * Insert bookmark items into specific folder. + * + * @param aFolderId + * id of folder where items will be inserted + * @param aItems + * bookmark items to be inserted + */ +function insertBookmarkItems(aFolderId, aItems) +{ + for (let i = 0; i < aItems.length; i++) { + let item = aItems[i]; + + try { + if (item.type == "url") { + PlacesUtils.bookmarks.insertBookmark(aFolderId, + NetUtil.newURI(item.url), + PlacesUtils.bookmarks.DEFAULT_INDEX, + item.name); + } else if (item.type == "folder") { + let newFolderId = + PlacesUtils.bookmarks.createFolder(aFolderId, + item.name, + PlacesUtils.bookmarks.DEFAULT_INDEX); + + insertBookmarkItems(newFolderId, item.children); + } + } catch (e) { + Cu.reportError(e); + } + } +} + + +function ChromeProfileMigrator() { + let chromeUserDataFolder = FileUtils.getDir( +#ifdef XP_WIN + "LocalAppData", ["Google", "Chrome", "User Data"] +#elifdef XP_MACOSX + "ULibDir", ["Application Support", "Google", "Chrome"] +#else + "Home", [".config", "google-chrome"] +#endif + , false); + this._chromeUserDataFolder = chromeUserDataFolder.exists() ? + chromeUserDataFolder : null; +} + +ChromeProfileMigrator.prototype = Object.create(MigratorPrototype); + +ChromeProfileMigrator.prototype.getResources = + function Chrome_getResources(aProfile) { + if (this._chromeUserDataFolder) { + let profileFolder = this._chromeUserDataFolder.clone(); + profileFolder.append(aProfile.id); + if (profileFolder.exists()) { + let possibleResources = [GetBookmarksResource(profileFolder), + GetHistoryResource(profileFolder), + GetCookiesResource(profileFolder), +#ifdef XP_WIN + GetWindowsPasswordsResource(profileFolder) +#endif + ]; + return [r for each (r in possibleResources) if (r != null)]; + } + } + return []; + }; + +Object.defineProperty(ChromeProfileMigrator.prototype, "sourceProfiles", { + get: function Chrome_sourceProfiles() { + if ("__sourceProfiles" in this) + return this.__sourceProfiles; + + if (!this._chromeUserDataFolder) + return []; + + let profiles = []; + try { + // Local State is a JSON file that contains profile info. + let localState = this._chromeUserDataFolder.clone(); + localState.append("Local State"); + if (!localState.exists()) + throw new Error("Chrome's 'Local State' file does not exist."); + if (!localState.isReadable()) + throw new Error("Chrome's 'Local State' file could not be read."); + + let fstream = Cc[FILE_INPUT_STREAM_CID].createInstance(Ci.nsIFileInputStream); + fstream.init(localState, -1, 0, 0); + let inputStream = NetUtil.readInputStreamToString(fstream, fstream.available(), + { charset: "UTF-8" }); + let info_cache = JSON.parse(inputStream).profile.info_cache; + for (let profileFolderName in info_cache) { + let profileFolder = this._chromeUserDataFolder.clone(); + profileFolder.append(profileFolderName); + profiles.push({ + id: profileFolderName, + name: info_cache[profileFolderName].name || profileFolderName, + }); + } + } catch (e) { + Cu.reportError("Error detecting Chrome profiles: " + e); + // If we weren't able to detect any profiles above, fallback to the Default profile. + let defaultProfileFolder = this._chromeUserDataFolder.clone(); + defaultProfileFolder.append("Default"); + if (defaultProfileFolder.exists()) { + profiles = [{ + id: "Default", + name: "Default", + }]; + } + } + + // Only list profiles from which any data can be imported + return this.__sourceProfiles = profiles.filter(function(profile) { + let resources = this.getResources(profile); + return resources && resources.length > 0; + }, this); + } +}); + +Object.defineProperty(ChromeProfileMigrator.prototype, "sourceHomePageURL", { + get: function Chrome_sourceHomePageURL() { + let prefsFile = this._chromeUserDataFolder.clone(); + prefsFile.append("Preferences"); + if (prefsFile.exists()) { + // XXX reading and parsing JSON is synchronous. + let fstream = Cc[FILE_INPUT_STREAM_CID]. + createInstance(Ci.nsIFileInputStream); + fstream.init(file, -1, 0, 0); + try { + return JSON.parse( + NetUtil.readInputStreamToString(fstream, fstream.available(), + { charset: "UTF-8" }) + ).homepage; + } + catch(e) { + Cu.reportError("Error parsing Chrome's preferences file: " + e); + } + } + return ""; + } +}); + +function GetBookmarksResource(aProfileFolder) { + let bookmarksFile = aProfileFolder.clone(); + bookmarksFile.append("Bookmarks"); + if (!bookmarksFile.exists()) + return null; + + return { + type: MigrationUtils.resourceTypes.BOOKMARKS, + + migrate: function(aCallback) { + NetUtil.asyncFetch(bookmarksFile, MigrationUtils.wrapMigrateFunction( + function(aInputStream, aResultCode) { + if (!Components.isSuccessCode(aResultCode)) + throw new Error("Could not read Bookmarks file"); + + // Parse Chrome bookmark file that is JSON format + let bookmarkJSON = NetUtil.readInputStreamToString( + aInputStream, aInputStream.available(), { charset : "UTF-8" }); + let roots = JSON.parse(bookmarkJSON).roots; + PlacesUtils.bookmarks.runInBatchMode({ + runBatched: function() { + // Importing bookmark bar items + if (roots.bookmark_bar.children && + roots.bookmark_bar.children.length > 0) { + // Toolbar + let parentId = PlacesUtils.toolbarFolderId; + if (!MigrationUtils.isStartupMigration) { + parentId = MigrationUtils.createImportedBookmarksFolder( + "Chrome", parentId); + } + insertBookmarkItems(parentId, roots.bookmark_bar.children); + } + + // Importing bookmark menu items + if (roots.other.children && + roots.other.children.length > 0) { + // Bookmark menu + let parentId = PlacesUtils.bookmarksMenuFolderId; + if (!MigrationUtils.isStartupMigration) { + parentId = MigrationUtils.createImportedBookmarksFolder( + "Chrome", parentId); + } + insertBookmarkItems(parentId, roots.other.children); + } + } + }, null); + }, aCallback)); + } + }; +} + +function GetHistoryResource(aProfileFolder) { + let historyFile = aProfileFolder.clone(); + historyFile.append("History"); + if (!historyFile.exists()) + return null; + + return { + type: MigrationUtils.resourceTypes.HISTORY, + + migrate: function(aCallback) { + let dbConn = Services.storage.openUnsharedDatabase(historyFile); + let stmt = dbConn.createAsyncStatement( + "SELECT url, title, last_visit_time, typed_count FROM urls WHERE hidden = 0"); + + stmt.executeAsync({ + handleResult : function(aResults) { + let places = []; + for (let row = aResults.getNextRow(); row; row = aResults.getNextRow()) { + try { + // if having typed_count, we changes transition type to typed. + let transType = PlacesUtils.history.TRANSITION_LINK; + if (row.getResultByName("typed_count") > 0) + transType = PlacesUtils.history.TRANSITION_TYPED; + + places.push({ + uri: NetUtil.newURI(row.getResultByName("url")), + title: row.getResultByName("title"), + visits: [{ + transitionType: transType, + visitDate: chromeTimeToDate( + row.getResultByName( + "last_visit_time")) * 1000, + }], + }); + } catch (e) { + Cu.reportError(e); + } + } + + try { + PlacesUtils.asyncHistory.updatePlaces(places); + } catch (e) { + Cu.reportError(e); + } + }, + + handleError : function(aError) { + Cu.reportError("Async statement execution returned with '" + + aError.result + "', '" + aError.message + "'"); + }, + + handleCompletion : function(aReason) { + dbConn.asyncClose(); + aCallback(aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED); + } + }); + stmt.finalize(); + } + }; +} + +function GetCookiesResource(aProfileFolder) { + let cookiesFile = aProfileFolder.clone(); + cookiesFile.append("Cookies"); + if (!cookiesFile.exists()) + return null; + + return { + type: MigrationUtils.resourceTypes.COOKIES, + + migrate: function(aCallback) { + let dbConn = Services.storage.openUnsharedDatabase(cookiesFile); + let stmt = dbConn.createAsyncStatement( + "SELECT host_key, path, name, value, secure, httponly, expires_utc FROM cookies"); + + stmt.executeAsync({ + handleResult : function(aResults) { + for (let row = aResults.getNextRow(); row; row = aResults.getNextRow()) { + let host_key = row.getResultByName("host_key"); + if (host_key.match(/^\./)) { + // 1st character of host_key may be ".", so we have to remove it + host_key = host_key.substr(1); + } + + try { + let expiresUtc = + chromeTimeToDate(row.getResultByName("expires_utc")) / 1000; + Services.cookies.add(host_key, + row.getResultByName("path"), + row.getResultByName("name"), + row.getResultByName("value"), + row.getResultByName("secure"), + row.getResultByName("httponly"), + false, + parseInt(expiresUtc)); + } catch (e) { + Cu.reportError(e); + } + } + }, + + handleError : function(aError) { + Cu.reportError("Async statement execution returned with '" + + aError.result + "', '" + aError.message + "'"); + }, + + handleCompletion : function(aReason) { + dbConn.asyncClose(); + aCallback(aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED); + }, + }); + stmt.finalize(); + } + } +} + +function GetWindowsPasswordsResource(aProfileFolder) { + let loginFile = aProfileFolder.clone(); + loginFile.append("Login Data"); + if (!loginFile.exists()) + return null; + + return { + type: MigrationUtils.resourceTypes.PASSWORDS, + + migrate(aCallback) { + let dbConn = Services.storage.openUnsharedDatabase(loginFile); + let stmt = dbConn.createAsyncStatement(` + SELECT origin_url, action_url, username_element, username_value, + password_element, password_value, signon_realm, scheme, date_created, + times_used FROM logins WHERE blacklisted_by_user = 0`); + let crypto = new OSCrypto(); + let utf8Converter = Cc["@mozilla.org/intl/utf8converterservice;1"].getService(Ci.nsIUTF8ConverterService); + + stmt.executeAsync({ + _rowToLoginInfo(row) { + let loginInfo = { + username: utf8Converter.convertURISpecToUTF8(row.getResultByName("username_value"), "UTF-8"), + password: utf8Converter.convertURISpecToUTF8( + crypto.decryptData(crypto.arrayToString(row.getResultByName("password_value")), null), + "UTF-8"), + hostName: NetUtil.newURI(row.getResultByName("origin_url")).prePath, + submitURL: null, + httpRealm: null, + usernameElement: row.getResultByName("username_element"), + passwordElement: row.getResultByName("password_element"), + timeCreated: chromeTimeToDate(row.getResultByName("date_created") + 0).getTime(), + timesUsed: row.getResultByName("times_used") + 0, + }; + + switch (row.getResultByName("scheme")) { + case AUTH_TYPE.SCHEME_HTML: + loginInfo.submitURL = NetUtil.newURI(row.getResultByName("action_url")).prePath; + break; + case AUTH_TYPE.SCHEME_BASIC: + case AUTH_TYPE.SCHEME_DIGEST: + // signon_realm format is URIrealm, so we need remove URI + loginInfo.httpRealm = row.getResultByName("signon_realm") + .substring(loginInfo.hostName.length + 1); + break; + default: + throw new Error("Login data scheme type not supported: " + + row.getResultByName("scheme")); + } + + return loginInfo; + }, + + handleResult(aResults) { + for (let row = aResults.getNextRow(); row; row = aResults.getNextRow()) { + try { + let loginInfo = this._rowToLoginInfo(row); + let login = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo); + + login.init(loginInfo.hostName, loginInfo.submitURL, loginInfo.httpRealm, + loginInfo.username, loginInfo.password, loginInfo.usernameElement, + loginInfo.passwordElement); + login.QueryInterface(Ci.nsILoginMetaInfo); + login.timeCreated = loginInfo.timeCreated; + login.timeLastUsed = loginInfo.timeCreated; + login.timePasswordChanged = loginInfo.timeCreated; + login.timesUsed = loginInfo.timesUsed; + + // Add the login only if there's not an existing entry + let logins = Services.logins.findLogins({}, login.hostname, + login.formSubmitURL, + login.httpRealm); + + // Bug 1187190: Password changes should be propagated depending on timestamps. + if (!logins.some(l => login.matches(l, true))) { + Services.logins.addLogin(login); + } + } catch (e) { + Cu.reportError(e); + } + } + }, + + handleError(aError) { + Cu.reportError("Async statement execution returned with '" + + aError.result + "', '" + aError.message + "'"); + }, + + handleCompletion(aReason) { + dbConn.asyncClose(); + aCallback(aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED); + crypto.finalize(); + }, + }); + stmt.finalize(); + } + }; +} + +ChromeProfileMigrator.prototype.classDescription = "Chrome Profile Migrator"; +ChromeProfileMigrator.prototype.contractID = "@mozilla.org/profile/migrator;1?app=browser&type=chrome"; +ChromeProfileMigrator.prototype.classID = Components.ID("{4cec1de4-1671-4fc3-a53e-6c539dc77a26}"); + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([ChromeProfileMigrator]); diff --git a/application/palemoon/components/migration/FirefoxProfileMigrator.js b/application/palemoon/components/migration/FirefoxProfileMigrator.js new file mode 100644 index 000000000..ab4ae55fb --- /dev/null +++ b/application/palemoon/components/migration/FirefoxProfileMigrator.js @@ -0,0 +1,117 @@ +/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- + * vim: sw=2 ts=2 sts=2 et */ + /* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/* + * Migrates from a Pale Moon profile in a lossy manner in order to clean up a + * user's profile. Data is only migrated where the benefits outweigh the + * potential problems caused by importing undesired/invalid configurations + * from the source profile. + */ + +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); +Components.utils.import("resource:///modules/MigrationUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PlacesBackups", + "resource://gre/modules/PlacesBackups.jsm"); + +function FirefoxProfileMigrator() { } + +FirefoxProfileMigrator.prototype = Object.create(MigratorPrototype); + +FirefoxProfileMigrator.prototype._getAllProfiles = function () { + let allProfiles = new Map(); + let profiles = + Components.classes["@mozilla.org/toolkit/profile-service;1"] + .getService(Components.interfaces.nsIToolkitProfileService) + .profiles; + while (profiles.hasMoreElements()) { + let profile = profiles.getNext().QueryInterface(Components.interfaces.nsIToolkitProfile); + let rootDir = profile.rootDir; + + if (rootDir.exists() && rootDir.isReadable() && + !rootDir.equals(MigrationUtils.profileStartup.directory)) { + allProfiles.set(profile.name, rootDir); + } + } + return allProfiles; +}; + +function sorter(a, b) { + return a.id.toLocaleLowerCase().localeCompare(b.id.toLocaleLowerCase()); +} + +Object.defineProperty(FirefoxProfileMigrator.prototype, "sourceProfiles", { + get: function() { + return [{id: x, name: x} for (x of this._getAllProfiles().keys())].sort(sorter); + } +}); + +FirefoxProfileMigrator.prototype.getResources = function(aProfile) { + let sourceProfileDir = aProfile ? this._getAllProfiles().get(aProfile.id) : + Components.classes["@mozilla.org/toolkit/profile-service;1"] + .getService(Components.interfaces.nsIToolkitProfileService) + .selectedProfile.rootDir; + if (!sourceProfileDir || !sourceProfileDir.exists() || + !sourceProfileDir.isReadable()) + return null; + + // Being a startup-only migrator, we can rely on + // MigrationUtils.profileStartup being set. + let currentProfileDir = MigrationUtils.profileStartup.directory; + + // Surely data cannot be imported from the current profile. + if (sourceProfileDir.equals(currentProfileDir)) + return null; + + let getFileResource = function(aMigrationType, aFileNames) { + let files = []; + for (let fileName of aFileNames) { + let file = sourceProfileDir.clone(); + file.append(fileName); + + if (file.exists()) { + files.push(file); + } + } + if (!files.length) { + return null; + } + return { + type: aMigrationType, + migrate: function(aCallback) { + for (let file of files) { + file.copyTo(currentProfileDir, ""); + } + aCallback(true); + } + }; + }; + + let types = MigrationUtils.resourceTypes; + let places = getFileResource(types.HISTORY, ["places.sqlite", "places.sqlite-wal"]); + let cookies = getFileResource(types.COOKIES, ["cookies.sqlite", "cookies.sqlite-wal"]); + let passwords = getFileResource(types.PASSWORDS, + ["signons.sqlite", "logins.json", "key3.db"]); + let formData = getFileResource(types.FORMDATA, ["formhistory.sqlite"]); + let bookmarksBackups = getFileResource(types.OTHERDATA, + [PlacesBackups.profileRelativeFolderPath]); + let dictionary = getFileResource(types.OTHERDATA, ["persdict.dat"]); + + return [r for each (r in [places, cookies, passwords, formData, + dictionary, bookmarksBackups]) if (r)]; +} + +Object.defineProperty(FirefoxProfileMigrator.prototype, "startupOnlyMigrator", { + get: function() true +}); + + +FirefoxProfileMigrator.prototype.classDescription = "Firefox Profile Migrator"; +FirefoxProfileMigrator.prototype.contractID = "@mozilla.org/profile/migrator;1?app=browser&type=firefox"; +FirefoxProfileMigrator.prototype.classID = Components.ID("{91185366-ba97-4438-acba-48deaca63386}"); + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([FirefoxProfileMigrator]); diff --git a/application/palemoon/components/migration/IEProfileMigrator.js b/application/palemoon/components/migration/IEProfileMigrator.js new file mode 100644 index 000000000..a46deae68 --- /dev/null +++ b/application/palemoon/components/migration/IEProfileMigrator.js @@ -0,0 +1,521 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; +const Cr = Components.results; + +const kMainKey = "Software\\Microsoft\\Internet Explorer\\Main"; +const kRegMultiSz = 7; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/NetUtil.jsm"); +Cu.import("resource:///modules/MigrationUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", + "resource://gre/modules/PlacesUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ctypes", + "resource://gre/modules/ctypes.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "WindowsRegistry", + "resource://gre/modules/WindowsRegistry.jsm"); + +Cu.importGlobalProperties(["File"]); + +//////////////////////////////////////////////////////////////////////////////// +//// Helpers. + +let CtypesHelpers = { + _structs: {}, + _functions: {}, + _libs: {}, + + /** + * Must be invoked once before first use of any of the provided helpers. + */ + initialize: function CH_initialize() { + const WORD = ctypes.uint16_t; + const DWORD = ctypes.uint32_t; + const BOOL = ctypes.int; + + this._structs.SYSTEMTIME = new ctypes.StructType('SYSTEMTIME', [ + {wYear: WORD}, + {wMonth: WORD}, + {wDayOfWeek: WORD}, + {wDay: WORD}, + {wHour: WORD}, + {wMinute: WORD}, + {wSecond: WORD}, + {wMilliseconds: WORD} + ]); + + this._structs.FILETIME = new ctypes.StructType('FILETIME', [ + {dwLowDateTime: DWORD}, + {dwHighDateTime: DWORD} + ]); + + try { + this._libs.kernel32 = ctypes.open("Kernel32"); + this._functions.FileTimeToSystemTime = + this._libs.kernel32.declare("FileTimeToSystemTime", + ctypes.default_abi, + BOOL, + this._structs.FILETIME.ptr, + this._structs.SYSTEMTIME.ptr); + } catch (ex) { + this.finalize(); + } + }, + + /** + * Must be invoked once after last use of any of the provided helpers. + */ + finalize: function CH_finalize() { + this._structs = {}; + this._functions = {}; + for each (let lib in this._libs) { + try { + lib.close(); + } catch (ex) {} + } + this._libs = {}; + }, + + /** + * Converts a FILETIME struct (2 DWORDS), to a SYSTEMTIME struct. + * + * @param aTimeHi + * Least significant DWORD. + * @param aTimeLo + * Most significant DWORD. + * @return a Date object representing the converted datetime. + */ + fileTimeToDate: function CH_fileTimeToDate(aTimeHi, aTimeLo) { + let fileTime = this._structs.FILETIME(); + fileTime.dwLowDateTime = aTimeLo; + fileTime.dwHighDateTime = aTimeHi; + let systemTime = this._structs.SYSTEMTIME(); + let result = this._functions.FileTimeToSystemTime(fileTime.address(), + systemTime.address()); + if (result == 0) + throw new Error(ctypes.winLastError); + + return new Date(systemTime.wYear, + systemTime.wMonth - 1, + systemTime.wDay, + systemTime.wHour, + systemTime.wMinute, + systemTime.wSecond, + systemTime.wMilliseconds); + } +}; + +/** + * Checks whether an host is an IP (v4 or v6) address. + * + * @param aHost + * The host to check. + * @return whether aHost is an IP address. + */ +function hostIsIPAddress(aHost) { + try { + Services.eTLD.getBaseDomainFromHost(aHost); + } catch (e if e.result == Cr.NS_ERROR_HOST_IS_IP_ADDRESS) { + return true; + } catch (e) {} + return false; +} + +//////////////////////////////////////////////////////////////////////////////// +//// Resources + +function Bookmarks() { +} + +Bookmarks.prototype = { + type: MigrationUtils.resourceTypes.BOOKMARKS, + + get exists() !!this._favoritesFolder, + + __favoritesFolder: null, + get _favoritesFolder() { + if (!this.__favoritesFolder) { + let favoritesFolder = Services.dirsvc.get("Favs", Ci.nsIFile); + if (favoritesFolder.exists() && favoritesFolder.isReadable()) + this.__favoritesFolder = favoritesFolder; + } + return this.__favoritesFolder; + }, + + __toolbarFolderName: null, + get _toolbarFolderName() { + if (!this.__toolbarFolderName) { + // Retrieve the name of IE's favorites subfolder that holds the bookmarks + // in the toolbar. This was previously stored in the registry and changed + // in IE7 to always be called "Links". + let folderName = WindowsRegistry.readRegKey(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, + "Software\\Microsoft\\Internet Explorer\\Toolbar", + "LinksFolderName"); + this.__toolbarFolderName = folderName || "Links"; + } + return this.__toolbarFolderName; + }, + + migrate: function B_migrate(aCallback) { + PlacesUtils.bookmarks.runInBatchMode({ + runBatched: (function migrateBatched() { + // Import to the bookmarks menu. + let destFolderId = PlacesUtils.bookmarksMenuFolderId; + if (!MigrationUtils.isStartupMigration) { + destFolderId = + MigrationUtils.createImportedBookmarksFolder("IE", destFolderId); + } + + this._migrateFolder(this._favoritesFolder, destFolderId); + + aCallback(true); + }).bind(this) + }, null); + }, + + _migrateFolder: function B__migrateFolder(aSourceFolder, aDestFolderId) { + // TODO (bug 741993): the favorites order is stored in the Registry, at + // HCU\Software\Microsoft\Windows\CurrentVersion\Explorer\MenuOrder\Favorites + // Until we support it, bookmarks are imported in alphabetical order. + let entries = aSourceFolder.directoryEntries; + while (entries.hasMoreElements()) { + let entry = entries.getNext().QueryInterface(Ci.nsIFile); + + // Make sure that entry.path == entry.target to not follow .lnk folder + // shortcuts which could lead to infinite cycles. + if (entry.isDirectory() && entry.path == entry.target) { + let destFolderId; + if (entry.leafName == this._toolbarFolderName && + entry.parent.equals(this._favoritesFolder)) { + // Import to the bookmarks toolbar. + destFolderId = PlacesUtils.toolbarFolderId; + if (!MigrationUtils.isStartupMigration) { + destFolderId = + MigrationUtils.createImportedBookmarksFolder("IE", destFolderId); + } + } + else { + // Import to a new folder. + destFolderId = + PlacesUtils.bookmarks.createFolder(aDestFolderId, entry.leafName, + PlacesUtils.bookmarks.DEFAULT_INDEX); + } + + if (entry.isReadable()) { + // Recursively import the folder. + this._migrateFolder(entry, destFolderId); + } + } + else { + // Strip the .url extension, to both check this is a valid link file, + // and get the associated title. + let matches = entry.leafName.match(/(.+)\.url$/i); + if (matches) { + let fileHandler = Cc["@mozilla.org/network/protocol;1?name=file"]. + getService(Ci.nsIFileProtocolHandler); + let uri = fileHandler.readURLFile(entry); + let title = matches[1]; + + PlacesUtils.bookmarks.insertBookmark(aDestFolderId, + uri, + PlacesUtils.bookmarks.DEFAULT_INDEX, + title); + } + } + } + } +}; + +function History() { +} + +History.prototype = { + type: MigrationUtils.resourceTypes.HISTORY, + + get exists() true, + + __typedURLs: null, + get _typedURLs() { + if (!this.__typedURLs) { + // The list of typed URLs is a sort of annotation stored in the registry. + // Currently, IE stores 25 entries and this value is not configurable, + // but we just keep reading up to the first non-existing entry to support + // possible future bumps of this limit. + this.__typedURLs = {}; + let registry = Cc["@mozilla.org/windows-registry-key;1"]. + createInstance(Ci.nsIWindowsRegKey); + try { + registry.open(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, + "Software\\Microsoft\\Internet Explorer\\TypedURLs", + Ci.nsIWindowsRegKey.ACCESS_READ); + for (let entry = 1; registry.hasValue("url" + entry); entry++) { + let url = registry.readStringValue("url" + entry); + this.__typedURLs[url] = true; + } + } catch (ex) { + } finally { + registry.close(); + } + } + return this.__typedURLs; + }, + + migrate: function H_migrate(aCallback) { + let places = []; + let historyEnumerator = Cc["@mozilla.org/profile/migrator/iehistoryenumerator;1"]. + createInstance(Ci.nsISimpleEnumerator); + while (historyEnumerator.hasMoreElements()) { + let entry = historyEnumerator.getNext().QueryInterface(Ci.nsIPropertyBag2); + let uri = entry.get("uri").QueryInterface(Ci.nsIURI); + // MSIE stores some types of URLs in its history that we don't handle, + // like HTMLHelp and others. Since we don't properly map handling for + // all of them we just avoid importing them. + if (["http", "https", "ftp", "file"].indexOf(uri.scheme) == -1) { + continue; + } + + let title = entry.get("title"); + // Embed visits have no title and don't need to be imported. + if (title.length == 0) { + continue; + } + + // The typed urls are already fixed-up, so we can use them for comparison. + let transitionType = this._typedURLs[uri.spec] ? + Ci.nsINavHistoryService.TRANSITION_TYPED : + Ci.nsINavHistoryService.TRANSITION_LINK; + let lastVisitTime = entry.get("time"); + + places.push( + { uri: uri, + title: title, + visits: [{ transitionType: transitionType, + visitDate: lastVisitTime }] + } + ); + } + + // Check whether there is any history to import. + if (places.length == 0) { + aCallback(true); + return; + } + + PlacesUtils.asyncHistory.updatePlaces(places, { + _success: false, + handleResult: function() { + // Importing any entry is considered a successful import. + this._success = true; + }, + handleError: function() {}, + handleCompletion: function() { + aCallback(this._success); + } + }); + } +}; + +function Cookies() { +} + +Cookies.prototype = { + type: MigrationUtils.resourceTypes.COOKIES, + + get exists() !!this._cookiesFolder, + + __cookiesFolder: null, + get _cookiesFolder() { + // Cookies are stored in txt files, in a Cookies folder whose path varies + // across the different OS versions. CookD takes care of most of these + // cases, though, in Windows Vista/7, UAC makes a difference. + // If UAC is enabled, the most common destination is CookD/Low. Though, + // if the user runs the application in administrator mode or disables UAC, + // cookies are stored in the original CookD destination. Cause running the + // browser in administrator mode is unsafe and discouraged, we just care + // about the UAC state. + if (!this.__cookiesFolder) { + let cookiesFolder = Services.dirsvc.get("CookD", Ci.nsIFile); + if (cookiesFolder.exists() && cookiesFolder.isReadable()) { + // Check if UAC is enabled. + if (Services.appinfo.QueryInterface(Ci.nsIWinAppHelper).userCanElevate) { + cookiesFolder.append("Low"); + } + this.__cookiesFolder = cookiesFolder; + } + } + return this.__cookiesFolder; + }, + + migrate: function C_migrate(aCallback) { + CtypesHelpers.initialize(); + + let cookiesGenerator = (function genCookie() { + let success = false; + let entries = this._cookiesFolder.directoryEntries; + while (entries.hasMoreElements()) { + let entry = entries.getNext().QueryInterface(Ci.nsIFile); + // Skip eventual bogus entries. + if (!entry.isFile() || !/\.txt$/.test(entry.leafName)) + continue; + + this._readCookieFile(entry, function(aSuccess) { + // Importing even a single cookie file is considered a success. + if (aSuccess) + success = true; + try { + cookiesGenerator.next(); + } catch (ex) {} + }); + + yield; + } + + CtypesHelpers.finalize(); + + aCallback(success); + }).apply(this); + cookiesGenerator.next(); + }, + + _readCookieFile: function C__readCookieFile(aFile, aCallback) { + let fileReader = Cc["@mozilla.org/files/filereader;1"]. + createInstance(Ci.nsIDOMFileReader); + fileReader.addEventListener("loadend", (function onLoadEnd() { + fileReader.removeEventListener("loadend", onLoadEnd, false); + + if (fileReader.readyState != fileReader.DONE) { + Cu.reportError("Could not read cookie contents: " + fileReader.error); + aCallback(false); + return; + } + + let success = true; + try { + this._parseCookieBuffer(fileReader.result); + } catch (ex) { + Components.utils.reportError("Unable to migrate cookie: " + ex); + success = false; + } finally { + aCallback(success); + } + }).bind(this), false); + fileReader.readAsText(new File(aFile)); + }, + + /** + * Parses a cookie file buffer and returns an array of the contained cookies. + * + * The cookie file format is a newline-separated-values with a "*" used as + * delimeter between multiple records. + * Each cookie has the following fields: + * - name + * - value + * - host/path + * - flags + * - Expiration time most significant integer + * - Expiration time least significant integer + * - Creation time most significant integer + * - Creation time least significant integer + * - Record delimiter "*" + * + * @note All the times are in FILETIME format. + */ + _parseCookieBuffer: function C__parseCookieBuffer(aTextBuffer) { + // Note the last record is an empty string. + let records = [r for each (r in aTextBuffer.split("*\n")) if (r)]; + for (let record of records) { + let [name, value, hostpath, flags, + expireTimeLo, expireTimeHi] = record.split("\n"); + + // IE stores deleted cookies with a zero-length value, skip them. + if (value.length == 0) + continue; + + let hostLen = hostpath.indexOf("/"); + let host = hostpath.substr(0, hostLen); + let path = hostpath.substr(hostLen); + + // For a non-null domain, assume it's what Mozilla considers + // a domain cookie. See bug 222343. + if (host.length > 0) { + // Fist delete any possible extant matching host cookie. + Services.cookies.remove(host, name, path, false); + // Now make it a domain cookie. + if (host[0] != "." && !hostIsIPAddress(host)) + host = "." + host; + } + + let expireTime = CtypesHelpers.fileTimeToDate(Number(expireTimeHi), + Number(expireTimeLo)); + Services.cookies.add(host, + path, + name, + value, + Number(flags) & 0x1, // secure + false, // httpOnly + false, // session + expireTime); + } + } +}; + + +//////////////////////////////////////////////////////////////////////////////// +//// Migrator + +function IEProfileMigrator() +{ +} + +IEProfileMigrator.prototype = Object.create(MigratorPrototype); + +IEProfileMigrator.prototype.getResources = function IE_getResources() { + let resources = [ + new Bookmarks() + , new History() + , new Cookies() + ]; + return [r for each (r in resources) if (r.exists)]; +}; + +Object.defineProperty(IEProfileMigrator.prototype, "sourceHomePageURL", { + get: function IE_get_sourceHomePageURL() { + let defaultStartPage = WindowsRegistry.readRegKey(Ci.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE, + kMainKey, "Default_Page_URL"); + let startPage = WindowsRegistry.readRegKey(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, + kMainKey, "Start Page"); + // If the user didn't customize the Start Page, he is still on the default + // page, that may be considered the equivalent of our about:home. There's + // no reason to retain it, since it is heavily targeted to IE. + let homepage = startPage != defaultStartPage ? startPage : ""; + + // IE7+ supports secondary home pages located in a REG_MULTI_SZ key. These + // are in addition to the Start Page, and no empty entries are possible, + // thus a Start Page is always defined if any of these exists, though it + // may be the default one. + let secondaryPages = WindowsRegistry.readRegKey(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, + kMainKey, "Secondary Start Pages"); + if (secondaryPages) { + if (homepage) + secondaryPages.unshift(homepage); + homepage = secondaryPages.join("|"); + } + + return homepage; + } +}); + +IEProfileMigrator.prototype.classDescription = "IE Profile Migrator"; +IEProfileMigrator.prototype.contractID = "@mozilla.org/profile/migrator;1?app=browser&type=ie"; +IEProfileMigrator.prototype.classID = Components.ID("{3d2532e3-4932-4774-b7ba-968f5899d3a4}"); + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([IEProfileMigrator]); diff --git a/application/palemoon/components/migration/MigrationUtils.jsm b/application/palemoon/components/migration/MigrationUtils.jsm new file mode 100644 index 000000000..fcd73a798 --- /dev/null +++ b/application/palemoon/components/migration/MigrationUtils.jsm @@ -0,0 +1,644 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +this.EXPORTED_SYMBOLS = ["MigrationUtils", "MigratorPrototype"]; + +const Cu = Components.utils; +const Ci = Components.interfaces; +const Cc = Components.classes; + +const TOPIC_WILL_IMPORT_BOOKMARKS = "initial-migration-will-import-default-bookmarks"; +const TOPIC_DID_IMPORT_BOOKMARKS = "initial-migration-did-import-default-bookmarks"; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "Dict", + "resource://gre/modules/Dict.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", + "resource://gre/modules/PlacesUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "BookmarkHTMLUtils", + "resource://gre/modules/BookmarkHTMLUtils.jsm"); + +let gMigrators = null; +let gProfileStartup = null; +let gMigrationBundle = null; + +function getMigrationBundle() { + if (!gMigrationBundle) { + gMigrationBundle = Services.strings.createBundle( + "chrome://browser/locale/migration/migration.properties"); + } + return gMigrationBundle; +} + +/** + * Figure out what is the default browser, and if there is a migrator + * for it, return that migrator's internal name. + * For the time being, the "internal name" of a migraotr is its contract-id + * trailer (e.g. ie for @mozilla.org/profile/migrator;1?app=browser&type=ie), + * but it will soon be exposed properly. + */ +function getMigratorKeyForDefaultBrowser() { + const APP_DESC_TO_KEY = { + "Internet Explorer": "ie", + "Safari": "safari", + "Pale Moon web browser": "firefox", + "Google Chrome": "chrome", // Windows, Linux + "Chrome": "chrome", // OS X + }; + + let browserDesc = ""; + try { + let browserDesc = + Cc["@mozilla.org/uriloader/external-protocol-service;1"]. + getService(Ci.nsIExternalProtocolService). + getApplicationDescription("http"); + return APP_DESC_TO_KEY[browserDesc] || ""; + } + catch(ex) { + Cu.reportError("Could not detect default browser: " + ex); + } + return ""; +} + +/** + * Shared prototype for migrators, implementing nsIBrowserProfileMigrator. + * + * To implement a migrator: + * 1. Import this module. + * 2. Create the prototype for the migrator, extending MigratorPrototype. + * Namely: MosaicMigrator.prototype = Object.create(MigratorPrototype); + * 3. Set classDescription, contractID and classID for your migrator, and set + * NSGetFactory appropriately. + * 4. If the migrator supports multiple profiles, override the sourceProfiles + * Here we default for single-profile migrator. + * 5. Implement getResources(aProfile) (see below). + * 6. If the migrator supports reading the home page of the source browser, + * override |sourceHomePageURL| getter. + * 7. For startup-only migrators, override |startupOnlyMigrator|. + */ +this.MigratorPrototype = { + QueryInterface: XPCOMUtils.generateQI([Ci.nsIBrowserProfileMigrator]), + + /** + * OVERRIDE IF AND ONLY IF the source supports multiple profiles. + * + * Returns array of profile objects from which data may be imported. The object + * should have the following keys: + * id - a unique string identifier for the profile + * name - a pretty name to display to the user in the UI + * + * Only profiles from which data can be imported should be listed. Otherwise + * the behavior of the migration wizard isn't well-defined. + * + * For a single-profile source (e.g. safari, ie), this returns null, + * and not an empty array. That is the default implementation. + */ + get sourceProfiles() null, + + /** + * MUST BE OVERRIDDEN. + * + * Returns an array of "migration resources" objects for the given profile, + * or for the "default" profile, if the migrator does not support multiple + * profiles. + * + * Each migration resource should provide: + * - a |type| getter, retunring any of the migration types (see + * nsIBrowserProfileMigrator). + * + * - a |migrate| method, taking a single argument, aCallback(bool success), + * for migrating the data for this resource. It may do its job + * synchronously or asynchronously. Either way, it must call + * aCallback(bool aSuccess) when it's done. In the case of an exception + * thrown from |migrate|, it's taken as if aCallback(false) is called. + * + * Note: In the case of a simple asynchronous implementation, you may find + * MigrationUtils.wrapMigrateFunction handy for handling aCallback easily. + * + * For each migration type listed in nsIBrowserProfileMigrator, multiple + * migration resources may be provided. This practice is useful when the + * data for a certain migration type is independently stored in few + * locations. For example, the mac version of Safari stores its "reading list" + * bookmarks in a separate property list. + * + * Note that the importation of a particular migration type is reported as + * successful if _any_ of its resources succeeded to import (that is, called, + * |aCallback(true)|). However, completion-status for a particular migration + * type is reported to the UI only once all of its migrators have called + * aCallback. + * + * @note The returned array should only include resources from which data + * can be imported. So, for example, before adding a resource for the + * BOOKMARKS migration type, you should check if you should check that the + * bookmarks file exists. + * + * @param aProfile + * The profile from which data may be imported, or an empty string + * in the case of a single-profile migrator. + * In the case of multiple-profiles migrator, it is guaranteed that + * aProfile is a value returned by the sourceProfiles getter (see + * above). + */ + getResources: function MP_getResources(aProfile) { + throw new Error("getResources must be overridden"); + }, + + /** + * OVERRIDE IF AND ONLY IF the migrator is a startup-only migrator (For now, + * that is just the Firefox migrator, see bug 737381). Default: false. + * + * Startup-only migrators are different in two ways: + * - they may only be used during startup. + * - the user-profile is half baked during migration. The folder exists, + * but it's only accessible through MigrationUtils.profileStartup. + * The migrator can call MigrationUtils.profileStartup.doStartup + * at any point in order to initialize the profile. + */ + get startupOnlyMigrator() false, + + /** + * OVERRIDE IF AND ONLY IF your migrator supports importing the homepage. + * @see nsIBrowserProfileMigrator + */ + get sourceHomePageURL() "", + + /** + * DO NOT OVERRIDE - After deCOMing migration, the UI will just call + * getResources. + * + * @see nsIBrowserProfileMigrator + */ + getMigrateData: function MP_getMigrateData(aProfile) { + let types = [r.type for each (r in this._getMaybeCachedResources(aProfile))]; + return types.reduce(function(a, b) a |= b, 0); + }, + + /** + * DO NOT OVERRIDE - After deCOMing migration, the UI will just call + * migrate for each resource. + * + * @see nsIBrowserProfileMigrator + */ + migrate: function MP_migrate(aItems, aStartup, aProfile) { + let resources = this._getMaybeCachedResources(aProfile); + if (resources.length == 0) + throw new Error("migrate called for a non-existent source"); + + if (aItems != Ci.nsIBrowserProfileMigrator.ALL) + resources = [r for each (r in resources) if (aItems & r.type)]; + + // Called either directly or through the bookmarks import callback. + function doMigrate() { + // TODO: use Map (for the items) and Set (for the resources) + // once they are iterable. + let resourcesGroupedByItems = new Dict(); + resources.forEach(function(resource) { + if (resourcesGroupedByItems.has(resource.type)) + resourcesGroupedByItems.get(resource.type).push(resource); + else + resourcesGroupedByItems.set(resource.type, [resource]); + }); + + if (resourcesGroupedByItems.count == 0) + throw new Error("No items to import"); + + let notify = function(aMsg, aItemType) { + Services.obs.notifyObservers(null, aMsg, aItemType); + } + + notify("Migration:Started"); + resourcesGroupedByItems.listkeys().forEach(function(migrationType) { + let migrationTypeA = migrationType; + let itemResources = resourcesGroupedByItems.get(migrationType); + notify("Migration:ItemBeforeMigrate", migrationType); + + let itemSuccess = false; + itemResources.forEach(function(resource) { + let resourceDone = function(aSuccess) { + let resourceIndex = itemResources.indexOf(resource); + if (resourceIndex != -1) { + itemResources.splice(resourceIndex, 1); + itemSuccess |= aSuccess; + if (itemResources.length == 0) { + resourcesGroupedByItems.del(migrationType); + notify(itemSuccess ? + "Migration:ItemAfterMigrate" : "Migration:ItemError", + migrationType); + if (resourcesGroupedByItems.count == 0) + notify("Migration:Ended"); + } + } + }; + + Services.tm.mainThread.dispatch(function() { + // If migrate throws, an error occurred, and the callback + // (itemMayBeDone) might haven't been called. + try { + resource.migrate(resourceDone); + } + catch(ex) { + Cu.reportError(ex); + resourceDone(false); + } + }, Ci.nsIThread.DISPATCH_NORMAL); + }); + }); + } + + if (MigrationUtils.isStartupMigration && !this.startupOnlyMigrator) { + MigrationUtils.profileStartup.doStartup(); + + // If we're about to migrate bookmarks, first import the default bookmarks. + // Note We do not need to do so for the Firefox migrator + // (=startupOnlyMigrator), as it just copies over the places database + // from another profile. + const BOOKMARKS = MigrationUtils.resourceTypes.BOOKMARKS; + let migratingBookmarks = resources.some(function(r) r.type == BOOKMARKS); + if (migratingBookmarks) { + let browserGlue = Cc["@mozilla.org/browser/browserglue;1"]. + getService(Ci.nsIObserver); + browserGlue.observe(null, TOPIC_WILL_IMPORT_BOOKMARKS, ""); + + // Note doMigrate doesn't care about the success of the import. + let onImportComplete = function() { + browserGlue.observe(null, TOPIC_DID_IMPORT_BOOKMARKS, ""); + doMigrate(); + }; + BookmarkHTMLUtils.importFromURL( + "resource:///defaults/profile/bookmarks.html", true).then( + onImportComplete, onImportComplete); + return; + } + } + doMigrate(); + }, + + /** + * DO NOT OVERRIDE - After deCOMing migration, this code + * won't be part of the migrator itself. + * + * @see nsIBrowserProfileMigrator + */ + get sourceExists() { + if (this.startupOnlyMigrator && !MigrationUtils.isStartupMigration) + return false; + + // For a single-profile source, check if any data is available. + // For multiple-profiles source, make sure that at least one + // profile is available. + let exists = false; + try { + let profiles = this.sourceProfiles; + if (!profiles) { + let resources = this._getMaybeCachedResources(""); + if (resources && resources.length > 0) + exists = true; + } + else { + exists = profiles.length > 0; + } + } + catch(ex) { + Cu.reportError(ex); + } + return exists; + }, + + /*** PRIVATE STUFF - DO NOT OVERRIDE ***/ + _getMaybeCachedResources: function PMB__getMaybeCachedResources(aProfile) { + let profileKey = aProfile ? aProfile.id : ""; + if (this._resourcesByProfile) { + if (profileKey in this._resourcesByProfile) + return this._resourcesByProfile[profileKey]; + } + else { + this._resourcesByProfile = { }; + } + return this._resourcesByProfile[profileKey] = this.getResources(aProfile); + } +}; + +this.MigrationUtils = Object.freeze({ + resourceTypes: { + SETTINGS: Ci.nsIBrowserProfileMigrator.SETTINGS, + COOKIES: Ci.nsIBrowserProfileMigrator.COOKIES, + HISTORY: Ci.nsIBrowserProfileMigrator.HISTORY, + FORMDATA: Ci.nsIBrowserProfileMigrator.FORMDATA, + PASSWORDS: Ci.nsIBrowserProfileMigrator.PASSWORDS, + BOOKMARKS: Ci.nsIBrowserProfileMigrator.BOOKMARKS, + OTHERDATA: Ci.nsIBrowserProfileMigrator.OTHERDATA + }, + + /** + * Helper for implementing simple asynchronous cases of migration resources' + * |migrate(aCallback)| (see MigratorPrototype). If your |migrate| method + * just waits for some file to be read, for example, and then migrates + * everything right away, you can wrap the async-function with this helper + * and not worry about notifying the callback. + * + * For example, instead of writing: + * setTimeout(function() { + * try { + * .... + * aCallback(true); + * } + * catch() { + * aCallback(false); + * } + * }, 0); + * + * You may write: + * setTimeout(MigrationUtils.wrapMigrateFunction(function() { + * if (importingFromMosaic) + * throw Cr.NS_ERROR_UNEXPECTED; + * }, aCallback), 0); + * + * ... and aCallback will be called with aSuccess=false when importing + * from Mosaic, or with aSuccess=true otherwise. + * + * @param aFunction + * the function that will be called sometime later. If aFunction + * throws when it's called, aCallback(false) is called, otherwise + * aCallback(true) is called. + * @param aCallback + * the callback function passed to |migrate|. + * @return the wrapped function. + */ + wrapMigrateFunction: function MU_wrapMigrateFunction(aFunction, aCallback) { + return function() { + let success = false; + try { + aFunction.apply(null, arguments); + success = true; + } + catch(ex) { + Cu.reportError(ex); + } + // Do not change this to call aCallback directly in try try & catch + // blocks, because if aCallback throws, we may end up calling aCallback + // twice. + aCallback(success); + } + }, + + /** + * Gets a string from the migration bundle. Shorthand for + * nsIStringBundle.GetStringFromName, if aReplacements isn't passed, or for + * nsIStringBundle.formatStringFromName if it is. + * + * This method also takes care of "bumped" keys (See bug 737381 comment 8 for + * details). + * + * @param aKey + * The key of the string to retrieve. + * @param aReplacemts + * [optioanl] Array of replacements to run on the retrieved string. + * @return the retrieved string. + * + * @see nsIStringBundle + */ + getLocalizedString: function MU_getLocalizedString(aKey, aReplacements) { + const OVERRIDES = { + "4_firefox": "4_firefox_history_and_bookmarks", + "64_firefox": "64_firefox_other" + }; + aKey = OVERRIDES[aKey] || aKey; + + if (aReplacements === undefined) + return getMigrationBundle().GetStringFromName(aKey); + return getMigrationBundle().formatStringFromName( + aKey, aReplacements, aReplacements.length); + }, + + /** + * Helper for creating a folder for imported bookmarks from a particular + * migration source. The folder is created at the end of the given folder. + * + * @param aSourceNameStr + * the source name (first letter capitalized). This is used + * for reading the localized source name from the migration + * bundle (e.g. if aSourceNameStr is Mosaic, this will try to read + * sourceNameMosaic from the migration bundle). + * @param aParentId + * the item-id of the folder in which the new folder should be + * created. + * @return the item-id of the new folder. + */ + createImportedBookmarksFolder: + function MU_createImportedBookmarksFolder(aSourceNameStr, aParentId) { + let source = this.getLocalizedString("sourceName" + aSourceNameStr); + let label = this.getLocalizedString("importedBookmarksFolder", [source]); + return PlacesUtils.bookmarks.createFolder( + aParentId, label, PlacesUtils.bookmarks.DEFAULT_INDEX); + }, + + get _migrators() gMigrators ? gMigrators : gMigrators = new Dict(), + + /* + * Returns the migrator for the given source, if any data is available + * for this source, or null otherwise. + * + * @param aKey internal name of the migration source. + * Supported values: ie (windows), + * safari (mac/windows), + * chrome (mac/windows/linux), + * firefox. + * + * If null is returned, either no data can be imported + * for the given migrator, or aMigratorKey is invalid (e.g. ie on mac, + * or mosaic everywhere). This method should be used rather than direct + * getService for future compatibility (see bug 718280). + * + * @return profile migrator implementing nsIBrowserProfileMigrator, if it can + * import any data, null otherwise. + */ + getMigrator: function MU_getMigrator(aKey) { + let migrator = null; + if (this._migrators.has(aKey)) { + migrator = this._migrators.get(aKey); + } + else { + try { + migrator = Cc["@mozilla.org/profile/migrator;1?app=browser&type=" + + aKey].createInstance(Ci.nsIBrowserProfileMigrator); + } + catch(ex) { } + this._migrators.set(aKey, migrator); + } + + return migrator && migrator.sourceExists ? migrator : null; + }, + + // Iterates the available migrators, in the most suitable + // order for the running platform. + get migrators() { + let migratorKeysOrdered = [ +#ifdef XP_WIN + "firefox", "ie", "chrome", "safari" +#elifdef XP_MACOSX + "firefox", "safari", "chrome" +#elifdef XP_UNIX + "firefox", "chrome" +#endif + ]; + + // If a supported default browser is found check it first + // so that the wizard defaults to import from that browser. + let defaultBrowserKey = getMigratorKeyForDefaultBrowser(); + if (defaultBrowserKey) + migratorKeysOrdered.sort(function (a, b) b == defaultBrowserKey ? 1 : 0); + + for (let migratorKey of migratorKeysOrdered) { + let migrator = this.getMigrator(migratorKey); + if (migrator) + yield migrator; + } + }, + + // Whether or not we're in the process of startup migration + get isStartupMigration() gProfileStartup != null, + + /** + * In the case of startup migration, this is set to the nsIProfileStartup + * instance passed to ProfileMigrator's migrate. + * + * @see showMigrationWizard + */ + get profileStartup() gProfileStartup, + + /** + * Show the migration wizard. On mac, this may just focus the wizard if it's + * already running, in which case aOpener and aParams are ignored. + * + * @param [optional] aOpener + * the window that asks to open the wizard. + * @param [optional] aParams + * arguments for the migration wizard, in the form of an nsIArray. + * This is passed as-is for the params argument of + * nsIWindowWatcher.openWindow. + */ + showMigrationWizard: + function MU_showMigrationWizard(aOpener, aParams) { + let features = "chrome,dialog,modal,centerscreen,titlebar,resizable=no"; +#ifdef XP_MACOSX + if (!this.isStartupMigration) { + let win = Services.wm.getMostRecentWindow("Browser:MigrationWizard"); + if (win) { + win.focus(); + return; + } + // On mac, the migration wiazrd should only be modal in the case of + // startup-migration. + features = "centerscreen,chrome,resizable=no"; + } +#endif + + Services.ww.openWindow(aOpener, + "chrome://browser/content/migration/migration.xul", + "_blank", + features, + aParams); + }, + + /** + * Show the migration wizard for startup-migration. This should only be + * called by ProfileMigrator (see ProfileMigrator.js), which implements + * nsIProfileMigrator. + * + * @param aProfileStartup + * the nsIProfileStartup instance provided to ProfileMigrator.migrate. + * @param [optional] aMigratorKey + * If set, the migration wizard will import from the corresponding + * migrator, bypassing the source-selection page. Otherwise, the + * source-selection page will be displayed, either with the default + * browser selected, if it could be detected and if there is a + * migrator for it, or with the first option selected as a fallback + * (The first option is hardcoded to be the most common browser for + * the OS we run on. See migration.xul). + * @param [optional] aProfileToMigrate + * If set, the migration wizard will import from the profile indicated. + * + * @throws if aMigratorKey is invalid or if it points to a non-existent + * source. + */ + startupMigration: + function MU_startupMigrator(aProfileStartup, aMigratorKey, aProfileToMigrate) { + if (!aProfileStartup) { + throw new Error("a profile-startup instance is required for startup-migration"); + } + gProfileStartup = aProfileStartup; + + let skipSourcePage = false, migrator = null, migratorKey = ""; + if (aMigratorKey) { + migrator = this.getMigrator(aMigratorKey); + if (!migrator) { + // aMigratorKey must point to a valid source, so, if it doesn't + // cleanup and throw. + this.finishMigration(); + throw new Error("startMigration was asked to open auto-migrate from " + + "a non-existent source: " + aMigratorKey); + } + migratorKey = aMigratorKey; + skipSourcePage = true; + } + else { + let defaultBrowserKey = getMigratorKeyForDefaultBrowser(); + if (defaultBrowserKey) { + migrator = this.getMigrator(defaultBrowserKey); + if (migrator) + migratorKey = defaultBrowserKey; + } + } + + if (!migrator) { + // If there's no migrator set so far, ensure that there is at least one + // migrator available before opening the wizard. + try { + this.migrators.next(); + } + catch(ex) { + this.finishMigration(); + if (!(ex instanceof StopIteration)) + throw ex; + return; + } + } + + let params = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray); + let keyCSTR = Cc["@mozilla.org/supports-cstring;1"]. + createInstance(Ci.nsISupportsCString); + keyCSTR.data = migratorKey; + let skipImportSourcePageBool = Cc["@mozilla.org/supports-PRBool;1"]. + createInstance(Ci.nsISupportsPRBool); + skipImportSourcePageBool.data = skipSourcePage; + let profileToMigrate = null; + if (aProfileToMigrate) { + profileToMigrate = Cc["@mozilla.org/supports-string;1"]. + createInstance(Ci.nsISupportsString); + profileToMigrate.data = aProfileToMigrate; + } + params.appendElement(keyCSTR, false); + params.appendElement(migrator, false); + params.appendElement(aProfileStartup, false); + params.appendElement(skipImportSourcePageBool, false); + params.appendElement(profileToMigrate, false); + + this.showMigrationWizard(null, params); + }, + + /** + * Cleans up references to migrators and nsIProfileInstance instances. + */ + finishMigration: function MU_finishMigration() { + gMigrators = null; + gProfileStartup = null; + gMigrationBundle = null; + } +}); diff --git a/application/palemoon/components/migration/ProfileMigrator.js b/application/palemoon/components/migration/ProfileMigrator.js new file mode 100644 index 000000000..f67823bae --- /dev/null +++ b/application/palemoon/components/migration/ProfileMigrator.js @@ -0,0 +1,21 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); +Components.utils.import("resource:///modules/MigrationUtils.jsm"); + +function ProfileMigrator() { +} + +ProfileMigrator.prototype = { + migrate: MigrationUtils.startupMigration.bind(MigrationUtils), + QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIProfileMigrator]), + classDescription: "Profile Migrator", + contractID: "@mozilla.org/toolkit/profile-migrator;1", + classID: Components.ID("6F8BB968-C14F-4D6F-9733-6C6737B35DCE") +}; + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([ProfileMigrator]); diff --git a/application/palemoon/components/migration/SafariProfileMigrator.js b/application/palemoon/components/migration/SafariProfileMigrator.js new file mode 100644 index 000000000..70804793d --- /dev/null +++ b/application/palemoon/components/migration/SafariProfileMigrator.js @@ -0,0 +1,416 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +let Cc = Components.classes; +let Ci = Components.interfaces; +let Cu = Components.utils; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/FileUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource:///modules/MigrationUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "PropertyListUtils", + "resource://gre/modules/PropertyListUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", + "resource://gre/modules/PlacesUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "FormHistory", + "resource://gre/modules/FormHistory.jsm"); + +function Bookmarks(aBookmarksFile) { + this._file = aBookmarksFile; +} +Bookmarks.prototype = { + type: MigrationUtils.resourceTypes.BOOKMARKS, + + migrate: function B_migrate(aCallback) { + PropertyListUtils.read(this._file, + MigrationUtils.wrapMigrateFunction(function migrateBookmarks(aDict) { + if (!aDict) + throw new Error("Could not read Bookmarks.plist"); + + let children = aDict.get("Children");; + if (!children) + throw new Error("Invalid Bookmarks.plist format"); + + PlacesUtils.bookmarks.runInBatchMode({ + runBatched: function() { + let collection = aDict.get("Title") == "com.apple.ReadingList" ? + this.READING_LIST_COLLECTION : this.ROOT_COLLECTION; + this._migrateCollection(children, collection); + }.bind(this) + }, null); + }.bind(this), aCallback)); + }, + + // Bookmarks collections in Safari. Constants for migrateCollection. + ROOT_COLLECTION: 0, + MENU_COLLECTION: 1, + TOOLBAR_COLLECTION: 2, + READING_LIST_COLLECTION: 3, + + /** + * Recursively migrate a Safari collection of bookmarks. + * + * @param aEntries + * the collection's children + * @param aCollection + * one of the values above. + */ + _migrateCollection: function B__migrateCollection(aEntries, aCollection) { + // A collection of bookmarks in Safari resembles places roots. In the + // property list files (Bookmarks.plist, ReadingList.plist) they are + // stored as regular bookmarks folders, and thus can only be distinguished + // from by their names and places in the hierarchy. + + let entriesFiltered = []; + if (aCollection == this.ROOT_COLLECTION) { + for (let entry of aEntries) { + let type = entry.get("WebBookmarkType"); + if (type == "WebBookmarkTypeList" && entry.has("Children")) { + let title = entry.get("Title"); + let children = entry.get("Children"); + if (title == "BookmarksBar") + this._migrateCollection(children, this.TOOLBAR_COLLECTION); + else if (title == "BookmarksMenu") + this._migrateCollection(children, this.MENU_COLLECTION); + else if (title == "com.apple.ReadingList") + this._migrateCollection(children, this.READING_LIST_COLLECTION); + else if (entry.get("ShouldOmitFromUI") !== true) + entriesFiltered.push(entry); + } + else if (type == "WebBookmarkTypeLeaf") { + entriesFiltered.push(entry); + } + } + } + else { + entriesFiltered = aEntries; + } + + if (entriesFiltered.length == 0) + return; + + let folder = -1; + switch (aCollection) { + case this.ROOT_COLLECTION: { + // In Safari, it is possible (though quite cumbersome) to move + // bookmarks to the bookmarks root, which is the parent folder of + // all bookmarks "collections". That is somewhat in parallel with + // both the places root and the unfiled-bookmarks root. + // Because the former is only an implementation detail in our UI, + // the unfiled root seems to be the best choice. + folder = PlacesUtils.unfiledBookmarksFolderId; + break; + } + case this.MENU_COLLECTION: { + folder = PlacesUtils.bookmarksMenuFolderId; + if (!MigrationUtils.isStartupMigration) { + folder = MigrationUtils.createImportedBookmarksFolder("Safari", + folder); + } + break; + } + case this.TOOLBAR_COLLECTION: { + folder = PlacesUtils.toolbarFolderId; + if (!MigrationUtils.isStartupMigration) { + folder = MigrationUtils.createImportedBookmarksFolder("Safari", + folder); + } + break; + } + case this.READING_LIST_COLLECTION: { + // Reading list items are imported as regular bookmarks. + // They are imported under their own folder, created either under the + // bookmarks menu (in the case of startup migration). + folder = PlacesUtils.bookmarks.createFolder( + PlacesUtils.bookmarksMenuFolderId, + MigrationUtils.getLocalizedString("importedSafariReadingList"), + PlacesUtils.bookmarks.DEFAULT_INDEX); + break; + } + default: + throw new Error("Unexpected value for aCollection!"); + } + + this._migrateEntries(entriesFiltered, folder); + }, + + // migrate the given array of safari bookmarks to the given places + // folder. + _migrateEntries: function B__migrateEntries(aEntries, aFolderId) { + for (let entry of aEntries) { + let type = entry.get("WebBookmarkType"); + if (type == "WebBookmarkTypeList" && entry.has("Children")) { + let title = entry.get("Title"); + let folderId = PlacesUtils.bookmarks.createFolder( + aFolderId, title, PlacesUtils.bookmarks.DEFAULT_INDEX); + + // Empty folders may not have a children array. + if (entry.has("Children")) + this._migrateEntries(entry.get("Children"), folderId, false); + } + else if (type == "WebBookmarkTypeLeaf" && entry.has("URLString")) { + let title, uri; + if (entry.has("URIDictionary")) + title = entry.get("URIDictionary").get("title"); + + try { + uri = NetUtil.newURI(entry.get("URLString")); + } + catch(ex) { + Cu.reportError("Invalid uri set for Safari bookmark: " + entry.get("URLString")); + } + if (uri) { + PlacesUtils.bookmarks.insertBookmark(aFolderId, uri, + PlacesUtils.bookmarks.DEFAULT_INDEX, title); + } + } + } + } +}; + +function History(aHistoryFile) { + this._file = aHistoryFile; +} +History.prototype = { + type: MigrationUtils.resourceTypes.HISTORY, + + // Helper method for converting the visit date property to a PRTime value. + // The visit date is stored as a string, so it's not read as a Date + // object by PropertyListUtils. + _parseCocoaDate: function H___parseCocoaDate(aCocoaDateStr) { + let asDouble = parseFloat(aCocoaDateStr); + if (!isNaN(asDouble)) { + // reference date of NSDate. + let date = new Date("1 January 2001, GMT"); + date.setMilliseconds(asDouble * 1000); + return date * 1000; + } + return 0; + }, + + migrate: function H_migrate(aCallback) { + PropertyListUtils.read(this._file, function migrateHistory(aDict) { + try { + if (!aDict) + throw new Error("Could not read history property list"); + if (!aDict.has("WebHistoryDates")) + throw new Error("Unexpected history-property list format"); + + // Safari's History file contains only top-level urls. It does not + // distinguish between typed urls and linked urls. + let transType = PlacesUtils.history.TRANSITION_LINK; + + let places = []; + let entries = aDict.get("WebHistoryDates"); + for (let entry of entries) { + if (entry.has("lastVisitedDate")) { + let visitDate = this._parseCocoaDate(entry.get("lastVisitedDate")); + places.push({ uri: NetUtil.newURI(entry.get("")), + title: entry.get("title"), + visits: [{ transitionType: transType, + visitDate: visitDate }] }); + } + } + if (places.length > 0) { + PlacesUtils.asyncHistory.updatePlaces(places, { + _success: false, + handleResult: function() { + // Importing any entry is considered a successful import. + this._success = true; + }, + handleError: function() {}, + handleCompletion: function() { + aCallback(this._success); + } + }); + } + else { + aCallback(false); + } + } + catch(ex) { + Cu.reportError(ex); + aCallback(false); + } + }.bind(this)); + } +}; + +/** + * Safari's preferences property list is independently used for three purposes: + * (a) importation of preferences + * (b) importation of search strings + * (c) retrieving the home page. + * + * So, rather than reading it three times, it's cached and managed here. + */ +function MainPreferencesPropertyList(aPreferencesFile) { + this._file = aPreferencesFile; + this._callbacks = []; +} +MainPreferencesPropertyList.prototype = { + /** + * @see PropertyListUtils.read + */ + read: function MPPL_read(aCallback) { + if ("_dict" in this) { + aCallback(this._dict); + return; + } + + let alreadyReading = this._callbacks.length > 0; + this._callbacks.push(aCallback); + if (!alreadyReading) { + PropertyListUtils.read(this._file, function readPrefs(aDict) { + this._dict = aDict; + for (let callback of this._callbacks) { + try { + callback(aDict); + } + catch(ex) { + Cu.reportError(ex); + } + } + this._callbacks.splice(0); + }.bind(this)); + } + }, + + // Workaround for nsIBrowserProfileMigrator.sourceHomePageURL until + // it's replaced with an async method. + _readSync: function MPPL__readSync() { + if ("_dict" in this) + return this._dict; + + let inputStream = Cc["@mozilla.org/network/file-input-stream;1"]. + createInstance(Ci.nsIFileInputStream); + inputStream.init(this._file, -1, -1, 0); + let binaryStream = Cc["@mozilla.org/binaryinputstream;1"]. + createInstance(Ci.nsIBinaryInputStream); + binaryStream.setInputStream(inputStream); + let bytes = binaryStream.readByteArray(inputStream.available()); + this._dict = PropertyListUtils._readFromArrayBufferSync( + Uint8Array(bytes).buffer); + return this._dict; + } +}; + +function SearchStrings(aMainPreferencesPropertyListInstance) { + this._mainPreferencesPropertyList = aMainPreferencesPropertyListInstance; +} +SearchStrings.prototype = { + type: MigrationUtils.resourceTypes.OTHERDATA, + + migrate: function SS_migrate(aCallback) { + this._mainPreferencesPropertyList.read(MigrationUtils.wrapMigrateFunction( + function migrateSearchStrings(aDict) { + if (!aDict) + throw new Error("Could not get preferences dictionary"); + + if (aDict.has("RecentSearchStrings")) { + let recentSearchStrings = aDict.get("RecentSearchStrings"); + if (recentSearchStrings && recentSearchStrings.length > 0) { + let changes = [{op: "add", + fieldname: "searchbar-history", + value: searchString} + for (searchString of recentSearchStrings)]; + FormHistory.update(changes); + } + } + }.bind(this), aCallback)); + } +}; + +function SafariProfileMigrator() { +} + +SafariProfileMigrator.prototype = Object.create(MigratorPrototype); + +SafariProfileMigrator.prototype.getResources = function SM_getResources() { + let profileDir = +#ifdef XP_MACOSX + FileUtils.getDir("ULibDir", ["Safari"], false); +#else + FileUtils.getDir("AppData", ["Apple Computer", "Safari"], false); +#endif + if (!profileDir.exists()) + return null; + + let resources = []; + let pushProfileFileResource = function(aFileName, aConstructor) { + let file = profileDir.clone(); + file.append(aFileName); + if (file.exists()) + resources.push(new aConstructor(file)); + }; + + pushProfileFileResource("History.plist", History); + pushProfileFileResource("Bookmarks.plist", Bookmarks); + + // The Reading List feature was introduced at the same time in Windows and + // Mac versions of Safari. Not surprisingly, they are stored in the same + // format in both versions. Surpsingly, only on Windows there is a + // separate property list for it. This isn't #ifdefed out on mac, because + // Apple may fix this at some point. + pushProfileFileResource("ReadingList.plist", Bookmarks); + + let prefsDir = +#ifdef XP_MACOSX + FileUtils.getDir("UsrPrfs", [], false); +#else + FileUtils.getDir("AppData", ["Apple Computer", "Preferences"], false); +#endif + + let prefs = this.mainPreferencesPropertyList; + if (prefs) { + resources.push(new SearchStrings(prefs)); + } + + return resources; +}; + +Object.defineProperty(SafariProfileMigrator.prototype, "mainPreferencesPropertyList", { + get: function get_mainPreferencesPropertyList() { + if (this._mainPreferencesPropertyList === undefined) { + let file = +#ifdef XP_MACOSX + FileUtils.getDir("UsrPrfs", [], false); +#else + FileUtils.getDir("AppData", ["Apple Computer", "Preferences"], false); +#endif + if (file.exists()) { + file.append("com.apple.Safari.plist"); + if (file.exists()) { + return this._mainPreferencesPropertyList = + new MainPreferencesPropertyList(file); + } + } + return this._mainPreferencesPropertyList = null; + } + return this._mainPreferencesPropertyList; + } +}); + +Object.defineProperty(SafariProfileMigrator.prototype, "sourceHomePageURL", { + get: function get_sourceHomePageURL() { + if (this.mainPreferencesPropertyList) { + let dict = this.mainPreferencesPropertyList._readSync(); + if (dict.has("HomePage")) + return dict.get("HomePage"); + } + return ""; + } +}); + +SafariProfileMigrator.prototype.classDescription = "Safari Profile Migrator"; +SafariProfileMigrator.prototype.contractID = "@mozilla.org/profile/migrator;1?app=browser&type=safari"; +SafariProfileMigrator.prototype.classID = Components.ID("{4b609ecf-60b2-4655-9df4-dc149e474da1}"); + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SafariProfileMigrator]); diff --git a/application/palemoon/components/migration/content/migration.js b/application/palemoon/components/migration/content/migration.js new file mode 100644 index 000000000..512197b8b --- /dev/null +++ b/application/palemoon/components/migration/content/migration.js @@ -0,0 +1,474 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; + +const kIMig = Ci.nsIBrowserProfileMigrator; +const kIPStartup = Ci.nsIProfileStartup; + +Cu.import("resource:///modules/MigrationUtils.jsm"); + +var MigrationWizard = { + _source: "", // Source Profile Migrator ContractID suffix + _itemsFlags: kIMig.ALL, // Selected Import Data Sources (16-bit bitfield) + _selectedProfile: null, // Selected Profile name to import from + _wiz: null, + _migrator: null, + _autoMigrate: null, + + init: function () + { + var os = Components.classes["@mozilla.org/observer-service;1"] + .getService(Components.interfaces.nsIObserverService); + os.addObserver(this, "Migration:Started", false); + os.addObserver(this, "Migration:ItemBeforeMigrate", false); + os.addObserver(this, "Migration:ItemAfterMigrate", false); + os.addObserver(this, "Migration:ItemError", false); + os.addObserver(this, "Migration:Ended", false); + + this._wiz = document.documentElement; + + if ("arguments" in window && window.arguments.length > 1) { + this._source = window.arguments[0]; + this._migrator = window.arguments[1] instanceof kIMig ? + window.arguments[1] : null; + this._autoMigrate = window.arguments[2].QueryInterface(kIPStartup); + this._skipImportSourcePage = window.arguments[3]; + if (this._migrator && window.arguments[4]) { + let sourceProfiles = this._migrator.sourceProfiles; + this._selectedProfile = sourceProfiles.find(profile => profile.id == window.arguments[4]); + } + + if (this._autoMigrate) { + // Show the "nothing" option in the automigrate case to provide an + // easily identifiable way to avoid migration and create a new profile. + var nothing = document.getElementById("nothing"); + nothing.hidden = false; + } + } + + this.onImportSourcePageShow(); + }, + + uninit: function () + { + var os = Components.classes["@mozilla.org/observer-service;1"] + .getService(Components.interfaces.nsIObserverService); + os.removeObserver(this, "Migration:Started"); + os.removeObserver(this, "Migration:ItemBeforeMigrate"); + os.removeObserver(this, "Migration:ItemAfterMigrate"); + os.removeObserver(this, "Migration:ItemError"); + os.removeObserver(this, "Migration:Ended"); + MigrationUtils.finishMigration(); + }, + + // 1 - Import Source + onImportSourcePageShow: function () + { + this._wiz.canRewind = false; + + var selectedMigrator = null; + + // Figure out what source apps are are available to import from: + var group = document.getElementById("importSourceGroup"); + for (var i = 0; i < group.childNodes.length; ++i) { + var migratorKey = group.childNodes[i].id; + if (migratorKey != "nothing") { + var migrator = MigrationUtils.getMigrator(migratorKey); + if (migrator) { + // Save this as the first selectable item, if we don't already have + // one, or if it is the migrator that was passed to us. + if (!selectedMigrator || this._source == migratorKey) + selectedMigrator = group.childNodes[i]; + } else { + // Hide this option + group.childNodes[i].hidden = true; + } + } + } + + if (selectedMigrator) + group.selectedItem = selectedMigrator; + else { + // We didn't find a migrator, notify the user + document.getElementById("noSources").hidden = false; + + this._wiz.canAdvance = false; + + document.getElementById("importBookmarks").hidden = true; + document.getElementById("importAll").hidden = true; + } + + // Advance to the next page if the caller told us to. + if (this._migrator && this._skipImportSourcePage) { + this._wiz.advance(); + this._wiz.canRewind = false; + } + }, + + onImportSourcePageAdvanced: function () + { + var newSource = document.getElementById("importSourceGroup").selectedItem.id; + + if (newSource == "nothing") { + document.documentElement.cancel(); + return false; + } + + if (!this._migrator || (newSource != this._source)) { + // Create the migrator for the selected source. + this._migrator = MigrationUtils.getMigrator(newSource); + + this._itemsFlags = kIMig.ALL; + this._selectedProfile = null; + } + this._source = newSource; + + // check for more than one source profile + var sourceProfiles = this._migrator.sourceProfiles; + if (this._skipImportSourcePage) { + this._wiz.currentPage.next = "homePageImport"; + } + else if (sourceProfiles && sourceProfiles.length > 1) { + this._wiz.currentPage.next = "selectProfile"; + } + else { + if (this._autoMigrate) + this._wiz.currentPage.next = "homePageImport"; + else + this._wiz.currentPage.next = "importItems"; + + if (sourceProfiles && sourceProfiles.length == 1) + this._selectedProfile = sourceProfiles[0]; + else + this._selectedProfile = null; + } + }, + + // 2 - [Profile Selection] + onSelectProfilePageShow: function () + { + // Disabling this for now, since we ask about import sources in automigration + // too and don't want to disable the back button + // if (this._autoMigrate) + // document.documentElement.getButton("back").disabled = true; + + var profiles = document.getElementById("profiles"); + while (profiles.hasChildNodes()) + profiles.removeChild(profiles.firstChild); + + // Note that this block is still reached even if the user chose 'From File' + // and we canceled the dialog. When that happens, _migrator will be null. + if (this._migrator) { + var sourceProfiles = this._migrator.sourceProfiles; + + for (let profile of sourceProfiles) { + var item = document.createElement("radio"); + item.id = profile.id; + item.setAttribute("label", profile.name); + profiles.appendChild(item); + } + } + + profiles.selectedItem = this._selectedProfile ? document.getElementById(this._selectedProfile.id) : profiles.firstChild; + }, + + onSelectProfilePageRewound: function () + { + var profiles = document.getElementById("profiles"); + this._selectedProfile = this._migrator.sourceProfiles.find( + profile => profile.id == profiles.selectedItem.id + ) || null; + }, + + onSelectProfilePageAdvanced: function () + { + var profiles = document.getElementById("profiles"); + this._selectedProfile = this._migrator.sourceProfiles.find( + profile => profile.id == profiles.selectedItem.id + ) || null; + + // If we're automigrating or just doing bookmarks don't show the item selection page + if (this._autoMigrate) + this._wiz.currentPage.next = "homePageImport"; + }, + + // 3 - ImportItems + onImportItemsPageShow: function () + { + var dataSources = document.getElementById("dataSources"); + while (dataSources.hasChildNodes()) + dataSources.removeChild(dataSources.firstChild); + + var items = this._migrator.getMigrateData(this._selectedProfile, this._autoMigrate); + for (var i = 0; i < 16; ++i) { + var itemID = (items >> i) & 0x1 ? Math.pow(2, i) : 0; + if (itemID > 0) { + var checkbox = document.createElement("checkbox"); + checkbox.id = itemID; + checkbox.setAttribute("label", + MigrationUtils.getLocalizedString(itemID + "_" + this._source)); + dataSources.appendChild(checkbox); + if (!this._itemsFlags || this._itemsFlags & itemID) + checkbox.checked = true; + } + } + }, + + onImportItemsPageRewound: function () + { + this._wiz.canAdvance = true; + this.onImportItemsPageAdvanced(); + }, + + onImportItemsPageAdvanced: function () + { + var dataSources = document.getElementById("dataSources"); + this._itemsFlags = 0; + for (var i = 0; i < dataSources.childNodes.length; ++i) { + var checkbox = dataSources.childNodes[i]; + if (checkbox.localName == "checkbox" && checkbox.checked) + this._itemsFlags |= parseInt(checkbox.id); + } + }, + + onImportItemCommand: function (aEvent) + { + var items = document.getElementById("dataSources"); + var checkboxes = items.getElementsByTagName("checkbox"); + + var oneChecked = false; + for (var i = 0; i < checkboxes.length; ++i) { + if (checkboxes[i].checked) { + oneChecked = true; + break; + } + } + + this._wiz.canAdvance = oneChecked; + }, + + // 4 - Home Page Selection + onHomePageMigrationPageShow: function () + { + // only want this on the first run + if (!this._autoMigrate) { + this._wiz.advance(); + return; + } + + var brandBundle = document.getElementById("brandBundle"); + // These strings don't exist when not using official branding. If that's + // the case, just skip this page. + try { + var pageTitle = brandBundle.getString("homePageMigrationPageTitle"); + var pageDesc = brandBundle.getString("homePageMigrationDescription"); + var mainStr = brandBundle.getString("homePageSingleStartMain"); + } + catch (e) { + this._wiz.advance(); + return; + } + + document.getElementById("homePageImport").setAttribute("label", pageTitle); + document.getElementById("homePageImportDesc").setAttribute("value", pageDesc); + + this._wiz._adjustWizardHeader(); + + var singleStart = document.getElementById("homePageSingleStart"); + singleStart.setAttribute("label", mainStr); + singleStart.setAttribute("value", "DEFAULT"); + + var source = null; + switch (this._source) { + case "ie": + source = "sourceNameIE"; + break; + case "safari": + source = "sourceNameSafari"; + break; + case "chrome": + source = "sourceNameChrome"; + break; + case "firefox": + source = "sourceNameFirefox"; + break; + } + + // semi-wallpaper for crash when multiple profiles exist, since we haven't initialized mSourceProfile in places + this._migrator.getMigrateData(this._selectedProfile, this._autoMigrate); + + var oldHomePageURL = this._migrator.sourceHomePageURL; + + if (oldHomePageURL && source) { + var appName = MigrationUtils.getLocalizedString(source); + var oldHomePageLabel = + brandBundle.getFormattedString("homePageImport", [appName]); + var oldHomePage = document.getElementById("oldHomePage"); + oldHomePage.setAttribute("label", oldHomePageLabel); + oldHomePage.setAttribute("value", oldHomePageURL); + oldHomePage.removeAttribute("hidden"); + } + else { + // if we don't have at least two options, just advance + this._wiz.advance(); + } + }, + + onHomePageMigrationPageAdvanced: function () + { + // we might not have a selectedItem if we're in fallback mode + try { + var radioGroup = document.getElementById("homePageRadiogroup"); + + this._newHomePage = radioGroup.selectedItem.value; + } catch(ex) {} + }, + + // 5 - Migrating + onMigratingPageShow: function () + { + this._wiz.getButton("cancel").disabled = true; + this._wiz.canRewind = false; + this._wiz.canAdvance = false; + + // When automigrating, show all of the data that can be received from this source. + if (this._autoMigrate) + this._itemsFlags = this._migrator.getMigrateData(this._selectedProfile, this._autoMigrate); + + this._listItems("migratingItems"); + setTimeout(this.onMigratingMigrate, 0, this); + }, + + onMigratingMigrate: function (aOuter) + { + aOuter._migrator.migrate(aOuter._itemsFlags, aOuter._autoMigrate, aOuter._selectedProfile); + }, + + _listItems: function (aID) + { + var items = document.getElementById(aID); + while (items.hasChildNodes()) + items.removeChild(items.firstChild); + + var brandBundle = document.getElementById("brandBundle"); + var itemID; + for (var i = 0; i < 16; ++i) { + var itemID = (this._itemsFlags >> i) & 0x1 ? Math.pow(2, i) : 0; + if (itemID > 0) { + var label = document.createElement("label"); + label.id = itemID + "_migrated"; + try { + label.setAttribute("value", + MigrationUtils.getLocalizedString(itemID + "_" + this._source)); + items.appendChild(label); + } + catch (e) { + // if the block above throws, we've enumerated all the import data types we + // currently support and are now just wasting time, break. + break; + } + } + } + }, + + observe: function (aSubject, aTopic, aData) + { + switch (aTopic) { + case "Migration:Started": + break; + case "Migration:ItemBeforeMigrate": + var label = document.getElementById(aData + "_migrated"); + if (label) + label.setAttribute("style", "font-weight: bold"); + break; + case "Migration:ItemAfterMigrate": + var label = document.getElementById(aData + "_migrated"); + if (label) + label.removeAttribute("style"); + break; + case "Migration:Ended": + if (this._autoMigrate) { + if (this._newHomePage) { + try { + // set homepage properly + var prefSvc = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefService); + var prefBranch = prefSvc.getBranch(null); + + if (this._newHomePage == "DEFAULT") { + prefBranch.clearUserPref("browser.startup.homepage"); + } + else { + var str = Components.classes["@mozilla.org/supports-string;1"] + .createInstance(Components.interfaces.nsISupportsString); + str.data = this._newHomePage; + prefBranch.setComplexValue("browser.startup.homepage", + Components.interfaces.nsISupportsString, + str); + } + + var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"] + .getService(Components.interfaces.nsIProperties); + var prefFile = dirSvc.get("ProfDS", Components.interfaces.nsIFile); + prefFile.append("prefs.js"); + prefSvc.savePrefFile(prefFile); + } catch(ex) { + dump(ex); + } + } + + // We're done now. + this._wiz.canAdvance = true; + this._wiz.advance(); + + setTimeout(close, 5000); + } + else { + this._wiz.canAdvance = true; + var nextButton = this._wiz.getButton("next"); + nextButton.click(); + } + break; + case "Migration:ItemError": + var type = "undefined"; + switch (parseInt(aData)) { + case Ci.nsIBrowserProfileMigrator.SETTINGS: + type = "settings"; + break; + case Ci.nsIBrowserProfileMigrator.COOKIES: + type = "cookies"; + break; + case Ci.nsIBrowserProfileMigrator.HISTORY: + type = "history"; + break; + case Ci.nsIBrowserProfileMigrator.FORMDATA: + type = "form data"; + break; + case Ci.nsIBrowserProfileMigrator.PASSWORDS: + type = "passwords"; + break; + case Ci.nsIBrowserProfileMigrator.BOOKMARKS: + type = "bookmarks"; + break; + case Ci.nsIBrowserProfileMigrator.OTHERDATA: + type = "misc. data"; + break; + } + Cc["@mozilla.org/consoleservice;1"] + .getService(Ci.nsIConsoleService) + .logStringMessage("some " + type + " did not successfully migrate."); + break; + } + }, + + onDonePageShow: function () + { + this._wiz.getButton("cancel").disabled = true; + this._wiz.canRewind = false; + this._listItems("doneItems"); + } +}; diff --git a/application/palemoon/components/migration/content/migration.xul b/application/palemoon/components/migration/content/migration.xul new file mode 100644 index 000000000..2c8df7b3e --- /dev/null +++ b/application/palemoon/components/migration/content/migration.xul @@ -0,0 +1,96 @@ + +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + + + + + + + + + + + + + + + + + + + + + + + diff --git a/application/palemoon/components/places/content/editBookmarkOverlay.js b/application/palemoon/components/places/content/editBookmarkOverlay.js new file mode 100644 index 000000000..98bfcccd7 --- /dev/null +++ b/application/palemoon/components/places/content/editBookmarkOverlay.js @@ -0,0 +1,1039 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +const LAST_USED_ANNO = "bookmarkPropertiesDialog/folderLastUsed"; +const MAX_FOLDER_ITEM_IN_MENU_LIST = 5; + +var gEditItemOverlay = { + _uri: null, + _itemId: -1, + _itemIds: [], + _uris: [], + _tags: [], + _allTags: [], + _multiEdit: false, + _itemType: -1, + _readOnly: false, + _hiddenRows: [], + _observersAdded: false, + _staticFoldersListBuilt: false, + _initialized: false, + _titleOverride: "", + + // the first field which was edited after this panel was initialized for + // a certain item + _firstEditedField: "", + + get itemId() { + return this._itemId; + }, + + get uri() { + return this._uri; + }, + + get multiEdit() { + return this._multiEdit; + }, + + /** + * Determines the initial data for the item edited or added by this dialog + */ + _determineInfo: function EIO__determineInfo(aInfo) { + // hidden rows + if (aInfo && aInfo.hiddenRows) + this._hiddenRows = aInfo.hiddenRows; + else + this._hiddenRows.splice(0, this._hiddenRows.length); + // force-read-only + this._readOnly = aInfo && aInfo.forceReadOnly; + this._titleOverride = aInfo && aInfo.titleOverride ? aInfo.titleOverride + : ""; + }, + + _showHideRows: function EIO__showHideRows() { + var isBookmark = this._itemId != -1 && + this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK; + var isQuery = false; + if (this._uri) + isQuery = this._uri.schemeIs("place"); + + this._element("nameRow").collapsed = this._hiddenRows.indexOf("name") != -1; + this._element("folderRow").collapsed = + this._hiddenRows.indexOf("folderPicker") != -1 || this._readOnly; + this._element("tagsRow").collapsed = !this._uri || + this._hiddenRows.indexOf("tags") != -1 || isQuery; + // Collapse the tag selector if the item does not accept tags. + if (!this._element("tagsSelectorRow").collapsed && + this._element("tagsRow").collapsed) + this.toggleTagsSelector(); + this._element("descriptionRow").collapsed = + this._hiddenRows.indexOf("description") != -1 || this._readOnly; + this._element("keywordRow").collapsed = !isBookmark || this._readOnly || + this._hiddenRows.indexOf("keyword") != -1 || isQuery; + this._element("locationRow").collapsed = !(this._uri && !isQuery) || + this._hiddenRows.indexOf("location") != -1; + this._element("loadInSidebarCheckbox").collapsed = !isBookmark || isQuery || + this._readOnly || this._hiddenRows.indexOf("loadInSidebar") != -1; + this._element("feedLocationRow").collapsed = !this._isLivemark || + this._hiddenRows.indexOf("feedLocation") != -1; + this._element("siteLocationRow").collapsed = !this._isLivemark || + this._hiddenRows.indexOf("siteLocation") != -1; + this._element("selectionCount").hidden = !this._multiEdit; + }, + + /** + * Initialize the panel + * @param aFor + * Either a places-itemId (of a bookmark, folder or a live bookmark), + * an array of itemIds (used for bulk tagging), or a URI object (in + * which case, the panel would be initialized in read-only mode). + * @param [optional] aInfo + * JS object which stores additional info for the panel + * initialization. The following properties may bet set: + * * hiddenRows (Strings array): list of rows to be hidden regardless + * of the item edited. Possible values: "title", "location", + * "description", "keyword", "loadInSidebar", "feedLocation", + * "siteLocation", folderPicker" + * * forceReadOnly - set this flag to initialize the panel to its + * read-only (view) mode even if the given item is editable. + */ + initPanel: function EIO_initPanel(aFor, aInfo) { + // For sanity ensure that the implementer has uninited the panel before + // trying to init it again, or we could end up leaking due to observers. + if (this._initialized) + this.uninitPanel(false); + + var aItemIdList; + if (Array.isArray(aFor)) { + aItemIdList = aFor; + aFor = aItemIdList[0]; + } + else if (this._multiEdit) { + this._multiEdit = false; + this._tags = []; + this._uris = []; + this._allTags = []; + this._itemIds = []; + this._element("selectionCount").hidden = true; + } + + this._folderMenuList = this._element("folderMenuList"); + this._folderTree = this._element("folderTree"); + + this._determineInfo(aInfo); + if (aFor instanceof Ci.nsIURI) { + this._itemId = -1; + this._uri = aFor; + this._readOnly = true; + } + else { + this._itemId = aFor; + // We can't store information on invalid itemIds. + this._readOnly = this._readOnly || this._itemId == -1; + + var containerId = PlacesUtils.bookmarks.getFolderIdForItem(this._itemId); + this._itemType = PlacesUtils.bookmarks.getItemType(this._itemId); + if (this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK) { + this._uri = PlacesUtils.bookmarks.getBookmarkURI(this._itemId); + this._initTextField("keywordField", + PlacesUtils.bookmarks + .getKeywordForBookmark(this._itemId)); + this._element("loadInSidebarCheckbox").checked = + PlacesUtils.annotations.itemHasAnnotation(this._itemId, + PlacesUIUtils.LOAD_IN_SIDEBAR_ANNO); + } + else { + this._uri = null; + this._isLivemark = false; + PlacesUtils.livemarks.getLivemark({id: this._itemId }) + .then(aLivemark => { + this._isLivemark = true; + this._initTextField("feedLocationField", aLivemark.feedURI.spec, true); + this._initTextField("siteLocationField", aLivemark.siteURI ? aLivemark.siteURI.spec : "", true); + this._showHideRows(); + }, () => undefined); + } + + // folder picker + this._initFolderMenuList(containerId); + + // description field + this._initTextField("descriptionField", + PlacesUIUtils.getItemDescription(this._itemId)); + } + + if (this._itemId == -1 || + this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK) { + this._isLivemark = false; + + this._initTextField("locationField", this._uri.spec); + if (!aItemIdList) { + var tags = PlacesUtils.tagging.getTagsForURI(this._uri).join(", "); + this._initTextField("tagsField", tags, false); + } + else { + this._multiEdit = true; + this._allTags = []; + this._itemIds = aItemIdList; + for (var i = 0; i < aItemIdList.length; i++) { + if (aItemIdList[i] instanceof Ci.nsIURI) { + this._uris[i] = aItemIdList[i]; + this._itemIds[i] = -1; + } + else + this._uris[i] = PlacesUtils.bookmarks.getBookmarkURI(this._itemIds[i]); + this._tags[i] = PlacesUtils.tagging.getTagsForURI(this._uris[i]); + } + this._allTags = this._getCommonTags(); + this._initTextField("tagsField", this._allTags.join(", "), false); + this._element("itemsCountText").value = + PlacesUIUtils.getPluralString("detailsPane.itemsCountLabel", + this._itemIds.length, + [this._itemIds.length]); + } + + // tags selector + this._rebuildTagsSelectorList(); + } + + // name picker + this._initNamePicker(); + + this._showHideRows(); + + // observe changes + if (!this._observersAdded) { + // Single bookmarks observe any change. History entries and multiEdit + // observe only tags changes, through bookmarks. + if (this._itemId != -1 || this._uri || this._multiEdit) + PlacesUtils.bookmarks.addObserver(this, false); + + this._element("namePicker").addEventListener("blur", this); + this._element("locationField").addEventListener("blur", this); + this._element("tagsField").addEventListener("blur", this); + this._element("keywordField").addEventListener("blur", this); + this._element("descriptionField").addEventListener("blur", this); + window.addEventListener("unload", this, false); + this._observersAdded = true; + } + + this._initialized = true; + }, + + /** + * Finds tags that are in common among this._tags entries that track tags + * for each selected uri. + * The tags arrays should be kept up-to-date for this to work properly. + * + * @return array of common tags for the selected uris. + */ + _getCommonTags: function() { + return this._tags[0].filter( + function (aTag) this._tags.every( + function (aTags) aTags.indexOf(aTag) != -1 + ), this + ); + }, + + _initTextField: function(aTextFieldId, aValue, aReadOnly) { + var field = this._element(aTextFieldId); + field.readOnly = aReadOnly !== undefined ? aReadOnly : this._readOnly; + + if (field.value != aValue) { + field.value = aValue; + + // clear the undo stack + var editor = field.editor; + if (editor) + editor.transactionManager.clear(); + } + }, + + /** + * Appends a menu-item representing a bookmarks folder to a menu-popup. + * @param aMenupopup + * The popup to which the menu-item should be added. + * @param aFolderId + * The identifier of the bookmarks folder. + * @return the new menu item. + */ + _appendFolderItemToMenupopup: + function EIO__appendFolderItemToMenuList(aMenupopup, aFolderId) { + // First make sure the folders-separator is visible + this._element("foldersSeparator").hidden = false; + + var folderMenuItem = document.createElement("menuitem"); + var folderTitle = PlacesUtils.bookmarks.getItemTitle(aFolderId) + folderMenuItem.folderId = aFolderId; + folderMenuItem.setAttribute("label", folderTitle); + folderMenuItem.className = "menuitem-iconic folder-icon"; + aMenupopup.appendChild(folderMenuItem); + return folderMenuItem; + }, + + _initFolderMenuList: function EIO__initFolderMenuList(aSelectedFolder) { + // clean up first + var menupopup = this._folderMenuList.menupopup; + while (menupopup.childNodes.length > 6) + menupopup.removeChild(menupopup.lastChild); + + const bms = PlacesUtils.bookmarks; + const annos = PlacesUtils.annotations; + + // Build the static list + var unfiledItem = this._element("unfiledRootItem"); + if (!this._staticFoldersListBuilt) { + unfiledItem.label = bms.getItemTitle(PlacesUtils.unfiledBookmarksFolderId); + unfiledItem.folderId = PlacesUtils.unfiledBookmarksFolderId; + var bmMenuItem = this._element("bmRootItem"); + bmMenuItem.label = bms.getItemTitle(PlacesUtils.bookmarksMenuFolderId); + bmMenuItem.folderId = PlacesUtils.bookmarksMenuFolderId; + var toolbarItem = this._element("toolbarFolderItem"); + toolbarItem.label = bms.getItemTitle(PlacesUtils.toolbarFolderId); + toolbarItem.folderId = PlacesUtils.toolbarFolderId; + this._staticFoldersListBuilt = true; + } + + // List of recently used folders: + var folderIds = annos.getItemsWithAnnotation(LAST_USED_ANNO); + + /** + * The value of the LAST_USED_ANNO annotation is the time (in the form of + * Date.getTime) at which the folder has been last used. + * + * First we build the annotated folders array, each item has both the + * folder identifier and the time at which it was last-used by this dialog + * set. Then we sort it descendingly based on the time field. + */ + this._recentFolders = []; + for (var i = 0; i < folderIds.length; i++) { + var lastUsed = annos.getItemAnnotation(folderIds[i], LAST_USED_ANNO); + this._recentFolders.push({ folderId: folderIds[i], lastUsed: lastUsed }); + } + this._recentFolders.sort(function(a, b) { + if (b.lastUsed < a.lastUsed) + return -1; + if (b.lastUsed > a.lastUsed) + return 1; + return 0; + }); + + var numberOfItems = Math.min(MAX_FOLDER_ITEM_IN_MENU_LIST, + this._recentFolders.length); + for (var i = 0; i < numberOfItems; i++) { + this._appendFolderItemToMenupopup(menupopup, + this._recentFolders[i].folderId); + } + + var defaultItem = this._getFolderMenuItem(aSelectedFolder); + this._folderMenuList.selectedItem = defaultItem; + + // Set a selectedIndex attribute to show special icons + this._folderMenuList.setAttribute("selectedIndex", + this._folderMenuList.selectedIndex); + + // Hide the folders-separator if no folder is annotated as recently-used + this._element("foldersSeparator").hidden = (menupopup.childNodes.length <= 6); + this._folderMenuList.disabled = this._readOnly; + }, + + QueryInterface: function EIO_QueryInterface(aIID) { + if (aIID.equals(Ci.nsIDOMEventListener) || + aIID.equals(Ci.nsINavBookmarkObserver) || + aIID.equals(Ci.nsISupports)) + return this; + + throw Cr.NS_ERROR_NO_INTERFACE; + }, + + _element: function EIO__element(aID) { + return document.getElementById("editBMPanel_" + aID); + }, + + _getItemStaticTitle: function EIO__getItemStaticTitle() { + if (this._titleOverride) + return this._titleOverride; + + let title = ""; + if (this._itemId == -1) { + title = PlacesUtils.history.getPageTitle(this._uri); + } + else { + title = PlacesUtils.bookmarks.getItemTitle(this._itemId); + } + return title; + }, + + _initNamePicker: function EIO_initNamePicker() { + var namePicker = this._element("namePicker"); + namePicker.value = this._getItemStaticTitle(); + namePicker.readOnly = this._readOnly; + + // clear the undo stack + var editor = namePicker.editor; + if (editor) + editor.transactionManager.clear(); + }, + + uninitPanel: function EIO_uninitPanel(aHideCollapsibleElements) { + if (aHideCollapsibleElements) { + // hide the folder tree if it was previously visible + var folderTreeRow = this._element("folderTreeRow"); + if (!folderTreeRow.collapsed) + this.toggleFolderTreeVisibility(); + + // hide the tag selector if it was previously visible + var tagsSelectorRow = this._element("tagsSelectorRow"); + if (!tagsSelectorRow.collapsed) + this.toggleTagsSelector(); + } + + if (this._observersAdded) { + if (this._itemId != -1 || this._uri || this._multiEdit) + PlacesUtils.bookmarks.removeObserver(this); + + this._element("namePicker").removeEventListener("blur", this); + this._element("locationField").removeEventListener("blur", this); + this._element("tagsField").removeEventListener("blur", this); + this._element("keywordField").removeEventListener("blur", this); + this._element("descriptionField").removeEventListener("blur", this); + + this._observersAdded = false; + } + + this._itemId = -1; + this._uri = null; + this._uris = []; + this._tags = []; + this._allTags = []; + this._itemIds = []; + this._multiEdit = false; + this._firstEditedField = ""; + this._initialized = false; + this._titleOverride = ""; + this._readOnly = false; + }, + + onTagsFieldBlur: function EIO_onTagsFieldBlur() { + if (this._updateTags()) // if anything has changed + this._mayUpdateFirstEditField("tagsField"); + }, + + _updateTags: function EIO__updateTags() { + if (this._multiEdit) + return this._updateMultipleTagsForItems(); + return this._updateSingleTagForItem(); + }, + + _updateSingleTagForItem: function EIO__updateSingleTagForItem() { + var currentTags = PlacesUtils.tagging.getTagsForURI(this._uri); + var tags = this._getTagsArrayFromTagField(); + if (tags.length > 0 || currentTags.length > 0) { + var tagsToRemove = []; + var tagsToAdd = []; + var txns = []; + for (var i = 0; i < currentTags.length; i++) { + if (tags.indexOf(currentTags[i]) == -1) + tagsToRemove.push(currentTags[i]); + } + for (var i = 0; i < tags.length; i++) { + if (currentTags.indexOf(tags[i]) == -1) + tagsToAdd.push(tags[i]); + } + + if (tagsToRemove.length > 0) { + let untagTxn = new PlacesUntagURITransaction(this._uri, tagsToRemove); + txns.push(untagTxn); + } + if (tagsToAdd.length > 0) { + let tagTxn = new PlacesTagURITransaction(this._uri, tagsToAdd); + txns.push(tagTxn); + } + + if (txns.length > 0) { + let aggregate = new PlacesAggregatedTransaction("Update tags", txns); + PlacesUtils.transactionManager.doTransaction(aggregate); + + // Ensure the tagsField is in sync, clean it up from empty tags + var tags = PlacesUtils.tagging.getTagsForURI(this._uri).join(", "); + this._initTextField("tagsField", tags, false); + return true; + } + } + return false; + }, + + /** + * Stores the first-edit field for this dialog, if the passed-in field + * is indeed the first edited field + * @param aNewField + * the id of the field that may be set (without the "editBMPanel_" + * prefix) + */ + _mayUpdateFirstEditField: function EIO__mayUpdateFirstEditField(aNewField) { + // * The first-edit-field behavior is not applied in the multi-edit case + // * if this._firstEditedField is already set, this is not the first field, + // so there's nothing to do + if (this._multiEdit || this._firstEditedField) + return; + + this._firstEditedField = aNewField; + + // set the pref + var prefs = Cc["@mozilla.org/preferences-service;1"]. + getService(Ci.nsIPrefBranch); + prefs.setCharPref("browser.bookmarks.editDialog.firstEditField", aNewField); + }, + + _updateMultipleTagsForItems: function EIO__updateMultipleTagsForItems() { + var tags = this._getTagsArrayFromTagField(); + if (tags.length > 0 || this._allTags.length > 0) { + var tagsToRemove = []; + var tagsToAdd = []; + var txns = []; + for (var i = 0; i < this._allTags.length; i++) { + if (tags.indexOf(this._allTags[i]) == -1) + tagsToRemove.push(this._allTags[i]); + } + for (var i = 0; i < this._tags.length; i++) { + tagsToAdd[i] = []; + for (var j = 0; j < tags.length; j++) { + if (this._tags[i].indexOf(tags[j]) == -1) + tagsToAdd[i].push(tags[j]); + } + } + + if (tagsToAdd.length > 0) { + for (let i = 0; i < this._uris.length; i++) { + if (tagsToAdd[i].length > 0) { + let tagTxn = new PlacesTagURITransaction(this._uris[i], + tagsToAdd[i]); + txns.push(tagTxn); + } + } + } + if (tagsToRemove.length > 0) { + for (let i = 0; i < this._uris.length; i++) { + let untagTxn = new PlacesUntagURITransaction(this._uris[i], + tagsToRemove); + txns.push(untagTxn); + } + } + + if (txns.length > 0) { + let aggregate = new PlacesAggregatedTransaction("Update tags", txns); + PlacesUtils.transactionManager.doTransaction(aggregate); + + this._allTags = tags; + this._tags = []; + for (let i = 0; i < this._uris.length; i++) { + this._tags[i] = PlacesUtils.tagging.getTagsForURI(this._uris[i]); + } + + // Ensure the tagsField is in sync, clean it up from empty tags + this._initTextField("tagsField", tags, false); + return true; + } + } + return false; + }, + + onNamePickerBlur: function EIO_onNamePickerBlur() { + if (this._itemId == -1) + return; + + var namePicker = this._element("namePicker") + + // Here we update either the item title or its cached static title + var newTitle = namePicker.value; + if (!newTitle && + PlacesUtils.bookmarks.getFolderIdForItem(this._itemId) == PlacesUtils.tagsFolderId) { + // We don't allow setting an empty title for a tag, restore the old one. + this._initNamePicker(); + } + else if (this._getItemStaticTitle() != newTitle) { + this._mayUpdateFirstEditField("namePicker"); + let txn = new PlacesEditItemTitleTransaction(this._itemId, newTitle); + PlacesUtils.transactionManager.doTransaction(txn); + } + }, + + onDescriptionFieldBlur: function EIO_onDescriptionFieldBlur() { + var description = this._element("descriptionField").value; + if (description != PlacesUIUtils.getItemDescription(this._itemId)) { + var annoObj = { name : PlacesUIUtils.DESCRIPTION_ANNO, + type : Ci.nsIAnnotationService.TYPE_STRING, + flags : 0, + value : description, + expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; + var txn = new PlacesSetItemAnnotationTransaction(this._itemId, annoObj); + PlacesUtils.transactionManager.doTransaction(txn); + } + }, + + onLocationFieldBlur: function EIO_onLocationFieldBlur() { + var uri; + try { + uri = PlacesUIUtils.createFixedURI(this._element("locationField").value); + } + catch(ex) { return; } + + if (!this._uri.equals(uri)) { + var txn = new PlacesEditBookmarkURITransaction(this._itemId, uri); + PlacesUtils.transactionManager.doTransaction(txn); + this._uri = uri; + } + }, + + onKeywordFieldBlur: function EIO_onKeywordFieldBlur() { + var keyword = this._element("keywordField").value; + if (keyword != PlacesUtils.bookmarks.getKeywordForBookmark(this._itemId)) { + var txn = new PlacesEditBookmarkKeywordTransaction(this._itemId, keyword); + PlacesUtils.transactionManager.doTransaction(txn); + } + }, + + onLoadInSidebarCheckboxCommand: + function EIO_onLoadInSidebarCheckboxCommand() { + let annoObj = { name : PlacesUIUtils.LOAD_IN_SIDEBAR_ANNO }; + if (this._element("loadInSidebarCheckbox").checked) + annoObj.value = true; + let txn = new PlacesSetItemAnnotationTransaction(this._itemId, annoObj); + PlacesUtils.transactionManager.doTransaction(txn); + }, + + toggleFolderTreeVisibility: function EIO_toggleFolderTreeVisibility() { + var expander = this._element("foldersExpander"); + var folderTreeRow = this._element("folderTreeRow"); + if (!folderTreeRow.collapsed) { + expander.className = "expander-down"; + expander.setAttribute("tooltiptext", + expander.getAttribute("tooltiptextdown")); + folderTreeRow.collapsed = true; + this._element("chooseFolderSeparator").hidden = + this._element("chooseFolderMenuItem").hidden = false; + } + else { + expander.className = "expander-up" + expander.setAttribute("tooltiptext", + expander.getAttribute("tooltiptextup")); + folderTreeRow.collapsed = false; + + // XXXmano: Ideally we would only do this once, but for some odd reason, + // the editable mode set on this tree, together with its collapsed state + // breaks the view. + const FOLDER_TREE_PLACE_URI = + "place:excludeItems=1&excludeQueries=1&excludeReadOnlyFolders=1&folder=" + + PlacesUIUtils.allBookmarksFolderId; + this._folderTree.place = FOLDER_TREE_PLACE_URI; + + this._element("chooseFolderSeparator").hidden = + this._element("chooseFolderMenuItem").hidden = true; + var currentFolder = this._getFolderIdFromMenuList(); + this._folderTree.selectItems([currentFolder]); + this._folderTree.focus(); + } + }, + + _getFolderIdFromMenuList: + function EIO__getFolderIdFromMenuList() { + var selectedItem = this._folderMenuList.selectedItem; + NS_ASSERT("folderId" in selectedItem, + "Invalid menuitem in the folders-menulist"); + return selectedItem.folderId; + }, + + /** + * Get the corresponding menu-item in the folder-menu-list for a bookmarks + * folder if such an item exists. Otherwise, this creates a menu-item for the + * folder. If the items-count limit (see MAX_FOLDERS_IN_MENU_LIST) is reached, + * the new item replaces the last menu-item. + * @param aFolderId + * The identifier of the bookmarks folder. + */ + _getFolderMenuItem: + function EIO__getFolderMenuItem(aFolderId) { + var menupopup = this._folderMenuList.menupopup; + + for (let i = 0; i < menupopup.childNodes.length; i++) { + if ("folderId" in menupopup.childNodes[i] && + menupopup.childNodes[i].folderId == aFolderId) + return menupopup.childNodes[i]; + } + + // 3 special folders + separator + folder-items-count limit + if (menupopup.childNodes.length == 4 + MAX_FOLDER_ITEM_IN_MENU_LIST) + menupopup.removeChild(menupopup.lastChild); + + return this._appendFolderItemToMenupopup(menupopup, aFolderId); + }, + + onFolderMenuListCommand: function EIO_onFolderMenuListCommand(aEvent) { + // Set a selectedIndex attribute to show special icons + this._folderMenuList.setAttribute("selectedIndex", + this._folderMenuList.selectedIndex); + + if (aEvent.target.id == "editBMPanel_chooseFolderMenuItem") { + // reset the selection back to where it was and expand the tree + // (this menu-item is hidden when the tree is already visible + var container = PlacesUtils.bookmarks.getFolderIdForItem(this._itemId); + var item = this._getFolderMenuItem(container); + this._folderMenuList.selectedItem = item; + // XXXmano HACK: setTimeout 100, otherwise focus goes back to the + // menulist right away + setTimeout(function(self) self.toggleFolderTreeVisibility(), 100, this); + return; + } + + // Move the item + var container = this._getFolderIdFromMenuList(); + if (PlacesUtils.bookmarks.getFolderIdForItem(this._itemId) != container) { + var txn = new PlacesMoveItemTransaction(this._itemId, + container, + PlacesUtils.bookmarks.DEFAULT_INDEX); + PlacesUtils.transactionManager.doTransaction(txn); + + // Mark the containing folder as recently-used if it isn't in the + // static list + if (container != PlacesUtils.unfiledBookmarksFolderId && + container != PlacesUtils.toolbarFolderId && + container != PlacesUtils.bookmarksMenuFolderId) + this._markFolderAsRecentlyUsed(container); + } + + // Update folder-tree selection + var folderTreeRow = this._element("folderTreeRow"); + if (!folderTreeRow.collapsed) { + var selectedNode = this._folderTree.selectedNode; + if (!selectedNode || + PlacesUtils.getConcreteItemId(selectedNode) != container) + this._folderTree.selectItems([container]); + } + }, + + onFolderTreeSelect: function EIO_onFolderTreeSelect() { + var selectedNode = this._folderTree.selectedNode; + + // Disable the "New Folder" button if we cannot create a new folder + this._element("newFolderButton") + .disabled = !this._folderTree.insertionPoint || !selectedNode; + + if (!selectedNode) + return; + + var folderId = PlacesUtils.getConcreteItemId(selectedNode); + if (this._getFolderIdFromMenuList() == folderId) + return; + + var folderItem = this._getFolderMenuItem(folderId); + this._folderMenuList.selectedItem = folderItem; + folderItem.doCommand(); + }, + + _markFolderAsRecentlyUsed: + function EIO__markFolderAsRecentlyUsed(aFolderId) { + var txns = []; + + // Expire old unused recent folders + var anno = this._getLastUsedAnnotationObject(false); + while (this._recentFolders.length > MAX_FOLDER_ITEM_IN_MENU_LIST) { + var folderId = this._recentFolders.pop().folderId; + let annoTxn = new PlacesSetItemAnnotationTransaction(folderId, anno); + txns.push(annoTxn); + } + + // Mark folder as recently used + anno = this._getLastUsedAnnotationObject(true); + let annoTxn = new PlacesSetItemAnnotationTransaction(aFolderId, anno); + txns.push(annoTxn); + + let aggregate = new PlacesAggregatedTransaction("Update last used folders", txns); + PlacesUtils.transactionManager.doTransaction(aggregate); + }, + + /** + * Returns an object which could then be used to set/unset the + * LAST_USED_ANNO annotation for a folder. + * + * @param aLastUsed + * Whether to set or unset the LAST_USED_ANNO annotation. + * @returns an object representing the annotation which could then be used + * with the transaction manager. + */ + _getLastUsedAnnotationObject: + function EIO__getLastUsedAnnotationObject(aLastUsed) { + var anno = { name: LAST_USED_ANNO, + type: Ci.nsIAnnotationService.TYPE_INT32, + flags: 0, + value: aLastUsed ? new Date().getTime() : null, + expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; + + return anno; + }, + + _rebuildTagsSelectorList: function EIO__rebuildTagsSelectorList() { + var tagsSelector = this._element("tagsSelector"); + var tagsSelectorRow = this._element("tagsSelectorRow"); + if (tagsSelectorRow.collapsed) + return; + + // Save the current scroll position and restore it after the rebuild. + let firstIndex = tagsSelector.getIndexOfFirstVisibleRow(); + let selectedIndex = tagsSelector.selectedIndex; + let selectedTag = selectedIndex >= 0 ? tagsSelector.selectedItem.label + : null; + + while (tagsSelector.hasChildNodes()) + tagsSelector.removeChild(tagsSelector.lastChild); + + var tagsInField = this._getTagsArrayFromTagField(); + var allTags = PlacesUtils.tagging.allTags; + for (var i = 0; i < allTags.length; i++) { + var tag = allTags[i]; + var elt = document.createElement("listitem"); + elt.setAttribute("type", "checkbox"); + elt.setAttribute("label", tag); + if (tagsInField.indexOf(tag) != -1) + elt.setAttribute("checked", "true"); + tagsSelector.appendChild(elt); + if (selectedTag === tag) + selectedIndex = tagsSelector.getIndexOfItem(elt); + } + + // Restore position. + // The listbox allows to scroll only if the required offset doesn't + // overflow its capacity, thus need to adjust the index for removals. + firstIndex = + Math.min(firstIndex, + tagsSelector.itemCount - tagsSelector.getNumberOfVisibleRows()); + tagsSelector.scrollToIndex(firstIndex); + if (selectedIndex >= 0 && tagsSelector.itemCount > 0) { + selectedIndex = Math.min(selectedIndex, tagsSelector.itemCount - 1); + tagsSelector.selectedIndex = selectedIndex; + tagsSelector.ensureIndexIsVisible(selectedIndex); + } + }, + + toggleTagsSelector: function EIO_toggleTagsSelector() { + var tagsSelector = this._element("tagsSelector"); + var tagsSelectorRow = this._element("tagsSelectorRow"); + var expander = this._element("tagsSelectorExpander"); + if (tagsSelectorRow.collapsed) { + expander.className = "expander-up"; + expander.setAttribute("tooltiptext", + expander.getAttribute("tooltiptextup")); + tagsSelectorRow.collapsed = false; + this._rebuildTagsSelectorList(); + + // This is a no-op if we've added the listener. + tagsSelector.addEventListener("CheckboxStateChange", this, false); + } + else { + expander.className = "expander-down"; + expander.setAttribute("tooltiptext", + expander.getAttribute("tooltiptextdown")); + tagsSelectorRow.collapsed = true; + } + }, + + /** + * Splits "tagsField" element value, returning an array of valid tag strings. + * + * @return Array of tag strings found in the field value. + */ + _getTagsArrayFromTagField: function EIO__getTagsArrayFromTagField() { + let tags = this._element("tagsField").value; + return tags.trim() + .split(/\s*,\s*/) // Split on commas and remove spaces. + .filter(function (tag) tag.length > 0); // Kill empty tags. + }, + + newFolder: function EIO_newFolder() { + var ip = this._folderTree.insertionPoint; + + // default to the bookmarks menu folder + if (!ip || ip.itemId == PlacesUIUtils.allBookmarksFolderId) { + ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, + PlacesUtils.bookmarks.DEFAULT_INDEX, + Ci.nsITreeView.DROP_ON); + } + + // XXXmano: add a separate "New Folder" string at some point... + var defaultLabel = this._element("newFolderButton").label; + var txn = new PlacesCreateFolderTransaction(defaultLabel, ip.itemId, ip.index); + PlacesUtils.transactionManager.doTransaction(txn); + this._folderTree.focus(); + this._folderTree.selectItems([this._lastNewItem]); + this._folderTree.startEditing(this._folderTree.view.selection.currentIndex, + this._folderTree.columns.getFirstColumn()); + }, + + // nsIDOMEventListener + handleEvent: function EIO_nsIDOMEventListener(aEvent) { + switch (aEvent.type) { + case "CheckboxStateChange": + // Update the tags field when items are checked/unchecked in the listbox + var tags = this._getTagsArrayFromTagField(); + + if (aEvent.target.checked) { + if (tags.indexOf(aEvent.target.label) == -1) + tags.push(aEvent.target.label); + } + else { + var indexOfItem = tags.indexOf(aEvent.target.label); + if (indexOfItem != -1) + tags.splice(indexOfItem, 1); + } + this._element("tagsField").value = tags.join(", "); + this._updateTags(); + break; + case "blur": + let replaceFn = (str, firstLetter) => firstLetter.toUpperCase(); + let nodeName = aEvent.target.id.replace(/editBMPanel_(\w)/, replaceFn); + this["on" + nodeName + "Blur"](); + break; + case "unload": + this.uninitPanel(false); + break; + } + }, + + // nsINavBookmarkObserver + onItemChanged: function EIO_onItemChanged(aItemId, aProperty, + aIsAnnotationProperty, aValue, + aLastModified, aItemType) { + if (aProperty == "tags") { + // Tags case is special, since they should be updated if either: + // - the notification is for the edited bookmark + // - the notification is for the edited history entry + // - the notification is for one of edited uris + let shouldUpdateTagsField = this._itemId == aItemId; + if (this._itemId == -1 || this._multiEdit) { + // Check if the changed uri is part of the modified ones. + let changedURI = PlacesUtils.bookmarks.getBookmarkURI(aItemId); + let uris = this._multiEdit ? this._uris : [this._uri]; + uris.forEach(function (aURI, aIndex) { + if (aURI.equals(changedURI)) { + shouldUpdateTagsField = true; + if (this._multiEdit) { + this._tags[aIndex] = PlacesUtils.tagging.getTagsForURI(this._uris[aIndex]); + } + } + }, this); + } + + if (shouldUpdateTagsField) { + if (this._multiEdit) { + this._allTags = this._getCommonTags(); + this._initTextField("tagsField", this._allTags.join(", "), false); + } + else { + let tags = PlacesUtils.tagging.getTagsForURI(this._uri).join(", "); + this._initTextField("tagsField", tags, false); + } + } + + // Any tags change should be reflected in the tags selector. + this._rebuildTagsSelectorList(); + return; + } + + if (this._itemId != aItemId) { + if (aProperty == "title") { + // If the title of a folder which is listed within the folders + // menulist has been changed, we need to update the label of its + // representing element. + var menupopup = this._folderMenuList.menupopup; + for (let i = 0; i < menupopup.childNodes.length; i++) { + if ("folderId" in menupopup.childNodes[i] && + menupopup.childNodes[i].folderId == aItemId) { + menupopup.childNodes[i].label = aValue; + break; + } + } + } + + return; + } + + switch (aProperty) { + case "title": + var namePicker = this._element("namePicker"); + if (namePicker.value != aValue) { + namePicker.value = aValue; + // clear undo stack + namePicker.editor.transactionManager.clear(); + } + break; + case "uri": + var locationField = this._element("locationField"); + if (locationField.value != aValue) { + this._uri = Cc["@mozilla.org/network/io-service;1"]. + getService(Ci.nsIIOService). + newURI(aValue, null, null); + this._initTextField("locationField", this._uri.spec); + this._initNamePicker(); + this._initTextField("tagsField", + PlacesUtils.tagging + .getTagsForURI(this._uri).join(", "), + false); + this._rebuildTagsSelectorList(); + } + break; + case "keyword": + this._initTextField("keywordField", + PlacesUtils.bookmarks + .getKeywordForBookmark(this._itemId)); + break; + case PlacesUIUtils.DESCRIPTION_ANNO: + this._initTextField("descriptionField", + PlacesUIUtils.getItemDescription(this._itemId)); + break; + case PlacesUIUtils.LOAD_IN_SIDEBAR_ANNO: + this._element("loadInSidebarCheckbox").checked = + PlacesUtils.annotations.itemHasAnnotation(this._itemId, + PlacesUIUtils.LOAD_IN_SIDEBAR_ANNO); + break; + case PlacesUtils.LMANNO_FEEDURI: + let feedURISpec = + PlacesUtils.annotations.getItemAnnotation(this._itemId, + PlacesUtils.LMANNO_FEEDURI); + this._initTextField("feedLocationField", feedURISpec, true); + break; + case PlacesUtils.LMANNO_SITEURI: + let siteURISpec = ""; + try { + siteURISpec = + PlacesUtils.annotations.getItemAnnotation(this._itemId, + PlacesUtils.LMANNO_SITEURI); + } catch (ex) {} + this._initTextField("siteLocationField", siteURISpec, true); + break; + } + }, + + onItemMoved: function EIO_onItemMoved(aItemId, aOldParent, aOldIndex, + aNewParent, aNewIndex, aItemType) { + if (aItemId != this._itemId || + aNewParent == this._getFolderIdFromMenuList()) + return; + + var folderItem = this._getFolderMenuItem(aNewParent); + + // just setting selectItem _does not_ trigger oncommand, so we don't + // recurse + this._folderMenuList.selectedItem = folderItem; + }, + + onItemAdded: function EIO_onItemAdded(aItemId, aParentId, aIndex, aItemType, + aURI) { + this._lastNewItem = aItemId; + }, + + onItemRemoved: function() { }, + onBeginUpdateBatch: function() { }, + onEndUpdateBatch: function() { }, + onItemVisited: function() { }, +}; diff --git a/application/palemoon/components/places/content/editBookmarkOverlay.xul b/application/palemoon/components/places/content/editBookmarkOverlay.xul new file mode 100644 index 000000000..196369dd2 --- /dev/null +++ b/application/palemoon/components/places/content/editBookmarkOverlay.xul @@ -0,0 +1,228 @@ + + + +%editBookmarkOverlayDTD; +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +
+

&privatebrowsingpage.howToStop3;

+

&privatebrowsingpage.howToStart3;

+
+ + +
+

+ &privatebrowsingpage.moreInfo; +

+ +
+ + + + + diff --git a/application/palemoon/components/privatebrowsing/jar.mn b/application/palemoon/components/privatebrowsing/jar.mn new file mode 100644 index 000000000..a01b7f0d3 --- /dev/null +++ b/application/palemoon/components/privatebrowsing/jar.mn @@ -0,0 +1,6 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +browser.jar: +* content/browser/aboutPrivateBrowsing.xhtml (content/aboutPrivateBrowsing.xhtml) diff --git a/application/palemoon/components/privatebrowsing/moz.build b/application/palemoon/components/privatebrowsing/moz.build new file mode 100644 index 000000000..c97072bba --- /dev/null +++ b/application/palemoon/components/privatebrowsing/moz.build @@ -0,0 +1,7 @@ +# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +JAR_MANIFESTS += ['jar.mn'] \ No newline at end of file diff --git a/application/palemoon/components/search/content/engineManager.js b/application/palemoon/components/search/content/engineManager.js new file mode 100644 index 000000000..92b6d59b7 --- /dev/null +++ b/application/palemoon/components/search/content/engineManager.js @@ -0,0 +1,491 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +Components.utils.import("resource://gre/modules/Services.jsm"); + +const Ci = Components.interfaces; +const Cc = Components.classes; + +const ENGINE_FLAVOR = "text/x-moz-search-engine"; + +const BROWSER_SUGGEST_PREF = "browser.search.suggest.enabled"; + +var gEngineView = null; + +var gEngineManagerDialog = { + init: function engineManager_init() { + gEngineView = new EngineView(new EngineStore()); + + var suggestEnabled = Services.prefs.getBoolPref(BROWSER_SUGGEST_PREF); + document.getElementById("enableSuggest").checked = suggestEnabled; + + var tree = document.getElementById("engineList"); + tree.view = gEngineView; + + Services.obs.addObserver(this, "browser-search-engine-modified", false); + }, + + destroy: function engineManager_destroy() { + // Remove the observer + Services.obs.removeObserver(this, "browser-search-engine-modified"); + }, + + observe: function engineManager_observe(aEngine, aTopic, aVerb) { + if (aTopic == "browser-search-engine-modified") { + aEngine.QueryInterface(Ci.nsISearchEngine); + switch (aVerb) { + case "engine-added": + gEngineView._engineStore.addEngine(aEngine); + gEngineView.rowCountChanged(gEngineView.lastIndex, 1); + break; + case "engine-changed": + gEngineView._engineStore.reloadIcons(); + gEngineView.invalidate(); + break; + case "engine-removed": + case "engine-current": + case "engine-default": + // Not relevant + break; + } + } + }, + + onOK: function engineManager_onOK() { + // Set the preference + var newSuggestEnabled = document.getElementById("enableSuggest").checked; + Services.prefs.setBoolPref(BROWSER_SUGGEST_PREF, newSuggestEnabled); + + // Commit the changes + gEngineView._engineStore.commit(); + }, + + onRestoreDefaults: function engineManager_onRestoreDefaults() { + var num = gEngineView._engineStore.restoreDefaultEngines(); + gEngineView.rowCountChanged(0, num); + gEngineView.invalidate(); + }, + + showRestoreDefaults: function engineManager_showRestoreDefaults(val) { + document.documentElement.getButton("extra2").disabled = !val; + }, + + loadAddEngines: function engineManager_loadAddEngines() { + this.onOK(); + window.opener.BrowserSearch.loadAddEngines(); + window.close(); + }, + + remove: function engineManager_remove() { + gEngineView._engineStore.removeEngine(gEngineView.selectedEngine); + var index = gEngineView.selectedIndex; + gEngineView.rowCountChanged(index, -1); + gEngineView.invalidate(); + gEngineView.selection.select(Math.min(index, gEngineView.lastIndex)); + gEngineView.ensureRowIsVisible(gEngineView.currentIndex); + document.getElementById("engineList").focus(); + }, + + /** + * Moves the selected engine either up or down in the engine list + * @param aDir + * -1 to move the selected engine down, +1 to move it up. + */ + bump: function engineManager_move(aDir) { + var selectedEngine = gEngineView.selectedEngine; + var newIndex = gEngineView.selectedIndex - aDir; + + gEngineView._engineStore.moveEngine(selectedEngine, newIndex); + + gEngineView.invalidate(); + gEngineView.selection.select(newIndex); + gEngineView.ensureRowIsVisible(newIndex); + this.showRestoreDefaults(true); + document.getElementById("engineList").focus(); + }, + + editKeyword: function engineManager_editKeyword() { + var selectedEngine = gEngineView.selectedEngine; + if (!selectedEngine) + return; + + var alias = { value: selectedEngine.alias }; + var strings = document.getElementById("engineManagerBundle"); + var title = strings.getString("editTitle"); + var msg = strings.getFormattedString("editMsg", [selectedEngine.name]); + + while (Services.prompt.prompt(window, title, msg, alias, null, {})) { + var bduplicate = false; + var eduplicate = false; + var dupName = ""; + + if (alias.value != "") { + try { + let bmserv = Cc["@mozilla.org/browser/nav-bookmarks-service;1"]. + getService(Ci.nsINavBookmarksService); + if (bmserv.getURIForKeyword(alias.value)) + bduplicate = true; + } catch(ex) {} + + // Check for duplicates in changes we haven't committed yet + let engines = gEngineView._engineStore.engines; + for each (let engine in engines) { + if (engine.alias == alias.value && + engine.name != selectedEngine.name) { + eduplicate = true; + dupName = engine.name; + break; + } + } + } + + // Notify the user if they have chosen an existing engine/bookmark keyword + if (eduplicate || bduplicate) { + var dtitle = strings.getString("duplicateTitle"); + var bmsg = strings.getString("duplicateBookmarkMsg"); + var emsg = strings.getFormattedString("duplicateEngineMsg", [dupName]); + + Services.prompt.alert(window, dtitle, eduplicate ? emsg : bmsg); + } else { + gEngineView._engineStore.changeEngine(selectedEngine, "alias", + alias.value); + gEngineView.invalidate(); + break; + } + } + }, + + onSelect: function engineManager_onSelect() { + // Buttons only work if an engine is selected and it's not the last engine, + // the latter is true when the selected is first and last at the same time. + var lastSelected = (gEngineView.selectedIndex == gEngineView.lastIndex); + var firstSelected = (gEngineView.selectedIndex == 0); + var noSelection = (gEngineView.selectedIndex == -1); + + document.getElementById("cmd_remove") + .setAttribute("disabled", noSelection || + (firstSelected && lastSelected)); + + document.getElementById("cmd_moveup") + .setAttribute("disabled", noSelection || firstSelected); + + document.getElementById("cmd_movedown") + .setAttribute("disabled", noSelection || lastSelected); + + document.getElementById("cmd_editkeyword") + .setAttribute("disabled", noSelection); + } +}; + +function onDragEngineStart(event) { + var selectedIndex = gEngineView.selectedIndex; + if (selectedIndex >= 0) { + event.dataTransfer.setData(ENGINE_FLAVOR, selectedIndex.toString()); + event.dataTransfer.effectAllowed = "move"; + } +} + +// "Operation" objects +function EngineMoveOp(aEngineClone, aNewIndex) { + if (!aEngineClone) + throw new Error("bad args to new EngineMoveOp!"); + this._engine = aEngineClone.originalEngine; + this._newIndex = aNewIndex; +} +EngineMoveOp.prototype = { + _engine: null, + _newIndex: null, + commit: function EMO_commit() { + Services.search.moveEngine(this._engine, this._newIndex); + } +} + +function EngineRemoveOp(aEngineClone) { + if (!aEngineClone) + throw new Error("bad args to new EngineRemoveOp!"); + this._engine = aEngineClone.originalEngine; +} +EngineRemoveOp.prototype = { + _engine: null, + commit: function ERO_commit() { + Services.search.removeEngine(this._engine); + } +} + +function EngineUnhideOp(aEngineClone, aNewIndex) { + if (!aEngineClone) + throw new Error("bad args to new EngineUnhideOp!"); + this._engine = aEngineClone.originalEngine; + this._newIndex = aNewIndex; +} +EngineUnhideOp.prototype = { + _engine: null, + _newIndex: null, + commit: function EUO_commit() { + this._engine.hidden = false; + Services.search.moveEngine(this._engine, this._newIndex); + } +} + +function EngineChangeOp(aEngineClone, aProp, aValue) { + if (!aEngineClone) + throw new Error("bad args to new EngineChangeOp!"); + + this._engine = aEngineClone.originalEngine; + this._prop = aProp; + this._newValue = aValue; +} +EngineChangeOp.prototype = { + _engine: null, + _prop: null, + _newValue: null, + commit: function ECO_commit() { + this._engine[this._prop] = this._newValue; + } +} + +function EngineStore() { + this._engines = Services.search.getVisibleEngines().map(this._cloneEngine); + this._defaultEngines = Services.search.getDefaultEngines().map(this._cloneEngine); + + this._ops = []; + + // check if we need to disable the restore defaults button + var someHidden = this._defaultEngines.some(function (e) e.hidden); + gEngineManagerDialog.showRestoreDefaults(someHidden); +} +EngineStore.prototype = { + _engines: null, + _defaultEngines: null, + _ops: null, + + get engines() { + return this._engines; + }, + set engines(val) { + this._engines = val; + return val; + }, + + _getIndexForEngine: function ES_getIndexForEngine(aEngine) { + return this._engines.indexOf(aEngine); + }, + + _getEngineByName: function ES_getEngineByName(aName) { + for each (var engine in this._engines) + if (engine.name == aName) + return engine; + + return null; + }, + + _cloneEngine: function ES_cloneEngine(aEngine) { + var clonedObj={}; + for (var i in aEngine) + clonedObj[i] = aEngine[i]; + clonedObj.originalEngine = aEngine; + return clonedObj; + }, + + // Callback for Array's some(). A thisObj must be passed to some() + _isSameEngine: function ES_isSameEngine(aEngineClone) { + return aEngineClone.originalEngine == this.originalEngine; + }, + + commit: function ES_commit() { + var currentEngine = this._cloneEngine(Services.search.currentEngine); + for (var i = 0; i < this._ops.length; i++) + this._ops[i].commit(); + + // Restore currentEngine if it is a default engine that is still visible. + // Needed if the user deletes currentEngine and then restores it. + if (this._defaultEngines.some(this._isSameEngine, currentEngine) && + !currentEngine.originalEngine.hidden) + Services.search.currentEngine = currentEngine.originalEngine; + }, + + addEngine: function ES_addEngine(aEngine) { + this._engines.push(this._cloneEngine(aEngine)); + }, + + moveEngine: function ES_moveEngine(aEngine, aNewIndex) { + if (aNewIndex < 0 || aNewIndex > this._engines.length - 1) + throw new Error("ES_moveEngine: invalid aNewIndex!"); + var index = this._getIndexForEngine(aEngine); + if (index == -1) + throw new Error("ES_moveEngine: invalid engine?"); + + if (index == aNewIndex) + return; // nothing to do + + // Move the engine in our internal store + var removedEngine = this._engines.splice(index, 1)[0]; + this._engines.splice(aNewIndex, 0, removedEngine); + + this._ops.push(new EngineMoveOp(aEngine, aNewIndex)); + }, + + removeEngine: function ES_removeEngine(aEngine) { + var index = this._getIndexForEngine(aEngine); + if (index == -1) + throw new Error("invalid engine?"); + + this._engines.splice(index, 1); + this._ops.push(new EngineRemoveOp(aEngine)); + if (this._defaultEngines.some(this._isSameEngine, aEngine)) + gEngineManagerDialog.showRestoreDefaults(true); + }, + + restoreDefaultEngines: function ES_restoreDefaultEngines() { + var added = 0; + + for (var i = 0; i < this._defaultEngines.length; ++i) { + var e = this._defaultEngines[i]; + + // If the engine is already in the list, just move it. + if (this._engines.some(this._isSameEngine, e)) { + this.moveEngine(this._getEngineByName(e.name), i); + } else { + // Otherwise, add it back to our internal store + this._engines.splice(i, 0, e); + this._ops.push(new EngineUnhideOp(e, i)); + added++; + } + } + gEngineManagerDialog.showRestoreDefaults(false); + return added; + }, + + changeEngine: function ES_changeEngine(aEngine, aProp, aNewValue) { + var index = this._getIndexForEngine(aEngine); + if (index == -1) + throw new Error("invalid engine?"); + + this._engines[index][aProp] = aNewValue; + this._ops.push(new EngineChangeOp(aEngine, aProp, aNewValue)); + }, + + reloadIcons: function ES_reloadIcons() { + this._engines.forEach(function (e) { + e.uri = e.originalEngine.uri; + }); + } +} + +function EngineView(aEngineStore) { + this._engineStore = aEngineStore; +} +EngineView.prototype = { + _engineStore: null, + tree: null, + + get lastIndex() { + return this.rowCount - 1; + }, + get selectedIndex() { + var seln = this.selection; + if (seln.getRangeCount() > 0) { + var min = {}; + seln.getRangeAt(0, min, {}); + return min.value; + } + return -1; + }, + get selectedEngine() { + return this._engineStore.engines[this.selectedIndex]; + }, + + // Helpers + rowCountChanged: function (index, count) { + this.tree.rowCountChanged(index, count); + }, + + invalidate: function () { + this.tree.invalidate(); + }, + + ensureRowIsVisible: function (index) { + this.tree.ensureRowIsVisible(index); + }, + + getSourceIndexFromDrag: function (dataTransfer) { + return parseInt(dataTransfer.getData(ENGINE_FLAVOR)); + }, + + // nsITreeView + get rowCount() { + return this._engineStore.engines.length; + }, + + getImageSrc: function(index, column) { + if (column.id == "engineName" && this._engineStore.engines[index].iconURI) + return this._engineStore.engines[index].iconURI.spec; + return ""; + }, + + getCellText: function(index, column) { + if (column.id == "engineName") + return this._engineStore.engines[index].name; + else if (column.id == "engineKeyword") + return this._engineStore.engines[index].alias; + return ""; + }, + + setTree: function(tree) { + this.tree = tree; + }, + + canDrop: function(targetIndex, orientation, dataTransfer) { + var sourceIndex = this.getSourceIndexFromDrag(dataTransfer); + return (sourceIndex != -1 && + sourceIndex != targetIndex && + sourceIndex != targetIndex + orientation); + }, + + drop: function(dropIndex, orientation, dataTransfer) { + var sourceIndex = this.getSourceIndexFromDrag(dataTransfer); + var sourceEngine = this._engineStore.engines[sourceIndex]; + + if (dropIndex > sourceIndex) { + if (orientation == Ci.nsITreeView.DROP_BEFORE) + dropIndex--; + } else { + if (orientation == Ci.nsITreeView.DROP_AFTER) + dropIndex++; + } + + this._engineStore.moveEngine(sourceEngine, dropIndex); + gEngineManagerDialog.showRestoreDefaults(true); + + // Redraw, and adjust selection + this.invalidate(); + this.selection.select(dropIndex); + }, + + selection: null, + getRowProperties: function(index) { return ""; }, + getCellProperties: function(index, column) { return ""; }, + getColumnProperties: function(column) { return ""; }, + isContainer: function(index) { return false; }, + isContainerOpen: function(index) { return false; }, + isContainerEmpty: function(index) { return false; }, + isSeparator: function(index) { return false; }, + isSorted: function(index) { return false; }, + getParentIndex: function(index) { return -1; }, + hasNextSibling: function(parentIndex, index) { return false; }, + getLevel: function(index) { return 0; }, + getProgressMode: function(index, column) { }, + getCellValue: function(index, column) { }, + toggleOpenState: function(index) { }, + cycleHeader: function(column) { }, + selectionChanged: function() { }, + cycleCell: function(row, column) { }, + isEditable: function(index, column) { return false; }, + isSelectable: function(index, column) { return false; }, + setCellValue: function(index, column, value) { }, + setCellText: function(index, column, value) { }, + performAction: function(action) { }, + performActionOnRow: function(action, index) { }, + performActionOnCell: function(action, index, column) { } +}; diff --git a/application/palemoon/components/search/content/engineManager.xul b/application/palemoon/components/search/content/engineManager.xul new file mode 100644 index 000000000..50181c066 --- /dev/null +++ b/application/palemoon/components/search/content/engineManager.xul @@ -0,0 +1,93 @@ + + + + + + + + + + +