Issue #303 Part 1: Move basilisk files from /browser to /application/basilisk

This commit is contained in:
wolfbeast 2018-06-04 13:17:38 +02:00 • committed by Roy Tam
commit 177b28a898
1938 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,42 @@
# nsBrowserContentHandler.js
component {5d0ce354-df01-421a-83fb-7ead0990c24e} nsBrowserContentHandler.js application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/browser/clh;1 {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
component {47cd0651-b1be-4a0f-b5c4-10e5a573ef71} nsBrowserContentHandler.js application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/browser/final-clh;1 {47cd0651-b1be-4a0f-b5c4-10e5a573ef71} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=text/html {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=application/vnd.mozilla.xul+xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=image/svg+xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=text/rdf {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=text/xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=application/xhtml+xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=text/css {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=text/plain {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=image/gif {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=image/jpeg {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=image/jpg {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=image/png {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=image/bmp {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=image/x-icon {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=image/vnd.microsoft.icon {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
contract @mozilla.org/uriloader/content-handler;1?type=application/http-index-format {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
category command-line-handler m-browser @mozilla.org/browser/clh;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
category command-line-handler x-default @mozilla.org/browser/final-clh;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
category command-line-validator b-browser @mozilla.org/browser/clh;1 application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
# nsBrowserGlue.js
# This component must restrict its registration for the app-startup category
# to the specific list of apps that use it so it doesn't get loaded in xpcshell.
# Thus we restrict it to these apps:
#
# b2g: {3c2e2abc-06d4-11e1-ac3b-374f68613e61}
# browser: {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
# mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110}
# mobile/xul: {a23983c0-fd0e-11dc-95ff-0800200c9a66}
# graphene: {d1bfe7d9-c01e-4237-998b-7b5f960a4314}
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={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66} application={d1bfe7d9-c01e-4237-998b-7b5f960a4314}
component {d8903bf6-68d5-4e97-bcd1-e4d3012f721a} nsBrowserGlue.js
contract @mozilla.org/content-permission/prompt;1 {d8903bf6-68d5-4e97-bcd1-e4d3012f721a}

View file

@ -0,0 +1,269 @@
/* -*- 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 "nsIAboutNewTabService.h"
#include "nsIChannel.h"
#include "nsIURI.h"
#include "nsIScriptSecurityManager.h"
#include "nsIProtocolHandler.h"
#include "mozilla/ArrayUtils.h"
#include "nsServiceManagerUtils.h"
namespace mozilla {
namespace browser {
NS_IMPL_ISUPPORTS(AboutRedirector, nsIAboutModule)
struct RedirEntry {
const char* id;
const char* url;
uint32_t flags;
};
/*
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[] = {
{
"basilisk", "chrome://global/content/memoriam.xhtml",
nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT |
nsIAboutModule::HIDE_FROM_ABOUTABOUT
},
#ifdef MOZ_SAFE_BROWSING
{
"blocked", "chrome://browser/content/blockedSite.xhtml",
nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT |
nsIAboutModule::URI_CAN_LOAD_IN_CHILD |
nsIAboutModule::ALLOW_SCRIPT |
nsIAboutModule::HIDE_FROM_ABOUTABOUT
},
#endif
{
"certerror", "chrome://browser/content/aboutNetError.xhtml",
nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT |
nsIAboutModule::URI_CAN_LOAD_IN_CHILD |
nsIAboutModule::ALLOW_SCRIPT |
nsIAboutModule::HIDE_FROM_ABOUTABOUT
},
{
"tabcrashed", "chrome://browser/content/aboutTabCrashed.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::URI_MUST_LOAD_IN_CHILD |
nsIAboutModule::ALLOW_SCRIPT
},
{
"rights", "chrome://global/content/aboutRights.xhtml",
nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT |
nsIAboutModule::MAKE_LINKABLE |
nsIAboutModule::ALLOW_SCRIPT
},
{
"robots", "chrome://browser/content/aboutRobots.xhtml",
nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT |
nsIAboutModule::ALLOW_SCRIPT
},
{
"searchreset", "chrome://browser/content/search/searchReset.xhtml",
nsIAboutModule::ALLOW_SCRIPT |
nsIAboutModule::HIDE_FROM_ABOUTABOUT
},
{
"sessionrestore", "chrome://browser/content/aboutSessionRestore.xhtml",
nsIAboutModule::ALLOW_SCRIPT
},
{
"welcomeback", "chrome://browser/content/aboutWelcomeBack.xhtml",
nsIAboutModule::ALLOW_SCRIPT
},
{
"sync-tabs", "chrome://browser/content/sync/aboutSyncTabs.xul",
nsIAboutModule::ALLOW_SCRIPT
},
{ "home", "chrome://browser/content/abouthome/aboutHome.xhtml",
nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT |
nsIAboutModule::URI_MUST_LOAD_IN_CHILD |
nsIAboutModule::ALLOW_SCRIPT |
// Linkable because of indexeddb use (bug 1228118)
nsIAboutModule::MAKE_LINKABLE |
nsIAboutModule::ENABLE_INDEXED_DB },
{
// the newtab's actual URL will be determined when the channel is created
"newtab", "about:blank",
nsIAboutModule::ALLOW_SCRIPT
},
{
"preferences", "chrome://browser/content/preferences/in-content/preferences.xul",
nsIAboutModule::ALLOW_SCRIPT
},
{
"downloads", "chrome://browser/content/downloads/contentAreaDownloadsView.xul",
nsIAboutModule::ALLOW_SCRIPT
},
#ifdef MOZ_SERVICES_HEALTHREPORT
{
"healthreport", "chrome://browser/content/abouthealthreport/abouthealth.xhtml",
nsIAboutModule::ALLOW_SCRIPT
},
#endif
{
"accounts", "chrome://browser/content/aboutaccounts/aboutaccounts.xhtml",
nsIAboutModule::ALLOW_SCRIPT
},
{
"reader", "chrome://global/content/reader/aboutReader.html",
nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT |
nsIAboutModule::ALLOW_SCRIPT |
nsIAboutModule::URI_MUST_LOAD_IN_CHILD |
nsIAboutModule::HIDE_FROM_ABOUTABOUT
},
};
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<nsIIOService> ioService = do_GetIOService(&rv);
NS_ENSURE_SUCCESS(rv, rv);
for (int i = 0; i < kRedirTotal; i++) {
if (!strcmp(path.get(), kRedirMap[i].id)) {
nsAutoCString url;
if (path.EqualsLiteral("newtab")) {
// let the aboutNewTabService decide where to redirect
nsCOMPtr<nsIAboutNewTabService> aboutNewTabService =
do_GetService("@mozilla.org/browser/aboutnewtab-service;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = aboutNewTabService->GetDefaultURL(url);
NS_ENSURE_SUCCESS(rv, rv);
// if about:newtab points to an external resource we have to make sure
// the content is signed and trusted
bool remoteEnabled = false;
rv = aboutNewTabService->GetRemoteEnabled(&remoteEnabled);
NS_ENSURE_SUCCESS(rv, rv);
if (remoteEnabled) {
NS_ENSURE_ARG_POINTER(aLoadInfo);
aLoadInfo->SetVerifySignedContent(true);
}
}
// fall back to the specified url in the map
if (url.IsEmpty()) {
url.AssignASCII(kRedirMap[i].url);
}
nsCOMPtr<nsIChannel> tempChannel;
nsCOMPtr<nsIURI> tempURI;
rv = NS_NewURI(getter_AddRefs(tempURI), url);
NS_ENSURE_SUCCESS(rv, rv);
// If tempURI links to an external URI (i.e. something other than
// chrome:// or resource://) then set the LOAD_REPLACE flag on the
// channel which forces the channel owner to reflect the displayed
// URL rather then being the systemPrincipal.
bool isUIResource = false;
rv = NS_URIChainHasFlags(tempURI, nsIProtocolHandler::URI_IS_UI_RESOURCE,
&isUIResource);
NS_ENSURE_SUCCESS(rv, rv);
nsLoadFlags loadFlags = isUIResource
? static_cast<nsLoadFlags>(nsIChannel::LOAD_NORMAL)
: static_cast<nsLoadFlags>(nsIChannel::LOAD_REPLACE);
rv = NS_NewChannelInternal(getter_AddRefs(tempChannel),
tempURI,
aLoadInfo,
nullptr, // aLoadGroup
nullptr, // aCallbacks
loadFlags);
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;
}
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

View file

@ -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__

View file

@ -0,0 +1,19 @@
# -*- Mode: python; 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',
]

View file

@ -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 =

View file

@ -0,0 +1,42 @@
# -*- Mode: python; 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 += [
'esent',
'netapi32',
'ole32',
'shell32',
'shlwapi',
'version',
]
DELAYLOAD_DLLS += [
'esent.dll',
'netapi32.dll',
]
# 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']

View file

@ -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 } }

View file

@ -0,0 +1,132 @@
/* -*- 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 "basilisk", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
#ifdef MOZ_SAFE_BROWSING
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "blocked", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
#endif
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "certerror", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "tabcrashed", &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 "robots", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "searchreset", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "sessionrestore", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "welcomeback", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "sync-tabs", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
{ 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 "preferences", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "downloads", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "accounts", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
#ifdef MOZ_SERVICES_HEALTHREPORT
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "healthreport", &kNS_BROWSER_ABOUT_REDIRECTOR_CID },
#endif
{ NS_ABOUT_MODULE_CONTRACTID_PREFIX "reader", &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;

View file

@ -0,0 +1,91 @@
[data-identity-color="blue"] {
--identity-tab-color: #0996f8;
--identity-icon-color: #00a7e0;
}
[data-identity-color="turquoise"] {
--identity-tab-color: #01bdad;
--identity-icon-color: #01bdad;
}
[data-identity-color="green"] {
--identity-tab-color: #57bd35;
--identity-icon-color: #7dc14c;
}
[data-identity-color="yellow"] {
--identity-tab-color: #ffcb00;
--identity-icon-color: #ffcb00;
}
[data-identity-color="orange"] {
--identity-tab-color: #ff9216;
--identity-icon-color: #ff9216;
}
[data-identity-color="red"] {
--identity-tab-color: #d92215;
--identity-icon-color: #d92215;
}
[data-identity-color="pink"] {
--identity-tab-color: #ea385e;
--identity-icon-color: #ee5195;
}
[data-identity-color="purple"] {
--identity-tab-color: #7a2f7a;
--identity-icon-color: #7a2f7a;
}
[data-identity-icon="fingerprint"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#fingerprint");
}
[data-identity-icon="briefcase"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#briefcase");
}
[data-identity-icon="dollar"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#dollar");
}
[data-identity-icon="cart"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#cart");
}
[data-identity-icon="circle"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#circle");
}
#userContext-indicator {
height: 16px;
width: 16px;
}
#userContext-label {
margin-inline-end: 3px;
color: var(--identity-tab-color);
}
#userContext-icons {
-moz-box-align: center;
}
.tabbrowser-tab[usercontextid] {
background-image: linear-gradient(to right, transparent 20%, var(--identity-tab-color) 30%, var(--identity-tab-color) 70%, transparent 80%);
background-size: auto 2px;
background-repeat: no-repeat;
}
.userContext-icon,
.menuitem-iconic[data-usercontextid] > .menu-iconic-left > .menu-iconic-icon,
.subviewbutton[usercontextid] > .toolbarbutton-icon,
#userContext-indicator {
background-image: var(--identity-icon);
filter: url(chrome://browser/skin/filters.svg#fill);
fill: var(--identity-icon-color);
background-size: contain;
background-repeat: no-repeat;
background-position: center center;
}

View file

@ -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/usercontext/usercontext.css (content/usercontext.css)

View file

@ -0,0 +1,7 @@
# -*- Mode: python; 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']

View file

@ -0,0 +1,189 @@
<!-- 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/. -->
<panel id="identity-popup"
type="arrow"
hidden="true"
role="alertdialog"
onpopupshown="gIdentityHandler.onPopupShown(event);"
onpopuphidden="gIdentityHandler.onPopupHidden(event);"
orient="vertical">
<broadcasterset>
<broadcaster id="identity-popup-mcb-learn-more" class="text-link plain" value="&identity.learnMore;"/>
<broadcaster id="identity-popup-insecure-login-forms-learn-more" class="text-link plain" value="&identity.learnMore;"/>
</broadcasterset>
<panelmultiview id="identity-popup-multiView"
mainViewId="identity-popup-mainView">
<panelview id="identity-popup-mainView" flex="1">
<!-- Security Section -->
<hbox id="identity-popup-security" class="identity-popup-section">
<vbox id="identity-popup-security-content" flex="1">
<label class="plain">
<label class="identity-popup-headline host"></label>
<label class="identity-popup-headline hostless" crop="end"/>
</label>
<description class="identity-popup-connection-not-secure"
value="&identity.connectionNotSecure;"
when-connection="not-secure secure-cert-user-overridden"/>
<description class="identity-popup-connection-secure"
value="&identity.connectionSecure;"
when-connection="secure secure-ev"/>
<description value="&identity.connectionInternal;"
when-connection="chrome"/>
<description value="&identity.connectionFile;"
when-connection="file"/>
<vbox id="identity-popup-security-descriptions">
<description class="identity-popup-warning-gray"
when-mixedcontent="active-blocked">&identity.activeBlocked;</description>
<description class="identity-popup-warning-yellow"
when-mixedcontent="passive-loaded">&identity.passiveLoaded;</description>
<description when-mixedcontent="active-loaded">&identity.activeLoaded;</description>
<description class="identity-popup-warning-yellow"
when-ciphers="weak">&identity.weakEncryption;</description>
<description when-loginforms="insecure">&identity.insecureLoginForms2;</description>
</vbox>
</vbox>
<button id="identity-popup-security-expander"
class="identity-popup-expander"
when-connection="not-secure secure secure-ev secure-cert-user-overridden"
oncommand="gIdentityHandler.toggleSubView('security', this)"/>
</hbox>
<!-- Tracking Protection Section -->
<hbox id="tracking-protection-container"
class="identity-popup-section"
when-connection="not-secure secure secure-ev secure-cert-user-overridden file">
<vbox id="tracking-protection-content" flex="1">
<description class="identity-popup-headline"
crop="end"
value="&trackingProtection.title;" />
<label id="tracking-blocked"
crop="end">&trackingProtection.detectedBlocked3;</label>
<label id="tracking-loaded"
crop="end">&trackingProtection.detectedNotBlocked3;</label>
<label id="tracking-not-detected"
crop="end">&trackingProtection.notDetected3;</label>
<button id="tracking-action-unblock"
label="&trackingProtection.unblock.label;"
accesskey="&trackingProtection.unblock.accesskey;"
oncommand="TrackingProtection.disableForCurrentPage();" />
<button id="tracking-action-unblock-private"
label="&trackingProtection.unblockPrivate.label;"
accesskey="&trackingProtection.unblockPrivate.accesskey;"
oncommand="TrackingProtection.disableForCurrentPage();" />
<button id="tracking-action-block"
label="&trackingProtection.block2.label;"
accesskey="&trackingProtection.block2.accesskey;"
oncommand="TrackingProtection.enableForCurrentPage();" />
</vbox>
</hbox>
<!-- Permissions Section -->
<hbox class="identity-popup-section">
<vbox id="identity-popup-permissions-content" flex="1">
<label id="identity-popup-permissions-headline"
class="identity-popup-headline"
value="&identity.permissions;"/>
<vbox id="identity-popup-permission-list"/>
<description id="identity-popup-permission-reload-hint">&identity.permissionsReloadHint;</description>
<description id="identity-popup-permission-empty-hint">&identity.permissionsEmpty;</description>
</vbox>
</hbox>
</panelview>
<!-- Security SubView -->
<panelview id="identity-popup-securityView" flex="1">
<vbox id="identity-popup-securityView-header">
<label class="plain">
<label class="identity-popup-headline host"></label>
<label class="identity-popup-headline hostless" crop="end"/>
</label>
<description class="identity-popup-connection-not-secure"
value="&identity.connectionNotSecure;"
when-connection="not-secure secure-cert-user-overridden"/>
<description class="identity-popup-connection-secure"
value="&identity.connectionSecure;"
when-connection="secure secure-ev"/>
</vbox>
<vbox id="identity-popup-securityView-body" flex="1">
<!-- (EV) Certificate Information -->
<description id="identity-popup-content-verified-by"
when-connection="secure-ev">&identity.connectionVerified2;</description>
<description id="identity-popup-content-owner"
when-connection="secure-ev"
class="header"/>
<description id="identity-popup-content-supplemental"
when-connection="secure-ev"/>
<description id="identity-popup-content-verifier"
when-connection="secure secure-ev secure-cert-user-overridden"/>
<!-- Remove Certificate Exception -->
<button when-connection="secure-cert-user-overridden"
label="&identity.removeCertException.label;"
accesskey="&identity.removeCertException.accesskey;"
oncommand="gIdentityHandler.removeCertException()"/>
<!-- Connection is Not Secure -->
<description when-connection="not-secure"
and-when-loginforms="secure">&identity.description.insecure;</description>
<!-- Insecure login forms -->
<description when-loginforms="insecure">&identity.description.insecureLoginForms; <label observes="identity-popup-insecure-login-forms-learn-more"/></description>
<!-- Weak Cipher -->
<description when-ciphers="weak">&identity.description.weakCipher;</description>
<description class="identity-popup-warning-yellow"
when-ciphers="weak">&identity.description.weakCipher2;</description>
<!-- Active Mixed Content Blocked -->
<description class="identity-popup-warning-gray"
when-mixedcontent="active-blocked">&identity.description.activeBlocked; <label observes="identity-popup-mcb-learn-more"/></description>
<!-- Passive Mixed Content Loaded -->
<description when-mixedcontent="passive-loaded">&identity.description.passiveLoaded;</description>
<description class="identity-popup-warning-yellow"
when-mixedcontent="passive-loaded">&identity.description.passiveLoaded2; <label observes="identity-popup-mcb-learn-more"/></description>
<!-- Passive Mixed Content Loaded, Active Mixed Content Blocked -->
<description when-mixedcontent="passive-loaded active-blocked">&identity.description.passiveLoaded;</description>
<description when-mixedcontent="passive-loaded active-blocked"
class="identity-popup-warning-yellow">&identity.description.passiveLoaded3; <label observes="identity-popup-mcb-learn-more"/></description>
<!-- Active Mixed Content Blocking Disabled -->
<description when-mixedcontent="active-loaded"
and-when-loginforms="secure">&identity.description.activeLoaded;</description>
<description when-mixedcontent="active-loaded"
and-when-loginforms="secure">&identity.description.activeLoaded2; <label observes="identity-popup-mcb-learn-more"/></description>
<!-- Show only the first message when there are insecure login forms,
and make sure the Learn More link is included. -->
<description when-mixedcontent="active-loaded"
and-when-loginforms="insecure">&identity.description.activeLoaded; <label observes="identity-popup-mcb-learn-more"/></description>
<!-- Buttons to enable/disable mixed content blocking. -->
<button when-mixedcontent="active-blocked"
label="&identity.disableMixedContentBlocking.label;"
accesskey="&identity.disableMixedContentBlocking.accesskey;"
oncommand="gIdentityHandler.disableMixedContentProtection()"/>
<button when-mixedcontent="active-loaded"
label="&identity.enableMixedContentBlocking.label;"
accesskey="&identity.enableMixedContentBlocking.accesskey;"
oncommand="gIdentityHandler.enableMixedContentProtection()"/>
</vbox>
<vbox id="identity-popup-securityView-footer">
<!-- More Security Information -->
<button label="&identity.moreInfoLinkText2;"
oncommand="gIdentityHandler.handleMoreInfoClick(event);"/>
</vbox>
</panelview>
</panelmultiview>
</panel>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,420 @@
/* 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:///modules/CustomizableUI.jsm");
var gManagers = new WeakMap();
const kPaletteId = "customization-palette";
const kPlaceholderClass = "panel-customization-placeholder";
this.EXPORTED_SYMBOLS = ["DragPositionManager"];
function AreaPositionManager(aContainer) {
// Caching the direction and bounds of the container for quick access later:
let window = aContainer.ownerGlobal;
this._dir = window.getComputedStyle(aContainer).direction;
let containerRect = aContainer.getBoundingClientRect();
this._containerInfo = {
left: containerRect.left,
right: containerRect.right,
top: containerRect.top,
width: containerRect.width
};
this._inPanel = aContainer.id == CustomizableUI.AREA_PANEL;
this._horizontalDistance = null;
this.update(aContainer);
}
AreaPositionManager.prototype = {
_nodePositionStore: null,
_wideCache: null,
update: function(aContainer) {
this._nodePositionStore = new WeakMap();
this._wideCache = new Set();
let last = null;
let singleItemHeight;
for (let child of aContainer.children) {
if (child.hidden) {
continue;
}
let isNodeWide = this._checkIfWide(child);
if (isNodeWide) {
this._wideCache.add(child.id);
}
let coordinates = this._lazyStoreGet(child);
// We keep a baseline horizontal distance between non-wide nodes around
// for use when we can't compare with previous/next nodes
if (!this._horizontalDistance && last && !isNodeWide) {
this._horizontalDistance = coordinates.left - last.left;
}
// We also keep the basic height of non-wide items for use below:
if (!isNodeWide && !singleItemHeight) {
singleItemHeight = coordinates.height;
}
last = !isNodeWide ? coordinates : null;
}
if (this._inPanel) {
this._heightToWidthFactor = CustomizableUI.PANEL_COLUMN_COUNT;
} else {
this._heightToWidthFactor = this._containerInfo.width / singleItemHeight;
}
},
/**
* Find the closest node in the container given the coordinates.
* "Closest" is defined in a somewhat strange manner: we prefer nodes
* which are in the same row over nodes that are in a different row.
* In order to implement this, we use a weighted cartesian distance
* where dy is more heavily weighted by a factor corresponding to the
* ratio between the container's width and the height of its elements.
*/
find: function(aContainer, aX, aY, aDraggedItemId) {
let closest = null;
let minCartesian = Number.MAX_VALUE;
let containerX = this._containerInfo.left;
let containerY = this._containerInfo.top;
for (let node of aContainer.children) {
let coordinates = this._lazyStoreGet(node);
let offsetX = coordinates.x - containerX;
let offsetY = coordinates.y - containerY;
let hDiff = offsetX - aX;
let vDiff = offsetY - aY;
// For wide widgets, we're always going to be further from the center
// horizontally. Compensate:
if (this.isWide(node)) {
hDiff /= CustomizableUI.PANEL_COLUMN_COUNT;
}
// Then compensate for the height/width ratio so that we prefer items
// which are in the same row:
hDiff /= this._heightToWidthFactor;
let cartesianDiff = hDiff * hDiff + vDiff * vDiff;
if (cartesianDiff < minCartesian) {
minCartesian = cartesianDiff;
closest = node;
}
}
// Now correct this node based on what we're dragging
if (closest) {
let doc = aContainer.ownerDocument;
let draggedItem = doc.getElementById(aDraggedItemId);
// If dragging a wide item, always pick the first item in a row:
if (this._inPanel && draggedItem &&
draggedItem.classList.contains(CustomizableUI.WIDE_PANEL_CLASS)) {
return this._firstInRow(closest);
}
let targetBounds = this._lazyStoreGet(closest);
let farSide = this._dir == "ltr" ? "right" : "left";
let outsideX = targetBounds[farSide];
// Check if we're closer to the next target than to this one:
// Only move if we're not targeting a node in a different row:
if (aY > targetBounds.top && aY < targetBounds.bottom) {
if ((this._dir == "ltr" && aX > outsideX) ||
(this._dir == "rtl" && aX < outsideX)) {
return closest.nextSibling || aContainer;
}
}
}
return closest;
},
/**
* "Insert" a "placeholder" by shifting the subsequent children out of the
* way. We go through all the children, and shift them based on the position
* they would have if we had inserted something before aBefore. We use CSS
* transforms for this, which are CSS transitioned.
*/
insertPlaceholder: function(aContainer, aBefore, aWide, aSize, aIsFromThisArea) {
let isShifted = false;
let shiftDown = aWide;
for (let child of aContainer.children) {
// Don't need to shift hidden nodes:
if (child.getAttribute("hidden") == "true") {
continue;
}
// If this is the node before which we're inserting, start shifting
// everything that comes after. One exception is inserting at the end
// of the menupanel, in which case we do not shift the placeholders:
if (child == aBefore && !child.classList.contains(kPlaceholderClass)) {
isShifted = true;
// If the node before which we're inserting is wide, we should
// shift everything one row down:
if (!shiftDown && this.isWide(child)) {
shiftDown = true;
}
}
// If we're moving items before a wide node that were already there,
// it's possible it's not necessary to shift nodes
// including & after the wide node.
if (this.__undoShift) {
isShifted = false;
}
if (isShifted) {
// Conversely, if we're adding something before a wide node, for
// simplicity's sake we move everything including the wide node down:
if (this.__moveDown) {
shiftDown = true;
}
if (aIsFromThisArea && !this._lastPlaceholderInsertion) {
child.setAttribute("notransition", "true");
}
// Determine the CSS transform based on the next node:
child.style.transform = this._getNextPos(child, shiftDown, aSize);
} else {
// If we're not shifting this node, reset the transform
child.style.transform = "";
}
}
if (aContainer.lastChild && aIsFromThisArea &&
!this._lastPlaceholderInsertion) {
// Flush layout:
aContainer.lastChild.getBoundingClientRect();
// then remove all the [notransition]
for (let child of aContainer.children) {
child.removeAttribute("notransition");
}
}
delete this.__moveDown;
delete this.__undoShift;
this._lastPlaceholderInsertion = aBefore;
},
isWide: function(aNode) {
return this._wideCache.has(aNode.id);
},
_checkIfWide: function(aNode) {
return this._inPanel && aNode && aNode.firstChild &&
aNode.firstChild.classList.contains(CustomizableUI.WIDE_PANEL_CLASS);
},
/**
* Reset all the transforms in this container, optionally without
* transitioning them.
* @param aContainer the container in which to reset transforms
* @param aNoTransition if truthy, adds a notransition attribute to the node
* while resetting the transform.
*/
clearPlaceholders: function(aContainer, aNoTransition) {
for (let child of aContainer.children) {
if (aNoTransition) {
child.setAttribute("notransition", true);
}
child.style.transform = "";
if (aNoTransition) {
// Need to force a reflow otherwise this won't work.
child.getBoundingClientRect();
child.removeAttribute("notransition");
}
}
// We snapped back, so we can assume there's no more
// "last" placeholder insertion point to keep track of.
if (aNoTransition) {
this._lastPlaceholderInsertion = null;
}
},
_getNextPos: function(aNode, aShiftDown, aSize) {
// Shifting down is easy:
if (this._inPanel && aShiftDown) {
return "translate(0, " + aSize.height + "px)";
}
return this._diffWithNext(aNode, aSize);
},
_diffWithNext: function(aNode, aSize) {
let xDiff;
let yDiff = null;
let nodeBounds = this._lazyStoreGet(aNode);
let side = this._dir == "ltr" ? "left" : "right";
let next = this._getVisibleSiblingForDirection(aNode, "next");
// First we determine the transform along the x axis.
// Usually, there will be a next node to base this on:
if (next) {
let otherBounds = this._lazyStoreGet(next);
xDiff = otherBounds[side] - nodeBounds[side];
// If the next node is a wide item in the panel, check if we could maybe
// just move further out in the same row, without snapping to the next
// one. This happens, for example, if moving an item that's before a wide
// node within its own row of items. There will be space to drop this
// item within the row, and the rest of the items do not need to shift.
if (this.isWide(next)) {
let otherXDiff = this._moveNextBasedOnPrevious(aNode, nodeBounds,
this._firstInRow(aNode));
// If this has the same sign as our original shift, we're still
// snapping to the start of the row. In this case, we should move
// everything after us a row down, so as not to display two nodes on
// top of each other:
// (we would be able to get away with checking for equality instead of
// equal signs here, but one of these is based on the x coordinate of
// the first item in row N and one on that for row N - 1, so this is
// safer, as their margins might differ)
if ((otherXDiff < 0) == (xDiff < 0)) {
this.__moveDown = true;
} else {
// Otherwise, we succeeded and can move further out. This also means
// we can stop shifting the rest of the content:
xDiff = otherXDiff;
this.__undoShift = true;
}
} else {
// We set this explicitly because otherwise some strange difference
// between the height and the actual difference between line creeps in
// and messes with alignments
yDiff = otherBounds.top - nodeBounds.top;
}
} else {
// We don't have a sibling whose position we can use. First, let's see
// if we're also the first item (which complicates things):
let firstNode = this._firstInRow(aNode);
if (aNode == firstNode) {
// Maybe we stored the horizontal distance between non-wide nodes,
// if not, we'll use the width of the incoming node as a proxy:
xDiff = this._horizontalDistance || aSize.width;
} else {
// If not, we should be able to get the distance to the previous node
// and use the inverse, unless there's no room for another node (ie we
// are the last node and there's no room for another one)
xDiff = this._moveNextBasedOnPrevious(aNode, nodeBounds, firstNode);
}
}
// If we've not determined the vertical difference yet, check it here
if (yDiff === null) {
// If the next node is behind rather than in front, we must have moved
// vertically:
if ((xDiff > 0 && this._dir == "rtl") || (xDiff < 0 && this._dir == "ltr")) {
yDiff = aSize.height;
} else {
// Otherwise, we haven't
yDiff = 0;
}
}
return "translate(" + xDiff + "px, " + yDiff + "px)";
},
/**
* Helper function to find the transform a node if there isn't a next node
* to base that on.
* @param aNode the node to transform
* @param aNodeBounds the bounding rect info of this node
* @param aFirstNodeInRow the first node in aNode's row
*/
_moveNextBasedOnPrevious: function(aNode, aNodeBounds, aFirstNodeInRow) {
let next = this._getVisibleSiblingForDirection(aNode, "previous");
let otherBounds = this._lazyStoreGet(next);
let side = this._dir == "ltr" ? "left" : "right";
let xDiff = aNodeBounds[side] - otherBounds[side];
// If, however, this means we move outside the container's box
// (i.e. the row in which this item is placed is full)
// we should move it to align with the first item in the next row instead
let bound = this._containerInfo[this._dir == "ltr" ? "right" : "left"];
if ((this._dir == "ltr" && xDiff + aNodeBounds.right > bound) ||
(this._dir == "rtl" && xDiff + aNodeBounds.left < bound)) {
xDiff = this._lazyStoreGet(aFirstNodeInRow)[side] - aNodeBounds[side];
}
return xDiff;
},
/**
* Get position details from our cache. If the node is not yet cached, get its position
* information and cache it now.
* @param aNode the node whose position info we want
* @return the position info
*/
_lazyStoreGet: function(aNode) {
let rect = this._nodePositionStore.get(aNode);
if (!rect) {
// getBoundingClientRect() returns a DOMRect that is live, meaning that
// as the element moves around, the rects values change. We don't want
// that - we want a snapshot of what the rect values are right at this
// moment, and nothing else. So we have to clone the values.
let clientRect = aNode.getBoundingClientRect();
rect = {
left: clientRect.left,
right: clientRect.right,
width: clientRect.width,
height: clientRect.height,
top: clientRect.top,
bottom: clientRect.bottom,
};
rect.x = rect.left + rect.width / 2;
rect.y = rect.top + rect.height / 2;
Object.freeze(rect);
this._nodePositionStore.set(aNode, rect);
}
return rect;
},
_firstInRow: function(aNode) {
// XXXmconley: I'm not entirely sure why we need to take the floor of these
// values - it looks like, periodically, we're getting fractional pixels back
// from lazyStoreGet. I've filed bug 994247 to investigate.
let bound = Math.floor(this._lazyStoreGet(aNode).top);
let rv = aNode;
let prev;
while (rv && (prev = this._getVisibleSiblingForDirection(rv, "previous"))) {
if (Math.floor(this._lazyStoreGet(prev).bottom) <= bound) {
return rv;
}
rv = prev;
}
return rv;
},
_getVisibleSiblingForDirection: function(aNode, aDirection) {
let rv = aNode;
do {
rv = rv[aDirection + "Sibling"];
} while (rv && rv.getAttribute("hidden") == "true")
return rv;
}
}
var DragPositionManager = {
start: function(aWindow) {
let areas = CustomizableUI.areas.filter((area) => CustomizableUI.getAreaType(area) != "toolbar");
areas = areas.map((area) => CustomizableUI.getCustomizeTargetForArea(area, aWindow));
areas.push(aWindow.document.getElementById(kPaletteId));
for (let areaNode of areas) {
let positionManager = gManagers.get(areaNode);
if (positionManager) {
positionManager.update(areaNode);
} else {
gManagers.set(areaNode, new AreaPositionManager(areaNode));
}
}
},
add: function(aWindow, aArea, aContainer) {
if (CustomizableUI.getAreaType(aArea) != "toolbar") {
return;
}
gManagers.set(aContainer, new AreaPositionManager(aContainer));
},
remove: function(aWindow, aArea, aContainer) {
if (CustomizableUI.getAreaType(aArea) != "toolbar") {
return;
}
gManagers.delete(aContainer);
},
stop: function() {
gManagers = new WeakMap();
},
getManagerForArea: function(aArea) {
return gManagers.get(aArea);
}
};
Object.freeze(DragPositionManager);

View file

@ -0,0 +1,172 @@
/* 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 {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
this.EXPORTED_SYMBOLS = ["PanelWideWidgetTracker"];
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "CustomizableUI",
"resource:///modules/CustomizableUI.jsm");
var gPanel = CustomizableUI.AREA_PANEL;
// We keep track of the widget placements for the panel locally:
var gPanelPlacements = [];
// All the wide widgets we know of:
var gWideWidgets = new Set();
// All the widgets we know of:
var gSeenWidgets = new Set();
var PanelWideWidgetTracker = {
// Listeners used to validate panel contents whenever they change:
onWidgetAdded: function(aWidgetId, aArea, aPosition) {
if (aArea == gPanel) {
gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel);
let moveForward = this.shouldMoveForward(aWidgetId, aPosition);
this.adjustWidgets(aWidgetId, moveForward);
}
},
onWidgetMoved: function(aWidgetId, aArea, aOldPosition, aNewPosition) {
if (aArea == gPanel) {
gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel);
let moveForward = this.shouldMoveForward(aWidgetId, aNewPosition);
this.adjustWidgets(aWidgetId, moveForward);
}
},
onWidgetRemoved: function(aWidgetId, aPrevArea) {
if (aPrevArea == gPanel) {
gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel);
this.adjustWidgets(aWidgetId, false);
}
},
onWidgetReset: function(aWidgetId) {
gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel);
},
// Listener to keep abreast of any new nodes. We use the DOM one because
// we need access to the actual node's classlist, so we can't use the ones above.
// Furthermore, onWidgetCreated only fires for API-based widgets, not for XUL ones.
onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer) {
if (!gSeenWidgets.has(aNode.id)) {
if (aNode.classList.contains(CustomizableUI.WIDE_PANEL_CLASS)) {
gWideWidgets.add(aNode.id);
}
gSeenWidgets.add(aNode.id);
}
},
// When widgets get destroyed, we remove them from our sets of stuff we care about:
onWidgetDestroyed: function(aWidgetId) {
gSeenWidgets.delete(aWidgetId);
gWideWidgets.delete(aWidgetId);
},
shouldMoveForward: function(aWidgetId, aPosition) {
let currentWidgetAtPosition = gPanelPlacements[aPosition + 1];
let rv = gWideWidgets.has(currentWidgetAtPosition) && !gWideWidgets.has(aWidgetId);
// We might now think we can move forward, but for that we need at least 2 more small
// widgets to be present:
if (rv) {
let furtherWidgets = gPanelPlacements.slice(aPosition + 2);
let realWidgets = 0;
if (furtherWidgets.length >= 2) {
while (furtherWidgets.length && realWidgets < 2) {
let w = furtherWidgets.shift();
if (!gWideWidgets.has(w) && this.checkWidgetStatus(w)) {
realWidgets++;
}
}
}
if (realWidgets < 2) {
rv = false;
}
}
return rv;
},
adjustWidgets: function(aWidgetId, aMoveForwards) {
if (this.adjusting) {
return;
}
this.adjusting = true;
let widgetsAffected = gPanelPlacements.filter((w) => gWideWidgets.has(w));
// If we're moving the wide widgets forwards (down/to the right in the panel)
// we want to start with the last widgets. Otherwise we move widgets over other wide
// widgets, which might mess up their order. Likewise, if moving backwards we should start with
// the first widget and work our way down/right from there.
let compareFn = aMoveForwards ? ((a, b) => a < b) : ((a, b) => a > b);
widgetsAffected.sort((a, b) => compareFn(gPanelPlacements.indexOf(a),
gPanelPlacements.indexOf(b)));
for (let widget of widgetsAffected) {
this.adjustPosition(widget, aMoveForwards);
}
this.adjusting = false;
},
// This function is called whenever an item gets moved in the menu panel. It
// adjusts the position of widgets within the panel to prevent "gaps" between
// wide widgets that could be filled up with single column widgets
adjustPosition: function(aWidgetId, aMoveForwards) {
// Make sure that there are n % columns = 0 narrow buttons before the widget.
let placementIndex = gPanelPlacements.indexOf(aWidgetId);
let prevSiblingCount = 0;
let fixedPos = null;
while (placementIndex--) {
let thisWidgetId = gPanelPlacements[placementIndex];
if (gWideWidgets.has(thisWidgetId)) {
continue;
}
let widgetStatus = this.checkWidgetStatus(thisWidgetId);
if (!widgetStatus) {
continue;
}
if (widgetStatus == "public-only") {
fixedPos = !fixedPos ? placementIndex : Math.min(fixedPos, placementIndex);
prevSiblingCount = 0;
} else {
prevSiblingCount++;
}
}
if (fixedPos !== null || prevSiblingCount % CustomizableUI.PANEL_COLUMN_COUNT) {
let desiredPos = (fixedPos !== null) ? fixedPos : gPanelPlacements.indexOf(aWidgetId);
let desiredChange = -(prevSiblingCount % CustomizableUI.PANEL_COLUMN_COUNT);
if (aMoveForwards && fixedPos == null) {
// +1 because otherwise we'd count ourselves:
desiredChange = CustomizableUI.PANEL_COLUMN_COUNT + desiredChange + 1;
}
desiredPos += desiredChange;
CustomizableUI.moveWidgetWithinArea(aWidgetId, desiredPos);
}
},
/*
* Check whether a widget id is actually known anywhere.
* @returns false if the widget doesn't exist,
* "public-only" if it's not shown in private windows
* "real" if it does exist and is shown even in private windows
*/
checkWidgetStatus: function(aWidgetId) {
let widgetWrapper = CustomizableUI.getWidget(aWidgetId);
// This widget might not actually exist:
if (!widgetWrapper) {
return false;
}
// This widget might still not actually exist:
if (widgetWrapper.provider == CustomizableUI.PROVIDER_XUL &&
widgetWrapper.instances.length == 0) {
return false;
}
// Or it might only be there some of the time:
if (widgetWrapper.provider == CustomizableUI.PROVIDER_API &&
widgetWrapper.showInPrivateBrowsing === false) {
return "public-only";
}
return "real";
},
init: function() {
// Initialize our local placements copy and register the listener
gPanelPlacements = CustomizableUI.getWidgetIdsInArea(gPanel);
CustomizableUI.addListener(this);
},
};

View file

@ -0,0 +1,65 @@
/* 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 = ["ScrollbarSampler"];
const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var gSystemScrollbarWidth = null;
this.ScrollbarSampler = {
getSystemScrollbarWidth: function() {
if (gSystemScrollbarWidth !== null) {
return Promise.resolve(gSystemScrollbarWidth);
}
return new Promise(resolve => {
this._sampleSystemScrollbarWidth().then(function(systemScrollbarWidth) {
gSystemScrollbarWidth = systemScrollbarWidth;
resolve(gSystemScrollbarWidth);
});
});
},
resetSystemScrollbarWidth: function() {
gSystemScrollbarWidth = null;
},
_sampleSystemScrollbarWidth: function() {
let hwin = Services.appShell.hiddenDOMWindow;
let hdoc = hwin.document.documentElement;
let iframe = hwin.document.createElementNS("http://www.w3.org/1999/xhtml",
"html:iframe");
iframe.setAttribute("srcdoc", '<body style="overflow-y: scroll"></body>');
hdoc.appendChild(iframe);
let cwindow = iframe.contentWindow;
let utils = cwindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
return new Promise(resolve => {
cwindow.addEventListener("load", function onLoad(aEvent) {
cwindow.removeEventListener("load", onLoad);
let sbWidth = {};
try {
utils.getScrollbarSize(true, sbWidth, {});
} catch (e) {
Cu.reportError("Could not sample scrollbar size: " + e + " -- " +
e.stack);
sbWidth.value = 0;
}
// Minimum width of 10 so that we have enough padding:
sbWidth.value = Math.max(sbWidth.value, 10);
resolve(sbWidth.value);
iframe.remove();
});
});
}
};
Object.freeze(this.ScrollbarSampler);

View file

@ -0,0 +1,82 @@
<!-- 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/. -->
<hbox id="customization-container" flex="1" hidden="true">
<vbox flex="1" id="customization-palette-container">
<label id="customization-header">
&customizeMode.menuAndToolbars.header2;
</label>
<hbox id="customization-empty" hidden="true">
<label>&customizeMode.menuAndToolbars.empty;</label>
<label onclick="BrowserOpenAddonsMgr('addons://discover/');"
onkeypress="BrowserOpenAddonsMgr('addons://discover/');"
id="customization-more-tools"
class="text-link">
&customizeMode.menuAndToolbars.emptyLink;
</label>
</hbox>
<vbox id="customization-palette" class="customization-palette"/>
<spacer id="customization-spacer"/>
<hbox id="customization-footer">
#ifdef CAN_DRAW_IN_TITLEBAR
<button id="customization-titlebar-visibility-button" class="customizationmode-button"
label="&customizeMode.titlebar;" type="checkbox"
#NB: because oncommand fires after click, by the time we've fired, the checkbox binding
# will already have switched the button's state, so this is correct:
oncommand="gCustomizeMode.toggleTitlebar(this.hasAttribute('checked'))"/>
#endif
<button id="customization-toolbar-visibility-button" label="&customizeMode.toolbars;" class="customizationmode-button" type="menu">
<menupopup id="customization-toolbar-menu" onpopupshowing="onViewToolbarsPopupShowing(event)"/>
</button>
<button id="customization-lwtheme-button" label="&customizeMode.lwthemes;" class="customizationmode-button" type="menu">
<panel type="arrow" id="customization-lwtheme-menu"
onpopupshowing="gCustomizeMode.onLWThemesMenuShowing(event);"
position="topcenter bottomleft"
flip="none"
role="menu">
<label id="customization-lwtheme-menu-header" value="&customizeMode.lwthemes.myThemes;"/>
<label id="customization-lwtheme-menu-recommended" value="&customizeMode.lwthemes.recommended;"/>
<hbox id="customization-lwtheme-menu-footer">
<toolbarbutton class="customization-lwtheme-menu-footeritem"
label="&customizeMode.lwthemes.menuManage;"
accesskey="&customizeMode.lwthemes.menuManage.accessKey;"
tabindex="0"
oncommand="gCustomizeMode.openAddonsManagerThemes(event);"/>
<toolbarbutton class="customization-lwtheme-menu-footeritem"
label="&customizeMode.lwthemes.menuGetMore;"
accesskey="&customizeMode.lwthemes.menuGetMore.accessKey;"
tabindex="0"
oncommand="gCustomizeMode.getMoreThemes(event);"/>
</hbox>
</panel>
</button>
<spacer id="customization-footer-spacer"/>
<button id="customization-undo-reset-button"
class="customizationmode-button"
hidden="true"
oncommand="gCustomizeMode.undoReset();"
label="&undoCmd.label;"/>
<button id="customization-reset-button"
oncommand="gCustomizeMode.reset();"
label="&customizeMode.restoreDefaults;"
class="customizationmode-button"/>
</hbox>
</vbox>
<vbox id="customization-panel-container">
<vbox id="customization-panelWrapper">
<html:style html:type="text/html" scoped="scoped">
@import url(chrome://global/skin/popup.css);
</html:style>
<box class="panel-arrowbox">
<box flex="1"/>
<image class="panel-arrow" side="top"/>
</box>
<box class="panel-arrowcontent" side="top" flex="1">
<hbox id="customization-panelHolder"/>
<box class="panel-inner-arrowcontentfooter" hidden="true"/>
</box>
</vbox>
</vbox>
</hbox>

View file

@ -0,0 +1,10 @@
# 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/customizableui/panelUI.css
content/browser/customizableui/panelUI.js
content/browser/customizableui/panelUI.xml
content/browser/customizableui/toolbar.xml

View file

@ -0,0 +1,7 @@
# -*- Mode: python; 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']

View file

@ -0,0 +1,31 @@
/* 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/. */
.panel-viewstack[viewtype="main"] > .panel-clickcapturer {
pointer-events: none;
}
.panel-mainview,
.panel-viewcontainer,
.panel-viewstack {
overflow: hidden;
}
.panel-viewstack {
position: relative;
}
.panel-subviews {
-moz-stack-sizing: ignore;
transform: translateX(0);
overflow-y: auto;
}
.panel-subviews[panelopen] {
transition: transform var(--panelui-subview-transition-duration);
}
.panel-viewcontainer[panelopen]:-moz-any(:not([viewtype="main"]),[transitioning="true"]) {
transition: height var(--panelui-subview-transition-duration);
}

View file

@ -0,0 +1,386 @@
<!-- 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/. -->
<panel id="PanelUI-popup"
role="group"
type="arrow"
hidden="true"
flip="slide"
position="bottomcenter topright"
noautofocus="true">
<panelmultiview id="PanelUI-multiView" mainViewId="PanelUI-mainView">
<panelview id="PanelUI-mainView" context="customizationPanelContextMenu">
<vbox id="PanelUI-contents-scroller">
<vbox id="PanelUI-contents" class="panelUI-grid"/>
</vbox>
<footer id="PanelUI-footer">
<toolbarbutton id="PanelUI-update-status"
oncommand="gMenuButtonUpdateBadge.onMenuPanelCommand(event);"
wrap="true"
hidden="true"/>
<hbox id="PanelUI-footer-fxa">
<hbox id="PanelUI-fxa-status"
defaultlabel="&fxaSignIn.label;"
signedinTooltiptext="&fxaSignedIn.tooltip;"
tooltiptext="&fxaSignedIn.tooltip;"
errorlabel="&fxaSignInError.label;"
unverifiedlabel="&fxaUnverified.label;"
onclick="if (event.which == 1) gFxAccounts.onMenuPanelCommand();">
<image id="PanelUI-fxa-avatar"/>
<toolbarbutton id="PanelUI-fxa-label"
fxabrandname="&syncBrand.fxAccount.label;"/>
</hbox>
<toolbarseparator/>
<toolbarbutton id="PanelUI-fxa-icon"
oncommand="gSyncUI.doSync();"
closemenu="none">
<observes element="sync-status" attribute="syncstatus"/>
<observes element="sync-status" attribute="tooltiptext"/>
</toolbarbutton>
</hbox>
<hbox id="PanelUI-footer-inner">
<toolbarbutton id="PanelUI-customize" label="&appMenuCustomize.label;"
exitLabel="&appMenuCustomizeExit.label;"
tooltiptext="&appMenuCustomize.tooltip;"
exitTooltiptext="&appMenuCustomizeExit.tooltip;"
closemenu="none"
oncommand="gCustomizeMode.toggle();"/>
<toolbarseparator/>
<toolbarbutton id="PanelUI-help" label="&helpMenu.label;"
closemenu="none"
tooltiptext="&appMenuHelp.tooltip;"
oncommand="PanelUI.showHelpView(this);"/>
<toolbarseparator/>
<toolbarbutton id="PanelUI-quit"
#ifdef XP_WIN
label="&quitApplicationCmdWin2.label;"
tooltiptext="&quitApplicationCmdWin2.tooltip;"
#else
#ifdef XP_MACOSX
label="&quitApplicationCmdMac2.label;"
#else
label="&quitApplicationCmd.label;"
#endif
#endif
command="cmd_quitApplication"/>
</hbox>
</footer>
</panelview>
<panelview id="PanelUI-history" flex="1">
<label value="&appMenuHistory.label;" class="panel-subview-header"/>
<vbox class="panel-subview-body">
<toolbarbutton id="appMenuViewHistorySidebar"
label="&appMenuHistory.viewSidebar.label;"
type="checkbox"
class="subviewbutton"
key="key_gotoHistory"
oncommand="SidebarUI.toggle('viewHistorySidebar'); PanelUI.hide();">
<observes element="viewHistorySidebar" attribute="checked"/>
</toolbarbutton>
<toolbarbutton id="appMenuClearRecentHistory"
label="&appMenuHistory.clearRecent.label;"
class="subviewbutton"
command="Tools:Sanitize"/>
<toolbarbutton id="appMenuRestoreLastSession"
label="&appMenuHistory.restoreSession.label;"
class="subviewbutton"
command="Browser:RestoreLastSession"/>
<menuseparator id="PanelUI-recentlyClosedTabs-separator"/>
<vbox id="PanelUI-recentlyClosedTabs" tooltip="bhTooltip"/>
<menuseparator id="PanelUI-recentlyClosedWindows-separator"/>
<vbox id="PanelUI-recentlyClosedWindows" tooltip="bhTooltip"/>
<menuseparator id="PanelUI-historyItems-separator"/>
<vbox id="PanelUI-historyItems" tooltip="bhTooltip"/>
</vbox>
<toolbarbutton id="PanelUI-historyMore"
class="panel-subview-footer subviewbutton"
label="&appMenuHistory.showAll.label;"
oncommand="PlacesCommandHook.showPlacesOrganizer('History'); CustomizableUI.hidePanelForNode(this);"/>
</panelview>
<panelview id="PanelUI-remotetabs" flex="1" class="PanelUI-subView">
<label value="&appMenuRemoteTabs.label;" class="panel-subview-header"/>
<vbox class="panel-subview-body">
<!-- this widget has 3 boxes in the body, but only 1 is ever visible -->
<!-- When Sync is ready to sync -->
<vbox id="PanelUI-remotetabs-main" observes="sync-syncnow-state">
<vbox id="PanelUI-remotetabs-buttons">
<toolbarbutton id="PanelUI-remotetabs-view-sidebar"
class="subviewbutton"
observes="viewTabsSidebar"
label="&appMenuRemoteTabs.sidebar.label;"/>
<toolbarbutton id="PanelUI-remotetabs-syncnow"
observes="sync-status"
class="subviewbutton"
oncommand="gSyncUI.doSync();"
closemenu="none"/>
<menuseparator id="PanelUI-remotetabs-separator"/>
</vbox>
<deck id="PanelUI-remotetabs-deck">
<!-- Sync is ready to Sync and the "tabs" engine is enabled -->
<vbox id="PanelUI-remotetabs-tabspane">
<vbox id="PanelUI-remotetabs-tabslist"
notabsforclientlabel="&appMenuRemoteTabs.notabs.label;"
/>
</vbox>
<!-- Sync is ready to Sync but the "tabs" engine isn't enabled-->
<hbox id="PanelUI-remotetabs-tabsdisabledpane" pack="center" flex="1">
<vbox class="PanelUI-remotetabs-instruction-box">
<hbox pack="center">
<image class="fxaSyncIllustration" alt=""/>
</hbox>
<label class="PanelUI-remotetabs-instruction-label">&appMenuRemoteTabs.tabsnotsyncing.label;</label>
<hbox pack="center">
<toolbarbutton class="PanelUI-remotetabs-prefs-button"
label="&appMenuRemoteTabs.openprefs.label;"
oncommand="gSyncUI.openSetup(null, 'synced-tabs');"/>
</hbox>
</vbox>
</hbox>
<!-- Sync is ready to Sync but we are still fetching the tabs to show -->
<vbox id="PanelUI-remotetabs-fetching">
<!-- Show intentionally blank panel, see bug 1239845 -->
</vbox>
<!-- Sync has only 1 (ie, this) device connected -->
<hbox id="PanelUI-remotetabs-nodevicespane" pack="center" flex="1">
<vbox class="PanelUI-remotetabs-instruction-box">
<hbox pack="center">
<image class="fxaSyncIllustration" alt=""/>
</hbox>
<label class="PanelUI-remotetabs-instruction-title">&appMenuRemoteTabs.noclients.title;</label>
<label class="PanelUI-remotetabs-instruction-label">&appMenuRemoteTabs.noclients.subtitle;</label>
<!-- The inner HTML for PanelUI-remotetabs-mobile-promo is built at runtime -->
<label id="PanelUI-remotetabs-mobile-promo" fxAccountsBrand="&syncBrand.fxAccount.label;"/>
</vbox>
</hbox>
</deck>
</vbox>
<!-- a box to ensure contained boxes are centered horizonally -->
<hbox pack="center" flex="1">
<!-- When Sync is not configured -->
<vbox id="PanelUI-remotetabs-setupsync"
flex="1"
align="center"
class="PanelUI-remotetabs-instruction-box"
observes="sync-setup-state">
<image class="fxaSyncIllustration" alt=""/>
<label class="PanelUI-remotetabs-instruction-label">&appMenuRemoteTabs.notsignedin.label;</label>
<toolbarbutton class="PanelUI-remotetabs-prefs-button"
label="&appMenuRemoteTabs.signin.label;"
oncommand="gSyncUI.openSetup(null, 'synced-tabs');"/>
</vbox>
<!-- When Sync needs re-authentication. This uses the exact same messaging
as "Sync is not configured" but remains a separate box so we get
the goodness of observing broadcasters to manage the hidden states -->
<vbox id="PanelUI-remotetabs-reauthsync"
flex="1"
align="center"
class="PanelUI-remotetabs-instruction-box"
observes="sync-reauth-state">
<image class="fxaSyncIllustration" alt=""/>
<label class="PanelUI-remotetabs-instruction-label">&appMenuRemoteTabs.notsignedin.label;</label>
<toolbarbutton class="PanelUI-remotetabs-prefs-button"
label="&appMenuRemoteTabs.signin.label;"
oncommand="gSyncUI.openSetup(null, 'synced-tabs');"/>
</vbox>
</hbox>
</vbox>
</panelview>
<panelview id="PanelUI-bookmarks" flex="1" class="PanelUI-subView">
<label value="&bookmarksMenu.label;" class="panel-subview-header"/>
<vbox class="panel-subview-body">
<toolbarbutton id="panelMenuBookmarkThisPage"
class="subviewbutton"
observes="bookmarkThisPageBroadcaster"
command="Browser:AddBookmarkAs"
onclick="PanelUI.hide();"/>
<toolbarseparator/>
<toolbarbutton id="panelMenu_viewBookmarksSidebar"
label="&viewBookmarksSidebar2.label;"
class="subviewbutton"
key="viewBookmarksSidebarKb"
oncommand="SidebarUI.toggle('viewBookmarksSidebar'); PanelUI.hide();">
<observes element="viewBookmarksSidebar" attribute="checked"/>
</toolbarbutton>
<toolbarbutton id="panelMenu_viewBookmarksToolbar"
label="&viewBookmarksToolbar.label;"
type="checkbox"
toolbarId="PersonalToolbar"
class="subviewbutton"
oncommand="onViewToolbarCommand(event); PanelUI.hide();"/>
<toolbarseparator/>
<toolbarbutton id="panelMenu_bookmarksToolbar"
label="&personalbarCmd.label;"
class="subviewbutton cui-withicon"
oncommand="PlacesCommandHook.showPlacesOrganizer('BookmarksToolbar'); PanelUI.hide();"/>
<toolbarbutton id="panelMenu_unsortedBookmarks"
label="&otherBookmarksCmd.label;"
class="subviewbutton cui-withicon"
oncommand="PlacesCommandHook.showPlacesOrganizer('UnfiledBookmarks'); PanelUI.hide();"/>
<toolbarseparator class="small-separator"/>
<toolbaritem id="panelMenu_bookmarksMenu"
orient="vertical"
smoothscroll="false"
onclick="if (event.button == 1) BookmarkingUI.onPanelMenuViewCommand(event, this._placesView);"
oncommand="BookmarkingUI.onPanelMenuViewCommand(event, this._placesView);"
flatList="true"
tooltip="bhTooltip">
<!-- bookmarks menu items will go here -->
</toolbaritem>
</vbox>
<toolbarbutton id="panelMenu_showAllBookmarks"
label="&showAllBookmarks2.label;"
class="subviewbutton panel-subview-footer"
command="Browser:ShowAllBookmarks"
onclick="PanelUI.hide();"/>
</panelview>
<panelview id="PanelUI-feeds" flex="1" oncommand="FeedHandler.subscribeToFeed(null, event);">
<label value="&feedsMenu2.label;" class="panel-subview-header"/>
</panelview>
<panelview id="PanelUI-containers" flex="1">
<label value="&containersMenu.label;" class="panel-subview-header"/>
<vbox id="PanelUI-containersItems"/>
</panelview>
<panelview id="PanelUI-helpView" flex="1" class="PanelUI-subView">
<label value="&helpMenu.label;" class="panel-subview-header"/>
<vbox id="PanelUI-helpItems" class="panel-subview-body"/>
</panelview>
<panelview id="PanelUI-developer" flex="1">
<label value="&webDeveloperMenu.label;" class="panel-subview-header"/>
<vbox id="PanelUI-developerItems" class="panel-subview-body"/>
</panelview>
<panelview id="PanelUI-sidebar" flex="1">
<label value="&appMenuSidebars.label;" class="panel-subview-header"/>
<vbox id="PanelUI-sidebarItems" class="panel-subview-body"/>
</panelview>
<panelview id="PanelUI-characterEncodingView" flex="1">
<label value="&charsetMenu2.label;" class="panel-subview-header"/>
<vbox class="panel-subview-body">
<vbox id="PanelUI-characterEncodingView-pinned"
class="PanelUI-characterEncodingView-list"/>
<toolbarseparator/>
<vbox id="PanelUI-characterEncodingView-charsets"
class="PanelUI-characterEncodingView-list"/>
<toolbarseparator/>
<vbox>
<label id="PanelUI-characterEncodingView-autodetect-label"/>
<vbox id="PanelUI-characterEncodingView-autodetect"
class="PanelUI-characterEncodingView-list"/>
</vbox>
</vbox>
</panelview>
<panelview id="PanelUI-panicView" flex="1">
<vbox class="panel-subview-body">
<hbox id="PanelUI-panic-timeframe">
<image id="PanelUI-panic-timeframe-icon" alt=""/>
<vbox flex="1">
<hbox id="PanelUI-panic-header">
<image id="PanelUI-panic-timeframe-icon-small" alt=""/>
<description id="PanelUI-panic-mainDesc" flex="1">&panicButton.view.mainTimeframeDesc;</description>
</hbox>
<radiogroup id="PanelUI-panic-timeSpan" aria-labelledby="PanelUI-panic-mainDesc" closemenu="none">
<radio id="PanelUI-panic-5min" label="&panicButton.view.5min;" selected="true"
value="5" class="subviewradio"/>
<radio id="PanelUI-panic-2hr" label="&panicButton.view.2hr;"
value="2" class="subviewradio"/>
<radio id="PanelUI-panic-day" label="&panicButton.view.day;"
value="6" class="subviewradio"/>
</radiogroup>
</vbox>
</hbox>
<vbox id="PanelUI-panic-explanations">
<label id="PanelUI-panic-actionlist-main-label">&panicButton.view.mainActionDesc;</label>
<label id="PanelUI-panic-actionlist-windows" class="PanelUI-panic-actionlist">&panicButton.view.deleteTabsAndWindows;</label>
<label id="PanelUI-panic-actionlist-cookies" class="PanelUI-panic-actionlist">&panicButton.view.deleteCookies;</label>
<label id="PanelUI-panic-actionlist-history" class="PanelUI-panic-actionlist">&panicButton.view.deleteHistory;</label>
<label id="PanelUI-panic-actionlist-newwindow" class="PanelUI-panic-actionlist">&panicButton.view.openNewWindow;</label>
<label id="PanelUI-panic-warning">&panicButton.view.undoWarning;</label>
</vbox>
<button id="PanelUI-panic-view-button"
label="&panicButton.view.forgetButton;"/>
</vbox>
</panelview>
</panelmultiview>
<!-- These menupopups are located here to prevent flickering,
see bug 492960 comment 20. -->
<menupopup id="customizationPanelItemContextMenu">
<menuitem oncommand="gCustomizeMode.addToToolbar(document.popupNode)"
closemenu="single"
class="customize-context-moveToToolbar"
accesskey="&customizeMenu.moveToToolbar.accesskey;"
label="&customizeMenu.moveToToolbar.label;"/>
<menuitem oncommand="gCustomizeMode.removeFromArea(document.popupNode)"
closemenu="single"
class="customize-context-removeFromPanel"
accesskey="&customizeMenu.removeFromMenu.accesskey;"
label="&customizeMenu.removeFromMenu.label;"/>
<menuseparator/>
<menuitem command="cmd_CustomizeToolbars"
class="viewCustomizeToolbar"
accesskey="&viewCustomizeToolbar.accesskey;"
label="&viewCustomizeToolbar.label;"/>
</menupopup>
<menupopup id="customizationPaletteItemContextMenu">
<menuitem oncommand="gCustomizeMode.addToToolbar(document.popupNode)"
class="customize-context-addToToolbar"
accesskey="&customizeMenu.addToToolbar.accesskey;"
label="&customizeMenu.addToToolbar.label;"/>
<menuitem oncommand="gCustomizeMode.addToPanel(document.popupNode)"
class="customize-context-addToPanel"
accesskey="&customizeMenu.addToPanel.accesskey;"
label="&customizeMenu.addToPanel.label;"/>
</menupopup>
<menupopup id="customizationPanelContextMenu">
<menuitem command="cmd_CustomizeToolbars"
accesskey="&customizeMenu.addMoreItems.accesskey;"
label="&customizeMenu.addMoreItems.label;"/>
</menupopup>
</panel>
<panel id="widget-overflow"
role="group"
type="arrow"
noautofocus="true"
context="toolbar-context-menu"
position="bottomcenter topright"
hidden="true">
<vbox id="widget-overflow-scroller">
<vbox id="widget-overflow-list" class="widget-overflow-list"
overflowfortoolbar="nav-bar"/>
</vbox>
</panel>
<panel id="panic-button-success-notification"
type="arrow"
position="bottomcenter topright"
hidden="true"
role="alert"
orient="vertical">
<hbox id="panic-button-success-header">
<image id="panic-button-success-icon" alt=""/>
<vbox>
<description>&panicButton.thankyou.msg1;</description>
<description>&panicButton.thankyou.msg2;</description>
</vbox>
</hbox>
<button label="&panicButton.thankyou.buttonlabel;"
id="panic-button-success-closebutton"
oncommand="PanicButtonNotifier.close()"/>
</panel>

View file

@ -0,0 +1,558 @@
/* 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/. */
XPCOMUtils.defineLazyModuleGetter(this, "CustomizableUI",
"resource:///modules/CustomizableUI.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ScrollbarSampler",
"resource:///modules/ScrollbarSampler.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ShortcutUtils",
"resource://gre/modules/ShortcutUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
"resource://gre/modules/AppConstants.jsm");
/**
* Maintains the state and dispatches events for the main menu panel.
*/
const PanelUI = {
/** Panel events that we listen for. **/
get kEvents() {
return ["popupshowing", "popupshown", "popuphiding", "popuphidden"];
},
/**
* Used for lazily getting and memoizing elements from the document. Lazy
* getters are set in init, and memoizing happens after the first retrieval.
*/
get kElements() {
return {
contents: "PanelUI-contents",
mainView: "PanelUI-mainView",
multiView: "PanelUI-multiView",
helpView: "PanelUI-helpView",
menuButton: "PanelUI-menu-button",
panel: "PanelUI-popup",
scroller: "PanelUI-contents-scroller"
};
},
_initialized: false,
init: function() {
for (let [k, v] of Object.entries(this.kElements)) {
// Need to do fresh let-bindings per iteration
let getKey = k;
let id = v;
this.__defineGetter__(getKey, function() {
delete this[getKey];
return this[getKey] = document.getElementById(id);
});
}
this.menuButton.addEventListener("mousedown", this);
this.menuButton.addEventListener("keypress", this);
this._overlayScrollListenerBoundFn = this._overlayScrollListener.bind(this);
window.matchMedia("(-moz-overlay-scrollbars)").addListener(this._overlayScrollListenerBoundFn);
CustomizableUI.addListener(this);
this._initialized = true;
},
_eventListenersAdded: false,
_ensureEventListenersAdded: function() {
if (this._eventListenersAdded)
return;
this._addEventListeners();
},
_addEventListeners: function() {
for (let event of this.kEvents) {
this.panel.addEventListener(event, this);
}
this.helpView.addEventListener("ViewShowing", this._onHelpViewShow, false);
this._eventListenersAdded = true;
},
uninit: function() {
for (let event of this.kEvents) {
this.panel.removeEventListener(event, this);
}
this.helpView.removeEventListener("ViewShowing", this._onHelpViewShow);
this.menuButton.removeEventListener("mousedown", this);
this.menuButton.removeEventListener("keypress", this);
window.matchMedia("(-moz-overlay-scrollbars)").removeListener(this._overlayScrollListenerBoundFn);
CustomizableUI.removeListener(this);
this._overlayScrollListenerBoundFn = null;
},
/**
* Customize mode extracts the mainView and puts it somewhere else while the
* user customizes. Upon completion, this function can be called to put the
* panel back to where it belongs in normal browsing mode.
*
* @param aMainView
* The mainView node to put back into place.
*/
setMainView: function(aMainView) {
this._ensureEventListenersAdded();
this.multiView.setMainView(aMainView);
},
/**
* Opens the menu panel if it's closed, or closes it if it's
* open.
*
* @param aEvent the event that triggers the toggle.
*/
toggle: function(aEvent) {
// Don't show the panel if the window is in customization mode,
// since this button doubles as an exit path for the user in this case.
if (document.documentElement.hasAttribute("customizing")) {
return;
}
this._ensureEventListenersAdded();
if (this.panel.state == "open") {
this.hide();
} else if (this.panel.state == "closed") {
this.show(aEvent);
}
},
/**
* Opens the menu panel. If the event target has a child with the
* toolbarbutton-icon attribute, the panel will be anchored on that child.
* Otherwise, the panel is anchored on the event target itself.
*
* @param aEvent the event (if any) that triggers showing the menu.
*/
show: function(aEvent) {
return new Promise(resolve => {
this.ensureReady().then(() => {
if (this.panel.state == "open" ||
document.documentElement.hasAttribute("customizing")) {
resolve();
return;
}
let editControlPlacement = CustomizableUI.getPlacementOfWidget("edit-controls");
if (editControlPlacement && editControlPlacement.area == CustomizableUI.AREA_PANEL) {
updateEditUIVisibility();
}
let personalBookmarksPlacement = CustomizableUI.getPlacementOfWidget("personal-bookmarks");
if (personalBookmarksPlacement &&
personalBookmarksPlacement.area == CustomizableUI.AREA_PANEL) {
PlacesToolbarHelper.customizeChange();
}
let anchor;
if (!aEvent ||
aEvent.type == "command") {
anchor = this.menuButton;
} else {
anchor = aEvent.target;
}
this.panel.addEventListener("popupshown", function onPopupShown() {
this.removeEventListener("popupshown", onPopupShown);
resolve();
});
let iconAnchor =
document.getAnonymousElementByAttribute(anchor, "class",
"toolbarbutton-icon");
this.panel.openPopup(iconAnchor || anchor);
}, (reason) => {
console.error("Error showing the PanelUI menu", reason);
});
});
},
/**
* If the menu panel is being shown, hide it.
*/
hide: function() {
if (document.documentElement.hasAttribute("customizing")) {
return;
}
this.panel.hidePopup();
},
handleEvent: function(aEvent) {
// Ignore context menus and menu button menus showing and hiding:
if (aEvent.type.startsWith("popup") &&
aEvent.target != this.panel) {
return;
}
switch (aEvent.type) {
case "popupshowing":
this._adjustLabelsForAutoHyphens();
// Fall through
case "popupshown":
// Fall through
case "popuphiding":
// Fall through
case "popuphidden":
this._updatePanelButton(aEvent.target);
break;
case "mousedown":
if (aEvent.button == 0)
this.toggle(aEvent);
break;
case "keypress":
this.toggle(aEvent);
break;
}
},
get isReady() {
return !!this._isReady;
},
/**
* Registering the menu panel is done lazily for performance reasons. This
* method is exposed so that CustomizationMode can force panel-readyness in the
* event that customization mode is started before the panel has been opened
* by the user.
*
* @param aCustomizing (optional) set to true if this was called while entering
* customization mode. If that's the case, we trust that customization
* mode will handle calling beginBatchUpdate and endBatchUpdate.
*
* @return a Promise that resolves once the panel is ready to roll.
*/
ensureReady: function(aCustomizing=false) {
if (this._readyPromise) {
return this._readyPromise;
}
this._readyPromise = Task.spawn(function*() {
if (!this._initialized) {
yield new Promise(resolve => {
let delayedStartupObserver = (aSubject, aTopic, aData) => {
if (aSubject == window) {
Services.obs.removeObserver(delayedStartupObserver, "browser-delayed-startup-finished");
resolve();
}
};
Services.obs.addObserver(delayedStartupObserver, "browser-delayed-startup-finished", false);
});
}
this.contents.setAttributeNS("http://www.w3.org/XML/1998/namespace", "lang",
getLocale());
if (!this._scrollWidth) {
// In order to properly center the contents of the panel, while ensuring
// that we have enough space on either side to show a scrollbar, we have to
// do a bit of hackery. In particular, we calculate a new width for the
// scroller, based on the system scrollbar width.
this._scrollWidth =
(yield ScrollbarSampler.getSystemScrollbarWidth()) + "px";
let cstyle = window.getComputedStyle(this.scroller);
let widthStr = cstyle.width;
// Get the calculated padding on the left and right sides of
// the scroller too. We'll use that in our final calculation so
// that if a scrollbar appears, we don't have the contents right
// up against the edge of the scroller.
let paddingLeft = cstyle.paddingLeft;
let paddingRight = cstyle.paddingRight;
let calcStr = [widthStr, this._scrollWidth,
paddingLeft, paddingRight].join(" + ");
this.scroller.style.width = "calc(" + calcStr + ")";
}
if (aCustomizing) {
CustomizableUI.registerMenuPanel(this.contents);
} else {
this.beginBatchUpdate();
try {
CustomizableUI.registerMenuPanel(this.contents);
} finally {
this.endBatchUpdate();
}
}
this._updateQuitTooltip();
this.panel.hidden = false;
this._isReady = true;
}.bind(this)).then(null, Cu.reportError);
return this._readyPromise;
},
/**
* Switch the panel to the main view if it's not already
* in that view.
*/
showMainView: function() {
this._ensureEventListenersAdded();
this.multiView.showMainView();
},
/**
* Switch the panel to the help view if it's not already
* in that view.
*/
showHelpView: function(aAnchor) {
this._ensureEventListenersAdded();
this.multiView.showSubView("PanelUI-helpView", aAnchor);
},
/**
* Shows a subview in the panel with a given ID.
*
* @param aViewId the ID of the subview to show.
* @param aAnchor the element that spawned the subview.
* @param aPlacementArea the CustomizableUI area that aAnchor is in.
*/
showSubView: Task.async(function*(aViewId, aAnchor, aPlacementArea) {
this._ensureEventListenersAdded();
let viewNode = document.getElementById(aViewId);
if (!viewNode) {
Cu.reportError("Could not show panel subview with id: " + aViewId);
return;
}
if (!aAnchor) {
Cu.reportError("Expected an anchor when opening subview with id: " + aViewId);
return;
}
if (aPlacementArea == CustomizableUI.AREA_PANEL) {
this.multiView.showSubView(aViewId, aAnchor);
} else if (!aAnchor.open) {
aAnchor.open = true;
let tempPanel = document.createElement("panel");
tempPanel.setAttribute("type", "arrow");
tempPanel.setAttribute("id", "customizationui-widget-panel");
tempPanel.setAttribute("class", "cui-widget-panel");
tempPanel.setAttribute("viewId", aViewId);
if (aAnchor.getAttribute("tabspecific")) {
tempPanel.setAttribute("tabspecific", true);
}
if (this._disableAnimations) {
tempPanel.setAttribute("animate", "false");
}
tempPanel.setAttribute("context", "");
document.getElementById(CustomizableUI.AREA_NAVBAR).appendChild(tempPanel);
// If the view has a footer, set a convenience class on the panel.
tempPanel.classList.toggle("cui-widget-panelWithFooter",
viewNode.querySelector(".panel-subview-footer"));
let multiView = document.createElement("panelmultiview");
multiView.setAttribute("id", "customizationui-widget-multiview");
multiView.setAttribute("nosubviews", "true");
tempPanel.appendChild(multiView);
multiView.setAttribute("mainViewIsSubView", "true");
multiView.setMainView(viewNode);
viewNode.classList.add("cui-widget-panelview");
let viewShown = false;
let panelRemover = () => {
viewNode.classList.remove("cui-widget-panelview");
if (viewShown) {
CustomizableUI.removePanelCloseListeners(tempPanel);
tempPanel.removeEventListener("popuphidden", panelRemover);
let evt = new CustomEvent("ViewHiding", {detail: viewNode});
viewNode.dispatchEvent(evt);
}
aAnchor.open = false;
this.multiView.appendChild(viewNode);
tempPanel.remove();
};
// Emit the ViewShowing event so that the widget definition has a chance
// to lazily populate the subview with things.
let detail = {
blockers: new Set(),
addBlocker(aPromise) {
this.blockers.add(aPromise);
},
};
let evt = new CustomEvent("ViewShowing", { bubbles: true, cancelable: true, detail });
viewNode.dispatchEvent(evt);
let cancel = evt.defaultPrevented;
if (detail.blockers.size) {
try {
let results = yield Promise.all(detail.blockers);
cancel = cancel || results.some(val => val === false);
} catch (e) {
Components.utils.reportError(e);
cancel = true;
}
}
if (cancel) {
panelRemover();
return;
}
viewShown = true;
CustomizableUI.addPanelCloseListeners(tempPanel);
tempPanel.addEventListener("popuphidden", panelRemover);
let iconAnchor =
document.getAnonymousElementByAttribute(aAnchor, "class",
"toolbarbutton-icon");
if (iconAnchor && aAnchor.id) {
iconAnchor.setAttribute("consumeanchor", aAnchor.id);
}
tempPanel.openPopup(iconAnchor || aAnchor, "bottomcenter topright");
}
}),
/**
* NB: The enable- and disableSingleSubviewPanelAnimations methods only
* affect the hiding/showing animations of single-subview panels (tempPanel
* in the showSubView method).
*/
disableSingleSubviewPanelAnimations: function() {
this._disableAnimations = true;
},
enableSingleSubviewPanelAnimations: function() {
this._disableAnimations = false;
},
onWidgetAfterDOMChange: function(aNode, aNextNode, aContainer, aWasRemoval) {
if (aContainer != this.contents) {
return;
}
if (aWasRemoval) {
aNode.removeAttribute("auto-hyphens");
}
},
onWidgetBeforeDOMChange: function(aNode, aNextNode, aContainer, aIsRemoval) {
if (aContainer != this.contents) {
return;
}
if (!aIsRemoval &&
(this.panel.state == "open" ||
document.documentElement.hasAttribute("customizing"))) {
this._adjustLabelsForAutoHyphens(aNode);
}
},
/**
* Signal that we're about to make a lot of changes to the contents of the
* panels all at once. For performance, we ignore the mutations.
*/
beginBatchUpdate: function() {
this._ensureEventListenersAdded();
this.multiView.ignoreMutations = true;
},
/**
* Signal that we're done making bulk changes to the panel. We now pay
* attention to mutations. This automatically synchronizes the multiview
* container with whichever view is displayed if the panel is open.
*/
endBatchUpdate: function(aReason) {
this._ensureEventListenersAdded();
this.multiView.ignoreMutations = false;
},
_adjustLabelsForAutoHyphens: function(aNode) {
let toolbarButtons = aNode ? [aNode] :
this.contents.querySelectorAll(".toolbarbutton-1");
for (let node of toolbarButtons) {
let label = node.getAttribute("label");
if (!label) {
continue;
}
if (label.includes("\u00ad")) {
node.setAttribute("auto-hyphens", "off");
} else {
node.removeAttribute("auto-hyphens");
}
}
},
/**
* Sets the anchor node into the open or closed state, depending
* on the state of the panel.
*/
_updatePanelButton: function() {
this.menuButton.open = this.panel.state == "open" ||
this.panel.state == "showing";
},
_onHelpViewShow: function(aEvent) {
// Call global menu setup function
buildHelpMenu();
let helpMenu = document.getElementById("menu_HelpPopup");
let items = this.getElementsByTagName("vbox")[0];
let attrs = ["oncommand", "onclick", "label", "key", "disabled"];
let NSXUL = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
// Remove all buttons from the view
while (items.firstChild) {
items.removeChild(items.firstChild);
}
// Add the current set of menuitems of the Help menu to this view
let menuItems = Array.prototype.slice.call(helpMenu.getElementsByTagName("menuitem"));
let fragment = document.createDocumentFragment();
for (let node of menuItems) {
if (node.hidden)
continue;
let button = document.createElementNS(NSXUL, "toolbarbutton");
// Copy specific attributes from a menuitem of the Help menu
for (let attrName of attrs) {
if (!node.hasAttribute(attrName))
continue;
button.setAttribute(attrName, node.getAttribute(attrName));
}
button.setAttribute("class", "subviewbutton");
fragment.appendChild(button);
}
items.appendChild(fragment);
},
_updateQuitTooltip: function() {
if (AppConstants.platform == "win") {
return;
}
let tooltipId = AppConstants.platform == "macosx" ?
"quit-button.tooltiptext.mac" :
"quit-button.tooltiptext.linux2";
let brands = Services.strings.createBundle("chrome://branding/locale/brand.properties");
let stringArgs = [brands.GetStringFromName("brandShortName")];
let key = document.getElementById("key_quitApplication");
stringArgs.push(ShortcutUtils.prettifyShortcut(key));
let tooltipString = CustomizableUI.getLocalizedProperty({x: tooltipId}, "x", stringArgs);
let quitButton = document.getElementById("PanelUI-quit");
quitButton.setAttribute("tooltiptext", tooltipString);
},
_overlayScrollListenerBoundFn: null,
_overlayScrollListener: function(aMQL) {
ScrollbarSampler.resetSystemScrollbarWidth();
this._scrollWidth = null;
},
};
XPCOMUtils.defineConstant(this, "PanelUI", PanelUI);
/**
* Gets the currently selected locale for display.
* @return the selected locale or "en-US" if none is selected
*/
function getLocale() {
try {
let chromeRegistry = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry);
return chromeRegistry.getSelectedLocale("browser");
} catch (ex) {
return "en-US";
}
}

View file

@ -0,0 +1,509 @@
<?xml version="1.0"?>
<!-- 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/. -->
<bindings id="browserPanelUIBindings"
xmlns="http://www.mozilla.org/xbl"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:xbl="http://www.mozilla.org/xbl">
<binding id="panelmultiview">
<resources>
<stylesheet src="chrome://browser/content/customizableui/panelUI.css"/>
</resources>
<content>
<xul:box anonid="viewContainer" class="panel-viewcontainer" xbl:inherits="panelopen,viewtype,transitioning">
<xul:stack anonid="viewStack" xbl:inherits="viewtype,transitioning" viewtype="main" class="panel-viewstack">
<xul:vbox anonid="mainViewContainer" class="panel-mainview" xbl:inherits="viewtype"/>
<!-- Used to capture click events over the PanelUI-mainView if we're in
subview mode. That way, any click on the PanelUI-mainView causes us
to revert to the mainView mode, whereupon PanelUI-click-capture then
allows click events to go through it. -->
<xul:vbox anonid="clickCapturer" class="panel-clickcapturer"/>
<!-- We manually set display: none (via a CSS attribute selector) on the
subviews that are not being displayed. We're using this over a deck
because a deck assumes the size of its largest child, regardless of
whether or not it is shown. That's not good for our case, since we
want to allow each subview to be uniquely sized. -->
<xul:vbox anonid="subViews" class="panel-subviews" xbl:inherits="panelopen">
<children includes="panelview"/>
</xul:vbox>
</xul:stack>
</xul:box>
</content>
<implementation implements="nsIDOMEventListener">
<field name="_clickCapturer" readonly="true">
document.getAnonymousElementByAttribute(this, "anonid", "clickCapturer");
</field>
<field name="_viewContainer" readonly="true">
document.getAnonymousElementByAttribute(this, "anonid", "viewContainer");
</field>
<field name="_mainViewContainer" readonly="true">
document.getAnonymousElementByAttribute(this, "anonid", "mainViewContainer");
</field>
<field name="_subViews" readonly="true">
document.getAnonymousElementByAttribute(this, "anonid", "subViews");
</field>
<field name="_viewStack" readonly="true">
document.getAnonymousElementByAttribute(this, "anonid", "viewStack");
</field>
<field name="_panel" readonly="true">
this.parentNode;
</field>
<field name="_currentSubView">null</field>
<field name="_anchorElement">null</field>
<field name="_mainViewHeight">0</field>
<field name="_subViewObserver">null</field>
<field name="__transitioning">false</field>
<field name="_ignoreMutations">false</field>
<property name="showingSubView" readonly="true"
onget="return this._viewStack.getAttribute('viewtype') == 'subview'"/>
<property name="_mainViewId" onget="return this.getAttribute('mainViewId');" onset="this.setAttribute('mainViewId', val); return val;"/>
<property name="_mainView" readonly="true"
onget="return this._mainViewId ? document.getElementById(this._mainViewId) : null;"/>
<property name="showingSubViewAsMainView" readonly="true"
onget="return this.getAttribute('mainViewIsSubView') == 'true'"/>
<property name="ignoreMutations">
<getter>
return this._ignoreMutations;
</getter>
<setter><![CDATA[
this._ignoreMutations = val;
if (!val && this._panel.state == "open") {
if (this.showingSubView) {
this._syncContainerWithSubView();
} else {
this._syncContainerWithMainView();
}
}
]]></setter>
</property>
<property name="_transitioning">
<getter>
return this.__transitioning;
</getter>
<setter><![CDATA[
this.__transitioning = val;
if (val) {
this.setAttribute("transitioning", "true");
} else {
this.removeAttribute("transitioning");
}
]]></setter>
</property>
<constructor><![CDATA[
this._clickCapturer.addEventListener("click", this);
this._panel.addEventListener("popupshowing", this);
this._panel.addEventListener("popupshown", this);
this._panel.addEventListener("popuphidden", this);
this._subViews.addEventListener("overflow", this);
this._mainViewContainer.addEventListener("overflow", this);
// Get a MutationObserver ready to react to subview size changes. We
// only attach this MutationObserver when a subview is being displayed.
this._subViewObserver =
new MutationObserver(this._syncContainerWithSubView.bind(this));
this._mainViewObserver =
new MutationObserver(this._syncContainerWithMainView.bind(this));
this._mainViewContainer.setAttribute("panelid",
this._panel.id);
if (this._mainView) {
this.setMainView(this._mainView);
}
this.setAttribute("viewtype", "main");
]]></constructor>
<destructor><![CDATA[
if (this._mainView) {
this._mainView.removeAttribute("mainview");
}
this._mainViewObserver.disconnect();
this._subViewObserver.disconnect();
this._panel.removeEventListener("popupshowing", this);
this._panel.removeEventListener("popupshown", this);
this._panel.removeEventListener("popuphidden", this);
this._subViews.removeEventListener("overflow", this);
this._mainViewContainer.removeEventListener("overflow", this);
this._clickCapturer.removeEventListener("click", this);
]]></destructor>
<method name="setMainView">
<parameter name="aNewMainView"/>
<body><![CDATA[
if (this._mainView) {
this._mainViewObserver.disconnect();
this._subViews.appendChild(this._mainView);
this._mainView.removeAttribute("mainview");
}
this._mainViewId = aNewMainView.id;
aNewMainView.setAttribute("mainview", "true");
this._mainViewContainer.appendChild(aNewMainView);
]]></body>
</method>
<method name="showMainView">
<body><![CDATA[
if (this.showingSubView) {
let viewNode = this._currentSubView;
let evt = document.createEvent("CustomEvent");
evt.initCustomEvent("ViewHiding", true, true, viewNode);
viewNode.dispatchEvent(evt);
viewNode.removeAttribute("current");
this._currentSubView = null;
this._subViewObserver.disconnect();
this._setViewContainerHeight(this._mainViewHeight);
this.setAttribute("viewtype", "main");
}
this._shiftMainView();
]]></body>
</method>
<method name="showSubView">
<parameter name="aViewId"/>
<parameter name="aAnchor"/>
<body><![CDATA[
Task.spawn(function*() {
let viewNode = this.querySelector("#" + aViewId);
viewNode.setAttribute("current", true);
// Emit the ViewShowing event so that the widget definition has a chance
// to lazily populate the subview with things.
let detail = {
blockers: new Set(),
addBlocker(aPromise) {
this.blockers.add(aPromise);
},
};
let evt = new CustomEvent("ViewShowing", { bubbles: true, cancelable: true, detail });
viewNode.dispatchEvent(evt);
let cancel = evt.defaultPrevented;
if (detail.blockers.size) {
try {
let results = yield Promise.all(detail.blockers);
cancel = cancel || results.some(val => val === false);
} catch (e) {
Components.utils.reportError(e);
cancel = true;
}
}
if (cancel) {
return;
}
this._currentSubView = viewNode;
// Now we have to transition the panel. There are a few parts to this:
//
// 1) The main view content gets shifted so that the center of the anchor
// node is at the left-most edge of the panel.
// 2) The subview deck slides in so that it takes up almost all of the
// panel.
// 3) If the subview is taller then the main panel contents, then the panel
// must grow to meet that new height. Otherwise, it must shrink.
//
// All three of these actions make use of CSS transformations, so they
// should all occur simultaneously.
this.setAttribute("viewtype", "subview");
this._shiftMainView(aAnchor);
this._mainViewHeight = this._viewStack.clientHeight;
let newHeight = this._heightOfSubview(viewNode, this._subViews);
this._setViewContainerHeight(newHeight);
this._subViewObserver.observe(viewNode, {
attributes: true,
characterData: true,
childList: true,
subtree: true
});
}.bind(this));
]]></body>
</method>
<method name="_setViewContainerHeight">
<parameter name="aHeight"/>
<body><![CDATA[
let container = this._viewContainer;
this._transitioning = true;
let onTransitionEnd = () => {
container.removeEventListener("transitionend", onTransitionEnd);
this._transitioning = false;
};
container.addEventListener("transitionend", onTransitionEnd);
container.style.height = `${aHeight}px`;
]]></body>
</method>
<method name="_shiftMainView">
<parameter name="aAnchor"/>
<body><![CDATA[
if (aAnchor) {
// We need to find the edge of the anchor, relative to the main panel.
// Then we need to add half the width of the anchor. This is the target
// that we need to transition to.
let anchorRect = aAnchor.getBoundingClientRect();
let mainViewRect = this._mainViewContainer.getBoundingClientRect();
let center = aAnchor.clientWidth / 2;
let direction = aAnchor.ownerDocument.defaultView.getComputedStyle(aAnchor, null).direction;
let edge;
if (direction == "ltr") {
edge = anchorRect.left - mainViewRect.left;
} else {
edge = mainViewRect.right - anchorRect.right;
}
// If the anchor is an element on the far end of the mainView we
// don't want to shift the mainView too far, we would reveal empty
// space otherwise.
let cstyle = window.getComputedStyle(document.documentElement, null);
let exitSubViewGutterWidth =
cstyle.getPropertyValue("--panel-ui-exit-subview-gutter-width");
let maxShift = mainViewRect.width - parseInt(exitSubViewGutterWidth);
let target = Math.min(maxShift, edge + center);
let neg = direction == "ltr" ? "-" : "";
this._mainViewContainer.style.transform = `translateX(${neg}${target}px)`;
aAnchor.setAttribute("panel-multiview-anchor", true);
} else {
this._mainViewContainer.style.transform = "";
if (this.anchorElement)
this.anchorElement.removeAttribute("panel-multiview-anchor");
}
this.anchorElement = aAnchor;
]]></body>
</method>
<method name="handleEvent">
<parameter name="aEvent"/>
<body><![CDATA[
if (aEvent.type.startsWith("popup") && aEvent.target != this._panel) {
// Shouldn't act on e.g. context menus being shown from within the panel.
return;
}
switch (aEvent.type) {
case "click":
if (aEvent.originalTarget == this._clickCapturer) {
this.showMainView();
}
break;
case "overflow":
if (aEvent.target.localName == "vbox") {
// Resize the right view on the next tick.
if (this.showingSubView) {
setTimeout(this._syncContainerWithSubView.bind(this), 0);
} else if (!this.transitioning) {
setTimeout(this._syncContainerWithMainView.bind(this), 0);
}
}
break;
case "popupshowing":
this.setAttribute("panelopen", "true");
// Bug 941196 - The panel can get taller when opening a subview. Disabling
// autoPositioning means that the panel won't jump around if an opened
// subview causes the panel to exceed the dimensions of the screen in the
// direction that the panel originally opened in. This property resets
// every time the popup closes, which is why we have to set it each time.
this._panel.autoPosition = false;
this._syncContainerWithMainView();
this._mainViewObserver.observe(this._mainView, {
attributes: true,
characterData: true,
childList: true,
subtree: true
});
break;
case "popupshown":
this._setMaxHeight();
break;
case "popuphidden":
this.removeAttribute("panelopen");
this._mainView.style.removeProperty("height");
this.showMainView();
this._mainViewObserver.disconnect();
break;
}
]]></body>
</method>
<method name="_shouldSetPosition">
<body><![CDATA[
return this.getAttribute("nosubviews") == "true";
]]></body>
</method>
<method name="_shouldSetHeight">
<body><![CDATA[
return this.getAttribute("nosubviews") != "true";
]]></body>
</method>
<method name="_setMaxHeight">
<body><![CDATA[
if (!this._shouldSetHeight())
return;
// Ignore the mutation that'll fire when we set the height of
// the main view.
this.ignoreMutations = true;
this._mainView.style.height =
this.getBoundingClientRect().height + "px";
this.ignoreMutations = false;
]]></body>
</method>
<method name="_adjustContainerHeight">
<body><![CDATA[
if (!this.ignoreMutations && !this.showingSubView && !this._transitioning) {
let height;
if (this.showingSubViewAsMainView) {
height = this._heightOfSubview(this._mainView);
} else {
height = this._mainView.scrollHeight;
}
this._viewContainer.style.height = height + "px";
}
]]></body>
</method>
<method name="_syncContainerWithSubView">
<body><![CDATA[
// Check that this panel is still alive:
if (!this._panel || !this._panel.parentNode) {
return;
}
if (!this.ignoreMutations && this.showingSubView) {
let newHeight = this._heightOfSubview(this._currentSubView, this._subViews);
this._viewContainer.style.height = newHeight + "px";
}
]]></body>
</method>
<method name="_syncContainerWithMainView">
<body><![CDATA[
// Check that this panel is still alive:
if (!this._panel || !this._panel.parentNode) {
return;
}
if (this._shouldSetPosition()) {
this._panel.adjustArrowPosition();
}
if (this._shouldSetHeight()) {
this._adjustContainerHeight();
}
]]></body>
</method>
<!-- Call this when the height of one of your views (the main view or a
subview) changes and you want the heights of the multiview and panel
to be the same as the view's height.
If the caller can give a hint of the expected height change with the
optional aExpectedChange parameter, it prevents flicker. -->
<method name="setHeightToFit">
<parameter name="aExpectedChange"/>
<body><![CDATA[
// Set the max-height to zero, wait until the height is actually
// updated, and then remove it. If it's not removed, weird things can
// happen, like widgets in the panel won't respond to clicks even
// though they're visible.
let count = 5;
let height = getComputedStyle(this).height;
if (aExpectedChange)
this.style.maxHeight = (parseInt(height) + aExpectedChange) + "px";
else
this.style.maxHeight = "0";
let interval = setInterval(() => {
if (height != getComputedStyle(this).height || --count == 0) {
clearInterval(interval);
this.style.removeProperty("max-height");
}
}, 0);
]]></body>
</method>
<method name="_heightOfSubview">
<parameter name="aSubview"/>
<parameter name="aContainerToCheck"/>
<body><![CDATA[
function getFullHeight(element) {
// XXXgijs: unfortunately, scrollHeight rounds values, and there's no alternative
// that works with overflow: auto elements. Fortunately for us,
// we have exactly 1 (potentially) scrolling element in here (the subview body),
// and rounding 1 value is OK - rounding more than 1 and adding them means we get
// off-by-1 errors. Now we might be off by a subpixel, but we care less about that.
// So, use scrollHeight *only* if the element is vertically scrollable.
let height;
let elementCS;
if (element.scrollTopMax) {
height = element.scrollHeight;
// Bounding client rects include borders, scrollHeight doesn't:
elementCS = win.getComputedStyle(element);
height += parseFloat(elementCS.borderTopWidth) +
parseFloat(elementCS.borderBottomWidth);
} else {
height = element.getBoundingClientRect().height;
if (height > 0) {
elementCS = win.getComputedStyle(element);
}
}
if (elementCS) {
// Include margins - but not borders or paddings because they
// were dealt with above.
height += parseFloat(elementCS.marginTop) + parseFloat(elementCS.marginBottom);
}
return height;
}
let win = aSubview.ownerDocument.defaultView;
let body = aSubview.querySelector(".panel-subview-body");
let height = getFullHeight(body || aSubview);
if (body) {
let header = aSubview.querySelector(".panel-subview-header");
let footer = aSubview.querySelector(".panel-subview-footer");
height += (header ? getFullHeight(header) : 0) +
(footer ? getFullHeight(footer) : 0);
}
if (aContainerToCheck) {
let containerCS = win.getComputedStyle(aContainerToCheck);
height += parseFloat(containerCS.paddingTop) + parseFloat(containerCS.paddingBottom);
}
return Math.ceil(height);
]]></body>
</method>
</implementation>
</binding>
<binding id="panelview">
<implementation>
<property name="panelMultiView" readonly="true">
<getter><![CDATA[
if (this.parentNode.localName != "panelmultiview") {
return document.getBindingParent(this.parentNode);
}
return this.parentNode;
]]></getter>
</property>
</implementation>
</binding>
</bindings>

View file

@ -0,0 +1,618 @@
<?xml version="1.0"?>
<!-- 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/. -->
<bindings id="browserToolbarBindings"
xmlns="http://www.mozilla.org/xbl"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:xbl="http://www.mozilla.org/xbl">
<binding id="toolbar" role="xul:toolbar">
<resources>
<stylesheet src="chrome://global/skin/toolbar.css"/>
</resources>
<implementation>
<field name="overflowedDuringConstruction">null</field>
<constructor><![CDATA[
let scope = {};
Cu.import("resource:///modules/CustomizableUI.jsm", scope);
// Add an early overflow event listener that will mark if the
// toolbar overflowed during construction.
if (scope.CustomizableUI.isAreaOverflowable(this.id)) {
this.addEventListener("overflow", this);
this.addEventListener("underflow", this);
}
if (document.readyState == "complete") {
this._init();
} else {
// Need to wait until XUL overlays are loaded. See bug 554279.
let self = this;
document.addEventListener("readystatechange", function onReadyStateChange() {
if (document.readyState != "complete")
return;
document.removeEventListener("readystatechange", onReadyStateChange, false);
self._init();
}, false);
}
]]></constructor>
<method name="_init">
<body><![CDATA[
let scope = {};
Cu.import("resource:///modules/CustomizableUI.jsm", scope);
let CustomizableUI = scope.CustomizableUI;
// Bug 989289: Forcibly set the now unsupported "mode" and "iconsize"
// attributes, just in case they accidentally get restored from
// persistence from a user that's been upgrading and downgrading.
if (CustomizableUI.isBuiltinToolbar(this.id)) {
const kAttributes = new Map([["mode", "icons"], ["iconsize", "small"]]);
for (let [attribute, value] of kAttributes) {
if (this.getAttribute(attribute) != value) {
this.setAttribute(attribute, value);
document.persist(this.id, attribute);
}
if (this.toolbox) {
if (this.toolbox.getAttribute(attribute) != value) {
this.toolbox.setAttribute(attribute, value);
document.persist(this.toolbox.id, attribute);
}
}
}
}
// Searching for the toolbox palette in the toolbar binding because
// toolbars are constructed first.
let toolbox = this.toolbox;
if (toolbox && !toolbox.palette) {
for (let node of toolbox.children) {
if (node.localName == "toolbarpalette") {
// Hold on to the palette but remove it from the document.
toolbox.palette = node;
toolbox.removeChild(node);
break;
}
}
}
// pass the current set of children for comparison with placements:
let children = Array.from(this.childNodes)
.filter(node => node.getAttribute("skipintoolbarset") != "true" && node.id)
.map(node => node.id);
CustomizableUI.registerToolbarNode(this, children);
]]></body>
</method>
<method name="handleEvent">
<parameter name="aEvent"/>
<body><![CDATA[
if (aEvent.type == "overflow" && aEvent.detail > 0) {
if (this.overflowable && this.overflowable.initialized) {
this.overflowable.onOverflow(aEvent);
} else {
this.overflowedDuringConstruction = aEvent;
}
} else if (aEvent.type == "underflow" && aEvent.detail > 0) {
this.overflowedDuringConstruction = null;
}
]]></body>
</method>
<method name="insertItem">
<parameter name="aId"/>
<parameter name="aBeforeElt"/>
<parameter name="aWrapper"/>
<body><![CDATA[
if (aWrapper) {
Cu.reportError("Can't insert " + aId + ": using insertItem " +
"no longer supports wrapper elements.");
return null;
}
// Hack, the customizable UI code makes this be the last position
let pos = null;
if (aBeforeElt) {
let beforeInfo = CustomizableUI.getPlacementOfWidget(aBeforeElt.id);
if (beforeInfo.area != this.id) {
Cu.reportError("Can't insert " + aId + " before " +
aBeforeElt.id + " which isn't in this area (" +
this.id + ").");
return null;
}
pos = beforeInfo.position;
}
CustomizableUI.addWidgetToArea(aId, this.id, pos);
return this.ownerDocument.getElementById(aId);
]]></body>
</method>
<property name="toolbarName"
onget="return this.getAttribute('toolbarname');"
onset="this.setAttribute('toolbarname', val); return val;"/>
<property name="customizationTarget" readonly="true">
<getter><![CDATA[
if (this._customizationTarget)
return this._customizationTarget;
let id = this.getAttribute("customizationtarget");
if (id)
this._customizationTarget = document.getElementById(id);
if (this._customizationTarget)
this._customizationTarget.insertItem = this.insertItem.bind(this);
else
this._customizationTarget = this;
return this._customizationTarget;
]]></getter>
</property>
<property name="toolbox" readonly="true">
<getter><![CDATA[
if (this._toolbox)
return this._toolbox;
let toolboxId = this.getAttribute("toolboxid");
if (toolboxId) {
let toolbox = document.getElementById(toolboxId);
if (toolbox) {
if (toolbox.externalToolbars.indexOf(this) == -1)
toolbox.externalToolbars.push(this);
this._toolbox = toolbox;
}
}
if (!this._toolbox && this.parentNode &&
this.parentNode.localName == "toolbox") {
this._toolbox = this.parentNode;
}
return this._toolbox;
]]></getter>
</property>
<property name="currentSet">
<getter><![CDATA[
let currentWidgets = new Set();
for (let node of this.customizationTarget.children) {
let realNode = node.localName == "toolbarpaletteitem" ? node.firstChild : node;
if (realNode.getAttribute("skipintoolbarset") != "true") {
currentWidgets.add(realNode.id);
}
}
if (this.getAttribute("overflowing") == "true") {
let overflowTarget = this.getAttribute("overflowtarget");
let overflowList = this.ownerDocument.getElementById(overflowTarget);
for (let node of overflowList.children) {
let realNode = node.localName == "toolbarpaletteitem" ? node.firstChild : node;
if (realNode.getAttribute("skipintoolbarset") != "true") {
currentWidgets.add(realNode.id);
}
}
}
let orderedPlacements = CustomizableUI.getWidgetIdsInArea(this.id);
return orderedPlacements.filter((x) => currentWidgets.has(x)).join(',');
]]></getter>
<setter><![CDATA[
// Get list of new and old ids:
let newVal = (val || '').split(',').filter(x => x);
let oldIds = CustomizableUI.getWidgetIdsInArea(this.id);
// Get a list of items only in the new list
let newIds = newVal.filter(id => oldIds.indexOf(id) == -1);
CustomizableUI.beginBatchUpdate();
try {
for (let newId of newIds) {
oldIds = CustomizableUI.getWidgetIdsInArea(this.id);
let nextId = newId;
let pos;
do {
// Get the next item
nextId = newVal[newVal.indexOf(nextId) + 1];
// Figure out where it is in the old list
pos = oldIds.indexOf(nextId);
// If it's not in the old list, repeat:
} while (pos == -1 && nextId);
if (pos == -1) {
pos = null; // We didn't find anything, insert at the end
}
CustomizableUI.addWidgetToArea(newId, this.id, pos);
}
let currentIds = this.currentSet.split(',');
let removedIds = currentIds.filter(id => newIds.indexOf(id) == -1 && newVal.indexOf(id) == -1);
for (let removedId of removedIds) {
CustomizableUI.removeWidgetFromArea(removedId);
}
} finally {
CustomizableUI.endBatchUpdate();
}
]]></setter>
</property>
</implementation>
</binding>
<binding id="toolbar-menubar-stub">
<implementation>
<property name="toolbox" readonly="true">
<getter><![CDATA[
if (this._toolbox)
return this._toolbox;
if (this.parentNode && this.parentNode.localName == "toolbox") {
this._toolbox = this.parentNode;
}
return this._toolbox;
]]></getter>
</property>
<property name="currentSet" readonly="true">
<getter><![CDATA[
return this.getAttribute("defaultset");
]]></getter>
</property>
<method name="insertItem">
<body><![CDATA[
return null;
]]></body>
</method>
</implementation>
</binding>
<!-- The toolbar-menubar-autohide and toolbar-drag bindings are almost
verbatim copies of their toolkit counterparts - they just inherit from
the customizableui's toolbar binding instead of toolkit's. We're currently
OK with the maintainance burden of having two copies of a binding, since
the long term goal is to move the customization framework into toolkit. -->
<binding id="toolbar-menubar-autohide"
extends="chrome://browser/content/customizableui/toolbar.xml#toolbar">
<implementation>
<constructor>
this._setInactive();
</constructor>
<destructor>
this._setActive();
</destructor>
<field name="_inactiveTimeout">null</field>
<field name="_contextMenuListener"><![CDATA[({
toolbar: this,
contextMenu: null,
get active () {
return !!this.contextMenu;
},
init: function (event) {
let node = event.target;
while (node != this.toolbar) {
if (node.localName == "menupopup")
return;
node = node.parentNode;
}
let contextMenuId = this.toolbar.getAttribute("context");
if (!contextMenuId)
return;
this.contextMenu = document.getElementById(contextMenuId);
if (!this.contextMenu)
return;
this.contextMenu.addEventListener("popupshown", this, false);
this.contextMenu.addEventListener("popuphiding", this, false);
this.toolbar.addEventListener("mousemove", this, false);
},
handleEvent: function (event) {
switch (event.type) {
case "popupshown":
this.toolbar.removeEventListener("mousemove", this, false);
break;
case "popuphiding":
case "mousemove":
this.toolbar._setInactiveAsync();
this.toolbar.removeEventListener("mousemove", this, false);
this.contextMenu.removeEventListener("popuphiding", this, false);
this.contextMenu.removeEventListener("popupshown", this, false);
this.contextMenu = null;
break;
}
}
})]]></field>
<method name="_setInactive">
<body><![CDATA[
this.setAttribute("inactive", "true");
]]></body>
</method>
<method name="_setInactiveAsync">
<body><![CDATA[
this._inactiveTimeout = setTimeout(function (self) {
if (self.getAttribute("autohide") == "true") {
self._inactiveTimeout = null;
self._setInactive();
}
}, 0, this);
]]></body>
</method>
<method name="_setActive">
<body><![CDATA[
if (this._inactiveTimeout) {
clearTimeout(this._inactiveTimeout);
this._inactiveTimeout = null;
}
this.removeAttribute("inactive");
]]></body>
</method>
</implementation>
<handlers>
<handler event="DOMMenuBarActive" action="this._setActive();"/>
<handler event="popupshowing" action="this._setActive();"/>
<handler event="mousedown" button="2" action="this._contextMenuListener.init(event);"/>
<handler event="DOMMenuBarInactive"><![CDATA[
if (!this._contextMenuListener.active)
this._setInactiveAsync();
]]></handler>
</handlers>
</binding>
<binding id="toolbar-drag"
extends="chrome://browser/content/customizableui/toolbar.xml#toolbar">
<implementation>
<field name="_dragBindingAlive">true</field>
<constructor><![CDATA[
if (!this._draggableStarted) {
this._draggableStarted = true;
try {
let tmp = {};
Components.utils.import("resource://gre/modules/WindowDraggingUtils.jsm", tmp);
let draggableThis = new tmp.WindowDraggingElement(this);
draggableThis.mouseDownCheck = function(e) {
return this._dragBindingAlive;
};
} catch (e) {}
}
]]></constructor>
</implementation>
</binding>
<!-- This is a peculiar binding. It is here to deal with overlayed/inserted add-on content,
and immediately direct such content elsewhere. -->
<binding id="addonbar-delegating">
<implementation>
<constructor><![CDATA[
// Reading these immediately so nobody messes with them anymore:
this._delegatingToolbar = this.getAttribute("toolbar-delegate");
this._wasCollapsed = this.getAttribute("collapsed") == "true";
// Leaving those in here to unbreak some code:
if (document.readyState == "complete") {
this._init();
} else {
// Need to wait until XUL overlays are loaded. See bug 554279.
let self = this;
document.addEventListener("readystatechange", function onReadyStateChange() {
if (document.readyState != "complete")
return;
document.removeEventListener("readystatechange", onReadyStateChange, false);
self._init();
}, false);
}
]]></constructor>
<method name="_init">
<body><![CDATA[
// Searching for the toolbox palette in the toolbar binding because
// toolbars are constructed first.
let toolbox = this.toolbox;
if (toolbox && !toolbox.palette) {
for (let node of toolbox.children) {
if (node.localName == "toolbarpalette") {
// Hold on to the palette but remove it from the document.
toolbox.palette = node;
toolbox.removeChild(node);
}
}
}
// pass the current set of children for comparison with placements:
let children = [];
for (let node of this.childNodes) {
if (node.getAttribute("skipintoolbarset") != "true" && node.id) {
// Force everything to be removable so that buildArea can chuck stuff
// out if the user has customized things / we've been here before:
if (!this._whiteListed.has(node.id)) {
node.setAttribute("removable", "true");
}
children.push(node);
}
}
CustomizableUI.registerToolbarNode(this, children);
let existingMigratedItems = (this.getAttribute("migratedset") || "").split(',');
for (let migratedItem of existingMigratedItems.filter((x) => !!x)) {
this._currentSetMigrated.add(migratedItem);
}
this.evictNodes();
// We can't easily use |this| or strong bindings for the observer fn here
// because that creates leaky circular references when the node goes away,
// and XBL destructors are unreliable.
let mutationObserver = new MutationObserver(function(mutations) {
if (!mutations.length) {
return;
}
let toolbar = mutations[0].target;
// Can't use our own attribute because we might not have one if we're set to
// collapsed
let areCustomizing = toolbar.ownerDocument.documentElement.getAttribute("customizing");
if (!toolbar._isModifying && !areCustomizing) {
toolbar.evictNodes();
}
});
mutationObserver.observe(this, {childList: true});
]]></body>
</method>
<method name="evictNodes">
<body><![CDATA[
this._isModifying = true;
let i = this.childNodes.length;
while (i--) {
let node = this.childNodes[i];
if (this.childNodes[i].id) {
this.evictNode(this.childNodes[i]);
} else {
node.remove();
}
}
this._isModifying = false;
this._updateMigratedSet();
]]></body>
</method>
<method name="evictNode">
<parameter name="aNode"/>
<body>
<![CDATA[
if (this._whiteListed.has(aNode.id) || CustomizableUI.isSpecialWidget(aNode.id)) {
return;
}
const kItemMaxWidth = 100;
let oldParent = aNode.parentNode;
aNode.setAttribute("removable", "true");
this._currentSetMigrated.add(aNode.id);
let movedOut = false;
if (!this._wasCollapsed) {
try {
let nodeWidth = aNode.getBoundingClientRect().width;
if (nodeWidth == 0 || nodeWidth > kItemMaxWidth) {
throw new Error(aNode.id + " is too big (" + nodeWidth +
"px wide), moving to the palette");
}
CustomizableUI.addWidgetToArea(aNode.id, this._delegatingToolbar);
movedOut = true;
} catch (ex) {
// This will throw if the node is too big, or can't be moved there for
// some reason. Report this:
Cu.reportError(ex);
}
}
/* We won't have moved the widget if either the add-on bar was collapsed,
* or if it was too wide to be inserted into the navbar. */
if (!movedOut) {
try {
CustomizableUI.removeWidgetFromArea(aNode.id);
} catch (ex) {
Cu.reportError(ex);
aNode.remove();
}
}
// Surprise: addWidgetToArea(palette) will get you nothing if the palette
// is not constructed yet. Fix:
if (aNode.parentNode == oldParent) {
let palette = this.toolbox.palette;
if (palette && oldParent != palette) {
palette.appendChild(aNode);
}
}
]]></body>
</method>
<method name="insertItem">
<parameter name="aId"/>
<parameter name="aBeforeElt"/>
<parameter name="aWrapper"/>
<body><![CDATA[
if (aWrapper) {
Cu.reportError("Can't insert " + aId + ": using insertItem " +
"no longer supports wrapper elements.");
return null;
}
let widget = CustomizableUI.getWidget(aId);
widget = widget && widget.forWindow(window);
let node = widget && widget.node;
if (!node) {
return null;
}
this._isModifying = true;
// Temporarily add it here so it can have a width, then ditch it:
this.appendChild(node);
this.evictNode(node);
this._isModifying = false;
this._updateMigratedSet();
// We will now have moved stuff around; kick off some events
// so add-ons know we've just moved their stuff:
// XXXgijs: only in this window. It's hard to know for sure what's the right
// thing to do here - typically insertItem is used on each window, so
// this seems to make the most sense, even if some of the effects of
// evictNode might affect multiple windows.
CustomizableUI.dispatchToolboxEvent("customizationchange", {}, window);
CustomizableUI.dispatchToolboxEvent("aftercustomization", {}, window);
return node;
]]></body>
</method>
<method name="getMigratedItems">
<body><![CDATA[
return [... this._currentSetMigrated];
]]></body>
</method>
<method name="_updateMigratedSet">
<body><![CDATA[
let newMigratedItems = this.getMigratedItems().join(',');
if (this.getAttribute("migratedset") != newMigratedItems) {
this.setAttribute("migratedset", newMigratedItems);
this.ownerDocument.persist(this.id, "migratedset");
}
]]></body>
</method>
<property name="customizationTarget" readonly="true">
<getter><![CDATA[
return this;
]]></getter>
</property>
<property name="currentSet">
<getter><![CDATA[
return Array.from(this.children, node => node.id).join(",");
]]></getter>
<setter><![CDATA[
let v = val.split(',');
let newButtons = v.filter(x => x && (!this._whiteListed.has(x) &&
!CustomizableUI.isSpecialWidget(x) &&
!this._currentSetMigrated.has(x)));
for (let newButton of newButtons) {
this._currentSetMigrated.add(newButton);
this.insertItem(newButton);
}
this._updateMigratedSet();
]]></setter>
</property>
<property name="toolbox" readonly="true">
<getter><![CDATA[
if (!this._toolbox && this.parentNode &&
this.parentNode.localName == "toolbox") {
this._toolbox = this.parentNode;
}
return this._toolbox;
]]></getter>
</property>
<field name="_whiteListed" readonly="true">new Set(["addonbar-closebutton", "status-bar"])</field>
<field name="_isModifying">false</field>
<field name="_currentSetMigrated">new Set()</field>
</implementation>
</binding>
</bindings>

View file

@ -0,0 +1,21 @@
# -*- Mode: python; 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/.
DIRS += [
'content',
]
EXTRA_JS_MODULES += [
'CustomizableUI.jsm',
'CustomizableWidgets.jsm',
'CustomizeMode.jsm',
'DragPositionManager.jsm',
'PanelWideWidgetTracker.jsm',
'ScrollbarSampler.jsm',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('windows', 'cocoa'):
DEFINES['CAN_DRAW_IN_TITLEBAR'] = 1

View file

@ -0,0 +1,286 @@
/* 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)
{
return NS_ERROR_FAILURE;
}
static void
AppendFileKey(const char *key, nsIProperties* aDirSvc,
nsCOMArray<nsIFile> &array)
{
nsCOMPtr<nsIFile> 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/
// |- <locale 1>/
// ...
// \- <locale N>/
// 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<nsIFile> &array)
{
nsCOMPtr<nsIFile> 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<nsIFile> 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<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
if (prefs) {
nsCOMPtr<nsIFile> localePlugins;
rv = searchPlugins->Clone(getter_AddRefs(localePlugins));
if (NS_FAILED(rv))
return;
localePlugins->AppendNative(NS_LITERAL_CSTRING("locale"));
nsCString defLocale;
rv = prefs->GetCharPref("distribution.searchplugins.defaultLocale",
getter_Copies(defLocale));
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIFile> 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);
return; // all done
}
}
}
// we didn't have a defaultLocale, use the user agent locale
nsCString locale;
nsCOMPtr<nsIPrefLocalizedString> 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<nsIFile> 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
}
}
}
}
}
NS_IMETHODIMP
DirectoryProvider::GetFiles(const char *aKey, nsISimpleEnumerator* *aResult)
{
/**
* We want to preserve the following order, since the search service loads
* engines in first-loaded-wins order.
* - distro search plugin locations (Loaded by the search service using
* NS_APP_DISTRIBUTION_SEARCH_DIR_LIST)
*
* - engines shipped in chrome (Loaded from jar files by the search
* service)
*
* Then other locations, from NS_APP_SEARCH_DIR_LIST:
* - extension search plugin locations (prepended below using
* NS_NewUnionEnumerator)
* - user search plugin locations (profile)
*/
nsresult rv;
if (!strcmp(aKey, NS_APP_DISTRIBUTION_SEARCH_DIR_LIST)) {
nsCOMPtr<nsIProperties> dirSvc
(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID));
if (!dirSvc)
return NS_ERROR_FAILURE;
nsCOMArray<nsIFile> distroFiles;
AppendDistroSearchDirs(dirSvc, distroFiles);
return NS_NewArrayEnumerator(aResult, distroFiles);
}
if (!strcmp(aKey, NS_APP_SEARCH_DIR_LIST)) {
nsCOMPtr<nsIProperties> dirSvc
(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID));
if (!dirSvc)
return NS_ERROR_FAILURE;
nsCOMArray<nsIFile> baseFiles;
AppendFileKey(NS_APP_USER_SEARCH_DIR, dirSvc, baseFiles);
nsCOMPtr<nsISimpleEnumerator> baseEnum;
rv = NS_NewArrayEnumerator(getter_AddRefs(baseEnum), baseFiles);
if (NS_FAILED(rv))
return rv;
nsCOMPtr<nsISimpleEnumerator> 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<nsISimpleEnumerator> 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<nsISupports> nextbasesupp;
mBase->GetNext(getter_AddRefs(nextbasesupp));
nsCOMPtr<nsIFile> 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

View file

@ -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<nsISimpleEnumerator> mBase;
char const *const *const mAppendList;
nsCOMPtr<nsIFile> mNext;
};
};
} // namespace browser
} // namespace mozilla
#endif // DirectoryProvider_h__

View file

@ -0,0 +1,19 @@
# -*- Mode: python; 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'
]

View file

@ -0,0 +1,504 @@
/* 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" ];
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cr = Components.results;
var Cu = Components.utils;
const DISTRIBUTION_CUSTOMIZATION_COMPLETE_TOPIC =
"distribution-customization-complete";
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/Preferences.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
this.DistributionCustomizer = function DistributionCustomizer() {
// For parallel xpcshell testing purposes allow loading the distribution.ini
// file from the profile folder through an hidden pref.
let loadFromProfile = false;
try {
loadFromProfile = Services.prefs.getBoolPref("distribution.testing.loadFromProfile");
} catch (ex) {}
let dirSvc = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties);
try {
let iniFile = loadFromProfile ? dirSvc.get("ProfD", Ci.nsIFile)
: dirSvc.get("XREAppDist", Ci.nsIFile);
if (loadFromProfile) {
iniFile.leafName = "distribution";
}
iniFile.append("distribution.ini");
if (iniFile.exists())
this._iniFile = iniFile;
} catch (ex) {}
}
DistributionCustomizer.prototype = {
_iniFile: null,
get _ini() {
let ini = null;
try {
if (this._iniFile) {
ini = Cc["@mozilla.org/xpcom/ini-parser-factory;1"].
getService(Ci.nsIINIParserFactory).
createINIParser(this._iniFile);
}
} catch (e) {
// Unable to parse INI.
Cu.reportError("Unable to parse distribution.ini");
}
this.__defineGetter__("_ini", () => ini);
return this._ini;
},
get _locale() {
let locale;
try {
locale = this._prefs.getCharPref("general.useragent.locale");
}
catch (e) {
locale = "en-US";
}
this.__defineGetter__("_locale", () => locale);
return this._locale;
},
get _language() {
let language = this._locale.split("-")[0];
this.__defineGetter__("_language", () => language);
return this._language;
},
get _prefSvc() {
let svc = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefService);
this.__defineGetter__("_prefSvc", () => svc);
return this._prefSvc;
},
get _prefs() {
let branch = this._prefSvc.getBranch(null);
this.__defineGetter__("_prefs", () => branch);
return this._prefs;
},
get _ioSvc() {
let svc = Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
this.__defineGetter__("_ioSvc", () => svc);
return this._ioSvc;
},
_makeURI: function DIST__makeURI(spec) {
return this._ioSvc.newURI(spec, null, null);
},
_parseBookmarksSection: Task.async(function* (parentGuid, section) {
let keys = Array.from(enumerate(this._ini.getKeys(section))).sort();
let re = /^item\.(\d+)\.(\w+)\.?(\w*)/;
let items = {};
let defaultIndex = -1;
let maxIndex = -1;
for (let key of keys) {
let m = re.exec(key);
if (m) {
let [, itemIndex, iprop, ilocale] = m;
itemIndex = parseInt(itemIndex);
if (ilocale)
continue;
if (keys.indexOf(key + "." + this._locale) >= 0) {
key += "." + this._locale;
} else if (keys.indexOf(key + "." + this._language) >= 0) {
key += "." + this._language;
}
if (!items[itemIndex])
items[itemIndex] = {};
items[itemIndex][iprop] = this._ini.getString(section, key);
if (iprop == "type" && items[itemIndex]["type"] == "default")
defaultIndex = itemIndex;
if (maxIndex < itemIndex)
maxIndex = itemIndex;
} else {
dump(`Key did not match: ${key}\n`);
}
}
let prependIndex = 0;
for (let itemIndex = 0; itemIndex <= maxIndex; itemIndex++) {
if (!items[itemIndex])
continue;
let index = PlacesUtils.bookmarks.DEFAULT_INDEX;
let item = items[itemIndex];
switch (item.type) {
case "default":
break;
case "folder":
if (itemIndex < defaultIndex)
index = prependIndex++;
let folder = yield PlacesUtils.bookmarks.insert({
type: PlacesUtils.bookmarks.TYPE_FOLDER,
parentGuid, index, title: item.title
});
yield this._parseBookmarksSection(folder.guid,
"BookmarksFolder-" + item.folderId);
if (item.description) {
let folderId = yield PlacesUtils.promiseItemId(folder.guid);
PlacesUtils.annotations.setItemAnnotation(folderId,
"bookmarkProperties/description",
item.description, 0,
PlacesUtils.annotations.EXPIRE_NEVER);
}
break;
case "separator":
if (itemIndex < defaultIndex)
index = prependIndex++;
yield PlacesUtils.bookmarks.insert({
type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
parentGuid, index
});
break;
case "livemark":
if (itemIndex < defaultIndex)
index = prependIndex++;
// Don't bother updating the livemark contents on creation.
let parentId = yield PlacesUtils.promiseItemId(parentGuid);
yield PlacesUtils.livemarks.addLivemark({
feedURI: this._makeURI(item.feedLink),
siteURI: this._makeURI(item.siteLink),
parentId, index, title: item.title
});
break;
case "bookmark":
default:
if (itemIndex < defaultIndex)
index = prependIndex++;
let bm = yield PlacesUtils.bookmarks.insert({
parentGuid, index, title: item.title, url: item.link
});
if (item.description) {
let bmId = yield PlacesUtils.promiseItemId(bm.guid);
PlacesUtils.annotations.setItemAnnotation(bmId,
"bookmarkProperties/description",
item.description, 0,
PlacesUtils.annotations.EXPIRE_NEVER);
}
if (item.icon && item.iconData) {
try {
let faviconURI = this._makeURI(item.icon);
PlacesUtils.favicons.replaceFaviconDataFromDataURL(
faviconURI, item.iconData, 0,
Services.scriptSecurityManager.getSystemPrincipal());
PlacesUtils.favicons.setAndFetchFaviconForPage(
this._makeURI(item.link), faviconURI, false,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
Services.scriptSecurityManager.getSystemPrincipal());
} catch (e) {
Cu.reportError(e);
}
}
if (item.keyword) {
try {
yield PlacesUtils.keywords.insert({ keyword: item.keyword,
url: item.link });
} catch (e) {
Cu.reportError(e);
}
}
break;
}
}
}),
_newProfile: false,
_customizationsApplied: false,
applyCustomizations: function DIST_applyCustomizations() {
this._customizationsApplied = true;
if (!Services.prefs.prefHasUserValue("browser.migration.version"))
this._newProfile = true;
if (!this._ini)
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: Task.async(function* () {
yield this._doApplyBookmarks();
this._bookmarksApplied = true;
this._checkCustomizationComplete();
}),
_doApplyBookmarks: Task.async(function* () {
if (!this._ini)
return;
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;
let globalPrefs = enumToObject(this._ini.getKeys("Global"));
if (!(globalPrefs["id"] && globalPrefs["version"] && globalPrefs["about"]))
return;
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"])
yield this._parseBookmarksSection(PlacesUtils.bookmarks.menuGuid,
"BookmarksMenu");
if (sections["BookmarksToolbar"])
yield this._parseBookmarksSection(PlacesUtils.bookmarks.toolbarGuid,
"BookmarksToolbar");
this._prefs.setBoolPref(bmProcessedPref, true);
}
}),
_prefDefaultsApplied: false,
applyPrefDefaults: function DIST_applyPrefDefaults() {
this._prefDefaultsApplied = true;
if (!this._ini)
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 = new Preferences({defaultBranch: true});
// Global really contains info we set as prefs. They're only
// separate because they are "special" (read: required)
defaults.set("distribution.id", this._ini.getString("Global", "id"));
defaults.set("distribution.version", this._ini.getString("Global", "version"));
let partnerAbout;
try {
if (globalPrefs["about." + this._locale]) {
partnerAbout = this._ini.getString("Global", "about." + this._locale);
} else if (globalPrefs["about." + this._language]) {
partnerAbout = this._ini.getString("Global", "about." + this._language);
} else {
partnerAbout = this._ini.getString("Global", "about");
}
defaults.set("distribution.about", partnerAbout);
} catch (e) {
/* ignore bad prefs due to bug 895473 and move on */
Cu.reportError(e);
}
var usedPreferences = [];
if (sections["Preferences-" + this._locale]) {
for (let key of enumerate(this._ini.getKeys("Preferences-" + this._locale))) {
try {
let value = this._ini.getString("Preferences-" + this._locale, key);
if (value) {
defaults.set(key, parseValue(value));
}
usedPreferences.push(key);
} catch (e) { /* ignore bad prefs and move on */ }
}
}
if (sections["Preferences-" + this._language]) {
for (let key of enumerate(this._ini.getKeys("Preferences-" + this._language))) {
if (usedPreferences.indexOf(key) > -1) {
continue;
}
try {
let value = this._ini.getString("Preferences-" + this._language, key);
if (value) {
defaults.set(key, parseValue(value));
}
usedPreferences.push(key);
} catch (e) { /* ignore bad prefs and move on */ }
}
}
if (sections["Preferences"]) {
for (let key of enumerate(this._ini.getKeys("Preferences"))) {
if (usedPreferences.indexOf(key) > -1) {
continue;
}
try {
let value = this._ini.getString("Preferences", key);
if (value) {
value = value.replace(/%LOCALE%/g, this._locale);
value = value.replace(/%LANGUAGE%/g, this._language);
defaults.set(key, parseValue(value));
}
} catch (e) { /* ignore bad prefs and move on */ }
}
}
let localizedStr = Cc["@mozilla.org/pref-localizedstring;1"].
createInstance(Ci.nsIPrefLocalizedString);
var usedLocalizablePreferences = [];
if (sections["LocalizablePreferences-" + this._locale]) {
for (let key of enumerate(this._ini.getKeys("LocalizablePreferences-" + this._locale))) {
try {
let value = this._ini.getString("LocalizablePreferences-" + this._locale, key);
if (value) {
value = parseValue(value);
localizedStr.data = "data:text/plain," + key + "=" + value;
defaults._prefBranch.setComplexValue(key, Ci.nsIPrefLocalizedString, localizedStr);
}
usedLocalizablePreferences.push(key);
} catch (e) { /* ignore bad prefs and move on */ }
}
}
if (sections["LocalizablePreferences-" + this._language]) {
for (let key of enumerate(this._ini.getKeys("LocalizablePreferences-" + this._language))) {
if (usedLocalizablePreferences.indexOf(key) > -1) {
continue;
}
try {
let value = this._ini.getString("LocalizablePreferences-" + this._language, key);
if (value) {
value = parseValue(value);
localizedStr.data = "data:text/plain," + key + "=" + value;
defaults._prefBranch.setComplexValue(key, Ci.nsIPrefLocalizedString, localizedStr);
}
usedLocalizablePreferences.push(key);
} catch (e) { /* ignore bad prefs and move on */ }
}
}
if (sections["LocalizablePreferences"]) {
for (let key of enumerate(this._ini.getKeys("LocalizablePreferences"))) {
if (usedLocalizablePreferences.indexOf(key) > -1) {
continue;
}
try {
let value = this._ini.getString("LocalizablePreferences", key);
if (value) {
value = parseValue(value);
value = value.replace(/%LOCALE%/g, this._locale);
value = value.replace(/%LANGUAGE%/g, this._language);
localizedStr.data = "data:text/plain," + key + "=" + value;
}
defaults._prefBranch.setComplexValue(key, Ci.nsIPrefLocalizedString, localizedStr);
} catch (e) { /* ignore bad prefs and move on */ }
}
}
return this._checkCustomizationComplete();
},
_checkCustomizationComplete: function DIST__checkCustomizationComplete() {
const BROWSER_DOCURL = "chrome://browser/content/browser.xul";
if (this._newProfile) {
let xulStore = Cc["@mozilla.org/xul/xulstore;1"].getService(Ci.nsIXULStore);
try {
var showPersonalToolbar = Services.prefs.getBoolPref("browser.showPersonalToolbar");
if (showPersonalToolbar) {
xulStore.setValue(BROWSER_DOCURL, "PersonalToolbar", "collapsed", "false");
}
} catch (e) {}
try {
var showMenubar = Services.prefs.getBoolPref("browser.showMenubar");
if (showMenubar) {
xulStore.setValue(BROWSER_DOCURL, "toolbar-menubar", "autohide", "false");
}
} catch (e) {}
}
let prefDefaultsApplied = this._prefDefaultsApplied || !this._ini;
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 parseValue(value) {
try {
value = JSON.parse(value);
} catch (e) {
// JSON.parse catches numbers and booleans.
// Anything else, we assume is a string.
// Remove the quotes that aren't needed anymore.
value = value.replace(/^"/, "");
value = value.replace(/"$/, "");
}
return value;
}
function* enumerate(UTF8Enumerator) {
while (UTF8Enumerator.hasMore())
yield UTF8Enumerator.getNext();
}
function enumToObject(UTF8Enumerator) {
let ret = {};
for (let i of enumerate(UTF8Enumerator))
ret[i] = 1;
return ret;
}

File diff suppressed because it is too large Load diff

View file

@ -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);
}
},
};

View file

@ -0,0 +1,395 @@
/* 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 module is imported by code that uses the "download.xml" binding, and
* provides prototypes for objects that handle input and display information.
*/
"use strict";
this.EXPORTED_SYMBOLS = [
"DownloadsViewUI",
];
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
"resource://gre/modules/Downloads.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "DownloadUtils",
"resource://gre/modules/DownloadUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "DownloadsCommon",
"resource:///modules/DownloadsCommon.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
this.DownloadsViewUI = {
/**
* Returns true if the given string is the name of a command that can be
* handled by the Downloads user interface, including standard commands.
*/
isCommandName(name) {
return name.startsWith("cmd_") || name.startsWith("downloadsCmd_");
},
};
/**
* A download element shell is responsible for handling the commands and the
* displayed data for a single element that uses the "download.xml" binding.
*
* The information to display is obtained through the associated Download object
* from the JavaScript API for downloads, and commands are executed using a
* combination of Download methods and DownloadsCommon.jsm helper functions.
*
* Specialized versions of this shell must be defined, and they are required to
* implement the "download" property or getter. Currently these objects are the
* HistoryDownloadElementShell and the DownloadsViewItem for the panel. The
* history view may use a HistoryDownload object in place of a Download object.
*/
this.DownloadsViewUI.DownloadElementShell = function () {}
this.DownloadsViewUI.DownloadElementShell.prototype = {
/**
* The richlistitem for the download, initialized by the derived object.
*/
element: null,
/**
* URI string for the file type icon displayed in the download element.
*/
get image() {
if (!this.download.target.path) {
// Old history downloads may not have a target path.
return "moz-icon://.unknown?size=32";
}
// When a download that was previously in progress finishes successfully, it
// means that the target file now exists and we can extract its specific
// icon, for example from a Windows executable. To ensure that the icon is
// reloaded, however, we must change the URI used by the XUL image element,
// for example by adding a query parameter. This only works if we add one of
// the parameters explicitly supported by the nsIMozIconURI interface.
return "moz-icon://" + this.download.target.path + "?size=32" +
(this.download.succeeded ? "&state=normal" : "");
},
/**
* The user-facing label for the download. This is normally the leaf name of
* the download target file. In case this is a very old history download for
* which the target file is unknown, the download source URI is displayed.
*/
get displayName() {
if (!this.download.target.path) {
return this.download.source.url;
}
return OS.Path.basename(this.download.target.path);
},
/**
* The progress element for the download, or undefined in case the XBL binding
* has not been applied yet.
*/
get _progressElement() {
if (!this.__progressElement) {
// If the element is not available now, we will try again the next time.
this.__progressElement =
this.element.ownerDocument.getAnonymousElementByAttribute(
this.element, "anonid",
"progressmeter");
}
return this.__progressElement;
},
/**
* Processes a major state change in the user interface, then proceeds with
* the normal progress update. This function is not called for every progress
* update in order to improve performance.
*/
_updateState() {
this.element.setAttribute("displayName", this.displayName);
this.element.setAttribute("image", this.image);
this.element.setAttribute("state",
DownloadsCommon.stateOfDownload(this.download));
if (!this.download.succeeded && this.download.error &&
this.download.error.becauseBlockedByReputationCheck) {
this.element.setAttribute("verdict",
this.download.error.reputationCheckVerdict);
} else {
this.element.removeAttribute("verdict");
}
// Since state changed, reset the time left estimation.
this.lastEstimatedSecondsLeft = Infinity;
this._updateProgress();
},
/**
* Updates the elements that change regularly for in-progress downloads,
* namely the progress bar and the status line.
*/
_updateProgress() {
if (this.download.succeeded) {
// We only need to add or remove this attribute for succeeded downloads.
if (this.download.target.exists) {
this.element.setAttribute("exists", "true");
} else {
this.element.removeAttribute("exists");
}
}
// When a block is confirmed, the removal of blocked data will not trigger a
// state change for the download, so this class must be updated here.
this.element.classList.toggle("temporary-block",
!!this.download.hasBlockedData);
// The progress bar is only displayed for in-progress downloads.
if (this.download.hasProgress) {
this.element.setAttribute("progressmode", "normal");
this.element.setAttribute("progress", this.download.progress);
} else {
this.element.setAttribute("progressmode", "undetermined");
}
if (this.download.stopped && this.download.canceled &&
this.download.hasPartialData) {
this.element.setAttribute("progresspaused", "true");
} else {
this.element.removeAttribute("progresspaused");
}
// Dispatch the ValueChange event for accessibility, if possible.
if (this._progressElement) {
let event = this.element.ownerDocument.createEvent("Events");
event.initEvent("ValueChange", true, true);
this._progressElement.dispatchEvent(event);
}
let status = this.statusTextAndTip;
this.element.setAttribute("status", status.text);
this.element.setAttribute("statusTip", status.tip);
},
lastEstimatedSecondsLeft: Infinity,
/**
* Returns the text for the status line and the associated tooltip. These are
* returned by a single property because they are computed together. The
* result may be overridden by derived objects.
*/
get statusTextAndTip() {
return this.rawStatusTextAndTip;
},
/**
* Derived objects may call this to get the status text.
*/
get rawStatusTextAndTip() {
let s = DownloadsCommon.strings;
let text = "";
let tip = "";
if (!this.download.stopped) {
let totalBytes = this.download.hasProgress ? this.download.totalBytes
: -1;
// By default, extended status information including the individual
// download rate is displayed in the tooltip. The history view overrides
// the getter and displays the datails in the main area instead.
[text] = DownloadUtils.getDownloadStatusNoRate(
this.download.currentBytes,
totalBytes,
this.download.speed,
this.lastEstimatedSecondsLeft);
let newEstimatedSecondsLeft;
[tip, newEstimatedSecondsLeft] = DownloadUtils.getDownloadStatus(
this.download.currentBytes,
totalBytes,
this.download.speed,
this.lastEstimatedSecondsLeft);
this.lastEstimatedSecondsLeft = newEstimatedSecondsLeft;
} else if (this.download.canceled && this.download.hasPartialData) {
let totalBytes = this.download.hasProgress ? this.download.totalBytes
: -1;
let transfer = DownloadUtils.getTransferTotal(this.download.currentBytes,
totalBytes);
// We use the same XUL label to display both the state and the amount
// transferred, for example "Paused - 1.1 MB".
text = s.statusSeparatorBeforeNumber(s.statePaused, transfer);
} else if (!this.download.succeeded && !this.download.canceled &&
!this.download.error) {
text = s.stateStarting;
} else {
let stateLabel;
if (this.download.succeeded) {
// For completed downloads, show the file size (e.g. "1.5 MB").
if (this.download.target.size !== undefined) {
let [size, unit] =
DownloadUtils.convertByteUnits(this.download.target.size);
stateLabel = s.sizeWithUnits(size, unit);
} else {
// History downloads may not have a size defined.
stateLabel = s.sizeUnknown;
}
} else if (this.download.canceled) {
stateLabel = s.stateCanceled;
} else if (this.download.error.becauseBlockedByParentalControls) {
stateLabel = s.stateBlockedParentalControls;
} else if (this.download.error.becauseBlockedByReputationCheck) {
stateLabel = this.rawBlockedTitleAndDetails[0];
} else {
stateLabel = s.stateFailed;
}
let referrer = this.download.source.referrer || this.download.source.url;
let [displayHost, fullHost] = DownloadUtils.getURIHost(referrer);
let date = new Date(this.download.endTime);
let [displayDate, fullDate] = DownloadUtils.getReadableDates(date);
let firstPart = s.statusSeparator(stateLabel, displayHost);
text = s.statusSeparator(firstPart, displayDate);
tip = s.statusSeparator(fullHost, fullDate);
}
return { text, tip: tip || text };
},
/**
* Returns [title, [details1, details2]] for blocked downloads.
*/
get rawBlockedTitleAndDetails() {
let s = DownloadsCommon.strings;
if (!this.download.error ||
!this.download.error.becauseBlockedByReputationCheck) {
return [null, null];
}
switch (this.download.error.reputationCheckVerdict) {
case Downloads.Error.BLOCK_VERDICT_UNCOMMON:
return [s.blockedUncommon2, [s.unblockTypeUncommon2, s.unblockTip2]];
case Downloads.Error.BLOCK_VERDICT_POTENTIALLY_UNWANTED:
return [s.blockedPotentiallyUnwanted,
[s.unblockTypePotentiallyUnwanted2, s.unblockTip2]];
case Downloads.Error.BLOCK_VERDICT_MALWARE:
return [s.blockedMalware, [s.unblockTypeMalware, s.unblockTip2]];
}
throw new Error("Unexpected reputationCheckVerdict: " +
this.download.error.reputationCheckVerdict);
// return anyway to avoid a JS strict warning.
return [null, null];
},
/**
* Shows the appropriate unblock dialog based on the verdict, and executes the
* action selected by the user in the dialog, which may involve unblocking,
* opening or removing the file.
*
* @param window
* The window to which the dialog should be anchored.
* @param dialogType
* Can be "unblock", "chooseUnblock", or "chooseOpen".
*/
confirmUnblock(window, dialogType) {
DownloadsCommon.confirmUnblockDownload({
verdict: this.download.error.reputationCheckVerdict,
window,
dialogType,
}).then(action => {
if (action == "open") {
return this.unblockAndOpenDownload();
} else if (action == "unblock") {
return this.download.unblock();
} else if (action == "confirmBlock") {
return this.download.confirmBlock();
}
}).catch(Cu.reportError);
},
/**
* Unblocks the downloaded file and opens it.
*
* @return A promise that's resolved after the file has been opened.
*/
unblockAndOpenDownload() {
return this.download.unblock().then(() => this.downloadsCmd_open());
},
/**
* Returns the name of the default command to use for the current state of the
* download, when there is a double click or another default interaction. If
* there is no default command for the current state, returns an empty string.
* The commands are implemented as functions on this object or derived ones.
*/
get currentDefaultCommandName() {
switch (DownloadsCommon.stateOfDownload(this.download)) {
case Ci.nsIDownloadManager.DOWNLOAD_NOTSTARTED:
return "downloadsCmd_cancel";
case Ci.nsIDownloadManager.DOWNLOAD_FAILED:
case Ci.nsIDownloadManager.DOWNLOAD_CANCELED:
return "downloadsCmd_retry";
case Ci.nsIDownloadManager.DOWNLOAD_PAUSED:
return "downloadsCmd_pauseResume";
case Ci.nsIDownloadManager.DOWNLOAD_FINISHED:
return "downloadsCmd_open";
case Ci.nsIDownloadManager.DOWNLOAD_BLOCKED_PARENTAL:
return "downloadsCmd_openReferrer";
case Ci.nsIDownloadManager.DOWNLOAD_DIRTY:
return "downloadsCmd_showBlockedInfo";
}
return "";
},
/**
* Returns true if the specified command can be invoked on the current item.
* The commands are implemented as functions on this object or derived ones.
*
* @param aCommand
* Name of the command to check, for example "downloadsCmd_retry".
*/
isCommandEnabled(aCommand) {
switch (aCommand) {
case "downloadsCmd_retry":
return this.download.canceled || this.download.error;
case "downloadsCmd_pauseResume":
return this.download.hasPartialData && !this.download.error;
case "downloadsCmd_openReferrer":
return !!this.download.source.referrer;
case "downloadsCmd_confirmBlock":
case "downloadsCmd_chooseUnblock":
case "downloadsCmd_chooseOpen":
case "downloadsCmd_unblock":
case "downloadsCmd_unblockAndOpen":
return this.download.hasBlockedData;
}
return false;
},
downloadsCmd_cancel() {
// This is the correct way to avoid race conditions when cancelling.
this.download.cancel().catch(() => {});
this.download.removePartialData().catch(Cu.reportError);
},
downloadsCmd_retry() {
// Errors when retrying are already reported as download failures.
this.download.start().catch(() => {});
},
downloadsCmd_pauseResume() {
if (this.download.stopped) {
this.download.start();
} else {
this.download.cancel();
}
},
downloadsCmd_confirmBlock() {
this.download.confirmBlock().catch(Cu.reportError);
},
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,131 @@
<?xml version="1.0"?>
# 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/.
<?xml-stylesheet href="chrome://browser/content/downloads/downloads.css"?>
<?xml-stylesheet href="chrome://browser/skin/downloads/allDownloadsViewOverlay.css"?>
<!DOCTYPE overlay [
<!ENTITY % downloadsDTD SYSTEM "chrome://browser/locale/downloads/downloads.dtd">
%downloadsDTD;
]>
<!-- This overlay provides a downloads view that lists both session downloads,
using the DownloadsView API, and history downloads, using places queries.
The view also implements a command controller and a context menu for
managing the downloads list. In order to use this view:
1. Apply this overlay to your window.
2. Insert in all the overlay entry-points, namely:
<richlistbox id="downloadsRichListBox"/>
<commandset id="downloadCommands"/>
<menupopup id="downloadsContextMenu"/>
3. Make sure your window has the editMenuOverlay overlay applied,
because the view implements cmd_copy and cmd_delete.
4. Make sure your window has the globalOverlay.js script loaded.
5. To initialize the view
let view = new DownloadsPlacesView(document.getElementById("downloadsRichListBox"));
// This is what the Places Library uses. It could be tweaked a bit as long as the
// transition-type is set correctly
view.place = "place:transition=7&sort=4";
-->
<overlay id="downloadsViewOverlay"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/javascript"
src="chrome://browser/content/downloads/allDownloadsViewOverlay.js"/>
<script type="application/javascript"
src="chrome://global/content/contentAreaUtils.js"/>
<richlistbox flex="1"
seltype="multiple"
id="downloadsRichListBox" context="downloadsContextMenu"
onscroll="return this._placesView.onScroll();"
onkeypress="return this._placesView.onKeyPress(event);"
ondblclick="return this._placesView.onDoubleClick(event);"
oncontextmenu="return this._placesView.onContextMenu(event);"
ondragstart="this._placesView.onDragStart(event);"
ondragover="this._placesView.onDragOver(event);"
ondrop="this._placesView.onDrop(event);"
onfocus="goUpdateDownloadCommands();"
onselect="this._placesView.onSelect();"
onblur="goUpdateDownloadCommands();"/>
<commandset id="downloadCommands"
commandupdater="true"
events="focus,select,contextmenu"
oncommandupdate="goUpdateDownloadCommands();">
<command id="downloadsCmd_pauseResume"
oncommand="goDoCommand('downloadsCmd_pauseResume')"/>
<command id="downloadsCmd_cancel"
oncommand="goDoCommand('downloadsCmd_cancel')"/>
<command id="downloadsCmd_unblock"
oncommand="goDoCommand('downloadsCmd_unblock')"/>
<command id="downloadsCmd_chooseUnblock"
oncommand="goDoCommand('downloadsCmd_chooseUnblock')"/>
<command id="downloadsCmd_chooseOpen"
oncommand="goDoCommand('downloadsCmd_chooseOpen')"/>
<command id="downloadsCmd_confirmBlock"
oncommand="goDoCommand('downloadsCmd_confirmBlock')"/>
<command id="downloadsCmd_open"
oncommand="goDoCommand('downloadsCmd_open')"/>
<command id="downloadsCmd_show"
oncommand="goDoCommand('downloadsCmd_show')"/>
<command id="downloadsCmd_retry"
oncommand="goDoCommand('downloadsCmd_retry')"/>
<command id="downloadsCmd_openReferrer"
oncommand="goDoCommand('downloadsCmd_openReferrer')"/>
<command id="downloadsCmd_clearDownloads"
oncommand="goDoCommand('downloadsCmd_clearDownloads')"/>
</commandset>
<menupopup id="downloadsContextMenu" class="download-state">
<menuitem command="downloadsCmd_pauseResume"
class="downloadPauseMenuItem"
label="&cmd.pause.label;"
accesskey="&cmd.pause.accesskey;"/>
<menuitem command="downloadsCmd_pauseResume"
class="downloadResumeMenuItem"
label="&cmd.resume.label;"
accesskey="&cmd.resume.accesskey;"/>
<menuitem command="downloadsCmd_cancel"
class="downloadCancelMenuItem"
label="&cmd.cancel.label;"
accesskey="&cmd.cancel.accesskey;"/>
<menuitem command="downloadsCmd_unblock"
class="downloadUnblockMenuItem"
label="&cmd.unblock2.label;"
accesskey="&cmd.unblock2.accesskey;"/>
<menuitem command="cmd_delete"
class="downloadRemoveFromHistoryMenuItem"
label="&cmd.removeFromHistory.label;"
accesskey="&cmd.removeFromHistory.accesskey;"/>
<menuitem command="downloadsCmd_show"
class="downloadShowMenuItem"
#ifdef XP_MACOSX
label="&cmd.showMac.label;"
accesskey="&cmd.showMac.accesskey;"
#else
label="&cmd.show.label;"
accesskey="&cmd.show.accesskey;"
#endif
/>
<menuseparator class="downloadCommandsSeparator"/>
<menuitem command="downloadsCmd_openReferrer"
label="&cmd.goToDownloadPage.label;"
accesskey="&cmd.goToDownloadPage.accesskey;"/>
<menuitem command="cmd_copy"
label="&cmd.copyDownloadLink.label;"
accesskey="&cmd.copyDownloadLink.accesskey;"/>
<menuseparator/>
<menuitem command="downloadsCmd_clearDownloads"
label="&cmd.clearDownloads.label;"
accesskey="&cmd.clearDownloads.accesskey;"/>
</menupopup>
</overlay>

View file

@ -0,0 +1,11 @@
/* 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/. */
#downloadsListEmptyDescription {
display: none;
}
#downloadsRichListBox:empty + #downloadsListEmptyDescription {
display: -moz-box;
}

View file

@ -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/. */
Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
var ContentAreaDownloadsView = {
init() {
let view = new DownloadsPlacesView(document.getElementById("downloadsRichListBox"));
// Do not display the Places downloads in private windows
if (!PrivateBrowsingUtils.isContentWindowPrivate(window)) {
view.place = "place:transition=7&sort=4";
}
// Set focus to Downloads list once it is created
document.getElementById("downloadsRichListBox").focus();
},
};

View file

@ -0,0 +1,46 @@
<?xml version="1.0"?>
# 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/.
<?xml-stylesheet href="chrome://global/skin/"?>
<?xml-stylesheet href="chrome://browser/content/downloads/contentAreaDownloadsView.css"?>
<?xml-stylesheet href="chrome://browser/skin/downloads/contentAreaDownloadsView.css"?>
<?xul-overlay href="chrome://browser/content/downloads/allDownloadsViewOverlay.xul"?>
<?xul-overlay href="chrome://global/content/editMenuOverlay.xul"?>
<!DOCTYPE window [
<!ENTITY % downloadsDTD SYSTEM "chrome://browser/locale/downloads/downloads.dtd">
%downloadsDTD;
]>
<window id="contentAreaDownloadsView"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
title="&downloads.title;"
onload="ContentAreaDownloadsView.init();">
<script type="application/javascript"
src="chrome://global/content/globalOverlay.js"/>
<script type="application/javascript"
src="chrome://browser/content/downloads/contentAreaDownloadsView.js"/>
<commandset id="editMenuCommands"/>
<keyset id="editMenuKeys">
#ifdef XP_MACOSX
<key id="key_delete2" keycode="VK_BACK" command="cmd_delete"/>
#endif
</keyset>
<stack flex="1">
<richlistbox id="downloadsRichListBox"/>
<description id="downloadsListEmptyDescription"
value="&downloadsListEmpty.label;"
mousethrough="always"/>
</stack>
<commandset id="downloadCommands"/>
<menupopup id="downloadsContextMenu"/>
</window>

View file

@ -0,0 +1,99 @@
<?xml version="1.0"?>
<!-- -*- Mode: HTML; 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/. -->
<!DOCTYPE bindings SYSTEM "chrome://browser/locale/downloads/downloads.dtd">
<bindings id="downloadBindings"
xmlns="http://www.mozilla.org/xbl"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:xbl="http://www.mozilla.org/xbl">
<binding id="download"
extends="chrome://global/content/bindings/richlistbox.xml#richlistitem">
<content orient="horizontal"
onclick="DownloadsView.onDownloadClick(event);">
<xul:hbox class="downloadMainArea"
flex="1"
align="center">
<xul:stack>
<xul:image class="downloadTypeIcon"
validate="always"
xbl:inherits="src=image"/>
<xul:image class="downloadBlockedBadge" />
</xul:stack>
<xul:vbox pack="center"
flex="1"
class="downloadContainer"
style="width: &downloadDetails.width;">
<!-- We're letting localizers put a min-width in here primarily
because of the downloads summary at the bottom of the list of
download items. An element in the summary has the same min-width
on a description, and we don't want the panel to change size if the
summary isn't being displayed, so we ensure that items share the
same minimum width.
-->
<xul:description class="downloadTarget"
crop="center"
style="min-width: &downloadsSummary.minWidth2;"
xbl:inherits="value=displayName,tooltiptext=displayName"/>
<xul:progressmeter anonid="progressmeter"
class="downloadProgress"
min="0"
max="100"
xbl:inherits="mode=progressmode,value=progress,paused=progresspaused"/>
<xul:description class="downloadDetails"
crop="end"
xbl:inherits="value=status,tooltiptext=statusTip"/>
</xul:vbox>
</xul:hbox>
<xul:toolbarseparator />
<xul:stack class="downloadButtonArea">
<xul:button class="downloadButton downloadCancel downloadIconCancel"
tooltiptext="&cmd.cancel.label;"
oncommand="DownloadsView.onDownloadCommand(event, 'downloadsCmd_cancel');"/>
<xul:button class="downloadButton downloadRetry downloadIconRetry"
tooltiptext="&cmd.retry.label;"
oncommand="DownloadsView.onDownloadCommand(event, 'downloadsCmd_retry');"/>
<xul:button class="downloadButton downloadShow downloadIconShow"
#ifdef XP_MACOSX
tooltiptext="&cmd.showMac.label;"
#else
tooltiptext="&cmd.show.label;"
#endif
oncommand="DownloadsView.onDownloadCommand(event, 'downloadsCmd_show');"/>
<xul:button class="downloadButton downloadConfirmBlock downloadIconCancel"
tooltiptext="&cmd.removeFile.label;"
oncommand="DownloadsView.onDownloadCommand(event, 'downloadsCmd_confirmBlock');"/>
<xul:button class="downloadButton downloadChooseUnblock downloadIconShow"
tooltiptext="&cmd.chooseUnblock.label;"
oncommand="DownloadsView.onDownloadCommand(event, 'downloadsCmd_chooseUnblock');"/>
<xul:button class="downloadButton downloadChooseOpen downloadIconShow"
tooltiptext="&cmd.chooseOpen.label;"
oncommand="DownloadsView.onDownloadCommand(event, 'downloadsCmd_chooseOpen');"/>
<xul:button class="downloadButton downloadShowBlockedInfo"
tooltiptext="&cmd.chooseUnblock.label;"
oncommand="DownloadsView.onDownloadCommand(event, 'downloadsCmd_showBlockedInfo');"/>
</xul:stack>
</content>
</binding>
<binding id="download-toolbarbutton"
extends="chrome://global/content/bindings/toolbarbutton.xml#toolbarbutton-badged">
<content>
<xul:stack class="toolbarbutton-badge-stack">
<children />
<xul:image class="toolbarbutton-icon" xbl:inherits="validate,src=image,label,consumeanchor"/>
<xul:label class="toolbarbutton-badge" xbl:inherits="value=badge" top="0" end="0" crop="none"/>
</xul:stack>
<xul:label class="toolbarbutton-text" crop="right" flex="1"
xbl:inherits="value=label,accesskey,crop,wrap"/>
<xul:label class="toolbarbutton-multiline-text" flex="1"
xbl:inherits="xbl:text=label,accesskey,wrap"/>
</content>
</binding>
</bindings>

View file

@ -0,0 +1,267 @@
/* 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/. */
/*** Downloads Panel ***/
richlistitem[type="download"] {
-moz-binding: url('chrome://browser/content/downloads/download.xml#download');
}
richlistitem[type="download"]:not([selected]) button {
/* Only focus buttons in the selected item. */
-moz-user-focus: none;
}
.downloadsHideDropmarker > #downloadsFooterButtonsSplitter,
.downloadsHideDropmarker > #downloadsFooterDropmarker {
display: none;
}
richlistitem[type="download"].download-state[state="1"]:not([exists]) > .downloadButtonArea,
richlistitem[type="download"].download-state[state="1"]:not([exists]) > toolbarseparator {
display: none;
}
#downloadsSummary:not([inprogress]) > vbox > #downloadsSummaryProgress,
#downloadsSummary:not([inprogress]) > vbox > #downloadsSummaryDetails,
#downloadsFooter:not([showingsummary]) #downloadsSummary {
display: none;
}
#downloadsFooter[showingdropdown] > stack > #downloadsSummary,
#downloadsFooter[showingsummary] > stack:hover > #downloadsSummary,
#downloadsFooter[showingsummary]:not([showingdropdown]) > stack:not(:hover) > #downloadsFooterButtons {
/* If we used "visibility: hidden;" then the mouseenter event of
#downloadsHistory wouldn't be triggered immediately, and the hover styling
of the button would not apply until the mouse is moved again.
"-moz-user-focus: ignore;" prevents the elements with "opacity: 0;" from
being focused with the keyboard. */
opacity: 0;
-moz-user-focus: ignore;
}
/*** Downloads View ***/
/**
* 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");
}
richlistitem.download button {
/* These buttons should never get focus, as that would "disable"
the downloads view controller (it's only used when the richlistbox
is focused). */
-moz-user-focus: none;
}
/*** Visibility of controls inside download items ***/
.download-state:not(:-moz-any([state="6"], /* Blocked (parental) */
[state="8"], /* Blocked (dirty) */
[state="9"]) /* Blocked (policy) */)
.downloadBlockedBadge,
.download-state:not(:-moz-any([state="-1"],/* Starting (initial) */
[state="5"], /* Starting (queued) */
[state="0"], /* Downloading */
[state="4"], /* Paused */
[state="7"]) /* Scanning */)
.downloadProgress,
.download-state:not( [state="0"] /* Downloading */)
.downloadPauseMenuItem,
.download-state:not( [state="4"] /* Paused */)
.downloadResumeMenuItem,
/* Blocked (dirty) downloads that have not been confirmed and
have temporary data. */
.download-state:not( [state="8"] /* Blocked (dirty) */)
.downloadUnblockMenuItem,
.download-state[state="8"]:not(.temporary-block)
.downloadUnblockMenuItem,
.download-state:not(:-moz-any([state="2"], /* Failed */
[state="4"]) /* Paused */)
.downloadCancelMenuItem,
.download-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"] .downloadCommandsSeparator
{
display: none;
}
/*** Visibility of download buttons ***/
.download-state:not(:-moz-any([state="-1"],/* Starting (initial) */
[state="5"], /* Starting (queued) */
[state="0"], /* Downloading */
[state="4"]) /* Paused */)
.downloadCancel,
/* Blocked (dirty) downloads that have not been confirmed and
have temporary data, for the Malware case. */
.download-state:not( [state="8"] /* Blocked (dirty) */)
.downloadConfirmBlock,
.download-state[state="8"]:not(.temporary-block)
.downloadConfirmBlock,
.download-state[state="8"].temporary-block:not([verdict="Malware"])
.downloadConfirmBlock,
/* Blocked (dirty) downloads that have not been confirmed and
have temporary data, for the Potentially Unwanted case. */
.download-state:not( [state="8"] /* Blocked (dirty) */)
.downloadChooseUnblock,
.download-state[state="8"]:not(.temporary-block)
.downloadChooseUnblock,
.download-state[state="8"].temporary-block:not([verdict="PotentiallyUnwanted"])
.downloadChooseUnblock,
/* Blocked (dirty) downloads that have not been confirmed and
have temporary data, for the Uncommon case. */
.download-state:not( [state="8"] /* Blocked (dirty) */)
.downloadChooseOpen,
.download-state[state="8"]:not(.temporary-block)
.downloadChooseOpen,
.download-state[state="8"].temporary-block:not([verdict="Uncommon"])
.downloadChooseOpen,
.download-state:not(:-moz-any([state="2"], /* Failed */
[state="3"]) /* Canceled */)
.downloadRetry,
.download-state:not( [state="1"] /* Finished */)
.downloadShow,
.download-state:-moz-any( [state="6"], /* Blocked (parental) */
[state="7"], /* Scanning */
[state="9"]) /* Blocked (policy) */
> toolbarseparator,
/* The "show blocked info" button is shown only in the downloads panel. */
.downloadShowBlockedInfo
{
display: none;
}
/*** Downloads panel ***/
#downloadsPanel[hasdownloads] #emptyDownloads,
#downloadsPanel:not([hasdownloads]) #downloadsListBox {
display: none;
}
/*** Downloads panel multiview (main view and blocked-downloads subview) ***/
/* Hide all the usual buttons. */
#downloadsPanel-mainView .download-state[state="8"] .downloadCancel,
#downloadsPanel-mainView .download-state[state="8"] .downloadConfirmBlock,
#downloadsPanel-mainView .download-state[state="8"] .downloadChooseUnblock,
#downloadsPanel-mainView .download-state[state="8"] .downloadChooseOpen,
#downloadsPanel-mainView .download-state[state="8"] .downloadRetry,
#downloadsPanel-mainView .download-state[state="8"] .downloadShow {
display: none;
}
/* Make the panel wide enough to show the download list items without improperly
truncating them. */
#downloadsPanel-multiView > .panel-viewcontainer,
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack,
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack > .panel-mainview {
max-width: unset;
}
/* Show the "show blocked info" button. */
#downloadsPanel-mainView .download-state[state="8"] .downloadShowBlockedInfo {
display: inline;
}
/** When the main view is showing... **/
/* The subview should be off to the right and not visible at all. */
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype=main] > .panel-subviews {
transform: translateX(101%);
transition: transform var(--panelui-subview-transition-duration);
}
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype=main] > .panel-subviews:-moz-locale-dir(rtl) {
transform: translateX(-101%);
}
/** When the subview is showing... **/
/* Hide the buttons of all downloads except the one that triggered the
subview. */
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype="subview"] .download-state:not([showingsubview]) .downloadButton {
visibility: hidden;
}
/* For the download that triggered the subview, move its button farther to the
right by removing padding so that a minimum amount of the main view's right
edge needs to be shown. */
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype="subview"] .download-state[showingsubview] {
padding: 0;
}
/* The main view should slide to the left and its right edge should remain
visible. */
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype=subview] > .panel-mainview {
transform: translateX(calc(-100% + 38px));
transition: transform var(--panelui-subview-transition-duration);
}
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype=subview] > .panel-mainview:-moz-locale-dir(rtl) {
transform: translateX(calc(100% - 38px));
}
/* The subview should leave the right edge of the main view uncovered. */
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack > .panel-subviews {
/* Use a margin instead of a transform like above so that the subview's width
isn't wider than the panel. */
-moz-margin-start: 38px !important;
}
/* Prevent keyboard interaction in the main view by preventing all elements in
the main view from being focused... */
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype="subview"] > .panel-mainview #downloadsListBox,
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype="subview"] > .panel-mainview richlistitem,
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype="subview"] > .panel-mainview .downloadButton,
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype="subview"] > .panel-mainview .downloadsPanelFooterButton,
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype="subview"] > .panel-mainview #downloadsSummary {
-moz-user-focus: ignore;
}
/* ... except for the downloadShowBlockedInfo button in the blocked download.
Selecting it with the keyboard should show the main view again. */
#downloadsPanel-multiView > .panel-viewcontainer > .panel-viewstack[viewtype="subview"] .download-state[showingsubview] .downloadShowBlockedInfo {
-moz-user-focus: normal;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,210 @@
<?xml version="1.0"?>
# -*- Mode: HTML; 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/.
<?xml-stylesheet href="chrome://browser/content/downloads/downloads.css"?>
<?xml-stylesheet href="chrome://browser/skin/downloads/downloads.css"?>
<!DOCTYPE overlay SYSTEM "chrome://browser/locale/downloads/downloads.dtd">
<overlay xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
id="downloadsOverlay">
<commandset>
<command id="downloadsCmd_doDefault"
oncommand="goDoCommand('downloadsCmd_doDefault')"/>
<command id="downloadsCmd_pauseResume"
oncommand="goDoCommand('downloadsCmd_pauseResume')"/>
<command id="downloadsCmd_cancel"
oncommand="goDoCommand('downloadsCmd_cancel')"/>
<command id="downloadsCmd_unblock"
oncommand="goDoCommand('downloadsCmd_unblock')"/>
<command id="downloadsCmd_chooseUnblock"
oncommand="goDoCommand('downloadsCmd_chooseUnblock')"/>
<command id="downloadsCmd_unblockAndOpen"
oncommand="goDoCommand('downloadsCmd_unblockAndOpen')"/>
<command id="downloadsCmd_confirmBlock"
oncommand="goDoCommand('downloadsCmd_confirmBlock')"/>
<command id="downloadsCmd_open"
oncommand="goDoCommand('downloadsCmd_open')"/>
<command id="downloadsCmd_show"
oncommand="goDoCommand('downloadsCmd_show')"/>
<command id="downloadsCmd_retry"
oncommand="goDoCommand('downloadsCmd_retry')"/>
<command id="downloadsCmd_openReferrer"
oncommand="goDoCommand('downloadsCmd_openReferrer')"/>
<command id="downloadsCmd_copyLocation"
oncommand="goDoCommand('downloadsCmd_copyLocation')"/>
<command id="downloadsCmd_clearList"
oncommand="goDoCommand('downloadsCmd_clearList')"/>
</commandset>
<popupset id="mainPopupSet">
<!-- The panel has level="top" to ensure that it is never hidden by the
taskbar on Windows. See bug 672365. For accessibility to screen
readers, we use a label on the panel instead of the anchor because the
panel can also be displayed without an anchor. -->
<panel id="downloadsPanel"
aria-label="&downloads.title;"
role="group"
type="arrow"
orient="vertical"
level="top"
onpopupshown="DownloadsPanel.onPopupShown(event);"
onpopuphidden="DownloadsPanel.onPopupHidden(event);">
<!-- The following popup menu should be a child of the panel element,
otherwise flickering may occur when the cursor is moved over the area
of a disabled menu item that overlaps the panel. See bug 492960. -->
<menupopup id="downloadsContextMenu"
onpopupshown="DownloadsView.onContextPopupShown(event);"
onpopuphidden="DownloadsView.onContextPopupHidden(event);"
class="download-state">
<menuitem command="downloadsCmd_pauseResume"
class="downloadPauseMenuItem"
label="&cmd.pause.label;"
accesskey="&cmd.pause.accesskey;"/>
<menuitem command="downloadsCmd_pauseResume"
class="downloadResumeMenuItem"
label="&cmd.resume.label;"
accesskey="&cmd.resume.accesskey;"/>
<menuitem command="downloadsCmd_cancel"
class="downloadCancelMenuItem"
label="&cmd.cancel.label;"
accesskey="&cmd.cancel.accesskey;"/>
<menuitem command="downloadsCmd_unblock"
class="downloadUnblockMenuItem"
label="&cmd.unblock2.label;"
accesskey="&cmd.unblock2.accesskey;"/>
<menuitem command="cmd_delete"
class="downloadRemoveFromHistoryMenuItem"
label="&cmd.removeFromHistory.label;"
accesskey="&cmd.removeFromHistory.accesskey;"/>
<menuitem command="downloadsCmd_show"
class="downloadShowMenuItem"
#ifdef XP_MACOSX
label="&cmd.showMac.label;"
accesskey="&cmd.showMac.accesskey;"
#else
label="&cmd.show.label;"
accesskey="&cmd.show.accesskey;"
#endif
/>
<menuseparator class="downloadCommandsSeparator"/>
<menuitem command="downloadsCmd_openReferrer"
label="&cmd.goToDownloadPage.label;"
accesskey="&cmd.goToDownloadPage.accesskey;"/>
<menuitem command="downloadsCmd_copyLocation"
label="&cmd.copyDownloadLink.label;"
accesskey="&cmd.copyDownloadLink.accesskey;"/>
<menuseparator/>
<menuitem command="downloadsCmd_clearList"
label="&cmd.clearList2.label;"
accesskey="&cmd.clearList2.accesskey;"/>
</menupopup>
<panelmultiview id="downloadsPanel-multiView"
mainViewId="downloadsPanel-mainView"
align="stretch">
<panelview id="downloadsPanel-mainView"
flex="1"
align="stretch">
<richlistbox id="downloadsListBox"
context="downloadsContextMenu"
onmouseover="DownloadsView.onDownloadMouseOver(event);"
onmouseout="DownloadsView.onDownloadMouseOut(event);"
oncontextmenu="DownloadsView.onDownloadContextMenu(event);"
ondragstart="DownloadsView.onDownloadDragStart(event);"/>
<description id="emptyDownloads"
mousethrough="always">
&downloadsPanelEmpty.label;
</description>
<spacer flex="1"/>
<vbox id="downloadsFooter"
class="downloadsPanelFooter">
<stack>
<hbox id="downloadsSummary"
align="center"
orient="horizontal"
onkeydown="DownloadsSummary.onKeyDown(event);"
onclick="DownloadsSummary.onClick(event);">
<image class="downloadTypeIcon" />
<vbox pack="center"
class="downloadContainer"
style="width: &downloadDetails.width;">
<description id="downloadsSummaryDescription"
style="min-width: &downloadsSummary.minWidth2;"/>
<progressmeter id="downloadsSummaryProgress"
class="downloadProgress"
min="0"
max="100"
mode="normal" />
<description id="downloadsSummaryDetails"
crop="end"/>
</vbox>
</hbox>
<hbox id="downloadsFooterButtons">
<button id="downloadsHistory"
class="downloadsPanelFooterButton"
label="&downloadsHistory.label;"
accesskey="&downloadsHistory.accesskey;"
flex="1"
oncommand="DownloadsPanel.showDownloadsHistory();"/>
<toolbarseparator id="downloadsFooterButtonsSplitter"
class="downloadsDropmarkerSplitter"/>
<button id="downloadsFooterDropmarker"
class="downloadsPanelFooterButton downloadsDropmarker"
type="menu">
<menupopup id="downloadSubPanel"
onpopupshowing="DownloadsPanel.onFooterPopupShowing(event);"
onpopuphidden="DownloadsPanel.onFooterPopupHidden(event);"
position="after_end">
<menuitem id="downloadsDropdownItemClearList"
command="downloadsCmd_clearList"
label="&cmd.clearList2.label;"/>
<menuitem id="downloadsDropdownItemOpenDownloadsFolder"
oncommand="DownloadsPanel.openDownloadsFolder();"
label="&openDownloadsFolder.label;"/>
</menupopup>
</button>
</hbox>
</stack>
</vbox>
</panelview>
<panelview id="downloadsPanel-blockedSubview"
orient="vertical"
flex="1">
<description id="downloadsPanel-blockedSubview-title"/>
<description id="downloadsPanel-blockedSubview-details1"/>
<description id="downloadsPanel-blockedSubview-details2"/>
<spacer flex="1"/>
<hbox id="downloadsPanel-blockedSubview-buttons"
class="downloadsPanelFooter"
align="stretch">
<button id="downloadsPanel-blockedSubview-openButton"
class="downloadsPanelFooterButton"
command="downloadsCmd_unblockAndOpen"
flex="1"/>
<toolbarseparator/>
<button id="downloadsPanel-blockedSubview-deleteButton"
class="downloadsPanelFooterButton"
oncommand="DownloadsBlockedSubview.confirmBlock();"
default="true"
flex="1"/>
</hbox>
</panelview>
</panelmultiview>
</panel>
</popupset>
</overlay>

View file

@ -0,0 +1,606 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 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/. */
/**
* Handles the indicator that displays the progress of ongoing downloads, which
* is also used as the anchor for the downloads panel.
*
* This module includes the following constructors and global objects:
*
* DownloadsButton
* Main entry point for the downloads indicator. Depending on how the toolbars
* have been customized, this object determines if we should show a fully
* functional indicator, a placeholder used during customization and in the
* customization palette, or a neutral view as a temporary anchor for the
* downloads panel.
*
* DownloadsIndicatorView
* Builds and updates the actual downloads status widget, responding to changes
* in the global status data, or provides a neutral view if the indicator is
* removed from the toolbars and only used as a temporary anchor. In addition,
* handles the user interaction events raised by the widget.
*/
"use strict";
////////////////////////////////////////////////////////////////////////////////
//// DownloadsButton
/**
* Main entry point for the downloads indicator. Depending on how the toolbars
* have been customized, this object determines if we should show a fully
* functional indicator, a placeholder used during customization and in the
* customization palette, or a neutral view as a temporary anchor for the
* downloads panel.
*/
const DownloadsButton = {
/**
* Location of the indicator overlay.
*/
get kIndicatorOverlay() {
return "chrome://browser/content/downloads/indicatorOverlay.xul";
},
/**
* Returns a reference to the downloads button position placeholder, or null
* if not available because it has been removed from the toolbars.
*/
get _placeholder() {
return document.getElementById("downloads-button");
},
/**
* This function is called asynchronously just after window initialization.
*
* NOTE: This function should limit the input/output it performs to improve
* startup time.
*/
initializeIndicator() {
DownloadsIndicatorView.ensureInitialized();
},
/**
* Indicates whether toolbar customization is in progress.
*/
_customizing: false,
/**
* This function is called when toolbar customization starts.
*
* During customization, we never show the actual download progress indication
* or the event notifications, but we show a neutral placeholder. The neutral
* placeholder is an ordinary button defined in the browser window that can be
* moved freely between the toolbars and the customization palette.
*/
customizeStart() {
// Prevent the indicator from being displayed as a temporary anchor
// during customization, even if requested using the getAnchor method.
this._customizing = true;
this._anchorRequested = false;
},
/**
* This function is called when toolbar customization ends.
*/
customizeDone() {
this._customizing = false;
DownloadsIndicatorView.afterCustomize();
},
/**
* Determines the position where the indicator should appear, and moves its
* associated element to the new position.
*
* @return Anchor element, or null if the indicator is not visible.
*/
_getAnchorInternal() {
let indicator = DownloadsIndicatorView.indicator;
if (!indicator) {
// Exit now if the indicator overlay isn't loaded yet, or if the button
// is not in the document.
return null;
}
indicator.open = this._anchorRequested;
let widget = CustomizableUI.getWidget("downloads-button")
.forWindow(window);
// Determine if the indicator is located on an invisible toolbar.
if (!isElementVisible(indicator.parentNode) && !widget.overflowed) {
return null;
}
return DownloadsIndicatorView.indicatorAnchor;
},
/**
* Checks whether the indicator is, or will soon be visible in the browser
* window.
*
* @param aCallback
* Called once the indicator overlay has loaded. Gets a boolean
* argument representing the indicator visibility.
*/
checkIsVisible(aCallback) {
DownloadsOverlayLoader.ensureOverlayLoaded(this.kIndicatorOverlay, () => {
if (!this._placeholder) {
aCallback(false);
} else {
let element = DownloadsIndicatorView.indicator || this._placeholder;
aCallback(isElementVisible(element.parentNode));
}
});
},
/**
* Indicates whether we should try and show the indicator temporarily as an
* anchor for the panel, even if the indicator would be hidden by default.
*/
_anchorRequested: false,
/**
* Ensures that there is an anchor available for the panel.
*
* @param aCallback
* Called when the anchor is available, passing the element where the
* panel should be anchored, or null if an anchor is not available (for
* example because both the tab bar and the navigation bar are hidden).
*/
getAnchor(aCallback) {
// Do not allow anchoring the panel to the element while customizing.
if (this._customizing) {
aCallback(null);
return;
}
DownloadsOverlayLoader.ensureOverlayLoaded(this.kIndicatorOverlay, () => {
this._anchorRequested = true;
aCallback(this._getAnchorInternal());
});
},
/**
* Allows the temporary anchor to be hidden.
*/
releaseAnchor() {
this._anchorRequested = false;
this._getAnchorInternal();
},
get _tabsToolbar() {
delete this._tabsToolbar;
return this._tabsToolbar = document.getElementById("TabsToolbar");
},
get _navBar() {
delete this._navBar;
return this._navBar = document.getElementById("nav-bar");
}
};
Object.defineProperty(this, "DownloadsButton", {
value: DownloadsButton,
enumerable: true,
writable: false
});
////////////////////////////////////////////////////////////////////////////////
//// DownloadsIndicatorView
/**
* Builds and updates the actual downloads status widget, responding to changes
* in the global status data, or provides a neutral view if the indicator is
* removed from the toolbars and only used as a temporary anchor. In addition,
* handles the user interaction events raised by the widget.
*/
const DownloadsIndicatorView = {
/**
* True when the view is connected with the underlying downloads data.
*/
_initialized: false,
/**
* True when the user interface elements required to display the indicator
* have finished loading in the browser window, and can be referenced.
*/
_operational: false,
/**
* Prepares the downloads indicator to be displayed.
*/
ensureInitialized() {
if (this._initialized) {
return;
}
this._initialized = true;
window.addEventListener("unload", this.onWindowUnload, false);
DownloadsCommon.getIndicatorData(window).addView(this);
},
/**
* Frees the internal resources related to the indicator.
*/
ensureTerminated() {
if (!this._initialized) {
return;
}
this._initialized = false;
window.removeEventListener("unload", this.onWindowUnload, false);
DownloadsCommon.getIndicatorData(window).removeView(this);
// Reset the view properties, so that a neutral indicator is displayed if we
// are visible only temporarily as an anchor.
this.counter = "";
this.percentComplete = 0;
this.paused = false;
this.attention = DownloadsCommon.ATTENTION_NONE;
},
/**
* Ensures that the user interface elements required to display the indicator
* are loaded, then invokes the given callback.
*/
_ensureOperational(aCallback) {
if (this._operational) {
if (aCallback) {
aCallback();
}
return;
}
// If we don't have a _placeholder, there's no chance that the overlay
// will load correctly: bail (and don't set _operational to true!)
if (!DownloadsButton._placeholder) {
return;
}
DownloadsOverlayLoader.ensureOverlayLoaded(
DownloadsButton.kIndicatorOverlay,
() => {
this._operational = true;
// If the view is initialized, we need to update the elements now that
// they are finally available in the document.
if (this._initialized) {
DownloadsCommon.getIndicatorData(window).refreshView(this);
}
if (aCallback) {
aCallback();
}
});
},
//////////////////////////////////////////////////////////////////////////////
//// Direct control functions
/**
* Set while we are waiting for a notification to fade out.
*/
_notificationTimeout: null,
/**
* Check if the panel containing aNode is open.
* @param aNode
* the node whose panel we're interested in.
*/
_isAncestorPanelOpen(aNode) {
while (aNode && aNode.localName != "panel") {
aNode = aNode.parentNode;
}
return aNode && aNode.state == "open";
},
/**
* If the status indicator is visible in its assigned position, shows for a
* brief time a visual notification of a relevant event, like a new download.
*
* @param aType
* Set to "start" for new downloads, "finish" for completed downloads.
*/
showEventNotification(aType) {
if (!this._initialized) {
return;
}
if (!DownloadsCommon.animateNotifications) {
return;
}
// No need to show visual notification if the panel is visible.
if (DownloadsPanel.isPanelShowing) {
return;
}
let anchor = DownloadsButton._placeholder;
let widgetGroup = CustomizableUI.getWidget("downloads-button");
let widget = widgetGroup.forWindow(window);
if (widget.overflowed || widgetGroup.areaType == CustomizableUI.TYPE_MENU_PANEL) {
if (anchor && this._isAncestorPanelOpen(anchor)) {
// If the containing panel is open, don't do anything, because the
// notification would appear under the open panel. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=984023
return;
}
// Otherwise, try to use the anchor of the panel:
anchor = widget.anchor;
}
if (!anchor || !isElementVisible(anchor.parentNode)) {
// Our container isn't visible, so can't show the animation:
return;
}
if (this._notificationTimeout) {
clearTimeout(this._notificationTimeout);
}
// The notification element is positioned to show in the same location as
// the downloads button. It's not in the downloads button itself in order to
// be able to anchor the notification elsewhere if required, and to ensure
// the notification isn't clipped by overflow properties of the anchor's
// container.
let notifier = this.notifier;
if (notifier.style.transform == '') {
let anchorRect = anchor.getBoundingClientRect();
let notifierRect = notifier.getBoundingClientRect();
let topDiff = anchorRect.top - notifierRect.top;
let leftDiff = anchorRect.left - notifierRect.left;
let heightDiff = anchorRect.height - notifierRect.height;
let widthDiff = anchorRect.width - notifierRect.width;
let translateX = (leftDiff + .5 * widthDiff) + "px";
let translateY = (topDiff + .5 * heightDiff) + "px";
notifier.style.transform = "translate(" + translateX + ", " + translateY + ")";
}
notifier.setAttribute("notification", aType);
this._notificationTimeout = setTimeout(() => {
notifier.removeAttribute("notification");
notifier.style.transform = '';
}, 1000);
},
//////////////////////////////////////////////////////////////////////////////
//// Callback functions from DownloadsIndicatorData
/**
* Indicates whether the indicator should be shown because there are some
* downloads to be displayed.
*/
set hasDownloads(aValue) {
if (this._hasDownloads != aValue || (!this._operational && aValue)) {
this._hasDownloads = aValue;
// If there is at least one download, ensure that the view elements are
if (aValue) {
this._ensureOperational();
}
}
return aValue;
},
get hasDownloads() {
return this._hasDownloads;
},
_hasDownloads: false,
/**
* Status text displayed in the indicator. If this is set to an empty value,
* then the small downloads icon is displayed instead of the text.
*/
set counter(aValue) {
if (!this._operational) {
return this._counter;
}
if (this._counter !== aValue) {
this._counter = aValue;
if (this._counter)
this.indicator.setAttribute("counter", "true");
else
this.indicator.removeAttribute("counter");
// We have to set the attribute instead of using the property because the
// XBL binding isn't applied if the element is invisible for any reason.
this._indicatorCounter.setAttribute("value", aValue);
}
return aValue;
},
_counter: null,
/**
* Progress indication to display, from 0 to 100, or -1 if unknown. The
* progress bar is hidden if the current progress is unknown and no status
* text is set in the "counter" property.
*/
set percentComplete(aValue) {
if (!this._operational) {
return this._percentComplete;
}
if (this._percentComplete !== aValue) {
this._percentComplete = aValue;
if (this._percentComplete >= 0)
this.indicator.setAttribute("progress", "true");
else
this.indicator.removeAttribute("progress");
// We have to set the attribute instead of using the property because the
// XBL binding isn't applied if the element is invisible for any reason.
this._indicatorProgress.setAttribute("value", Math.max(aValue, 0));
}
return aValue;
},
_percentComplete: null,
/**
* Indicates whether the progress won't advance because of a paused state.
* Setting this property forces a paused progress bar to be displayed, even if
* the current progress information is unavailable.
*/
set paused(aValue) {
if (!this._operational) {
return this._paused;
}
if (this._paused != aValue) {
this._paused = aValue;
if (this._paused) {
this.indicator.setAttribute("paused", "true")
} else {
this.indicator.removeAttribute("paused");
}
}
return aValue;
},
_paused: false,
/**
* Set when the indicator should draw user attention to itself.
*/
set attention(aValue) {
if (!this._operational) {
return this._attention;
}
if (this._attention != aValue) {
this._attention = aValue;
// Check if the downloads button is in the menu panel, to determine which
// button needs to get a badge.
let widgetGroup = CustomizableUI.getWidget("downloads-button");
let inMenu = widgetGroup.areaType == CustomizableUI.TYPE_MENU_PANEL;
if (aValue == DownloadsCommon.ATTENTION_NONE) {
this.indicator.removeAttribute("attention");
if (inMenu) {
gMenuButtonBadgeManager.removeBadge(gMenuButtonBadgeManager.BADGEID_DOWNLOAD);
}
} else {
this.indicator.setAttribute("attention", aValue);
if (inMenu) {
let badgeClass = "download-" + aValue;
gMenuButtonBadgeManager.addBadge(gMenuButtonBadgeManager.BADGEID_DOWNLOAD, badgeClass);
}
}
}
return aValue;
},
_attention: DownloadsCommon.ATTENTION_NONE,
//////////////////////////////////////////////////////////////////////////////
//// User interface event functions
onWindowUnload() {
// This function is registered as an event listener, we can't use "this".
DownloadsIndicatorView.ensureTerminated();
},
onCommand(aEvent) {
// If the downloads button is in the menu panel, open the Library
let widgetGroup = CustomizableUI.getWidget("downloads-button");
if (widgetGroup.areaType == CustomizableUI.TYPE_MENU_PANEL) {
DownloadsPanel.showDownloadsHistory();
} else {
DownloadsPanel.showPanel();
}
aEvent.stopPropagation();
},
onDragOver(aEvent) {
browserDragAndDrop.dragOver(aEvent);
},
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 links = browserDragAndDrop.dropLinks(aEvent);
if (!links.length)
return;
let sourceDoc = dt.mozSourceNode ? dt.mozSourceNode.ownerDocument : document;
let handled = false;
for (let link of links) {
if (link.url.startsWith("about:"))
continue;
saveURL(link.url, link.name, null, true, true, null, sourceDoc);
handled = true;
}
if (handled) {
aEvent.preventDefault();
}
},
_indicator: null,
__indicatorCounter: null,
__indicatorProgress: null,
/**
* Returns a reference to the main indicator element, or null if the element
* is not present in the browser window yet.
*/
get indicator() {
if (this._indicator) {
return this._indicator;
}
let indicator = document.getElementById("downloads-button");
if (!indicator || indicator.getAttribute("indicator") != "true") {
return null;
}
return this._indicator = indicator;
},
get indicatorAnchor() {
let widget = CustomizableUI.getWidget("downloads-button")
.forWindow(window);
if (widget.overflowed) {
return widget.anchor;
}
return document.getElementById("downloads-indicator-anchor");
},
get _indicatorCounter() {
return this.__indicatorCounter ||
(this.__indicatorCounter = document.getElementById("downloads-indicator-counter"));
},
get _indicatorProgress() {
return this.__indicatorProgress ||
(this.__indicatorProgress = document.getElementById("downloads-indicator-progress"));
},
get notifier() {
return this._notifier ||
(this._notifier = document.getElementById("downloads-notification-anchor"));
},
_onCustomizedAway() {
this._indicator = null;
this.__indicatorCounter = null;
this.__indicatorProgress = null;
},
afterCustomize() {
// If the cached indicator is not the one currently in the document,
// invalidate our references
if (this._indicator != document.getElementById("downloads-button")) {
this._onCustomizedAway();
this._operational = false;
this.ensureTerminated();
this.ensureInitialized();
}
},
};
Object.defineProperty(this, "DownloadsIndicatorView", {
value: DownloadsIndicatorView,
enumerable: true,
writable: false
});

View file

@ -0,0 +1,36 @@
<?xml version="1.0"?>
<!-- -*- Mode: HTML; 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/. -->
<!DOCTYPE overlay [
<!ENTITY % browserDTD SYSTEM "chrome://browser/locale/browser.dtd" >
%browserDTD;
]>
<overlay xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
id="indicatorOverlay">
<!-- We dynamically add the stack with the progress meter and notification icon,
originally loaded lazily because of performance reasons, to the existing
downloads-button. -->
<toolbarbutton id="downloads-button" indicator="true">
<!-- The panel's anchor area is smaller than the outer button, but must
always be visible and must not move or resize when the indicator
state changes, otherwise the panel could change its position or lose
its arrow unexpectedly. -->
<stack id="downloads-indicator-anchor"
consumeanchor="downloads-button">
<vbox id="downloads-indicator-progress-area" pack="center">
<description id="downloads-indicator-counter"/>
<progressmeter id="downloads-indicator-progress" class="plain"
min="0" max="100"/>
</vbox>
<vbox id="downloads-indicator-icon"/>
</stack>
</toolbarbutton>
</overlay>

View file

@ -0,0 +1,16 @@
# 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/downloads/download.xml (content/download.xml)
content/browser/downloads/downloads.css (content/downloads.css)
content/browser/downloads/downloads.js (content/downloads.js)
* content/browser/downloads/downloadsOverlay.xul (content/downloadsOverlay.xul)
content/browser/downloads/indicator.js (content/indicator.js)
content/browser/downloads/indicatorOverlay.xul (content/indicatorOverlay.xul)
* content/browser/downloads/allDownloadsViewOverlay.xul (content/allDownloadsViewOverlay.xul)
content/browser/downloads/allDownloadsViewOverlay.js (content/allDownloadsViewOverlay.js)
* content/browser/downloads/contentAreaDownloadsView.xul (content/contentAreaDownloadsView.xul)
content/browser/downloads/contentAreaDownloadsView.js (content/contentAreaDownloadsView.js)
content/browser/downloads/contentAreaDownloadsView.css (content/contentAreaDownloadsView.css)

View file

@ -0,0 +1,13 @@
# -*- Mode: python; 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']
EXTRA_JS_MODULES += [
'DownloadsCommon.jsm',
'DownloadsTaskbar.jsm',
'DownloadsViewUI.jsm',
]

View file

@ -0,0 +1,25 @@
# This component must restrict its registration for the app-startup category
# to the specific list of apps that use it so it doesn't get loaded in xpcshell.
# Thus we restrict it to these apps:
#
# b2g: {3c2e2abc-06d4-11e1-ac3b-374f68613e61}
# browser: {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
# mobile/android: {aa3c5121-dab2-40e2-81ca-7ea25febc110}
# mobile/xul: {a23983c0-fd0e-11dc-95ff-0800200c9a66}
# graphene: {d1bfe7d9-c01e-4237-998b-7b5f960a4314}
component {229fa115-9412-4d32-baf3-2fc407f76fb1} FeedConverter.js
contract @mozilla.org/streamconv;1?from=application/vnd.mozilla.maybe.feed&to=*/* {229fa115-9412-4d32-baf3-2fc407f76fb1}
contract @mozilla.org/streamconv;1?from=application/vnd.mozilla.maybe.video.feed&to=*/* {229fa115-9412-4d32-baf3-2fc407f76fb1}
contract @mozilla.org/streamconv;1?from=application/vnd.mozilla.maybe.audio.feed&to=*/* {229fa115-9412-4d32-baf3-2fc407f76fb1}
component {2376201c-bbc6-472f-9b62-7548040a61c6} FeedConverter.js
contract @mozilla.org/browser/feeds/result-service;1 {2376201c-bbc6-472f-9b62-7548040a61c6}
component {4f91ef2e-57ba-472e-ab7a-b4999e42d6c0} FeedConverter.js
contract @mozilla.org/network/protocol;1?name=feed {4f91ef2e-57ba-472e-ab7a-b4999e42d6c0}
component {1c31ed79-accd-4b94-b517-06e0c81999d5} FeedConverter.js
contract @mozilla.org/network/protocol;1?name=pcast {1c31ed79-accd-4b94-b517-06e0c81999d5}
component {49bb6593-3aff-4eb3-a068-2712c28bd58e} FeedWriter.js
contract @mozilla.org/browser/feeds/result-writer;1 {49bb6593-3aff-4eb3-a068-2712c28bd58e}
component {792a7e82-06a0-437c-af63-b2d12e808acc} WebContentConverter.js
contract @mozilla.org/embeddor.implemented/web-content-handler-registrar;1 {792a7e82-06a0-437c-af63-b2d12e808acc}
category app-startup WebContentConverter service,@mozilla.org/embeddor.implemented/web-content-handler-registrar;1 application={3c2e2abc-06d4-11e1-ac3b-374f68613e61} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} application={aa3c5121-dab2-40e2-81ca-7ea25febc110} application={a23983c0-fd0e-11dc-95ff-0800200c9a66} application={d1bfe7d9-c01e-4237-998b-7b5f960a4314}

View file

@ -0,0 +1,568 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 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/. */
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/debug.js");
Components.utils.import("resource://gre/modules/Services.jsm");
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
function LOG(str) {
dump("*** " + str + "\n");
}
const FS_CONTRACTID = "@mozilla.org/browser/feeds/result-service;1";
const FPH_CONTRACTID = "@mozilla.org/network/protocol;1?name=feed";
const PCPH_CONTRACTID = "@mozilla.org/network/protocol;1?name=pcast";
const TYPE_MAYBE_FEED = "application/vnd.mozilla.maybe.feed";
const TYPE_MAYBE_VIDEO_FEED = "application/vnd.mozilla.maybe.video.feed";
const TYPE_MAYBE_AUDIO_FEED = "application/vnd.mozilla.maybe.audio.feed";
const TYPE_ANY = "*/*";
const PREF_SELECTED_APP = "browser.feeds.handlers.application";
const PREF_SELECTED_WEB = "browser.feeds.handlers.webservice";
const PREF_SELECTED_ACTION = "browser.feeds.handler";
const PREF_SELECTED_READER = "browser.feeds.handler.default";
const PREF_VIDEO_SELECTED_APP = "browser.videoFeeds.handlers.application";
const PREF_VIDEO_SELECTED_WEB = "browser.videoFeeds.handlers.webservice";
const PREF_VIDEO_SELECTED_ACTION = "browser.videoFeeds.handler";
const PREF_VIDEO_SELECTED_READER = "browser.videoFeeds.handler.default";
const PREF_AUDIO_SELECTED_APP = "browser.audioFeeds.handlers.application";
const PREF_AUDIO_SELECTED_WEB = "browser.audioFeeds.handlers.webservice";
const PREF_AUDIO_SELECTED_ACTION = "browser.audioFeeds.handler";
const PREF_AUDIO_SELECTED_READER = "browser.audioFeeds.handler.default";
function getPrefAppForType(t) {
switch (t) {
case Ci.nsIFeed.TYPE_VIDEO:
return PREF_VIDEO_SELECTED_APP;
case Ci.nsIFeed.TYPE_AUDIO:
return PREF_AUDIO_SELECTED_APP;
default:
return PREF_SELECTED_APP;
}
}
function getPrefWebForType(t) {
switch (t) {
case Ci.nsIFeed.TYPE_VIDEO:
return PREF_VIDEO_SELECTED_WEB;
case Ci.nsIFeed.TYPE_AUDIO:
return PREF_AUDIO_SELECTED_WEB;
default:
return PREF_SELECTED_WEB;
}
}
function getPrefActionForType(t) {
switch (t) {
case Ci.nsIFeed.TYPE_VIDEO:
return PREF_VIDEO_SELECTED_ACTION;
case Ci.nsIFeed.TYPE_AUDIO:
return PREF_AUDIO_SELECTED_ACTION;
default:
return PREF_SELECTED_ACTION;
}
}
function getPrefReaderForType(t) {
switch (t) {
case Ci.nsIFeed.TYPE_VIDEO:
return PREF_VIDEO_SELECTED_READER;
case Ci.nsIFeed.TYPE_AUDIO:
return PREF_AUDIO_SELECTED_READER;
default:
return PREF_SELECTED_READER;
}
}
function safeGetCharPref(pref, defaultValue) {
var prefs =
Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
try {
return prefs.getCharPref(pref);
}
catch (e) {
}
return defaultValue;
}
function FeedConverter() {
}
FeedConverter.prototype = {
classID: Components.ID("{229fa115-9412-4d32-baf3-2fc407f76fb1}"),
/**
* This is the downloaded text data for the feed.
*/
_data: null,
/**
* This is the object listening to the conversion, which is ultimately the
* docshell for the load.
*/
_listener: null,
/**
* Records if the feed was sniffed
*/
_sniffed: false,
/**
* See nsIStreamConverter.idl
*/
convert(sourceStream, sourceType, destinationType,
context) {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
},
/**
* See nsIStreamConverter.idl
*/
asyncConvertData(sourceType, destinationType,
listener, context) {
this._listener = listener;
},
/**
* Whether or not the preview page is being forced.
*/
_forcePreviewPage: false,
/**
* Release our references to various things once we're done using them.
*/
_releaseHandles() {
this._listener = null;
this._request = null;
this._processor = null;
},
/**
* See nsIFeedResultListener.idl
*/
handleResult(result) {
// Feeds come in various content types, which our feed sniffer coerces to
// the maybe.feed type. However, feeds are used as a transport for
// different data types, e.g. news/blogs (traditional feed), video/audio
// (podcasts) and photos (photocasts, photostreams). Each of these is
// different in that there's a different class of application suitable for
// handling feeds of that type, but without a content-type differentiation
// it is difficult for us to disambiguate.
//
// The other problem is that if the user specifies an auto-action handler
// for one feed application, the fact that the content type is shared means
// that all other applications will auto-load with that handler too,
// regardless of the content-type.
//
// This means that content-type alone is not enough to determine whether
// or not a feed should be auto-handled. This means that for feeds we need
// to always use this stream converter, even when an auto-action is
// specified, not the basic one provided by WebContentConverter. This
// converter needs to consume all of the data and parse it, and based on
// that determination make a judgment about type.
//
// Since there are no content types for this content, and I'm not going to
// invent any, the upshot is that while a user can set an auto-handler for
// generic feed content, the system will prevent them from setting an auto-
// handler for other stream types. In those cases, the user will always see
// the preview page and have to select a handler. We can guess and show
// a client handler, but will not be able to show web handlers for those
// types.
//
// If this is just a feed, not some kind of specialized application, then
// auto-handlers can be set and we should obey them.
try {
let feedService =
Cc["@mozilla.org/browser/feeds/result-service;1"].
getService(Ci.nsIFeedResultService);
if (!this._forcePreviewPage && result.doc) {
let feed = result.doc.QueryInterface(Ci.nsIFeed);
let handler = safeGetCharPref(getPrefActionForType(feed.type), "ask");
if (handler != "ask") {
if (handler == "reader")
handler = safeGetCharPref(getPrefReaderForType(feed.type), "bookmarks");
switch (handler) {
case "web":
let wccr =
Cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"].
getService(Ci.nsIWebContentConverterService);
if ((feed.type == Ci.nsIFeed.TYPE_FEED &&
wccr.getAutoHandler(TYPE_MAYBE_FEED)) ||
(feed.type == Ci.nsIFeed.TYPE_VIDEO &&
wccr.getAutoHandler(TYPE_MAYBE_VIDEO_FEED)) ||
(feed.type == Ci.nsIFeed.TYPE_AUDIO &&
wccr.getAutoHandler(TYPE_MAYBE_AUDIO_FEED))) {
wccr.loadPreferredHandler(this._request);
return;
}
break;
default:
LOG("unexpected handler: " + handler);
// fall through -- let feed service handle error
case "bookmarks":
case "client":
case "default":
try {
let title = feed.title ? feed.title.plainText() : "";
let desc = feed.subtitle ? feed.subtitle.plainText() : "";
feedService.addToClientReader(result.uri.spec, title, desc, feed.type, handler);
return;
} catch (ex) { /* fallback to preview mode */ }
}
}
}
let ios =
Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
let chromeChannel;
// handling a redirect, hence forwarding the loadInfo from the old channel
// to the newchannel.
let oldChannel = this._request.QueryInterface(Ci.nsIChannel);
let loadInfo = oldChannel.loadInfo;
// If there was no automatic handler, or this was a podcast,
// photostream or some other kind of application, show the preview page
// if the parser returned a document.
if (result.doc) {
// Store the result in the result service so that the display
// page can access it.
feedService.addFeedResult(result);
// Now load the actual XUL document.
let aboutFeedsURI = ios.newURI("about:feeds", null, null);
chromeChannel = ios.newChannelFromURIWithLoadInfo(aboutFeedsURI, loadInfo);
chromeChannel.originalURI = result.uri;
// carry the origin attributes from the channel that loaded the feed.
chromeChannel.owner =
Services.scriptSecurityManager.createCodebasePrincipal(aboutFeedsURI,
loadInfo.originAttributes);
} else {
chromeChannel = ios.newChannelFromURIWithLoadInfo(result.uri, loadInfo);
}
chromeChannel.loadGroup = this._request.loadGroup;
chromeChannel.asyncOpen2(this._listener);
}
finally {
this._releaseHandles();
}
},
/**
* See nsIStreamListener.idl
*/
onDataAvailable(request, context, inputStream,
sourceOffset, count) {
if (this._processor)
this._processor.onDataAvailable(request, context, inputStream,
sourceOffset, count);
},
/**
* See nsIRequestObserver.idl
*/
onStartRequest(request, context) {
let channel = request.QueryInterface(Ci.nsIChannel);
// Check for a header that tells us there was no sniffing
// The value doesn't matter.
try {
let httpChannel = channel.QueryInterface(Ci.nsIHttpChannel);
// Make sure to check requestSucceeded before the potentially-throwing
// getResponseHeader.
if (!httpChannel.requestSucceeded) {
// Just give up, but don't forget to cancel the channel first!
request.cancel(Cr.NS_BINDING_ABORTED);
return;
}
// Note: this throws if the header is not set.
httpChannel.getResponseHeader("X-Moz-Is-Feed");
}
catch (ex) {
this._sniffed = true;
}
this._request = request;
// Save and reset the forced state bit early, in case there's some kind of
// error.
let feedService =
Cc["@mozilla.org/browser/feeds/result-service;1"].
getService(Ci.nsIFeedResultService);
this._forcePreviewPage = feedService.forcePreviewPage;
feedService.forcePreviewPage = false;
// Parse feed data as it comes in
this._processor =
Cc["@mozilla.org/feed-processor;1"].
createInstance(Ci.nsIFeedProcessor);
this._processor.listener = this;
this._processor.parseAsync(null, channel.URI);
this._processor.onStartRequest(request, context);
},
/**
* See nsIRequestObserver.idl
*/
onStopRequest(request, context, status) {
if (this._processor)
this._processor.onStopRequest(request, context, status);
},
/**
* See nsISupports.idl
*/
QueryInterface(iid) {
if (iid.equals(Ci.nsIFeedResultListener) ||
iid.equals(Ci.nsIStreamConverter) ||
iid.equals(Ci.nsIStreamListener) ||
iid.equals(Ci.nsIRequestObserver)||
iid.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
};
/**
* Keeps parsed FeedResults around for use elsewhere in the UI after the stream
* converter completes.
*/
function FeedResultService() {
}
FeedResultService.prototype = {
classID: Components.ID("{2376201c-bbc6-472f-9b62-7548040a61c6}"),
/**
* A URI spec -> [nsIFeedResult] hash. We have to keep a list as the
* value in case the same URI is requested concurrently.
*/
_results: { },
/**
* See nsIFeedResultService.idl
*/
forcePreviewPage: false,
/**
* See nsIFeedResultService.idl
*/
addToClientReader(spec, title, subtitle, feedType, feedReader) {
if (!feedReader) {
feedReader = "default";
}
let handler = safeGetCharPref(getPrefActionForType(feedType), "bookmarks");
if (handler == "ask" || handler == "reader")
handler = feedReader;
switch (handler) {
case "client":
Services.cpmm.sendAsyncMessage("FeedConverter:ExecuteClientApp",
{ spec,
title,
subtitle,
feedHandler: getPrefAppForType(feedType) });
break;
case "default":
// Default system feed reader
Services.cpmm.sendAsyncMessage("FeedConverter:ExecuteClientApp",
{ spec,
title,
subtitle,
feedHandler: "default" });
break;
default:
// "web" should have been handled elsewhere
LOG("unexpected handler: " + handler);
// fall through
case "bookmarks":
Services.cpmm.sendAsyncMessage("FeedConverter:addLiveBookmark",
{ spec, title, subtitle });
break;
}
},
/**
* See nsIFeedResultService.idl
*/
addFeedResult(feedResult) {
NS_ASSERT(feedResult.uri != null, "null URI!");
NS_ASSERT(feedResult.uri != null, "null feedResult!");
let spec = feedResult.uri.spec;
if (!this._results[spec])
this._results[spec] = [];
this._results[spec].push(feedResult);
},
/**
* See nsIFeedResultService.idl
*/
getFeedResult(uri) {
NS_ASSERT(uri != null, "null URI!");
let resultList = this._results[uri.spec];
for (let result of resultList) {
if (result.uri == uri)
return result;
}
return null;
},
/**
* See nsIFeedResultService.idl
*/
removeFeedResult(uri) {
NS_ASSERT(uri != null, "null URI!");
let resultList = this._results[uri.spec];
if (!resultList)
return;
let deletions = 0;
for (let i = 0; i < resultList.length; ++i) {
if (resultList[i].uri == uri) {
delete resultList[i];
++deletions;
}
}
// send the holes to the end
resultList.sort();
// and trim the list
resultList.splice(resultList.length - deletions, deletions);
if (resultList.length == 0)
delete this._results[uri.spec];
},
createInstance(outer, iid) {
if (outer != null)
throw Cr.NS_ERROR_NO_AGGREGATION;
return this.QueryInterface(iid);
},
QueryInterface(iid) {
if (iid.equals(Ci.nsIFeedResultService) ||
iid.equals(Ci.nsIFactory) ||
iid.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
},
};
/**
* A protocol handler that attempts to deal with the variant forms of feed:
* URIs that are actually either http or https.
*/
function GenericProtocolHandler() {
}
GenericProtocolHandler.prototype = {
_init(scheme) {
let ios =
Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
this._http = ios.getProtocolHandler("http");
this._scheme = scheme;
},
get scheme() {
return this._scheme;
},
get protocolFlags() {
let {URI_DANGEROUS_TO_LOAD, ALLOWS_PROXY_HTTP, ALLOWS_PROXY} =
Ci.nsIProtocolHandler;
return URI_DANGEROUS_TO_LOAD | ALLOWS_PROXY | ALLOWS_PROXY_HTTP;
},
get defaultPort() {
return this._http.defaultPort;
},
allowPort(port, scheme) {
return this._http.allowPort(port, scheme);
},
newURI(spec, originalCharset, baseURI) {
// Feed URIs can be either nested URIs of the form feed:realURI (in which
// case we create a nested URI for the realURI) or feed://example.com, in
// which case we create a nested URI for the real protocol which is http.
let scheme = this._scheme + ":";
if (spec.substr(0, scheme.length) != scheme)
throw Cr.NS_ERROR_MALFORMED_URI;
let prefix = spec.substr(scheme.length, 2) == "//" ? "http:" : "";
let inner = Services.io.newURI(spec.replace(scheme, prefix),
originalCharset, baseURI);
if (!["http", "https"].includes(inner.scheme))
throw Cr.NS_ERROR_MALFORMED_URI;
let uri = Services.io.QueryInterface(Ci.nsINetUtil).newSimpleNestedURI(inner);
uri.spec = inner.spec.replace(prefix, scheme);
return uri;
},
newChannel2(aUri, aLoadInfo) {
let inner = aUri.QueryInterface(Ci.nsINestedURI).innerURI;
let channel = Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService).
newChannelFromURIWithLoadInfo(inner, aLoadInfo);
if (channel instanceof Components.interfaces.nsIHttpChannel)
// Set this so we know this is supposed to be a feed
channel.setRequestHeader("X-Moz-Is-Feed", "1", false);
channel.originalURI = aUri;
return channel;
},
QueryInterface(iid) {
if (iid.equals(Ci.nsIProtocolHandler) ||
iid.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
}
};
function FeedProtocolHandler() {
this._init('feed');
}
FeedProtocolHandler.prototype = new GenericProtocolHandler();
FeedProtocolHandler.prototype.classID = Components.ID("{4f91ef2e-57ba-472e-ab7a-b4999e42d6c0}");
function PodCastProtocolHandler() {
this._init('pcast');
}
PodCastProtocolHandler.prototype = new GenericProtocolHandler();
PodCastProtocolHandler.prototype.classID = Components.ID("{1c31ed79-accd-4b94-b517-06e0c81999d5}");
var components = [FeedConverter,
FeedResultService,
FeedProtocolHandler,
PodCastProtocolHandler];
this.NSGetFactory = XPCOMUtils.generateNSGetFactory(components);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 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/. */
/* global BrowserFeedWriter */
var SubscribeHandler = {
/**
* The nsIFeedWriter object that produces the UI
*/
_feedWriter: null,
init: function SH_init() {
this._feedWriter = new BrowserFeedWriter();
},
writeContent: function SH_writeContent() {
this._feedWriter.writeContent();
},
uninit: function SH_uninit() {
this._feedWriter.close();
}
};

View file

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-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/. -->
<!DOCTYPE html [
<!ENTITY % htmlDTD
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
%htmlDTD;
<!ENTITY % globalDTD
SYSTEM "chrome://global/locale/global.dtd">
%globalDTD;
<!ENTITY % feedDTD
SYSTEM "chrome://browser/locale/feeds/subscribe.dtd">
%feedDTD;
]>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<html id="feedHandler"
xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>&feedPage.title;</title>
<link rel="stylesheet"
href="chrome://browser/skin/feeds/subscribe.css"
type="text/css"
media="all"/>
<script type="application/javascript"
src="chrome://browser/content/feeds/subscribe.js"/>
</head>
<body onload="SubscribeHandler.writeContent();" onunload="SubscribeHandler.uninit();">
<div id="feedHeaderContainer">
<div id="feedHeader" dir="&locale.dir;">
<div id="feedIntroText">
<p id="feedSubscriptionInfo1" />
<p id="feedSubscriptionInfo2" />
</div>
<div id="feedSubscribeLine">
<label id="subscribeUsingDescription">
<select id="handlersMenuList">
<option id="liveBookmarksMenuItem" selected="true">&feedLiveBookmarks;</option>
<option disabled="true">&#x2501;&#x2501;&#x2501;&#x2501;&#x2501;&#x2501;&#x2501;</option>
</select>
</label>
<label id="checkboxText">
<input type="checkbox" id="alwaysUse" class="alwaysUse" checked="false"/>
</label>
<button id="subscribeButton">&feedSubscribeNow;</button>
</div>
</div>
<div id="feedHeaderContainerSpacer"/>
</div>
<script type="application/javascript">
/* import-globals-from subscribe.js */
SubscribeHandler.init();
</script>
<div id="feedBody">
<div id="feedTitle">
<a id="feedTitleLink">
<img id="feedTitleImage"/>
</a>
<div id="feedTitleContainer">
<h1 id="feedTitleText"/>
<h2 id="feedSubtitleText"/>
</div>
</div>
<div id="feedContent"/>
</div>
</body>
</html>

View file

@ -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/feeds/subscribe.xhtml (content/subscribe.xhtml)
content/browser/feeds/subscribe.js (content/subscribe.js)

View file

@ -0,0 +1,34 @@
# -*- Mode: python; 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',
'FeedWriter.js',
'WebContentConverter.js',
]
FINAL_LIBRARY = 'browsercomps'
for var in ('MOZ_APP_NAME', 'MOZ_MACBUNDLE_NAME'):
DEFINES[var] = CONFIG[var]
LOCAL_INCLUDES += [
'../build',
]

View file

@ -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 <algorithm>
#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<nsIHttpChannel> 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<nsIStreamConverterService> converterService(do_GetService(NS_STREAMCONVERTERSERVICE_CONTRACTID));
if (converterService) {
ToLowerCase(contentEncoding);
nsCOMPtr<nsIStreamListener> converter;
rv = converterService->AsyncConvertData(contentEncoding.get(),
"uncompressed", this, nullptr,
getter_AddRefs(converter));
NS_ENSURE_SUCCESS(rv, rv);
converter->OnStartRequest(request, nullptr);
nsCOMPtr<nsIStringInputStream> 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<int N>
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: <rss, <feed, <rdf:RDF must be the "document"
* element within the XML DOM, i.e. the root container element. Otherwise,
* it's possible that someone embedded one of these tags inside a document of
* another type, e.g. a HTML document, and we don't want to show the preview
* page if the document isn't actually a feed.
*
* @param start
* The beginning of the data being sniffed
* @param end
* The end of the data being sniffed, right before the substring that
* was found.
* @returns true if the found substring is the documentElement, false
* otherwise.
*/
static bool
IsDocumentElement(const char *start, const char* end)
{
// For every tag in the buffer, check to see if it's a PI, Doctype or
// comment, our desired substring or something invalid.
while ( (start = FindChar('<', start, end)) ) {
++start;
if (start >= 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: <!-- <rdf:RDF .. > -->
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<nsIHttpChannel> 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<nsIURI> 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, "<rss");
// Atom 1.0
if (!isFeed)
isFeed = ContainsTopLevelSubstring(dataString, "<feed");
// RSS 1.0
if (!isFeed) {
isFeed = ContainsTopLevelSubstring(dataString, "<rdf:RDF") &&
dataString.Find(NS_RDF) != -1 &&
dataString.Find(NS_RSS) != -1;
}
// If we sniffed a feed, coerce our internal type
if (isFeed && !HasAttachmentDisposition(channel))
sniffedType.AssignLiteral(TYPE_MAYBE_FEED);
else
sniffedType.Truncate();
return NS_OK;
}
NS_IMETHODIMP
nsFeedSniffer::OnStartRequest(nsIRequest* request, nsISupports* context)
{
return NS_OK;
}
nsresult
nsFeedSniffer::AppendSegmentToString(nsIInputStream* inputStream,
void* closure,
const char* rawSegment,
uint32_t toOffset,
uint32_t count,
uint32_t* writeCount)
{
nsCString* decodedData = static_cast<nsCString*>(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;
}

View file

@ -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 nsresult 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;
};

View file

@ -0,0 +1,70 @@
/* -*- 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(95309fd2-7b3a-47fb-97f3-5c460d9473cd)]
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
* @param feedReader
* The type of feed reader we're using (client, bookmarks, default)
* If this parameter is null, the type is set to default
*/
void addToClientReader(in AUTF8String uri,
in AString title,
in AString subtitle,
in unsigned long feedType,
[optional] in AString feedReader);
/**
* 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);
};

View file

@ -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);
};

View file

@ -0,0 +1,82 @@
"use strict";
module.exports = { // eslint-disable-line no-undef
"extends": [
"../../.eslintrc.js"
],
"globals": {
"Components": true,
"dump": true,
"Iterator": true
},
"env": { "browser": true },
"rules": {
"block-scoped-var": "error",
// "brace-style": ["warn", "1tbs", {"allowSingleLine": true}],
"comma-dangle": "off",
"comma-spacing": ["warn", {"before": false, "after": true}],
"comma-style": ["warn", "last"],
// "complexity": "warn",
"consistent-return": "error",
//"curly": "error",
"dot-notation": "error",
"eol-last": "error",
"indent": ["warn", 2, {"SwitchCase": 1}],
// "key-spacing": ["warn", {"beforeColon": false, "afterColon": true}],
"keyword-spacing": "warn",
"max-nested-callbacks": ["error", 3],
"new-parens": "error",
"no-array-constructor": "error",
"no-cond-assign": "error",
"no-control-regex": "error",
"no-debugger": "error",
"no-delete-var": "error",
"no-dupe-args": "error",
"no-dupe-keys": "error",
"no-duplicate-case": "error",
"no-else-return": "error",
"no-eval": "error",
"no-extend-native": "error",
// "no-extra-bind": "error",
"no-extra-boolean-cast": "error",
"no-extra-semi": "warn",
"no-fallthrough": ["error", { "commentPattern": ".*[Ii]ntentional(?:ly)?\\s+fall(?:ing)?[\\s-]*through.*" }],
"no-lonely-if": "error",
"no-mixed-spaces-and-tabs": "error",
"no-multi-spaces": "warn",
"no-multi-str": "warn",
"no-native-reassign": "error",
"no-nested-ternary": "error",
"no-redeclare": "error",
"no-return-assign": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-shadow": "warn",
"no-shadow-restricted-names": "error",
// "no-spaced-func": "warn",
"no-throw-literal": "error",
"no-trailing-spaces": "error",
"no-undef": "error",
"no-unneeded-ternary": "error",
"no-unreachable": "error",
"no-unused-vars": ["error", { "varsIgnorePattern": "^C[ciur]$" }],
"no-with": "error",
"padded-blocks": ["warn", "never"],
"quotes": ["error", "double", { "avoidEscape": true, "allowTemplateLiterals": true }],
"semi": ["error", "always", {"omitLastInOneLineBlock": true }],
"semi-spacing": ["warn", {"before": false, "after": true}],
"space-before-blocks": ["warn", "always"],
// "space-before-function-paren": ["warn", "never"],
"space-in-parens": ["warn", "never"],
"space-infix-ops": ["warn", {"int32Hint": true}],
// "space-unary-ops": ["warn", { "words": true, "nonwords": false }],
"strict": ["error", "global"],
"use-isnan": "error",
"valid-typeof": "error",
"yoda": "error"
}
};

View file

@ -0,0 +1,328 @@
/* 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 { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
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://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/osfile.jsm"); /* globals OS */
Cu.import("resource:///modules/MigrationUtils.jsm"); /* globals MigratorPrototype */
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Sqlite",
"resource://gre/modules/Sqlite.jsm");
const kBookmarksFileName = "360sefav.db";
function copyToTempUTF8File(file, charset) {
let inputStream = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
inputStream.init(file, -1, -1, 0);
let inputStr = NetUtil.readInputStreamToString(
inputStream, inputStream.available(), { charset });
// Use random to reduce the likelihood of a name collision in createUnique.
let rand = Math.floor(Math.random() * Math.pow(2, 15));
let leafName = "mozilla-temp-" + rand;
let tempUTF8File = FileUtils.getFile(
"TmpD", ["mozilla-temp-files", leafName], true);
tempUTF8File.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
let out = FileUtils.openAtomicFileOutputStream(tempUTF8File);
try {
let bufferedOut = Cc["@mozilla.org/network/buffered-output-stream;1"]
.createInstance(Ci.nsIBufferedOutputStream);
bufferedOut.init(out, 4096);
try {
let converterOut = Cc["@mozilla.org/intl/converter-output-stream;1"]
.createInstance(Ci.nsIConverterOutputStream);
converterOut.init(bufferedOut, "utf-8", 0, 0x0000);
try {
converterOut.writeString(inputStr || "");
bufferedOut.QueryInterface(Ci.nsISafeOutputStream).finish();
} finally {
converterOut.close();
}
} finally {
bufferedOut.close();
}
} finally {
out.close();
}
return tempUTF8File;
}
function parseINIStrings(file) {
let factory = Cc["@mozilla.org/xpcom/ini-parser-factory;1"].
getService(Ci.nsIINIParserFactory);
let parser = factory.createINIParser(file);
let obj = {};
let sections = parser.getSections();
while (sections.hasMore()) {
let section = sections.getNext();
obj[section] = {};
let keys = parser.getKeys(section);
while (keys.hasMore()) {
let key = keys.getNext();
obj[section][key] = parser.getString(section, key);
}
}
return obj;
}
function getHash(aStr) {
// return the two-digit hexadecimal code for a byte
let toHexString = charCode => ("0" + charCode.toString(16)).slice(-2);
let hasher = Cc["@mozilla.org/security/hash;1"].
createInstance(Ci.nsICryptoHash);
hasher.init(Ci.nsICryptoHash.MD5);
let stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
createInstance(Ci.nsIStringInputStream);
stringStream.data = aStr;
hasher.updateFromStream(stringStream, -1);
// convert the binary hash data to a hex string.
let binary = hasher.finish(false);
return Array.from(binary, (c, i) => toHexString(binary.charCodeAt(i))).join("").toLowerCase();
}
function Bookmarks(aProfileFolder) {
let file = aProfileFolder.clone();
file.append(kBookmarksFileName);
this._file = file;
}
Bookmarks.prototype = {
type: MigrationUtils.resourceTypes.BOOKMARKS,
get exists() {
return this._file.exists() && this._file.isReadable();
},
migrate(aCallback) {
return Task.spawn(function* () {
let idToGuid = new Map();
let folderGuid = PlacesUtils.bookmarks.toolbarGuid;
if (!MigrationUtils.isStartupMigration) {
folderGuid =
yield MigrationUtils.createImportedBookmarksFolder("360se", folderGuid);
}
idToGuid.set(0, folderGuid);
let connection = yield Sqlite.openConnection({
path: this._file.path
});
try {
let rows = yield connection.execute(
`WITH RECURSIVE
bookmark(id, parent_id, is_folder, title, url, pos) AS (
VALUES(0, -1, 1, '', '', 0)
UNION
SELECT f.id, f.parent_id, f.is_folder, f.title, f.url, f.pos
FROM tb_fav AS f
JOIN bookmark AS b ON f.parent_id = b.id
ORDER BY f.pos ASC
)
SELECT id, parent_id, is_folder, title, url FROM bookmark WHERE id`);
for (let row of rows) {
let id = parseInt(row.getResultByName("id"), 10);
let parent_id = parseInt(row.getResultByName("parent_id"), 10);
let is_folder = parseInt(row.getResultByName("is_folder"), 10);
let title = row.getResultByName("title");
let url = row.getResultByName("url");
let parentGuid = idToGuid.get(parent_id) || idToGuid.get("fallback");
if (!parentGuid) {
parentGuid = PlacesUtils.bookmarks.unfiledGuid;
if (!MigrationUtils.isStartupMigration) {
parentGuid =
yield MigrationUtils.createImportedBookmarksFolder("360se", parentGuid);
}
idToGuid.set("fallback", parentGuid);
}
try {
if (is_folder == 1) {
let newFolderGuid = (yield MigrationUtils.insertBookmarkWrapper({
parentGuid,
type: PlacesUtils.bookmarks.TYPE_FOLDER,
title
})).guid;
idToGuid.set(id, newFolderGuid);
} else {
yield MigrationUtils.insertBookmarkWrapper({
parentGuid,
url,
title
});
}
} catch (ex) {
Cu.reportError(ex);
}
}
} finally {
yield connection.close();
}
}.bind(this)).then(() => aCallback(true),
e => { Cu.reportError(e); aCallback(false) });
}
};
function Qihoo360seProfileMigrator() {
let paths = [
// for v6 and above
{
users: ["360se6", "apps", "data", "users"],
defaultUser: "default"
},
// for earlier versions
{
users: ["360se"],
defaultUser: "data"
}
];
this._usersDir = null;
this._defaultUserPath = null;
for (let path of paths) {
let usersDir = FileUtils.getDir("AppData", path.users, false);
if (usersDir.exists()) {
this._usersDir = usersDir;
this._defaultUserPath = path.defaultUser;
break;
}
}
}
Qihoo360seProfileMigrator.prototype = Object.create(MigratorPrototype);
Object.defineProperty(Qihoo360seProfileMigrator.prototype, "sourceProfiles", {
get: function() {
if ("__sourceProfiles" in this)
return this.__sourceProfiles;
if (!this._usersDir) {
this.__sourceProfiles = [];
return this.__sourceProfiles;
}
let profiles = [];
let noLoggedInUser = true;
try {
let loginIni = this._usersDir.clone();
loginIni.append("login.ini");
if (!loginIni.exists()) {
throw new Error("360 Secure Browser's 'login.ini' does not exist.");
}
if (!loginIni.isReadable()) {
throw new Error("360 Secure Browser's 'login.ini' file could not be read.");
}
let loginIniInUtf8 = copyToTempUTF8File(loginIni, "gbk");
let loginIniObj = parseINIStrings(loginIniInUtf8);
try {
loginIniInUtf8.remove(false);
} catch (ex) {}
let nowLoginEmail = loginIniObj.NowLogin && loginIniObj.NowLogin.email;
/*
* NowLogin section may:
* 1. be missing or without email, before any user logs in.
* 2. represents the current logged in user
* 3. represents the most recent logged in user
*
* In the second case, user represented by NowLogin should be the first
* profile; otherwise the default user should be selected by default.
*/
if (nowLoginEmail) {
if (loginIniObj.NowLogin.IsLogined === "1") {
noLoggedInUser = false;
}
profiles.push({
id: this._getIdFromConfig(loginIniObj.NowLogin),
name: nowLoginEmail,
});
}
for (let section in loginIniObj) {
if (!loginIniObj[section].email ||
(nowLoginEmail && loginIniObj[section].email == nowLoginEmail)) {
continue;
}
profiles.push({
id: this._getIdFromConfig(loginIniObj[section]),
name: loginIniObj[section].email,
});
}
} catch (e) {
Cu.reportError("Error detecting 360 Secure Browser profiles: " + e);
} finally {
profiles[noLoggedInUser ? "unshift" : "push"]({
id: this._defaultUserPath,
name: "Default",
});
}
this.__sourceProfiles = profiles.filter(profile => {
let resources = this.getResources(profile);
return resources && resources.length > 0;
});
return this.__sourceProfiles;
}
});
Qihoo360seProfileMigrator.prototype._getIdFromConfig = function(aConfig) {
return aConfig.UserMd5 || getHash(aConfig.email);
};
Qihoo360seProfileMigrator.prototype.getResources = function(aProfile) {
let profileFolder = this._usersDir.clone();
profileFolder.append(aProfile.id);
if (!profileFolder.exists()) {
return [];
}
let resources = [
new Bookmarks(profileFolder)
];
return resources.filter(r => r.exists);
};
Qihoo360seProfileMigrator.prototype.getLastUsedDate = function() {
let bookmarksPaths = this.sourceProfiles.map(({id}) => {
return OS.Path.join(this._usersDir.path, id, kBookmarksFileName);
});
if (!bookmarksPaths.length) {
return Promise.resolve(new Date(0));
}
let datePromises = bookmarksPaths.map(path => {
return OS.File.stat(path).catch(() => null).then(info => {
return info ? info.lastModificationDate : 0;
});
});
return Promise.all(datePromises).then(dates => {
return new Date(Math.max.apply(Math, dates));
});
};
Qihoo360seProfileMigrator.prototype.classDescription = "360 Secure Browser Profile Migrator";
Qihoo360seProfileMigrator.prototype.contractID = "@mozilla.org/profile/migrator;1?app=browser&type=360se";
Qihoo360seProfileMigrator.prototype.classID = Components.ID("{d0037b95-296a-4a4e-94b2-c3d075d20ab1}");
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([Qihoo360seProfileMigrator]);

View file

@ -0,0 +1,670 @@
/* 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 = ["AutoMigrate"];
const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
const kAutoMigrateEnabledPref = "browser.migrate.automigrate.enabled";
const kUndoUIEnabledPref = "browser.migrate.automigrate.ui.enabled";
const kAutoMigrateBrowserPref = "browser.migrate.automigrate.browser";
const kAutoMigrateImportedItemIds = "browser.migrate.automigrate.imported-items";
const kAutoMigrateLastUndoPromptDateMsPref = "browser.migrate.automigrate.lastUndoPromptDateMs";
const kAutoMigrateDaysToOfferUndoPref = "browser.migrate.automigrate.daysToOfferUndo";
const kAutoMigrateUndoSurveyPref = "browser.migrate.automigrate.undo-survey";
const kAutoMigrateUndoSurveyLocalePref = "browser.migrate.automigrate.undo-survey-locales";
const kNotificationId = "automigration-undo";
Cu.import("resource:///modules/MigrationUtils.jsm");
Cu.import("resource://gre/modules/Preferences.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown",
"resource://gre/modules/AsyncShutdown.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper",
"resource://gre/modules/LoginHelper.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabUtils",
"resource://gre/modules/NewTabUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "TelemetryStopwatch",
"resource://gre/modules/TelemetryStopwatch.jsm");
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
const kBrandBundle = "chrome://branding/locale/brand.properties";
return Services.strings.createBundle(kBrandBundle);
});
XPCOMUtils.defineLazyGetter(this, "gHardcodedStringBundle", function() {
const kBundleURI = "chrome://browser/content/migration/extra-migration-strings.properties";
return Services.strings.createBundle(kBundleURI);
});
Cu.importGlobalProperties(["URL"]);
/* globals kUndoStateFullPath */
XPCOMUtils.defineLazyGetter(this, "kUndoStateFullPath", function() {
return OS.Path.join(OS.Constants.Path.profileDir, "initialMigrationMetadata.jsonlz4");
});
const AutoMigrate = {
get resourceTypesToUse() {
let {BOOKMARKS, HISTORY, PASSWORDS} = Ci.nsIBrowserProfileMigrator;
return BOOKMARKS | HISTORY | PASSWORDS;
},
_checkIfEnabled() {
let pref = Preferences.get(kAutoMigrateEnabledPref, false);
// User-set values should take precedence:
if (Services.prefs.prefHasUserValue(kAutoMigrateEnabledPref)) {
return pref;
}
// If we're using the default value, make sure the distribution.ini
// value is taken into account even early on startup.
try {
let distributionFile = Services.dirsvc.get("XREAppDist", Ci.nsIFile);
distributionFile.append("distribution.ini");
let parser = Cc["@mozilla.org/xpcom/ini-parser-factory;1"].
getService(Ci.nsIINIParserFactory).
createINIParser(distributionFile);
return JSON.parse(parser.getString("Preferences", kAutoMigrateEnabledPref));
} catch (ex) { /* ignore exceptions (file doesn't exist, invalid value, etc.) */ }
return pref;
},
init() {
this.enabled = this._checkIfEnabled();
},
/**
* Automatically pick a migrator and resources to migrate,
* then migrate those and start up.
*
* @throws if automatically deciding on migrators/data
* failed for some reason.
*/
migrate(profileStartup, migratorKey, profileToMigrate) {
let histogram = Services.telemetry.getHistogramById(
"FX_STARTUP_MIGRATION_AUTOMATED_IMPORT_PROCESS_SUCCESS");
histogram.add(0);
let {migrator, pickedKey} = this.pickMigrator(migratorKey);
histogram.add(5);
profileToMigrate = this.pickProfile(migrator, profileToMigrate);
histogram.add(10);
let resourceTypes = migrator.getMigrateData(profileToMigrate, profileStartup);
if (!(resourceTypes & this.resourceTypesToUse)) {
throw new Error("No usable resources were found for the selected browser!");
}
histogram.add(15);
let sawErrors = false;
let migrationObserver = (subject, topic) => {
if (topic == "Migration:ItemError") {
sawErrors = true;
} else if (topic == "Migration:Ended") {
histogram.add(25);
if (sawErrors) {
histogram.add(26);
}
Services.obs.removeObserver(migrationObserver, "Migration:Ended");
Services.obs.removeObserver(migrationObserver, "Migration:ItemError");
Services.prefs.setCharPref(kAutoMigrateBrowserPref, pickedKey);
// Save the undo history and block shutdown on that save completing.
AsyncShutdown.profileBeforeChange.addBlocker(
"AutoMigrate Undo saving", this.saveUndoState(), () => {
return {state: this._saveUndoStateTrackerForShutdown};
});
}
};
MigrationUtils.initializeUndoData();
Services.obs.addObserver(migrationObserver, "Migration:Ended", false);
Services.obs.addObserver(migrationObserver, "Migration:ItemError", false);
migrator.migrate(this.resourceTypesToUse, profileStartup, profileToMigrate);
histogram.add(20);
},
/**
* Pick and return a migrator to use for automatically migrating.
*
* @param {String} migratorKey optional, a migrator key to prefer/pick.
* @returns {Object} an object with the migrator to use for migrating, as
* well as the key we eventually ended up using to obtain it.
*/
pickMigrator(migratorKey) {
if (!migratorKey) {
let defaultKey = MigrationUtils.getMigratorKeyForDefaultBrowser();
if (!defaultKey) {
throw new Error("Could not determine default browser key to migrate from");
}
migratorKey = defaultKey;
}
if (migratorKey == "firefox") {
throw new Error("Can't automatically migrate from Firefox.");
}
let migrator = MigrationUtils.getMigrator(migratorKey);
if (!migrator) {
throw new Error("Migrator specified or a default was found, but the migrator object is not available (or has no data).");
}
return {migrator, pickedKey: migratorKey};
},
/**
* Pick a source profile (from the original browser) to use.
*
* @param {Migrator} migrator the migrator object to use
* @param {String} suggestedId the id of the profile to migrate, if pre-specified, or null
* @returns the profile to migrate, or null if migrating
* from the default profile.
*/
pickProfile(migrator, suggestedId) {
let profiles = migrator.sourceProfiles;
if (profiles && !profiles.length) {
throw new Error("No profile data found to migrate.");
}
if (suggestedId) {
if (!profiles) {
throw new Error("Profile specified but only a default profile found.");
}
let suggestedProfile = profiles.find(profile => profile.id == suggestedId);
if (!suggestedProfile) {
throw new Error("Profile specified was not found.");
}
return suggestedProfile;
}
if (profiles && profiles.length > 1) {
throw new Error("Don't know how to pick a profile when more than 1 profile is present.");
}
return profiles ? profiles[0] : null;
},
_pendingUndoTasks: false,
canUndo: Task.async(function* () {
if (this._savingPromise) {
yield this._savingPromise;
}
if (this._pendingUndoTasks) {
return false;
}
let fileExists = false;
try {
fileExists = yield OS.File.exists(kUndoStateFullPath);
} catch (ex) {
Cu.reportError(ex);
}
return fileExists;
}),
undo: Task.async(function* () {
let browserId = Preferences.get(kAutoMigrateBrowserPref, "unknown");
TelemetryStopwatch.startKeyed("FX_STARTUP_MIGRATION_UNDO_TOTAL_MS", browserId);
let histogram = Services.telemetry.getHistogramById("FX_STARTUP_MIGRATION_AUTOMATED_IMPORT_UNDO");
histogram.add(0);
if (!(yield this.canUndo())) {
histogram.add(5);
throw new Error("Can't undo!");
}
this._pendingUndoTasks = true;
this._removeNotificationBars();
histogram.add(10);
let readPromise = OS.File.read(kUndoStateFullPath, {
encoding: "utf-8",
compression: "lz4",
});
let stateData = this._dejsonifyUndoState(yield readPromise);
histogram.add(12);
this._errorMap = {bookmarks: 0, visits: 0, logins: 0};
let reportErrorTelemetry = (type) => {
let histogramId = `FX_STARTUP_MIGRATION_UNDO_${type.toUpperCase()}_ERRORCOUNT`;
Services.telemetry.getKeyedHistogramById(histogramId).add(browserId, this._errorMap[type]);
};
let startTelemetryStopwatch = resourceType => {
let histogramId = `FX_STARTUP_MIGRATION_UNDO_${resourceType.toUpperCase()}_MS`;
TelemetryStopwatch.startKeyed(histogramId, browserId);
};
let stopTelemetryStopwatch = resourceType => {
let histogramId = `FX_STARTUP_MIGRATION_UNDO_${resourceType.toUpperCase()}_MS`;
TelemetryStopwatch.finishKeyed(histogramId, browserId);
};
startTelemetryStopwatch("bookmarks");
yield this._removeUnchangedBookmarks(stateData.get("bookmarks")).catch(ex => {
Cu.reportError("Uncaught exception when removing unchanged bookmarks!");
Cu.reportError(ex);
});
stopTelemetryStopwatch("bookmarks");
reportErrorTelemetry("bookmarks");
histogram.add(15);
startTelemetryStopwatch("visits");
yield this._removeSomeVisits(stateData.get("visits")).catch(ex => {
Cu.reportError("Uncaught exception when removing history visits!");
Cu.reportError(ex);
});
stopTelemetryStopwatch("visits");
reportErrorTelemetry("visits");
histogram.add(20);
startTelemetryStopwatch("logins");
yield this._removeUnchangedLogins(stateData.get("logins")).catch(ex => {
Cu.reportError("Uncaught exception when removing unchanged logins!");
Cu.reportError(ex);
});
stopTelemetryStopwatch("logins");
reportErrorTelemetry("logins");
histogram.add(25);
// This is async, but no need to wait for it.
NewTabUtils.links.populateCache(() => {
NewTabUtils.allPages.update();
}, true);
this._purgeUndoState(this.UNDO_REMOVED_REASON_UNDO_USED);
histogram.add(30);
TelemetryStopwatch.finishKeyed("FX_STARTUP_MIGRATION_UNDO_TOTAL_MS", browserId);
}),
_removeNotificationBars() {
let browserWindows = Services.wm.getEnumerator("navigator:browser");
while (browserWindows.hasMoreElements()) {
let win = browserWindows.getNext();
if (!win.closed) {
for (let browser of win.gBrowser.browsers) {
let nb = win.gBrowser.getNotificationBox(browser);
let notification = nb.getNotificationWithValue(kNotificationId);
if (notification) {
nb.removeNotification(notification);
}
}
}
}
},
_purgeUndoState(reason) {
// We don't wait for the off-main-thread removal to complete. OS.File will
// ensure it happens before shutdown.
OS.File.remove(kUndoStateFullPath, {ignoreAbsent: true}).then(() => {
this._pendingUndoTasks = false;
});
let migrationBrowser = Preferences.get(kAutoMigrateBrowserPref, "unknown");
Services.prefs.clearUserPref(kAutoMigrateBrowserPref);
let histogram =
Services.telemetry.getKeyedHistogramById("FX_STARTUP_MIGRATION_UNDO_REASON");
histogram.add(migrationBrowser, reason);
},
getBrowserUsedForMigration() {
let browserId = Services.prefs.getCharPref(kAutoMigrateBrowserPref);
if (browserId) {
return MigrationUtils.getBrowserName(browserId);
}
return null;
},
/**
* Show the user a notification bar indicating we automatically imported
* their data and offering them the possibility of removing it.
* @param target (xul:browser)
* The browser in which we should show the notification.
*/
maybeShowUndoNotification: Task.async(function* (target) {
if (!(yield this.canUndo())) {
return;
}
// The tab might have navigated since we requested the undo state:
let canUndoFromThisPage = ["about:home", "about:newtab"].includes(target.currentURI.spec);
if (!canUndoFromThisPage ||
!Preferences.get(kUndoUIEnabledPref, false)) {
return;
}
let win = target.ownerGlobal;
let notificationBox = win.gBrowser.getNotificationBox(target);
if (!notificationBox || notificationBox.getNotificationWithValue(kNotificationId)) {
return;
}
// At this stage we're committed to show the prompt - unless we shouldn't,
// in which case we remove the undo prefs (which will cause canUndo() to
// return false from now on.):
if (!this.shouldStillShowUndoPrompt()) {
this._purgeUndoState(this.UNDO_REMOVED_REASON_OFFER_EXPIRED);
this._removeNotificationBars();
return;
}
let browserName = this.getBrowserUsedForMigration();
if (!browserName) {
browserName = gHardcodedStringBundle.GetStringFromName("automigration.undo.unknownbrowser");
}
const kMessageId = "automigration.undo.message." +
Preferences.get(kAutoMigrateImportedItemIds, "all");
const kBrandShortName = gBrandBundle.GetStringFromName("brandShortName");
let message = gHardcodedStringBundle.formatStringFromName(kMessageId,
[browserName, kBrandShortName], 2);
let buttons = [
{
label: gHardcodedStringBundle.GetStringFromName("automigration.undo.keep2.label"),
accessKey: gHardcodedStringBundle.GetStringFromName("automigration.undo.keep2.accesskey"),
callback: () => {
this._purgeUndoState(this.UNDO_REMOVED_REASON_OFFER_REJECTED);
this._removeNotificationBars();
},
},
{
label: gHardcodedStringBundle.GetStringFromName("automigration.undo.dontkeep2.label"),
accessKey: gHardcodedStringBundle.GetStringFromName("automigration.undo.dontkeep2.accesskey"),
callback: () => {
this._maybeOpenUndoSurveyTab(win);
this.undo();
},
},
];
notificationBox.appendNotification(
message, kNotificationId, null, notificationBox.PRIORITY_INFO_HIGH, buttons
);
let remainingDays = Preferences.get(kAutoMigrateDaysToOfferUndoPref, 0);
Services.telemetry.getHistogramById("FX_STARTUP_MIGRATION_UNDO_OFFERED").add(4 - remainingDays);
}),
shouldStillShowUndoPrompt() {
let today = new Date();
// Round down to midnight:
today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
// We store the unix timestamp corresponding to midnight on the last day
// on which we prompted. Fetch that and compare it to today's date.
// (NB: stored as a string because int prefs are too small for unix
// timestamps.)
let previousPromptDateMsStr = Preferences.get(kAutoMigrateLastUndoPromptDateMsPref, "0");
let previousPromptDate = new Date(parseInt(previousPromptDateMsStr, 10));
if (previousPromptDate < today) {
let remainingDays = Preferences.get(kAutoMigrateDaysToOfferUndoPref, 4) - 1;
Preferences.set(kAutoMigrateDaysToOfferUndoPref, remainingDays);
Preferences.set(kAutoMigrateLastUndoPromptDateMsPref, today.valueOf().toString());
if (remainingDays <= 0) {
return false;
}
}
return true;
},
UNDO_REMOVED_REASON_UNDO_USED: 0,
UNDO_REMOVED_REASON_SYNC_SIGNIN: 1,
UNDO_REMOVED_REASON_PASSWORD_CHANGE: 2,
UNDO_REMOVED_REASON_BOOKMARK_CHANGE: 3,
UNDO_REMOVED_REASON_OFFER_EXPIRED: 4,
UNDO_REMOVED_REASON_OFFER_REJECTED: 5,
_jsonifyUndoState(state) {
if (!state) {
return "null";
}
// Deal with date serialization.
let bookmarks = state.get("bookmarks");
for (let bm of bookmarks) {
bm.lastModified = bm.lastModified.getTime();
}
let serializableState = {
bookmarks,
logins: state.get("logins"),
visits: state.get("visits"),
};
return JSON.stringify(serializableState);
},
_dejsonifyUndoState(state) {
state = JSON.parse(state);
if (!state) {
return new Map();
}
for (let bm of state.bookmarks) {
bm.lastModified = new Date(bm.lastModified);
}
return new Map([
["bookmarks", state.bookmarks],
["logins", state.logins],
["visits", state.visits],
]);
},
/**
* Store the items we've saved into a pref. We use this to be able to show
* a detailed message to the user indicating what we've imported.
* @param state (Map)
* The 'undo' state for the import, which contains info about
* how many items of each kind we've (tried to) import.
*/
_setImportedItemPrefFromState(state) {
let itemsWithData = [];
if (state) {
for (let itemType of state.keys()) {
if (state.get(itemType).length) {
itemsWithData.push(itemType);
}
}
}
if (itemsWithData.length == 3) {
itemsWithData = "all";
} else {
itemsWithData = itemsWithData.sort().join(".");
}
if (itemsWithData) {
Preferences.set(kAutoMigrateImportedItemIds, itemsWithData);
}
},
/**
* Used for the shutdown blocker's information field.
*/
_saveUndoStateTrackerForShutdown: "not running",
/**
* Store the information required for using 'undo' of the automatic
* migration in the user's profile.
*/
saveUndoState: Task.async(function* () {
let resolveSavingPromise;
this._saveUndoStateTrackerForShutdown = "processing undo history";
this._savingPromise = new Promise(resolve => { resolveSavingPromise = resolve });
let state = yield MigrationUtils.stopAndRetrieveUndoData();
if (!state || ![...state.values()].some(ary => ary.length > 0)) {
// If we didn't import anything, abort now.
resolveSavingPromise();
return Promise.resolve();
}
this._saveUndoStateTrackerForShutdown = "saving imported item list";
this._setImportedItemPrefFromState(state);
this._saveUndoStateTrackerForShutdown = "writing undo history";
this._undoSavePromise = OS.File.writeAtomic(
kUndoStateFullPath, this._jsonifyUndoState(state), {
encoding: "utf-8",
compression: "lz4",
tmpPath: kUndoStateFullPath + ".tmp",
});
this._undoSavePromise.then(
rv => {
resolveSavingPromise(rv);
delete this._savingPromise;
},
e => {
Cu.reportError("Could not write undo state for automatic migration.");
throw e;
});
return this._undoSavePromise;
}),
_removeUnchangedBookmarks: Task.async(function* (bookmarks) {
if (!bookmarks.length) {
return;
}
let guidToLMMap = new Map(bookmarks.map(b => [b.guid, b.lastModified]));
let bookmarksFromDB = [];
let bmPromises = Array.from(guidToLMMap.keys()).map(guid => {
// Ignore bookmarks where the promise doesn't resolve (ie that are missing)
// Also check that the bookmark fetch returns isn't null before adding it.
try {
return PlacesUtils.bookmarks.fetch(guid).then(bm => bm && bookmarksFromDB.push(bm), () => {});
} catch (ex) {
// Ignore immediate exceptions, too.
}
return Promise.resolve();
});
// We can't use the result of Promise.all because that would include nulls
// for bookmarks that no longer exist (which we're catching above).
yield Promise.all(bmPromises);
let unchangedBookmarks = bookmarksFromDB.filter(bm => {
return bm.lastModified.getTime() == guidToLMMap.get(bm.guid).getTime();
});
// We need to remove items without children first, followed by their
// parents, etc. In order to do this, find out how many ancestors each item
// has that also appear in our list of things to remove, and sort the items
// by those numbers. This ensures that children are always removed before
// their parents.
function determineAncestorCount(bm) {
if (bm._ancestorCount) {
return bm._ancestorCount;
}
let myCount = 0;
let parentBM = unchangedBookmarks.find(item => item.guid == bm.parentGuid);
if (parentBM) {
myCount = determineAncestorCount(parentBM) + 1;
}
bm._ancestorCount = myCount;
return myCount;
}
unchangedBookmarks.forEach(determineAncestorCount);
unchangedBookmarks.sort((a, b) => b._ancestorCount - a._ancestorCount);
for (let {guid} of unchangedBookmarks) {
// Can't just use a .catch() because Bookmarks.remove() can throw (rather
// than returning rejected promises).
try {
yield PlacesUtils.bookmarks.remove(guid, {preventRemovalOfNonEmptyFolders: true});
} catch (err) {
if (err && err.message != "Cannot remove a non-empty folder.") {
this._errorMap.bookmarks++;
Cu.reportError(err);
}
}
}
}),
_removeUnchangedLogins: Task.async(function* (logins) {
for (let login of logins) {
let foundLogins = LoginHelper.searchLoginsWithObject({guid: login.guid});
if (foundLogins.length) {
let foundLogin = foundLogins[0];
foundLogin.QueryInterface(Ci.nsILoginMetaInfo);
if (foundLogin.timePasswordChanged == login.timePasswordChanged) {
try {
Services.logins.removeLogin(foundLogin);
} catch (ex) {
Cu.reportError("Failed to remove a login for " + foundLogins.hostname);
Cu.reportError(ex);
this._errorMap.logins++;
}
}
}
}
}),
_removeSomeVisits: Task.async(function* (visits) {
for (let urlVisits of visits) {
let urlObj;
try {
urlObj = new URL(urlVisits.url);
} catch (ex) {
continue;
}
let visitData = {
url: urlObj,
beginDate: PlacesUtils.toDate(urlVisits.first),
endDate: PlacesUtils.toDate(urlVisits.last),
limit: urlVisits.visitCount,
};
try {
yield PlacesUtils.history.removeVisitsByFilter(visitData);
} catch (ex) {
this._errorMap.visits++;
try {
visitData.url = visitData.url.href;
} catch (ignoredEx) {}
Cu.reportError("Failed to remove a visit: " + JSON.stringify(visitData));
Cu.reportError(ex);
}
}
}),
/**
* Maybe open a new tab with a survey. The tab will only be opened if all of
* the following are true:
* - the 'browser.migrate.automigrate.undo-survey' pref is not empty.
* It should contain the URL of the survey to open.
* - the 'browser.migrate.automigrate.undo-survey-locales' pref, a
* comma-separated list of language codes, contains the language code
* that is currently in use for the 'global' chrome pacakge (ie the
* locale in which the user is currently using Firefox).
* The URL will be passed through nsIURLFormatter to allow including
* build ids etc. The special additional formatting variable
* "%IMPORTEDBROWSER" is also replaced with the name of the browser
* from which we imported data.
*
* @param {Window} chromeWindow A reference to the window in which to open a link.
*/
_maybeOpenUndoSurveyTab(chromeWindow) {
let canDoSurveyInLocale = false;
try {
let surveyLocales = Preferences.get(kAutoMigrateUndoSurveyLocalePref, "");
surveyLocales = surveyLocales.split(",").map(str => str.trim());
// Strip out any empty elements, so an empty pref doesn't
// lead to a an array with 1 empty string in it.
surveyLocales = new Set(surveyLocales.filter(str => !!str));
let chromeRegistry = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry);
canDoSurveyInLocale =
surveyLocales.has(chromeRegistry.getSelectedLocale("global"));
} catch (ex) {
/* ignore exceptions and just don't do the survey. */
}
let migrationBrowser = this.getBrowserUsedForMigration();
let rawURL = Preferences.get(kAutoMigrateUndoSurveyPref, "");
if (!canDoSurveyInLocale || !migrationBrowser || !rawURL) {
return;
}
let url = Services.urlFormatter.formatURL(rawURL);
url = url.replace("%IMPORTEDBROWSER%", encodeURIComponent(migrationBrowser));
chromeWindow.openUILinkIn(url, "tab");
},
QueryInterface: XPCOMUtils.generateQI(
[Ci.nsIObserver, Ci.nsINavBookmarkObserver, Ci.nsISupportsWeakReference]
),
};
AutoMigrate.init();

View file

@ -0,0 +1,33 @@
component {6F8BB968-C14F-4D6F-9733-6C6737B35DCE} ProfileMigrator.js
contract @mozilla.org/toolkit/profile-migrator;1 {6F8BB968-C14F-4D6F-9733-6C6737B35DCE}
#if defined(XP_WIN) || defined(XP_MACOSX)
component {4bf85aa5-4e21-46ca-825f-f9c51a5e8c76} ChromeProfileMigrator.js
contract @mozilla.org/profile/migrator;1?app=browser&type=canary {4bf85aa5-4e21-46ca-825f-f9c51a5e8c76}
#endif
component {4cec1de4-1671-4fc3-a53e-6c539dc77a26} ChromeProfileMigrator.js
contract @mozilla.org/profile/migrator;1?app=browser&type=chrome {4cec1de4-1671-4fc3-a53e-6c539dc77a26}
component {8cece922-9720-42de-b7db-7cef88cb07ca} ChromeProfileMigrator.js
contract @mozilla.org/profile/migrator;1?app=browser&type=chromium {8cece922-9720-42de-b7db-7cef88cb07ca}
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_EDGE_MIGRATOR
component {62e8834b-2d17-49f5-96ff-56344903a2ae} EdgeProfileMigrator.js
contract @mozilla.org/profile/migrator;1?app=browser&type=edge {62e8834b-2d17-49f5-96ff-56344903a2ae}
#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
#ifdef HAS_360SE_MIGRATOR
component {d0037b95-296a-4a4e-94b2-c3d075d20ab1} 360seProfileMigrator.js
contract @mozilla.org/profile/migrator;1?app=browser&type=360se {d0037b95-296a-4a4e-94b2-c3d075d20ab1}
#endif

View file

@ -0,0 +1,557 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 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 { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
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/AppConstants.jsm");
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://gre/modules/osfile.jsm"); /* globals OS */
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource:///modules/MigrationUtils.jsm"); /* globals MigratorPrototype */
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OSCrypto",
"resource://gre/modules/OSCrypto.jsm");
/**
* Get an nsIFile instance representing the expected location of user data
* for this copy of Chrome/Chromium/Canary on different OSes.
* @param subfoldersWin {Array} an array of subfolders to use for Windows
* @param subfoldersOSX {Array} an array of subfolders to use for OS X
* @param subfoldersUnix {Array} an array of subfolders to use for *nix systems
* @returns {nsIFile} the place we expect data to live. Might not actually exist!
*/
function getDataFolder(subfoldersWin, subfoldersOSX, subfoldersUnix) {
let dirServiceID, subfolders;
if (AppConstants.platform == "win") {
dirServiceID = "LocalAppData";
subfolders = subfoldersWin.concat(["User Data"]);
} else if (AppConstants.platform == "macosx") {
dirServiceID = "ULibDir";
subfolders = ["Application Support"].concat(subfoldersOSX);
} else {
dirServiceID = "Home";
subfolders = [".config"].concat(subfoldersUnix);
}
return FileUtils.getDir(dirServiceID, subfolders, false);
}
/**
* 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);
}
/**
* Convert Date object to Chrome time format
*
* @param aDate
* Date object or integer equivalent
* @return Chrome time
* @note For details on Chrome time, see chromeTimeToDate.
*/
function dateToChromeTime(aDate) {
return (aDate * 10000 + S100NS_FROM1601TO1970) / S100NS_PER_MS;
}
/**
* Insert bookmark items into specific folder.
*
* @param parentGuid
* GUID of the folder where items will be inserted
* @param items
* bookmark items to be inserted
* @param errorAccumulator
* function that gets called with any errors thrown so we don't drop them on the floor.
*/
function* insertBookmarkItems(parentGuid, items, errorAccumulator) {
for (let item of items) {
try {
if (item.type == "url") {
if (item.url.trim().startsWith("chrome:")) {
// Skip invalid chrome URIs. Creating an actual URI always reports
// messages to the console, so we avoid doing that.
continue;
}
yield MigrationUtils.insertBookmarkWrapper({
parentGuid, url: item.url, title: item.name
});
} else if (item.type == "folder") {
let newFolderGuid = (yield MigrationUtils.insertBookmarkWrapper({
parentGuid, type: PlacesUtils.bookmarks.TYPE_FOLDER, title: item.name
})).guid;
yield insertBookmarkItems(newFolderGuid, item.children, errorAccumulator);
}
} catch (e) {
Cu.reportError(e);
errorAccumulator(e);
}
}
}
function ChromeProfileMigrator() {
let chromeUserDataFolder =
getDataFolder(["Google", "Chrome"], ["Google", "Chrome"], ["google-chrome"]);
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),
];
if (AppConstants.platform == "win") {
possibleResources.push(GetWindowsPasswordsResource(profileFolder));
}
return possibleResources.filter(r => r != null);
}
}
return [];
};
ChromeProfileMigrator.prototype.getLastUsedDate =
function Chrome_getLastUsedDate() {
let datePromises = this.sourceProfiles.map(profile => {
let basePath = OS.Path.join(this._chromeUserDataFolder.path, profile.id);
let fileDatePromises = ["Bookmarks", "History", "Cookies"].map(leafName => {
let path = OS.Path.join(basePath, leafName);
return OS.File.stat(path).catch(() => null).then(info => {
return info ? info.lastModificationDate : 0;
});
});
return Promise.all(fileDatePromises).then(dates => {
return Math.max.apply(Math, dates);
});
});
return Promise.all(datePromises).then(dates => {
dates.push(0);
return new Date(Math.max.apply(Math, dates));
});
};
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
this.__sourceProfiles = profiles.filter(function(profile) {
let resources = this.getResources(profile);
return resources && resources.length > 0;
}, this);
return this.__sourceProfiles;
}
});
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(prefsFile, -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 "";
}
});
Object.defineProperty(ChromeProfileMigrator.prototype, "sourceLocked", {
get: function Chrome_sourceLocked() {
// There is an exclusive lock on some SQLite databases. Assume they are locked for now.
return true;
},
});
function GetBookmarksResource(aProfileFolder) {
let bookmarksFile = aProfileFolder.clone();
bookmarksFile.append("Bookmarks");
if (!bookmarksFile.exists())
return null;
return {
type: MigrationUtils.resourceTypes.BOOKMARKS,
migrate: function(aCallback) {
return Task.spawn(function* () {
let gotErrors = false;
let errorGatherer = function() { gotErrors = true };
let jsonStream = yield new Promise((resolve, reject) => {
let options = {
uri: NetUtil.newURI(bookmarksFile),
loadUsingSystemPrincipal: true
};
NetUtil.asyncFetch(options, (inputStream, resultCode) => {
if (Components.isSuccessCode(resultCode)) {
resolve(inputStream);
} else {
reject(new Error("Could not read Bookmarks file"));
}
});
});
// Parse Chrome bookmark file that is JSON format
let bookmarkJSON = NetUtil.readInputStreamToString(
jsonStream, jsonStream.available(), { charset : "UTF-8" });
let roots = JSON.parse(bookmarkJSON).roots;
// Importing bookmark bar items
if (roots.bookmark_bar.children &&
roots.bookmark_bar.children.length > 0) {
// Toolbar
let parentGuid = PlacesUtils.bookmarks.toolbarGuid;
if (!MigrationUtils.isStartupMigration) {
parentGuid =
yield MigrationUtils.createImportedBookmarksFolder("Chrome", parentGuid);
}
yield insertBookmarkItems(parentGuid, roots.bookmark_bar.children, errorGatherer);
}
// Importing bookmark menu items
if (roots.other.children &&
roots.other.children.length > 0) {
// Bookmark menu
let parentGuid = PlacesUtils.bookmarks.menuGuid;
if (!MigrationUtils.isStartupMigration) {
parentGuid =
yield MigrationUtils.createImportedBookmarksFolder("Chrome", parentGuid);
}
yield insertBookmarkItems(parentGuid, roots.other.children, errorGatherer);
}
if (gotErrors) {
throw new Error("The migration included errors.");
}
}.bind(this)).then(() => aCallback(true),
() => aCallback(false));
}
};
}
function GetHistoryResource(aProfileFolder) {
let historyFile = aProfileFolder.clone();
historyFile.append("History");
if (!historyFile.exists())
return null;
return {
type: MigrationUtils.resourceTypes.HISTORY,
migrate(aCallback) {
Task.spawn(function* () {
const MAX_AGE_IN_DAYS = Services.prefs.getIntPref("browser.migrate.chrome.history.maxAgeInDays");
const LIMIT = Services.prefs.getIntPref("browser.migrate.chrome.history.limit");
let query = "SELECT url, title, last_visit_time, typed_count FROM urls WHERE hidden = 0";
if (MAX_AGE_IN_DAYS) {
let maxAge = dateToChromeTime(Date.now() - MAX_AGE_IN_DAYS * 24 * 60 * 60 * 1000);
query += " AND last_visit_time > " + maxAge;
}
if (LIMIT) {
query += " ORDER BY last_visit_time DESC LIMIT " + LIMIT;
}
let rows =
yield MigrationUtils.getRowsFromDBWithoutLocks(historyFile.path, "Chrome history", query);
let places = [];
for (let row of rows) {
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);
}
}
if (places.length > 0) {
yield new Promise((resolve, reject) => {
MigrationUtils.insertVisitsWrapper(places, {
_success: false,
handleResult: function() {
// Importing any entry is considered a successful import.
this._success = true;
},
handleError: function() {},
handleCompletion: function() {
if (this._success) {
resolve();
} else {
reject(new Error("Couldn't add visits"));
}
}
});
});
}
}).then(() => { aCallback(true) },
ex => {
Cu.reportError(ex);
aCallback(false);
});
}
};
}
function GetCookiesResource(aProfileFolder) {
let cookiesFile = aProfileFolder.clone();
cookiesFile.append("Cookies");
if (!cookiesFile.exists())
return null;
return {
type: MigrationUtils.resourceTypes.COOKIES,
migrate: Task.async(function* (aCallback) {
// We don't support decrypting cookies yet so only import plaintext ones.
let rows = yield MigrationUtils.getRowsFromDBWithoutLocks(cookiesFile.path, "Chrome cookies",
`SELECT host_key, name, value, path, expires_utc, secure, httponly, encrypted_value
FROM cookies
WHERE length(encrypted_value) = 0`).catch(ex => {
Cu.reportError(ex);
aCallback(false);
});
// If the promise was rejected we will have already called aCallback,
// so we can just return here.
if (!rows) {
return;
}
for (let row of rows) {
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);
}
}
aCallback(true);
}),
};
}
function GetWindowsPasswordsResource(aProfileFolder) {
let loginFile = aProfileFolder.clone();
loginFile.append("Login Data");
if (!loginFile.exists())
return null;
return {
type: MigrationUtils.resourceTypes.PASSWORDS,
migrate: Task.async(function* (aCallback) {
let rows = yield MigrationUtils.getRowsFromDBWithoutLocks(loginFile.path, "Chrome passwords",
`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`).catch(ex => {
Cu.reportError(ex);
aCallback(false);
});
// If the promise was rejected we will have already called aCallback,
// so we can just return here.
if (!rows) {
return;
}
let crypto = new OSCrypto();
for (let row of rows) {
try {
let origin_url = NetUtil.newURI(row.getResultByName("origin_url"));
// Ignore entries for non-http(s)/ftp URLs because we likely can't
// use them anyway.
const kValidSchemes = new Set(["https", "http", "ftp"]);
if (!kValidSchemes.has(origin_url.scheme)) {
continue;
}
let loginInfo = {
username: row.getResultByName("username_value"),
password: crypto.
decryptData(crypto.arrayToString(row.getResultByName("password_value")),
null),
hostname: origin_url.prePath,
formSubmitURL: 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:
let action_url = NetUtil.newURI(row.getResultByName("action_url"));
if (!kValidSchemes.has(action_url.scheme)) {
continue; // This continues the outer for loop.
}
loginInfo.formSubmitURL = 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"));
}
MigrationUtils.insertLoginWrapper(loginInfo);
} catch (e) {
Cu.reportError(e);
}
}
crypto.finalize();
aCallback(true);
}),
};
}
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}");
/**
* Chromium migration
**/
function ChromiumProfileMigrator() {
let chromiumUserDataFolder = getDataFolder(["Chromium"], ["Chromium"], ["chromium"]);
this._chromeUserDataFolder = chromiumUserDataFolder.exists() ? chromiumUserDataFolder : null;
}
ChromiumProfileMigrator.prototype = Object.create(ChromeProfileMigrator.prototype);
ChromiumProfileMigrator.prototype.classDescription = "Chromium Profile Migrator";
ChromiumProfileMigrator.prototype.contractID = "@mozilla.org/profile/migrator;1?app=browser&type=chromium";
ChromiumProfileMigrator.prototype.classID = Components.ID("{8cece922-9720-42de-b7db-7cef88cb07ca}");
var componentsArray = [ChromeProfileMigrator, ChromiumProfileMigrator];
/**
* Chrome Canary
* Not available on Linux
**/
function CanaryProfileMigrator() {
let chromeUserDataFolder = getDataFolder(["Google", "Chrome SxS"], ["Google", "Chrome Canary"]);
this._chromeUserDataFolder = chromeUserDataFolder.exists() ? chromeUserDataFolder : null;
}
CanaryProfileMigrator.prototype = Object.create(ChromeProfileMigrator.prototype);
CanaryProfileMigrator.prototype.classDescription = "Chrome Canary Profile Migrator";
CanaryProfileMigrator.prototype.contractID = "@mozilla.org/profile/migrator;1?app=browser&type=canary";
CanaryProfileMigrator.prototype.classID = Components.ID("{4bf85aa5-4e21-46ca-825f-f9c51a5e8c76}");
if (AppConstants.platform == "win" || AppConstants.platform == "macosx") {
componentsArray.push(CanaryProfileMigrator);
}
this.NSGetFactory = XPCOMUtils.generateNSGetFactory(componentsArray);

View file

@ -0,0 +1,590 @@
/* 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 = ["ESEDBReader"]; /* exported ESEDBReader */
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/ctypes.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyGetter(this, "log", () => {
let ConsoleAPI = Cu.import("resource://gre/modules/Console.jsm", {}).ConsoleAPI;
let consoleOptions = {
maxLogLevelPref: "browser.esedbreader.loglevel",
prefix: "ESEDBReader",
};
return new ConsoleAPI(consoleOptions);
});
// We have a globally unique identifier for ESE instances. A new one
// is used for each different database opened.
let gESEInstanceCounter = 0;
// We limit the length of strings that we read from databases.
const MAX_STR_LENGTH = 64 * 1024;
// Kernel-related types:
const KERNEL = {};
KERNEL.FILETIME = new ctypes.StructType("FILETIME", [
{dwLowDateTime: ctypes.uint32_t},
{dwHighDateTime: ctypes.uint32_t}
]);
KERNEL.SYSTEMTIME = new ctypes.StructType("SYSTEMTIME", [
{wYear: ctypes.uint16_t},
{wMonth: ctypes.uint16_t},
{wDayOfWeek: ctypes.uint16_t},
{wDay: ctypes.uint16_t},
{wHour: ctypes.uint16_t},
{wMinute: ctypes.uint16_t},
{wSecond: ctypes.uint16_t},
{wMilliseconds: ctypes.uint16_t}
]);
// DB column types, cribbed from the ESE header
var COLUMN_TYPES = {
JET_coltypBit: 1, /* True, False, or NULL */
JET_coltypUnsignedByte: 2, /* 1-byte integer, unsigned */
JET_coltypShort: 3, /* 2-byte integer, signed */
JET_coltypLong: 4, /* 4-byte integer, signed */
JET_coltypCurrency: 5, /* 8 byte integer, signed */
JET_coltypIEEESingle: 6, /* 4-byte IEEE single precision */
JET_coltypIEEEDouble: 7, /* 8-byte IEEE double precision */
JET_coltypDateTime: 8, /* Integral date, fractional time */
JET_coltypBinary: 9, /* Binary data, < 255 bytes */
JET_coltypText: 10, /* ANSI text, case insensitive, < 255 bytes */
JET_coltypLongBinary: 11, /* Binary data, long value */
JET_coltypLongText: 12, /* ANSI text, long value */
JET_coltypUnsignedLong: 14, /* 4-byte unsigned integer */
JET_coltypLongLong: 15, /* 8-byte signed integer */
JET_coltypGUID: 16, /* 16-byte globally unique identifier */
};
// Not very efficient, but only used for error messages
function getColTypeName(numericValue) {
return Object.keys(COLUMN_TYPES).find(t => COLUMN_TYPES[t] == numericValue) || "unknown";
}
// All type constants and method wrappers go on this object:
const ESE = {};
ESE.JET_ERR = ctypes.long;
ESE.JET_PCWSTR = ctypes.char16_t.ptr;
// The ESE header calls this JET_API_PTR, but because it isn't ever used as a
// pointer and because OS.File code implies that the name you give a type
// matters, I opted for a different name.
// Note that this is defined differently on 32 vs. 64-bit in the header.
ESE.JET_API_ITEM = ctypes.voidptr_t.size == 4 ? ctypes.unsigned_long : ctypes.uint64_t;
ESE.JET_INSTANCE = ESE.JET_API_ITEM;
ESE.JET_SESID = ESE.JET_API_ITEM;
ESE.JET_TABLEID = ESE.JET_API_ITEM;
ESE.JET_COLUMNID = ctypes.unsigned_long;
ESE.JET_GRBIT = ctypes.unsigned_long;
ESE.JET_COLTYP = ctypes.unsigned_long;
ESE.JET_DBID = ctypes.unsigned_long;
ESE.JET_COLUMNDEF = new ctypes.StructType("JET_COLUMNDEF", [
{"cbStruct": ctypes.unsigned_long},
{"columnid": ESE.JET_COLUMNID },
{"coltyp": ESE.JET_COLTYP },
{"wCountry": ctypes.unsigned_short }, // sepcifies the country/region for the column definition
{"langid": ctypes.unsigned_short },
{"cp": ctypes.unsigned_short },
{"wCollate": ctypes.unsigned_short }, /* Must be 0 */
{"cbMax": ctypes.unsigned_long },
{"grbit": ESE.JET_GRBIT }
]);
// Track open databases
let gOpenDBs = new Map();
// Track open libraries
let gLibs = {};
this.ESE = ESE; // Required for tests.
this.KERNEL = KERNEL; // ditto
this.gLibs = gLibs; // ditto
function convertESEError(errorCode) {
switch (errorCode) {
case -1213 /* JET_errPageSizeMismatch */:
case -1002 /* JET_errInvalidName*/:
case -1507 /* JET_errColumnNotFound */:
// The DB format has changed and we haven't updated this migration code:
return "The database format has changed, error code: " + errorCode;
case -1207 /* JET_errDatabaseLocked */:
case -1302 /* JET_errTableLocked */:
return "The database or table is locked, error code: " + errorCode;
case -1809 /* JET_errPermissionDenied*/:
case -1907 /* JET_errAccessDenied */:
return "Access or permission denied, error code: " + errorCode;
case -1044 /* JET_errInvalidFilename */:
return "Invalid file name";
case -1811 /* JET_errFileNotFound */:
return "File not found";
case -550 /* JET_errDatabaseDirtyShutdown */:
return "Database in dirty shutdown state (without the requisite logs?)";
case -514 /* JET_errBadLogVersion */:
return "Database log version does not match the version of ESE in use.";
default:
return "Unknown error: " + errorCode;
}
}
function handleESEError(method, methodName, shouldThrow = true, errorLog = true) {
return function () {
let rv;
try {
rv = method.apply(null, arguments);
} catch (ex) {
log.error("Error calling into ctypes method", methodName, ex);
throw ex;
}
let resultCode = parseInt(rv.toString(10), 10);
if (resultCode < 0) {
if (errorLog) {
log.error("Got error " + resultCode + " calling " + methodName);
}
if (shouldThrow) {
throw new Error(convertESEError(rv));
}
} else if (resultCode > 0 && errorLog) {
log.warn("Got warning " + resultCode + " calling " + methodName);
}
return resultCode;
};
}
function declareESEFunction(methodName, ...args) {
let declaration = ["Jet" + methodName, ctypes.winapi_abi, ESE.JET_ERR].concat(args);
let ctypeMethod = gLibs.ese.declare.apply(gLibs.ese, declaration);
ESE[methodName] = handleESEError(ctypeMethod, methodName);
ESE["FailSafe" + methodName] = handleESEError(ctypeMethod, methodName, false);
ESE["Manual" + methodName] = handleESEError(ctypeMethod, methodName, false, false);
}
function declareESEFunctions() {
declareESEFunction("GetDatabaseFileInfoW", ESE.JET_PCWSTR, ctypes.voidptr_t,
ctypes.unsigned_long, ctypes.unsigned_long);
declareESEFunction("GetSystemParameterW", ESE.JET_INSTANCE, ESE.JET_SESID,
ctypes.unsigned_long, ESE.JET_API_ITEM.ptr,
ESE.JET_PCWSTR, ctypes.unsigned_long);
declareESEFunction("SetSystemParameterW", ESE.JET_INSTANCE.ptr,
ESE.JET_SESID, ctypes.unsigned_long, ESE.JET_API_ITEM,
ESE.JET_PCWSTR);
declareESEFunction("CreateInstanceW", ESE.JET_INSTANCE.ptr, ESE.JET_PCWSTR);
declareESEFunction("Init", ESE.JET_INSTANCE.ptr);
declareESEFunction("BeginSessionW", ESE.JET_INSTANCE, ESE.JET_SESID.ptr,
ESE.JET_PCWSTR, ESE.JET_PCWSTR);
declareESEFunction("AttachDatabaseW", ESE.JET_SESID, ESE.JET_PCWSTR,
ESE.JET_GRBIT);
declareESEFunction("DetachDatabaseW", ESE.JET_SESID, ESE.JET_PCWSTR);
declareESEFunction("OpenDatabaseW", ESE.JET_SESID, ESE.JET_PCWSTR,
ESE.JET_PCWSTR, ESE.JET_DBID.ptr, ESE.JET_GRBIT);
declareESEFunction("OpenTableW", ESE.JET_SESID, ESE.JET_DBID, ESE.JET_PCWSTR,
ctypes.voidptr_t, ctypes.unsigned_long, ESE.JET_GRBIT,
ESE.JET_TABLEID.ptr);
declareESEFunction("GetColumnInfoW", ESE.JET_SESID, ESE.JET_DBID,
ESE.JET_PCWSTR, ESE.JET_PCWSTR, ctypes.voidptr_t,
ctypes.unsigned_long, ctypes.unsigned_long);
declareESEFunction("Move", ESE.JET_SESID, ESE.JET_TABLEID, ctypes.long,
ESE.JET_GRBIT);
declareESEFunction("RetrieveColumn", ESE.JET_SESID, ESE.JET_TABLEID,
ESE.JET_COLUMNID, ctypes.voidptr_t, ctypes.unsigned_long,
ctypes.unsigned_long.ptr, ESE.JET_GRBIT, ctypes.voidptr_t);
declareESEFunction("CloseTable", ESE.JET_SESID, ESE.JET_TABLEID);
declareESEFunction("CloseDatabase", ESE.JET_SESID, ESE.JET_DBID,
ESE.JET_GRBIT);
declareESEFunction("EndSession", ESE.JET_SESID, ESE.JET_GRBIT);
declareESEFunction("Term", ESE.JET_INSTANCE);
}
function unloadLibraries() {
log.debug("Unloading");
if (gOpenDBs.size) {
log.error("Shouldn't unload libraries before DBs are closed!");
for (let db of gOpenDBs.values()) {
db._close();
}
}
for (let k of Object.keys(ESE)) {
delete ESE[k];
}
gLibs.ese.close();
gLibs.kernel.close();
delete gLibs.ese;
delete gLibs.kernel;
}
function loadLibraries() {
Services.obs.addObserver(unloadLibraries, "xpcom-shutdown", false);
gLibs.ese = ctypes.open("esent.dll");
gLibs.kernel = ctypes.open("kernel32.dll");
KERNEL.FileTimeToSystemTime = gLibs.kernel.declare("FileTimeToSystemTime",
ctypes.default_abi, ctypes.int, KERNEL.FILETIME.ptr, KERNEL.SYSTEMTIME.ptr);
declareESEFunctions();
}
function ESEDB(rootPath, dbPath, logPath) {
log.info("Created db");
this.rootPath = rootPath;
this.dbPath = dbPath;
this.logPath = logPath;
this._references = 0;
this._init();
}
ESEDB.prototype = {
rootPath: null,
dbPath: null,
logPath: null,
_opened: false,
_attached: false,
_sessionCreated: false,
_instanceCreated: false,
_dbId: null,
_sessionId: null,
_instanceId: null,
_init() {
if (!gLibs.ese) {
loadLibraries();
}
this.incrementReferenceCounter();
this._internalOpen();
},
_internalOpen() {
try {
let dbinfo = new ctypes.unsigned_long();
ESE.GetDatabaseFileInfoW(this.dbPath, dbinfo.address(),
ctypes.unsigned_long.size, 17);
let pageSize = ctypes.UInt64.lo(dbinfo.value);
ESE.SetSystemParameterW(null, 0, 64 /* JET_paramDatabasePageSize*/,
pageSize, null);
this._instanceId = new ESE.JET_INSTANCE();
ESE.CreateInstanceW(this._instanceId.address(),
"firefox-dbreader-" + (gESEInstanceCounter++));
this._instanceCreated = true;
ESE.SetSystemParameterW(this._instanceId.address(), 0,
0 /* JET_paramSystemPath*/, 0, this.rootPath);
ESE.SetSystemParameterW(this._instanceId.address(), 0,
1 /* JET_paramTempPath */, 0, this.rootPath);
ESE.SetSystemParameterW(this._instanceId.address(), 0,
2 /* JET_paramLogFilePath*/, 0, this.logPath);
// Shouldn't try to call JetTerm if the following call fails.
this._instanceCreated = false;
ESE.Init(this._instanceId.address());
this._instanceCreated = true;
this._sessionId = new ESE.JET_SESID();
ESE.BeginSessionW(this._instanceId, this._sessionId.address(), null,
null);
this._sessionCreated = true;
const JET_bitDbReadOnly = 1;
ESE.AttachDatabaseW(this._sessionId, this.dbPath, JET_bitDbReadOnly);
this._attached = true;
this._dbId = new ESE.JET_DBID();
ESE.OpenDatabaseW(this._sessionId, this.dbPath, null,
this._dbId.address(), JET_bitDbReadOnly);
this._opened = true;
} catch (ex) {
try {
this._close();
} catch (innerException) {
Cu.reportError(innerException);
}
// Make sure caller knows we failed.
throw ex;
}
gOpenDBs.set(this.dbPath, this);
},
checkForColumn(tableName, columnName) {
if (!this._opened) {
throw new Error("The database was closed!");
}
let columnInfo;
try {
columnInfo = this._getColumnInfo(tableName, [{name: columnName}]);
} catch (ex) {
return null;
}
return columnInfo[0];
},
tableExists(tableName) {
if (!this._opened) {
throw new Error("The database was closed!");
}
let tableId = new ESE.JET_TABLEID();
let rv = ESE.ManualOpenTableW(this._sessionId, this._dbId, tableName, null,
0, 4 /* JET_bitTableReadOnly */,
tableId.address());
if (rv == -1305 /* JET_errObjectNotFound */) {
return false;
}
if (rv < 0) {
log.error("Got error " + rv + " calling OpenTableW");
throw new Error(convertESEError(rv));
}
if (rv > 0) {
log.error("Got warning " + rv + " calling OpenTableW");
}
ESE.FailSafeCloseTable(this._sessionId, tableId);
return true;
},
tableItems: function*(tableName, columns) {
if (!this._opened) {
throw new Error("The database was closed!");
}
let tableOpened = false;
let tableId;
try {
tableId = this._openTable(tableName);
tableOpened = true;
let columnInfo = this._getColumnInfo(tableName, columns);
let rv = ESE.ManualMove(this._sessionId, tableId,
-2147483648 /* JET_MoveFirst */, 0);
if (rv == -1603 /* JET_errNoCurrentRecord */) {
// There are no rows in the table.
this._closeTable(tableId);
return;
}
if (rv != 0) {
throw new Error(convertESEError(rv));
}
do {
let rowContents = {};
for (let column of columnInfo) {
let [buffer, bufferSize] = this._getBufferForColumn(column);
// We handle errors manually so we accurately deal with NULL values.
let err = ESE.ManualRetrieveColumn(this._sessionId, tableId,
column.id, buffer.address(),
bufferSize, null, 0, null);
rowContents[column.name] = this._convertResult(column, buffer, err);
}
yield rowContents;
} while (ESE.ManualMove(this._sessionId, tableId, 1 /* JET_MoveNext */, 0) === 0);
} catch (ex) {
if (tableOpened) {
this._closeTable(tableId);
}
throw ex;
}
this._closeTable(tableId);
},
_openTable(tableName) {
let tableId = new ESE.JET_TABLEID();
ESE.OpenTableW(this._sessionId, this._dbId, tableName, null,
0, 4 /* JET_bitTableReadOnly */, tableId.address());
return tableId;
},
_getBufferForColumn(column) {
let buffer;
if (column.type == "string") {
let wchar_tArray = ctypes.ArrayType(ctypes.char16_t);
// size on the column is in bytes, 2 bytes to a wchar, so:
let charCount = column.dbSize >> 1;
buffer = new wchar_tArray(charCount);
} else if (column.type == "boolean") {
buffer = new ctypes.uint8_t();
} else if (column.type == "date") {
buffer = new KERNEL.FILETIME();
} else if (column.type == "guid") {
let byteArray = ctypes.ArrayType(ctypes.uint8_t);
buffer = new byteArray(column.dbSize);
} else {
throw new Error("Unknown type " + column.type);
}
return [buffer, buffer.constructor.size];
},
_convertResult(column, buffer, err) {
if (err != 0) {
if (err == 1004) {
// Deal with null values:
buffer = null;
} else {
Cu.reportError("Unexpected JET error: " + err + ";" + " retrieving value for column " + column.name);
throw new Error(convertESEError(err));
}
}
if (column.type == "string") {
return buffer ? buffer.readString() : "";
}
if (column.type == "boolean") {
return buffer ? (buffer.value == 255) : false;
}
if (column.type == "guid") {
if (buffer.length != 16) {
Cu.reportError("Buffer size for guid field " + column.id + " should have been 16!");
return "";
}
let rv = "{";
for (let i = 0; i < 16; i++) {
if (i == 4 || i == 6 || i == 8 || i == 10) {
rv += "-";
}
let byteValue = buffer.addressOfElement(i).contents;
// Ensure there's a leading 0
rv += ("0" + byteValue.toString(16)).substr(-2);
}
return rv + "}";
}
if (column.type == "date") {
if (!buffer) {
return null;
}
let systemTime = new KERNEL.SYSTEMTIME();
let result = KERNEL.FileTimeToSystemTime(buffer.address(), systemTime.address());
if (result == 0) {
throw new Error(ctypes.winLastError);
}
// System time is in UTC, so we use Date.UTC to get milliseconds from epoch,
// then divide by 1000 to get seconds, and round down:
return new Date(Date.UTC(systemTime.wYear,
systemTime.wMonth - 1,
systemTime.wDay,
systemTime.wHour,
systemTime.wMinute,
systemTime.wSecond,
systemTime.wMilliseconds));
}
return undefined;
},
_getColumnInfo(tableName, columns) {
let rv = [];
for (let column of columns) {
let columnInfoFromDB = new ESE.JET_COLUMNDEF();
ESE.GetColumnInfoW(this._sessionId, this._dbId, tableName, column.name,
columnInfoFromDB.address(), ESE.JET_COLUMNDEF.size, 0 /* JET_ColInfo */);
let dbType = parseInt(columnInfoFromDB.coltyp.toString(10), 10);
let dbSize = parseInt(columnInfoFromDB.cbMax.toString(10), 10);
if (column.type == "string") {
if (dbType != COLUMN_TYPES.JET_coltypLongText &&
dbType != COLUMN_TYPES.JET_coltypText) {
throw new Error("Invalid column type for column " + column.name +
"; expected text type, got type " + getColTypeName(dbType));
}
if (dbSize > MAX_STR_LENGTH) {
throw new Error("Column " + column.name + " has more than 64k data in it. This API is not designed to handle data that large.");
}
} else if (column.type == "boolean") {
if (dbType != COLUMN_TYPES.JET_coltypBit) {
throw new Error("Invalid column type for column " + column.name +
"; expected bit type, got type " + getColTypeName(dbType));
}
} else if (column.type == "date") {
if (dbType != COLUMN_TYPES.JET_coltypLongLong) {
throw new Error("Invalid column type for column " + column.name +
"; expected long long type, got type " + getColTypeName(dbType));
}
} else if (column.type == "guid") {
if (dbType != COLUMN_TYPES.JET_coltypGUID) {
throw new Error("Invalid column type for column " + column.name +
"; expected guid type, got type " + getColTypeName(dbType));
}
} else if (column.type) {
throw new Error("Unknown column type " + column.type + " requested for column " +
column.name + ", don't know what to do.");
}
rv.push({name: column.name, id: columnInfoFromDB.columnid, type: column.type, dbSize, dbType});
}
return rv;
},
_closeTable(tableId) {
ESE.FailSafeCloseTable(this._sessionId, tableId);
},
_close() {
this._internalClose();
gOpenDBs.delete(this.dbPath);
},
_internalClose() {
if (this._opened) {
log.debug("close db");
ESE.FailSafeCloseDatabase(this._sessionId, this._dbId, 0);
log.debug("finished close db");
this._opened = false;
}
if (this._attached) {
log.debug("detach db");
ESE.FailSafeDetachDatabaseW(this._sessionId, this.dbPath);
this._attached = false;
}
if (this._sessionCreated) {
log.debug("end session");
ESE.FailSafeEndSession(this._sessionId, 0);
this._sessionCreated = false;
}
if (this._instanceCreated) {
log.debug("term");
ESE.FailSafeTerm(this._instanceId);
this._instanceCreated = false;
}
},
incrementReferenceCounter() {
this._references++;
},
decrementReferenceCounter() {
this._references--;
if (this._references <= 0) {
this._close();
}
},
};
let ESEDBReader = {
openDB(rootDir, dbFile, logDir) {
let dbFilePath = dbFile.path;
if (gOpenDBs.has(dbFilePath)) {
let db = gOpenDBs.get(dbFilePath);
db.incrementReferenceCounter();
return db;
}
// ESE is really picky about the trailing slashes according to the docs,
// so we do as we're told and ensure those are there:
return new ESEDB(rootDir.path + "\\", dbFilePath, logDir.path + "\\");
},
closeDB(db) {
db.decrementReferenceCounter();
},
COLUMN_TYPES,
};

View file

@ -0,0 +1,450 @@
/* 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 { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/AppConstants.jsm");
Cu.import("resource://gre/modules/osfile.jsm"); /* globals OS */
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource:///modules/MigrationUtils.jsm"); /* globals MigratorPrototype */
Cu.import("resource:///modules/MSMigrationUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ESEDBReader",
"resource:///modules/ESEDBReader.jsm");
const kEdgeRegistryRoot = "SOFTWARE\\Classes\\Local Settings\\Software\\" +
"Microsoft\\Windows\\CurrentVersion\\AppContainer\\Storage\\" +
"microsoft.microsoftedge_8wekyb3d8bbwe\\MicrosoftEdge";
const kEdgeDatabasePath = "AC\\MicrosoftEdge\\User\\Default\\DataStore\\Data\\";
XPCOMUtils.defineLazyGetter(this, "gEdgeDatabase", function() {
let edgeDir = MSMigrationUtils.getEdgeLocalDataFolder();
if (!edgeDir) {
return null;
}
edgeDir.appendRelativePath(kEdgeDatabasePath);
if (!edgeDir.exists() || !edgeDir.isReadable() || !edgeDir.isDirectory()) {
return null;
}
let expectedLocation = edgeDir.clone();
expectedLocation.appendRelativePath("nouser1\\120712-0049\\DBStore\\spartan.edb");
if (expectedLocation.exists() && expectedLocation.isReadable() && expectedLocation.isFile()) {
return expectedLocation;
}
// We used to recurse into arbitrary subdirectories here, but that code
// went unused, so it likely isn't necessary, even if we don't understand
// where the magic folders above come from, they seem to be the same for
// everyone. Just return null if they're not there:
return null;
});
/**
* Get rows from a table in the Edge DB as an array of JS objects.
*
* @param {String} tableName the name of the table to read.
* @param {String[]|function} columns a list of column specifiers
* (see ESEDBReader.jsm) or a function that
* generates them based on the database
* reference once opened.
* @param {function} filterFn a function that is called for each row.
* Only rows for which it returns a truthy
* value are included in the result.
* @param {nsIFile} dbFile the database file to use. Defaults to
* the main Edge database.
* @returns {Array} An array of row objects.
*/
function readTableFromEdgeDB(tableName, columns, filterFn, dbFile = gEdgeDatabase) {
let database;
let rows = [];
try {
let logFile = dbFile.parent;
logFile.append("LogFiles");
database = ESEDBReader.openDB(dbFile.parent, dbFile, logFile);
if (typeof columns == "function") {
columns = columns(database);
}
let tableReader = database.tableItems(tableName, columns);
for (let row of tableReader) {
if (filterFn(row)) {
rows.push(row);
}
}
} catch (ex) {
Cu.reportError("Failed to extract items from table " + tableName + " in Edge database at " +
dbFile.path + " due to the following error: " + ex);
// Deliberately make this fail so we expose failure in the UI:
throw ex;
} finally {
if (database) {
ESEDBReader.closeDB(database);
}
}
return rows;
}
function EdgeTypedURLMigrator() {
}
EdgeTypedURLMigrator.prototype = {
type: MigrationUtils.resourceTypes.HISTORY,
get _typedURLs() {
if (!this.__typedURLs) {
this.__typedURLs = MSMigrationUtils.getTypedURLs(kEdgeRegistryRoot);
}
return this.__typedURLs;
},
get exists() {
return this._typedURLs.size > 0;
},
migrate: function(aCallback) {
let typedURLs = this._typedURLs;
let places = [];
for (let [urlString, time] of typedURLs) {
let uri;
try {
uri = Services.io.newURI(urlString, null, null);
if (["http", "https", "ftp"].indexOf(uri.scheme) == -1) {
continue;
}
} catch (ex) {
Cu.reportError(ex);
continue;
}
// Note that the time will be in microseconds (PRTime),
// and Date.now() returns milliseconds. Places expects PRTime,
// so we multiply the Date.now return value to make up the difference.
let visitDate = time || (Date.now() * 1000);
places.push({
uri,
visits: [{ transitionType: Ci.nsINavHistoryService.TRANSITION_TYPED,
visitDate}]
});
}
if (places.length == 0) {
aCallback(typedURLs.size == 0);
return;
}
MigrationUtils.insertVisitsWrapper(places, {
_success: false,
handleResult: function() {
// Importing any entry is considered a successful import.
this._success = true;
},
handleError: function() {},
handleCompletion: function() {
aCallback(this._success);
}
});
},
};
function EdgeReadingListMigrator() {
}
EdgeReadingListMigrator.prototype = {
type: MigrationUtils.resourceTypes.BOOKMARKS,
get exists() {
return !!gEdgeDatabase;
},
migrate(callback) {
this._migrateReadingList(PlacesUtils.bookmarks.menuGuid).then(
() => callback(true),
ex => {
Cu.reportError(ex);
callback(false);
}
);
},
_migrateReadingList: Task.async(function*(parentGuid) {
let columnFn = db => {
let columns = [
{name: "URL", type: "string"},
{name: "Title", type: "string"},
{name: "AddedDate", type: "date"}
];
// Later versions have an IsDeleted column:
let isDeletedColumn = db.checkForColumn("ReadingList", "IsDeleted");
if (isDeletedColumn && isDeletedColumn.dbType == ESEDBReader.COLUMN_TYPES.JET_coltypBit) {
columns.push({name: "IsDeleted", type: "boolean"});
}
return columns;
};
let filterFn = row => {
return !row.IsDeleted;
};
let readingListItems = readTableFromEdgeDB("ReadingList", columnFn, filterFn);
if (!readingListItems.length) {
return;
}
let destFolderGuid = yield this._ensureReadingListFolder(parentGuid);
let exceptionThrown;
for (let item of readingListItems) {
let dateAdded = item.AddedDate || new Date();
yield MigrationUtils.insertBookmarkWrapper({
parentGuid: destFolderGuid, url: item.URL, title: item.Title, dateAdded
}).catch(ex => {
if (!exceptionThrown) {
exceptionThrown = ex;
}
Cu.reportError(ex);
});
}
if (exceptionThrown) {
throw exceptionThrown;
}
}),
_ensureReadingListFolder: Task.async(function*(parentGuid) {
if (!this.__readingListFolderGuid) {
let folderTitle = MigrationUtils.getLocalizedString("importedEdgeReadingList");
let folderSpec = {type: PlacesUtils.bookmarks.TYPE_FOLDER, parentGuid, title: folderTitle};
this.__readingListFolderGuid = (yield MigrationUtils.insertBookmarkWrapper(folderSpec)).guid;
}
return this.__readingListFolderGuid;
}),
};
function EdgeBookmarksMigrator(dbOverride) {
this.dbOverride = dbOverride;
}
EdgeBookmarksMigrator.prototype = {
type: MigrationUtils.resourceTypes.BOOKMARKS,
get db() { return this.dbOverride || gEdgeDatabase },
get TABLE_NAME() { return "Favorites" },
get exists() {
if (!("_exists" in this)) {
this._exists = !!this.db;
}
return this._exists;
},
migrate(callback) {
this._migrateBookmarks(PlacesUtils.bookmarks.menuGuid).then(
() => callback(true),
ex => {
Cu.reportError(ex);
callback(false);
}
);
},
_migrateBookmarks: Task.async(function*(rootGuid) {
let {bookmarks, folderMap} = this._fetchBookmarksFromDB();
if (!bookmarks.length) {
return;
}
yield this._importBookmarks(bookmarks, folderMap, rootGuid);
}),
_importBookmarks: Task.async(function*(bookmarks, folderMap, rootGuid) {
if (!MigrationUtils.isStartupMigration) {
rootGuid =
yield MigrationUtils.createImportedBookmarksFolder("Edge", rootGuid);
}
let exceptionThrown;
for (let bookmark of bookmarks) {
// If this is a folder, we might have created it already to put other bookmarks in.
if (bookmark.IsFolder && bookmark._guid) {
continue;
}
// If this is a folder, just create folders up to and including that folder.
// Otherwise, create folders until we have a parent for this bookmark.
// This avoids duplicating logic for the bookmarks bar.
let folderId = bookmark.IsFolder ? bookmark.ItemId : bookmark.ParentId;
let parentGuid = yield this._getGuidForFolder(folderId, folderMap, rootGuid).catch(ex => {
if (!exceptionThrown) {
exceptionThrown = ex;
}
Cu.reportError(ex);
});
// If this was a folder, we're done with this item
if (bookmark.IsFolder) {
continue;
}
if (!parentGuid) {
// If we couldn't sort out a parent, fall back to importing on the root:
parentGuid = rootGuid;
}
let placesInfo = {
parentGuid,
url: bookmark.URL,
dateAdded: bookmark.DateUpdated || new Date(),
title: bookmark.Title,
};
yield MigrationUtils.insertBookmarkWrapper(placesInfo).catch(ex => {
if (!exceptionThrown) {
exceptionThrown = ex;
}
Cu.reportError(ex);
});
}
if (exceptionThrown) {
throw exceptionThrown;
}
}),
_fetchBookmarksFromDB() {
let folderMap = new Map();
let columns = [
{name: "URL", type: "string"},
{name: "Title", type: "string"},
{name: "DateUpdated", type: "date"},
{name: "IsFolder", type: "boolean"},
{name: "IsDeleted", type: "boolean"},
{name: "ParentId", type: "guid"},
{name: "ItemId", type: "guid"}
];
let filterFn = row => {
if (row.IsDeleted) {
return false;
}
if (row.IsFolder) {
folderMap.set(row.ItemId, row);
}
return true;
};
let bookmarks = readTableFromEdgeDB(this.TABLE_NAME, columns, filterFn, this.db);
return {bookmarks, folderMap};
},
_getGuidForFolder: Task.async(function*(folderId, folderMap, rootGuid) {
// If the folderId is not known as a folder in the folder map, we assume
// we just need the root
if (!folderMap.has(folderId)) {
return rootGuid;
}
let folder = folderMap.get(folderId);
// If the folder already has a places guid, just return that.
if (folder._guid) {
return folder._guid;
}
// Hacks! The bookmarks bar is special:
if (folder.Title == "_Favorites_Bar_") {
let toolbarGuid = PlacesUtils.bookmarks.toolbarGuid;
if (!MigrationUtils.isStartupMigration) {
toolbarGuid =
yield MigrationUtils.createImportedBookmarksFolder("Edge", toolbarGuid);
}
folder._guid = toolbarGuid;
return folder._guid;
}
// Otherwise, get the right parent guid recursively:
let parentGuid = yield this._getGuidForFolder(folder.ParentId, folderMap, rootGuid);
let folderInfo = {
title: folder.Title,
type: PlacesUtils.bookmarks.TYPE_FOLDER,
dateAdded: folder.DateUpdated || new Date(),
parentGuid,
};
// and add ourselves as a kid, and return the guid we got.
let parentBM = yield MigrationUtils.insertBookmarkWrapper(folderInfo);
folder._guid = parentBM.guid;
return folder._guid;
}),
};
function EdgeProfileMigrator() {
this.wrappedJSObject = this;
}
EdgeProfileMigrator.prototype = Object.create(MigratorPrototype);
EdgeProfileMigrator.prototype.getESEMigratorForTesting = function(dbOverride) {
return new EdgeBookmarksMigrator(dbOverride);
};
EdgeProfileMigrator.prototype.getResources = function() {
let resources = [
new EdgeBookmarksMigrator(),
MSMigrationUtils.getCookiesMigrator(MSMigrationUtils.MIGRATION_TYPE_EDGE),
new EdgeTypedURLMigrator(),
new EdgeReadingListMigrator(),
];
let windowsVaultFormPasswordsMigrator =
MSMigrationUtils.getWindowsVaultFormPasswordsMigrator();
windowsVaultFormPasswordsMigrator.name = "EdgeVaultFormPasswords";
resources.push(windowsVaultFormPasswordsMigrator);
return resources.filter(r => r.exists);
};
EdgeProfileMigrator.prototype.getLastUsedDate = function() {
// Don't do this if we don't have a single profile (see the comment for
// sourceProfiles) or if we can't find the database file:
if (this.sourceProfiles !== null || !gEdgeDatabase) {
return Promise.resolve(new Date(0));
}
let logFilePath = OS.Path.join(gEdgeDatabase.parent.path, "LogFiles", "edb.log");
let dbPath = gEdgeDatabase.path;
let cookieMigrator = MSMigrationUtils.getCookiesMigrator(MSMigrationUtils.MIGRATION_TYPE_EDGE);
let cookiePaths = cookieMigrator._cookiesFolders.map(f => f.path);
let datePromises = [logFilePath, dbPath, ... cookiePaths].map(path => {
return OS.File.stat(path).catch(() => null).then(info => {
return info ? info.lastModificationDate : 0;
});
});
datePromises.push(new Promise(resolve => {
let typedURLs = new Map();
try {
typedURLs = MSMigrationUtils.getTypedURLs(kEdgeRegistryRoot);
} catch (ex) {}
let times = [0, ... typedURLs.values()];
resolve(Math.max.apply(Math, times));
}));
return Promise.all(datePromises).then(dates => {
return new Date(Math.max.apply(Math, dates));
});
};
/* Somewhat counterintuitively, this returns:
* - |null| to indicate "There is only 1 (default) profile" (on win10+)
* - |[]| to indicate "There are no profiles" (on <=win8.1) which will avoid using this migrator.
* See MigrationUtils.jsm for slightly more info on how sourceProfiles is used.
*/
EdgeProfileMigrator.prototype.__defineGetter__("sourceProfiles", function() {
let isWin10OrHigher = AppConstants.isPlatformAndVersionAtLeast("win", "10");
return isWin10OrHigher ? null : [];
});
EdgeProfileMigrator.prototype.__defineGetter__("sourceLocked", function() {
// There is an exclusive lock on some databases. Assume they are locked for now.
return true;
});
EdgeProfileMigrator.prototype.classDescription = "Edge Profile Migrator";
EdgeProfileMigrator.prototype.contractID = "@mozilla.org/profile/migrator;1?app=browser&type=edge";
EdgeProfileMigrator.prototype.classID = Components.ID("{62e8834b-2d17-49f5-96ff-56344903a2ae}");
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([EdgeProfileMigrator]);

View file

@ -0,0 +1,255 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 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 Basilisk 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.
*/
const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource:///modules/MigrationUtils.jsm"); /* globals MigratorPrototype */
Cu.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesBackups",
"resource://gre/modules/PlacesBackups.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "SessionMigration",
"resource:///modules/sessionstore/SessionMigration.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
"resource://gre/modules/FileUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ProfileAge",
"resource://gre/modules/ProfileAge.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
"resource://gre/modules/AppConstants.jsm");
function FirefoxProfileMigrator() {
this.wrappedJSObject = this; // for testing...
}
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(Ci.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 [...this._getAllProfiles().keys()].map(x => ({id: x, name: x})).sort(sorter);
}
});
FirefoxProfileMigrator.prototype._getFileObject = function(dir, fileName) {
let file = dir.clone();
file.append(fileName);
// File resources are monolithic. We don't make partial copies since
// they are not expected to work alone. Return null to avoid trying to
// copy non-existing files.
return file.exists() ? file : null;
};
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;
return this._getResourcesInternal(sourceProfileDir, currentProfileDir);
};
FirefoxProfileMigrator.prototype.getLastUsedDate = function() {
// We always pretend we're really old, so that we don't mess
// up the determination of which browser is the most 'recent'
// to import from.
return Promise.resolve(new Date(0));
};
FirefoxProfileMigrator.prototype._getResourcesInternal = function(sourceProfileDir, currentProfileDir) {
let getFileResource = function(aMigrationType, aFileNames) {
let files = [];
for (let fileName of aFileNames) {
let file = this._getFileObject(sourceProfileDir, fileName);
if (file)
files.push(file);
}
if (!files.length) {
return null;
}
return {
type: aMigrationType,
migrate: function(aCallback) {
for (let file of files) {
file.copyTo(currentProfileDir, "");
}
aCallback(true);
}
};
}.bind(this);
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",
"signedInUser.json"]);
let formData = getFileResource(types.FORMDATA, ["formhistory.sqlite"]);
let bookmarksBackups = getFileResource(types.OTHERDATA,
[PlacesBackups.profileRelativeFolderPath]);
let dictionary = getFileResource(types.OTHERDATA, ["persdict.dat"]);
let sessionCheckpoints = this._getFileObject(sourceProfileDir, "sessionCheckpoints.json");
let sessionFile = this._getFileObject(sourceProfileDir, "sessionstore.js");
let session;
if (sessionFile) {
session = {
type: types.SESSION,
migrate: function(aCallback) {
sessionCheckpoints.copyTo(currentProfileDir, "sessionCheckpoints.json");
let newSessionFile = currentProfileDir.clone();
newSessionFile.append("sessionstore.js");
let migrationPromise = SessionMigration.migrate(sessionFile.path, newSessionFile.path);
migrationPromise.then(function() {
let buildID = Services.appinfo.platformBuildID;
let mstone = Services.appinfo.platformVersion;
// Force the browser to one-off resume the session that we give it:
Services.prefs.setBoolPref("browser.sessionstore.resume_session_once", true);
// Reset the homepage_override prefs so that the browser doesn't override our
// session with the "what's new" page:
Services.prefs.setCharPref("browser.startup.homepage_override.mstone", mstone);
Services.prefs.setCharPref("browser.startup.homepage_override.buildID", buildID);
// It's too early in startup for the pref service to have a profile directory,
// so we have to manually tell it where to save the prefs file.
let newPrefsFile = currentProfileDir.clone();
newPrefsFile.append("prefs.js");
Services.prefs.savePrefFile(newPrefsFile);
aCallback(true);
}, function() {
aCallback(false);
});
}
};
}
// Telemetry related migrations.
let times = {
name: "times", // name is used only by tests.
type: types.OTHERDATA,
migrate: aCallback => {
let file = this._getFileObject(sourceProfileDir, "times.json");
if (file) {
file.copyTo(currentProfileDir, "");
}
// And record the fact a migration (ie, a reset) happened.
let timesAccessor = new ProfileAge(currentProfileDir.path);
timesAccessor.recordProfileReset().then(
() => aCallback(true),
() => aCallback(false)
);
}
};
let telemetry = {
name: "telemetry", // name is used only by tests...
type: types.OTHERDATA,
migrate: aCallback => {
let createSubDir = (name) => {
let dir = currentProfileDir.clone();
dir.append(name);
dir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
return dir;
};
// If the 'datareporting' directory exists we migrate files from it.
let haveStateFile = false;
let dataReportingDir = this._getFileObject(sourceProfileDir, "datareporting");
if (dataReportingDir && dataReportingDir.isDirectory()) {
// Copy only specific files.
let toCopy = ["state.json", "session-state.json"];
let dest = createSubDir("datareporting");
let enumerator = dataReportingDir.directoryEntries;
while (enumerator.hasMoreElements()) {
let file = enumerator.getNext().QueryInterface(Ci.nsIFile);
if (file.isDirectory() || toCopy.indexOf(file.leafName) == -1) {
continue;
}
if (file.leafName == "state.json") {
haveStateFile = true;
}
file.copyTo(dest, "");
}
}
if (!haveStateFile) {
// Fall back to migrating the state file that contains the client id from healthreport/.
// We first moved the client id management from the FHR implementation to the datareporting
// service.
// Consequently, we try to migrate an existing FHR state file here as a fallback.
let healthReportDir = this._getFileObject(sourceProfileDir, "healthreport");
if (healthReportDir && healthReportDir.isDirectory()) {
let stateFile = this._getFileObject(healthReportDir, "state.json");
if (stateFile) {
let dest = createSubDir("healthreport");
stateFile.copyTo(dest, "");
}
}
}
aCallback(true);
}
};
return [places, cookies, passwords, formData, dictionary, bookmarksBackups,
session, times, telemetry].filter(r => r);
};
Object.defineProperty(FirefoxProfileMigrator.prototype, "startupOnlyMigrator", {
get: () => 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]);

View file

@ -0,0 +1,542 @@
/* 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 kLoginsKey = "Software\\Microsoft\\Internet Explorer\\IntelliForms\\Storage2";
const kMainKey = "Software\\Microsoft\\Internet Explorer\\Main";
Cu.import("resource://gre/modules/AppConstants.jsm");
Cu.import("resource://gre/modules/osfile.jsm"); /* globals OS */
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource:///modules/MigrationUtils.jsm"); /* globals MigratorPrototype */
Cu.import("resource:///modules/MSMigrationUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ctypes",
"resource://gre/modules/ctypes.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OSCrypto",
"resource://gre/modules/OSCrypto.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "WindowsRegistry",
"resource://gre/modules/WindowsRegistry.jsm");
Cu.importGlobalProperties(["URL"]);
// Resources
function History() {
}
History.prototype = {
type: MigrationUtils.resourceTypes.HISTORY,
get exists() {
return true;
},
migrate: function H_migrate(aCallback) {
let places = [];
let typedURLs = MSMigrationUtils.getTypedURLs("Software\\Microsoft\\Internet Explorer");
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 = typedURLs.has(uri.spec) ?
Ci.nsINavHistoryService.TRANSITION_TYPED :
Ci.nsINavHistoryService.TRANSITION_LINK;
// use the current date if we have no visits for this entry.
// Note that the entry will have a time in microseconds (PRTime),
// and Date.now() returns milliseconds. Places expects PRTime,
// so we multiply the Date.now return value to make up the difference.
let lastVisitTime = entry.get("time") || (Date.now() * 1000);
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;
}
MigrationUtils.insertVisitsWrapper(places, {
_success: false,
handleResult: function() {
// Importing any entry is considered a successful import.
this._success = true;
},
handleError: function() {},
handleCompletion: function() {
aCallback(this._success);
}
});
}
};
// IE form password migrator supporting windows from XP until 7 and IE from 7 until 11
function IE7FormPasswords() {
// used to distinguish between this migrator and other passwords migrators in tests.
this.name = "IE7FormPasswords";
}
IE7FormPasswords.prototype = {
type: MigrationUtils.resourceTypes.PASSWORDS,
get exists() {
// work only on windows until 7
if (AppConstants.isPlatformAndVersionAtLeast("win", "6.2")) {
return false;
}
try {
let nsIWindowsRegKey = Ci.nsIWindowsRegKey;
let key = Cc["@mozilla.org/windows-registry-key;1"].
createInstance(nsIWindowsRegKey);
key.open(nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, kLoginsKey,
nsIWindowsRegKey.ACCESS_READ);
let count = key.valueCount;
key.close();
return count > 0;
} catch (e) {
return false;
}
},
migrate(aCallback) {
let historyEnumerator = Cc["@mozilla.org/profile/migrator/iehistoryenumerator;1"].
createInstance(Ci.nsISimpleEnumerator);
let uris = []; // the uris of the websites that are going to be migrated
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 are not going to import the logins that are performed in these URLs
// we can just skip them.
if (["http", "https", "ftp"].indexOf(uri.scheme) == -1) {
continue;
}
uris.push(uri);
}
this._migrateURIs(uris);
aCallback(true);
},
/**
* Migrate the logins that were saved for the uris arguments.
* @param {nsIURI[]} uris - the uris that are going to be migrated.
*/
_migrateURIs(uris) {
this.ctypesKernelHelpers = new MSMigrationUtils.CtypesKernelHelpers();
this._crypto = new OSCrypto();
let nsIWindowsRegKey = Ci.nsIWindowsRegKey;
let key = Cc["@mozilla.org/windows-registry-key;1"].
createInstance(nsIWindowsRegKey);
key.open(nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, kLoginsKey,
nsIWindowsRegKey.ACCESS_READ);
let urlsSet = new Set(); // set of the already processed urls.
// number of the successfully decrypted registry values
let successfullyDecryptedValues = 0;
/* The logins are stored in the registry, where the key is a hashed URL and its
* value contains the encrypted details for all logins for that URL.
*
* First iterate through IE history, hashing each URL and looking for a match. If
* found, decrypt the value, using the URL as a salt. Finally add any found logins
* to the Firefox password manager.
*/
for (let uri of uris) {
try {
// remove the query and the ref parts of the URL
let urlObject = new URL(uri.spec);
let url = urlObject.origin + urlObject.pathname;
// if the current url is already processed, it should be skipped
if (urlsSet.has(url)) {
continue;
}
urlsSet.add(url);
// hash value of the current uri
let hashStr = this._crypto.getIELoginHash(url);
if (!key.hasValue(hashStr)) {
continue;
}
let value = key.readBinaryValue(hashStr);
// if no value was found, the uri is skipped
if (value == null) {
continue;
}
let data;
try {
// the url is used as salt to decrypt the registry value
data = this._crypto.decryptData(value, url, true);
} catch (e) {
continue;
}
// extract the login details from the decrypted data
let ieLogins = this._extractDetails(data, uri);
// if at least a credential was found in the current data, successfullyDecryptedValues should
// be incremented by one
if (ieLogins.length) {
successfullyDecryptedValues++;
}
this._addLogins(ieLogins);
} catch (e) {
Cu.reportError("Error while importing logins for " + uri.spec + ": " + e);
}
}
// if the number of the imported values is less than the number of values in the key, it means
// that not all the values were imported and an error should be reported
if (successfullyDecryptedValues < key.valueCount) {
Cu.reportError("We failed to decrypt and import some logins. " +
"This is likely because we didn't find the URLs where these " +
"passwords were submitted in the IE history and which are needed to be used " +
"as keys in the decryption.");
}
key.close();
this._crypto.finalize();
this.ctypesKernelHelpers.finalize();
},
_crypto: null,
/**
* Add the logins to the password manager.
* @param {Object[]} logins - array of the login details.
*/
_addLogins(ieLogins) {
for (let ieLogin of ieLogins) {
try {
// create a new login
let login = {
username: ieLogin.username,
password: ieLogin.password,
hostname: ieLogin.url,
timeCreated: ieLogin.creation,
};
MigrationUtils.insertLoginWrapper(login);
} catch (e) {
Cu.reportError(e);
}
}
},
/**
* Extract the details of one or more logins from the raw decrypted data.
* @param {string} data - the decrypted data containing raw information.
* @param {nsURI} uri - the nsURI of page where the login has occur.
* @returns {Object[]} array of objects where each of them contains the username, password, URL,
* and creation time representing all the logins found in the data arguments.
*/
_extractDetails(data, uri) {
// the structure of the header of the IE7 decrypted data for all the logins sharing the same URL
let loginData = new ctypes.StructType("loginData", [
// Bytes 0-3 are not needed and not documented
{"unknown1": ctypes.uint32_t},
// Bytes 4-7 are the header size
{"headerSize": ctypes.uint32_t},
// Bytes 8-11 are the data size
{"dataSize": ctypes.uint32_t},
// Bytes 12-19 are not needed and not documented
{"unknown2": ctypes.uint32_t},
{"unknown3": ctypes.uint32_t},
// Bytes 20-23 are the data count: each username and password is considered as a data
{"dataMax": ctypes.uint32_t},
// Bytes 24-35 are not needed and not documented
{"unknown4": ctypes.uint32_t},
{"unknown5": ctypes.uint32_t},
{"unknown6": ctypes.uint32_t}
]);
// the structure of a IE7 decrypted login item
let loginItem = new ctypes.StructType("loginItem", [
// Bytes 0-3 are the offset of the username
{"usernameOffset": ctypes.uint32_t},
// Bytes 4-11 are the date
{"loDateTime": ctypes.uint32_t},
{"hiDateTime": ctypes.uint32_t},
// Bytes 12-15 are not needed and not documented
{"foo": ctypes.uint32_t},
// Bytes 16-19 are the offset of the password
{"passwordOffset": ctypes.uint32_t},
// Bytes 20-31 are not needed and not documented
{"unknown1": ctypes.uint32_t},
{"unknown2": ctypes.uint32_t},
{"unknown3": ctypes.uint32_t}
]);
let url = uri.prePath;
let results = [];
let arr = this._crypto.stringToArray(data);
// convert data to ctypes.unsigned_char.array(arr.length)
let cdata = ctypes.unsigned_char.array(arr.length)(arr);
// Bytes 0-35 contain the loginData data structure for all the logins sharing the same URL
let currentLoginData = ctypes.cast(cdata, loginData);
let headerSize = currentLoginData.headerSize;
let currentInfoIndex = loginData.size;
// pointer to the current login item
let currentLoginItemPointer = ctypes.cast(cdata.addressOfElement(currentInfoIndex),
loginItem.ptr);
// currentLoginData.dataMax is the data count: each username and password is considered as
// a data. So, the number of logins is the number of data dived by 2
let numLogins = currentLoginData.dataMax / 2;
for (let n = 0; n < numLogins; n++) {
// Bytes 0-31 starting from currentInfoIndex contain the loginItem data structure for the
// current login
let currentLoginItem = currentLoginItemPointer.contents;
let creation = this.ctypesKernelHelpers.
fileTimeToSecondsSinceEpoch(currentLoginItem.hiDateTime,
currentLoginItem.loDateTime) * 1000;
let currentResult = {
creation: creation,
url: url,
};
// The username is UTF-16 and null-terminated.
currentResult.username =
ctypes.cast(cdata.addressOfElement(headerSize + 12 + currentLoginItem.usernameOffset),
ctypes.char16_t.ptr).readString();
// The password is UTF-16 and null-terminated.
currentResult.password =
ctypes.cast(cdata.addressOfElement(headerSize + 12 + currentLoginItem.passwordOffset),
ctypes.char16_t.ptr).readString();
results.push(currentResult);
// move to the next login item
currentLoginItemPointer = currentLoginItemPointer.increment();
}
return results;
},
};
function Settings() {
}
Settings.prototype = {
type: MigrationUtils.resourceTypes.SETTINGS,
get exists() {
return true;
},
migrate: function S_migrate(aCallback) {
// Converts from yes/no to a boolean.
let yesNoToBoolean = v => v == "yes";
// Converts source format like "en-us,ar-kw;q=0.7,ar-om;q=0.3" into
// destination format like "en-us, ar-kw, ar-om".
// Final string is sorted by quality (q=) param.
function parseAcceptLanguageList(v) {
return v.match(/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/gi)
.sort(function(a, b) {
let qA = parseFloat(a.split(";q=")[1]) || 1.0;
let qB = parseFloat(b.split(";q=")[1]) || 1.0;
return qB - qA;
})
.map(a => a.split(";")[0]);
}
// For reference on some of the available IE Registry settings:
// * http://msdn.microsoft.com/en-us/library/cc980058%28v=prot.13%29.aspx
// * http://msdn.microsoft.com/en-us/library/cc980059%28v=prot.13%29.aspx
// Note that only settings exposed in our UI should be migrated.
this._set("Software\\Microsoft\\Internet Explorer\\International",
"AcceptLanguage",
"intl.accept_languages",
parseAcceptLanguageList);
// TODO (bug 745853): For now, only x-western font is translated.
this._set("Software\\Microsoft\\Internet Explorer\\International\\Scripts\\3",
"IEFixedFontName",
"font.name.monospace.x-western");
this._set(kMainKey,
"Use FormSuggest",
"browser.formfill.enable",
yesNoToBoolean);
this._set(kMainKey,
"FormSuggest Passwords",
"signon.rememberSignons",
yesNoToBoolean);
this._set(kMainKey,
"Anchor Underline",
"browser.underline_anchors",
yesNoToBoolean);
this._set(kMainKey,
"Display Inline Images",
"permissions.default.image",
v => yesNoToBoolean(v) ? 1 : 2);
this._set(kMainKey,
"Move System Caret",
"accessibility.browsewithcaret",
yesNoToBoolean);
this._set("Software\\Microsoft\\Internet Explorer\\Settings",
"Always Use My Colors",
"browser.display.document_color_use",
v => (!v ? 0 : 2));
this._set("Software\\Microsoft\\Internet Explorer\\Settings",
"Always Use My Font Face",
"browser.display.use_document_fonts",
v => !v);
this._set(kMainKey,
"SmoothScroll",
"general.smoothScroll",
Boolean);
this._set("Software\\Microsoft\\Internet Explorer\\TabbedBrowsing\\",
"WarnOnClose",
"browser.tabs.warnOnClose",
Boolean);
this._set("Software\\Microsoft\\Internet Explorer\\TabbedBrowsing\\",
"OpenInForeground",
"browser.tabs.loadInBackground",
v => !v);
aCallback(true);
},
/**
* Reads a setting from the Registry and stores the converted result into
* the appropriate Firefox preference.
*
* @param aPath
* Registry path under HKCU.
* @param aKey
* Name of the key.
* @param aPref
* Firefox preference.
* @param [optional] aTransformFn
* Conversion function from the Registry format to the pref format.
*/
_set: function S__set(aPath, aKey, aPref, aTransformFn) {
let value = WindowsRegistry.readRegKey(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
aPath, aKey);
// Don't import settings that have never been flipped.
if (value === undefined)
return;
if (aTransformFn)
value = aTransformFn(value);
switch (typeof value) {
case "string":
Services.prefs.setCharPref(aPref, value);
break;
case "number":
Services.prefs.setIntPref(aPref, value);
break;
case "boolean":
Services.prefs.setBoolPref(aPref, value);
break;
default:
throw new Error("Unexpected value type: " + (typeof value));
}
}
};
function IEProfileMigrator()
{
this.wrappedJSObject = this; // export this to be able to use it in the unittest.
}
IEProfileMigrator.prototype = Object.create(MigratorPrototype);
IEProfileMigrator.prototype.getResources = function IE_getResources() {
let resources = [
MSMigrationUtils.getBookmarksMigrator(),
new History(),
MSMigrationUtils.getCookiesMigrator(),
new Settings(),
];
// Only support the form password migrator for Windows XP to 7.
if (AppConstants.isPlatformAndVersionAtMost("win", "6.1")) {
resources.push(new IE7FormPasswords());
}
let windowsVaultFormPasswordsMigrator =
MSMigrationUtils.getWindowsVaultFormPasswordsMigrator();
windowsVaultFormPasswordsMigrator.name = "IEVaultFormPasswords";
resources.push(windowsVaultFormPasswordsMigrator);
return resources.filter(r => r.exists);
};
IEProfileMigrator.prototype.getLastUsedDate = function IE_getLastUsedDate() {
let datePromises = ["Favs", "CookD"].map(dirId => {
let {path} = Services.dirsvc.get(dirId, Ci.nsIFile);
return OS.File.stat(path).catch(() => null).then(info => {
return info ? info.lastModificationDate : 0;
});
});
datePromises.push(new Promise(resolve => {
let typedURLs = new Map();
try {
typedURLs = MSMigrationUtils.getTypedURLs("Software\\Microsoft\\Internet Explorer");
} catch (ex) {}
let dates = [0, ... typedURLs.values()];
resolve(Math.max.apply(Math, dates));
}));
return Promise.all(datePromises).then(dates => {
return new Date(Math.max.apply(Math, dates));
});
};
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]);

View file

@ -0,0 +1,889 @@
/* 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 = ["MSMigrationUtils"];
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/AppConstants.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource:///modules/MigrationUtils.jsm");
Cu.importGlobalProperties(["FileReader"]);
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "WindowsRegistry",
"resource://gre/modules/WindowsRegistry.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ctypes",
"resource://gre/modules/ctypes.jsm");
const EDGE_COOKIE_PATH_OPTIONS = ["", "#!001\\", "#!002\\"];
const EDGE_COOKIES_SUFFIX = "MicrosoftEdge\\Cookies";
const EDGE_FAVORITES = "AC\\MicrosoftEdge\\User\\Default\\Favorites";
const FREE_CLOSE_FAILED = 0;
const INTERNET_EXPLORER_EDGE_GUID = [0x3CCD5499,
0x4B1087A8,
0x886015A2,
0x553BDD88];
const RESULT_SUCCESS = 0;
const VAULT_ENUMERATE_ALL_ITEMS = 512;
const WEB_CREDENTIALS_VAULT_ID = [0x4BF4C442,
0x41A09B8A,
0x4ADD80B3,
0x28DB4D70];
Cu.importGlobalProperties(["File"]);
const wintypes = {
BOOL: ctypes.int,
DWORD: ctypes.uint32_t,
DWORDLONG: ctypes.uint64_t,
CHAR: ctypes.char,
PCHAR: ctypes.char.ptr,
LPCWSTR: ctypes.char16_t.ptr,
PDWORD: ctypes.uint32_t.ptr,
VOIDP: ctypes.voidptr_t,
WORD: ctypes.uint16_t,
};
// TODO: Bug 1202978 - Refactor MSMigrationUtils ctypes helpers
function CtypesKernelHelpers() {
this._structs = {};
this._functions = {};
this._libs = {};
this._structs.SYSTEMTIME = new ctypes.StructType("SYSTEMTIME", [
{wYear: wintypes.WORD},
{wMonth: wintypes.WORD},
{wDayOfWeek: wintypes.WORD},
{wDay: wintypes.WORD},
{wHour: wintypes.WORD},
{wMinute: wintypes.WORD},
{wSecond: wintypes.WORD},
{wMilliseconds: wintypes.WORD}
]);
this._structs.FILETIME = new ctypes.StructType("FILETIME", [
{dwLowDateTime: wintypes.DWORD},
{dwHighDateTime: wintypes.DWORD}
]);
try {
this._libs.kernel32 = ctypes.open("Kernel32");
this._functions.FileTimeToSystemTime =
this._libs.kernel32.declare("FileTimeToSystemTime",
ctypes.default_abi,
wintypes.BOOL,
this._structs.FILETIME.ptr,
this._structs.SYSTEMTIME.ptr);
} catch (ex) {
this.finalize();
}
}
CtypesKernelHelpers.prototype = {
/**
* Must be invoked once after last use of any of the provided helpers.
*/
finalize() {
this._structs = {};
this._functions = {};
for (let key in this._libs) {
let lib = this._libs[key];
try {
lib.close();
} catch (ex) {}
}
this._libs = {};
},
/**
* Converts a FILETIME struct (2 DWORDS), to a SYSTEMTIME struct,
* and then deduces the number of seconds since the epoch (which
* is the data we want for the cookie expiry date).
*
* @param aTimeHi
* Least significant DWORD.
* @param aTimeLo
* Most significant DWORD.
* @return the number of seconds since the epoch
*/
fileTimeToSecondsSinceEpoch(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);
// System time is in UTC, so we use Date.UTC to get milliseconds from epoch,
// then divide by 1000 to get seconds, and round down:
return Math.floor(Date.UTC(systemTime.wYear,
systemTime.wMonth - 1,
systemTime.wDay,
systemTime.wHour,
systemTime.wMinute,
systemTime.wSecond,
systemTime.wMilliseconds) / 1000);
}
};
function CtypesVaultHelpers() {
this._structs = {};
this._functions = {};
this._structs.GUID = new ctypes.StructType("GUID", [
{id: wintypes.DWORD.array(4)},
]);
this._structs.VAULT_ITEM_ELEMENT = new ctypes.StructType("VAULT_ITEM_ELEMENT", [
// not documented
{schemaElementId: wintypes.DWORD},
// not documented
{unknown1: wintypes.DWORD},
// vault type
{type: wintypes.DWORD},
// not documented
{unknown2: wintypes.DWORD},
// value of the item
{itemValue: wintypes.LPCWSTR},
// not documented
{unknown3: wintypes.CHAR.array(12)},
]);
this._structs.VAULT_ELEMENT = new ctypes.StructType("VAULT_ELEMENT", [
// vault item schemaId
{schemaId: this._structs.GUID},
// a pointer to the name of the browser VAULT_ITEM_ELEMENT
{pszCredentialFriendlyName: wintypes.LPCWSTR},
// a pointer to the url VAULT_ITEM_ELEMENT
{pResourceElement: this._structs.VAULT_ITEM_ELEMENT.ptr},
// a pointer to the username VAULT_ITEM_ELEMENT
{pIdentityElement: this._structs.VAULT_ITEM_ELEMENT.ptr},
// not documented
{pAuthenticatorElement: this._structs.VAULT_ITEM_ELEMENT.ptr},
// not documented
{pPackageSid: this._structs.VAULT_ITEM_ELEMENT.ptr},
// time stamp in local format
{lowLastModified: wintypes.DWORD},
{highLastModified: wintypes.DWORD},
// not documented
{flags: wintypes.DWORD},
// not documented
{dwPropertiesCount: wintypes.DWORD},
// not documented
{pPropertyElements: this._structs.VAULT_ITEM_ELEMENT.ptr},
]);
try {
this._vaultcliLib = ctypes.open("vaultcli.dll");
this._functions.VaultOpenVault =
this._vaultcliLib.declare("VaultOpenVault",
ctypes.winapi_abi,
wintypes.DWORD,
// GUID
this._structs.GUID.ptr,
// Flags
wintypes.DWORD,
// Vault Handle
wintypes.VOIDP.ptr);
this._functions.VaultEnumerateItems =
this._vaultcliLib.declare("VaultEnumerateItems",
ctypes.winapi_abi,
wintypes.DWORD,
// Vault Handle
wintypes.VOIDP,
// Flags
wintypes.DWORD,
// Items Count
wintypes.PDWORD,
// Items
ctypes.voidptr_t);
this._functions.VaultCloseVault =
this._vaultcliLib.declare("VaultCloseVault",
ctypes.winapi_abi,
wintypes.DWORD,
// Vault Handle
wintypes.VOIDP);
this._functions.VaultGetItem =
this._vaultcliLib.declare("VaultGetItem",
ctypes.winapi_abi,
wintypes.DWORD,
// Vault Handle
wintypes.VOIDP,
// Schema Id
this._structs.GUID.ptr,
// Resource
this._structs.VAULT_ITEM_ELEMENT.ptr,
// Identity
this._structs.VAULT_ITEM_ELEMENT.ptr,
// Package Sid
this._structs.VAULT_ITEM_ELEMENT.ptr,
// HWND Owner
wintypes.DWORD,
// Flags
wintypes.DWORD,
// Items
this._structs.VAULT_ELEMENT.ptr.ptr);
this._functions.VaultFree =
this._vaultcliLib.declare("VaultFree",
ctypes.winapi_abi,
wintypes.DWORD,
// Memory
this._structs.VAULT_ELEMENT.ptr);
} catch (ex) {
this.finalize();
}
}
CtypesVaultHelpers.prototype = {
/**
* Must be invoked once after last use of any of the provided helpers.
*/
finalize() {
this._structs = {};
this._functions = {};
try {
this._vaultcliLib.close();
} catch (ex) {}
this._vaultcliLib = null;
}
};
/**
* 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) {
return e.result == Cr.NS_ERROR_HOST_IS_IP_ADDRESS;
}
return false;
}
var gEdgeDir;
function getEdgeLocalDataFolder() {
if (gEdgeDir) {
return gEdgeDir.clone();
}
let packages = Services.dirsvc.get("LocalAppData", Ci.nsIFile);
packages.append("Packages");
let edgeDir = packages.clone();
edgeDir.append("Microsoft.MicrosoftEdge_8wekyb3d8bbwe");
try {
if (edgeDir.exists() && edgeDir.isReadable() && edgeDir.isDirectory()) {
gEdgeDir = edgeDir;
return edgeDir.clone();
}
// Let's try the long way:
let dirEntries = packages.directoryEntries;
while (dirEntries.hasMoreElements()) {
let subDir = dirEntries.getNext();
subDir.QueryInterface(Ci.nsIFile);
if (subDir.leafName.startsWith("Microsoft.MicrosoftEdge") && subDir.isReadable() &&
subDir.isDirectory()) {
gEdgeDir = subDir;
return subDir.clone();
}
}
} catch (ex) {
Cu.reportError("Exception trying to find the Edge favorites directory: " + ex);
}
return null;
}
function Bookmarks(migrationType) {
this._migrationType = migrationType;
}
Bookmarks.prototype = {
type: MigrationUtils.resourceTypes.BOOKMARKS,
get exists() {
return !!this._favoritesFolder;
},
get importedAppLabel() {
return this._migrationType == MSMigrationUtils.MIGRATION_TYPE_IE ? "IE" : "Edge";
},
__favoritesFolder: null,
get _favoritesFolder() {
if (!this.__favoritesFolder) {
if (this._migrationType == MSMigrationUtils.MIGRATION_TYPE_IE) {
let favoritesFolder = Services.dirsvc.get("Favs", Ci.nsIFile);
if (favoritesFolder.exists() && favoritesFolder.isReadable()) {
this.__favoritesFolder = favoritesFolder;
}
} else if (this._migrationType == MSMigrationUtils.MIGRATION_TYPE_EDGE) {
let edgeDir = getEdgeLocalDataFolder();
if (edgeDir) {
edgeDir.appendRelativePath(EDGE_FAVORITES);
if (edgeDir.exists() && edgeDir.isReadable() && edgeDir.isDirectory()) {
this.__favoritesFolder = edgeDir;
}
}
}
}
return this.__favoritesFolder;
},
__toolbarFolderName: null,
get _toolbarFolderName() {
if (!this.__toolbarFolderName) {
if (this._migrationType == MSMigrationUtils.MIGRATION_TYPE_IE) {
// 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";
} else {
this.__toolbarFolderName = "Links";
}
}
return this.__toolbarFolderName;
},
migrate: function B_migrate(aCallback) {
return Task.spawn(function* () {
// Import to the bookmarks menu.
let folderGuid = PlacesUtils.bookmarks.menuGuid;
if (!MigrationUtils.isStartupMigration) {
folderGuid =
yield MigrationUtils.createImportedBookmarksFolder(this.importedAppLabel, folderGuid);
}
yield this._migrateFolder(this._favoritesFolder, folderGuid);
}.bind(this)).then(() => aCallback(true),
e => { Cu.reportError(e); aCallback(false) });
},
_migrateFolder: Task.async(function* (aSourceFolder, aDestFolderGuid) {
// TODO (bug 741993): the favorites order is stored in the Registry, at
// HCU\Software\Microsoft\Windows\CurrentVersion\Explorer\MenuOrder\Favorites
// for IE, and in a similar location for Edge.
// Until we support it, bookmarks are imported in alphabetical order.
let entries = aSourceFolder.directoryEntries;
let succeeded = true;
while (entries.hasMoreElements()) {
let entry = entries.getNext().QueryInterface(Ci.nsIFile);
try {
// Make sure that entry.path == entry.target to not follow .lnk folder
// shortcuts which could lead to infinite cycles.
// Don't use isSymlink(), since it would throw for invalid
// lnk files pointing to URLs or to unresolvable paths.
if (entry.path == entry.target && entry.isDirectory()) {
let folderGuid;
if (entry.leafName == this._toolbarFolderName &&
entry.parent.equals(this._favoritesFolder)) {
// Import to the bookmarks toolbar.
folderGuid = PlacesUtils.bookmarks.toolbarGuid;
if (!MigrationUtils.isStartupMigration) {
folderGuid =
yield MigrationUtils.createImportedBookmarksFolder(this.importedAppLabel, folderGuid);
}
}
else {
// Import to a new folder.
folderGuid = (yield MigrationUtils.insertBookmarkWrapper({
type: PlacesUtils.bookmarks.TYPE_FOLDER,
parentGuid: aDestFolderGuid,
title: entry.leafName
})).guid;
}
if (entry.isReadable()) {
// Recursively import the folder.
yield this._migrateFolder(entry, folderGuid);
}
}
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];
yield MigrationUtils.insertBookmarkWrapper({
parentGuid: aDestFolderGuid, url: uri, title
});
}
}
} catch (ex) {
Components.utils.reportError("Unable to import " + this.importedAppLabel + " favorite (" + entry.leafName + "): " + ex);
succeeded = false;
}
}
if (!succeeded) {
throw new Error("Failed to import all bookmarks correctly.");
}
}),
};
function Cookies(migrationType) {
this._migrationType = migrationType;
}
Cookies.prototype = {
type: MigrationUtils.resourceTypes.COOKIES,
get exists() {
if (this._migrationType == MSMigrationUtils.MIGRATION_TYPE_IE) {
return !!this._cookiesFolder;
}
return !!this._cookiesFolders;
},
__cookiesFolder: null,
get _cookiesFolder() {
// Edge stores cookies in a number of places, and this shouldn't get called:
if (this._migrationType != MSMigrationUtils.MIGRATION_TYPE_IE) {
throw new Error("Shouldn't be looking for a single cookie folder unless we're migrating IE");
}
// 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;
},
__cookiesFolders: null,
get _cookiesFolders() {
if (this._migrationType != MSMigrationUtils.MIGRATION_TYPE_EDGE) {
throw new Error("Shouldn't be looking for multiple cookie folders unless we're migrating Edge");
}
let folders = [];
let edgeDir = getEdgeLocalDataFolder();
if (edgeDir) {
edgeDir.append("AC");
for (let path of EDGE_COOKIE_PATH_OPTIONS) {
let folder = edgeDir.clone();
let fullPath = path + EDGE_COOKIES_SUFFIX;
folder.appendRelativePath(fullPath);
if (folder.exists() && folder.isReadable() && folder.isDirectory()) {
folders.push(folder);
}
}
}
this.__cookiesFolders = folders.length ? folders : null;
return this.__cookiesFolders;
},
migrate(aCallback) {
this.ctypesKernelHelpers = new CtypesKernelHelpers();
let cookiesGenerator = (function* genCookie() {
let success = false;
let folders = this._migrationType == MSMigrationUtils.MIGRATION_TYPE_EDGE ?
this.__cookiesFolders : [this.__cookiesFolder];
for (let folder of folders) {
let entries = folder.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 undefined;
}
}
this.ctypesKernelHelpers.finalize();
aCallback(success);
}).apply(this);
cookiesGenerator.next();
},
_readCookieFile(aFile, aCallback) {
let fileReader = new FileReader();
let 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);
}
};
fileReader.addEventListener("loadend", onLoadEnd, false);
fileReader.readAsText(File.createFromNsIFile(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 "*"
*
* Unfortunately, "*" can also occur inside the value of the cookie, so we
* can't rely exclusively on it as a record separator.
*
* @note All the times are in FILETIME format.
*/
_parseCookieBuffer(aTextBuffer) {
// Note the last record is an empty string...
let records = [];
let lines = aTextBuffer.split("\n");
while (lines.length > 0) {
let record = lines.splice(0, 9);
// ... which means this is going to be a 1-element array for that record
if (record.length > 1) {
records.push(record);
}
}
for (let record of records) {
let [name, value, hostpath, flags,
expireTimeLo, expireTimeHi] = record;
// IE stores deleted cookies with a zero-length value, skip them.
if (value.length == 0)
continue;
// IE sometimes has cookies created by apps that use "~~local~~/local/file/path"
// as the hostpath, ignore those:
if (hostpath.startsWith("~~local~~"))
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;
}
// Fallback: expire in 1h (NB: time is in seconds since epoch, so we have
// to divide the result of Date.now() (which is in milliseconds) by 1000).
let expireTime = Math.floor(Date.now() / 1000) + 3600;
try {
expireTime = this.ctypesKernelHelpers.fileTimeToSecondsSinceEpoch(Number(expireTimeHi),
Number(expireTimeLo));
} catch (ex) {
Cu.reportError("Failed to get expiry time for cookie for " + host);
}
Services.cookies.add(host,
path,
name,
value,
Number(flags) & 0x1, // secure
false, // httpOnly
false, // session
expireTime,
{});
}
}
};
function getTypedURLs(registryKeyPath) {
// The list of typed URLs is a sort of annotation stored in the registry.
// The number of entries stored is not UI-configurable, but has changed
// between different Windows versions. We just keep reading up to the first
// non-existing entry to support different limits / states of the registry.
let typedURLs = new Map();
let typedURLKey = Cc["@mozilla.org/windows-registry-key;1"].
createInstance(Ci.nsIWindowsRegKey);
let typedURLTimeKey = Cc["@mozilla.org/windows-registry-key;1"].
createInstance(Ci.nsIWindowsRegKey);
let cTypes = new CtypesKernelHelpers();
try {
typedURLKey.open(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
registryKeyPath + "\\TypedURLs",
Ci.nsIWindowsRegKey.ACCESS_READ);
try {
typedURLTimeKey.open(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
registryKeyPath + "\\TypedURLsTime",
Ci.nsIWindowsRegKey.ACCESS_READ);
} catch (ex) {
typedURLTimeKey = null;
}
let entryName;
for (let entry = 1; typedURLKey.hasValue((entryName = "url" + entry)); entry++) {
let url = typedURLKey.readStringValue(entryName);
let timeTyped = 0;
if (typedURLTimeKey && typedURLTimeKey.hasValue(entryName)) {
let urlTime = "";
try {
urlTime = typedURLTimeKey.readBinaryValue(entryName);
} catch (ex) {
Cu.reportError("Couldn't read url time for " + entryName);
}
if (urlTime.length == 8) {
let urlTimeHex = [];
for (let i = 0; i < 8; i++) {
let c = urlTime.charCodeAt(i).toString(16);
if (c.length == 1)
c = "0" + c;
urlTimeHex.unshift(c);
}
try {
let hi = parseInt(urlTimeHex.slice(0, 4).join(""), 16);
let lo = parseInt(urlTimeHex.slice(4, 8).join(""), 16);
// Convert to seconds since epoch:
timeTyped = cTypes.fileTimeToSecondsSinceEpoch(hi, lo);
// Callers expect PRTime, which is microseconds since epoch:
timeTyped *= 1000 * 1000;
} catch (ex) {
// Ignore conversion exceptions. Callers will have to deal
// with the fallback value (0).
}
}
}
typedURLs.set(url, timeTyped);
}
} catch (ex) {
Cu.reportError("Error reading typed URL history: " + ex);
} finally {
if (typedURLKey) {
typedURLKey.close();
}
if (typedURLTimeKey) {
typedURLTimeKey.close();
}
cTypes.finalize();
}
return typedURLs;
}
// Migrator for form passwords on Windows 8 and higher.
function WindowsVaultFormPasswords () {
}
WindowsVaultFormPasswords.prototype = {
type: MigrationUtils.resourceTypes.PASSWORDS,
get exists() {
// work only on windows 8+
if (AppConstants.isPlatformAndVersionAtLeast("win", "6.2")) {
// check if there are passwords available for migration.
return this.migrate(() => {}, true);
}
return false;
},
/**
* If aOnlyCheckExists is false, import the form passwords on Windows 8 and higher from the vault
* and then call the aCallback.
* Otherwise, check if there are passwords in the vault.
* @param {function} aCallback - a callback called when the migration is done.
* @param {boolean} [aOnlyCheckExists=false] - if aOnlyCheckExists is true, just check if there are some
* passwords to migrate. Import the passwords from the vault and call aCallback otherwise.
* @return true if there are passwords in the vault and aOnlyCheckExists is set to true,
* false if there is no password in the vault and aOnlyCheckExists is set to true, undefined if
* aOnlyCheckExists is set to false.
*/
migrate(aCallback, aOnlyCheckExists = false) {
// check if the vault item is an IE/Edge one
function _isIEOrEdgePassword(id) {
return id[0] == INTERNET_EXPLORER_EDGE_GUID[0] &&
id[1] == INTERNET_EXPLORER_EDGE_GUID[1] &&
id[2] == INTERNET_EXPLORER_EDGE_GUID[2] &&
id[3] == INTERNET_EXPLORER_EDGE_GUID[3];
}
let ctypesVaultHelpers = new CtypesVaultHelpers();
let ctypesKernelHelpers = new CtypesKernelHelpers();
let migrationSucceeded = true;
let successfulVaultOpen = false;
let error, vault;
try {
// web credentials vault id
let vaultGuid = new ctypesVaultHelpers._structs.GUID(WEB_CREDENTIALS_VAULT_ID);
error = new wintypes.DWORD();
// web credentials vault
vault = new wintypes.VOIDP();
// open the current vault using the vaultGuid
error = ctypesVaultHelpers._functions.VaultOpenVault(vaultGuid.address(), 0, vault.address());
if (error != RESULT_SUCCESS) {
throw new Error("Unable to open Vault: " + error);
}
successfulVaultOpen = true;
let item = new ctypesVaultHelpers._structs.VAULT_ELEMENT.ptr();
let itemCount = new wintypes.DWORD();
// enumerate all the available items. This api is going to return a table of all the
// available items and item is going to point to the first element of this table.
error = ctypesVaultHelpers._functions.VaultEnumerateItems(vault, VAULT_ENUMERATE_ALL_ITEMS,
itemCount.address(),
item.address());
if (error != RESULT_SUCCESS) {
throw new Error("Unable to enumerate Vault items: " + error);
}
for (let j = 0; j < itemCount.value; j++) {
try {
// if it's not an ie/edge password, skip it
if (!_isIEOrEdgePassword(item.contents.schemaId.id)) {
continue;
}
let url = item.contents.pResourceElement.contents.itemValue.readString();
let realURL;
try {
realURL = Services.io.newURI(url, null, null);
} catch (ex) { /* leave realURL as null */ }
if (!realURL || ["http", "https", "ftp"].indexOf(realURL.scheme) == -1) {
// Ignore items for non-URLs or URLs that aren't HTTP(S)/FTP
continue;
}
// if aOnlyCheckExists is set to true, the purpose of the call is to return true if there is at
// least a password which is true in this case because a password was by now already found
if (aOnlyCheckExists) {
return true;
}
let username = item.contents.pIdentityElement.contents.itemValue.readString();
// the current login credential object
let credential = new ctypesVaultHelpers._structs.VAULT_ELEMENT.ptr();
error = ctypesVaultHelpers._functions.VaultGetItem(vault,
item.contents.schemaId.address(),
item.contents.pResourceElement,
item.contents.pIdentityElement, null,
0, 0, credential.address());
if (error != RESULT_SUCCESS) {
throw new Error("Unable to get item: " + error);
}
let password = credential.contents.pAuthenticatorElement.contents.itemValue.readString();
let creation = Date.now();
try {
// login manager wants time in milliseconds since epoch, so convert
// to seconds since epoch and multiply to get milliseconds:
creation = ctypesKernelHelpers.
fileTimeToSecondsSinceEpoch(item.contents.highLastModified,
item.contents.lowLastModified) * 1000;
} catch (ex) {
// Ignore exceptions in the dates and just create the login for right now.
}
// create a new login
let login = {
username, password,
hostname: realURL.prePath,
timeCreated: creation,
};
MigrationUtils.insertLoginWrapper(login);
// close current item
error = ctypesVaultHelpers._functions.VaultFree(credential);
if (error == FREE_CLOSE_FAILED) {
throw new Error("Unable to free item: " + error);
}
} catch (e) {
migrationSucceeded = false;
Cu.reportError(e);
} finally {
// move to next item in the table returned by VaultEnumerateItems
item = item.increment();
}
}
} catch (e) {
Cu.reportError(e);
migrationSucceeded = false;
} finally {
if (successfulVaultOpen) {
// close current vault
error = ctypesVaultHelpers._functions.VaultCloseVault(vault);
if (error == FREE_CLOSE_FAILED) {
Cu.reportError("Unable to close vault: " + error);
}
}
ctypesKernelHelpers.finalize();
ctypesVaultHelpers.finalize();
aCallback(migrationSucceeded);
}
if (aOnlyCheckExists) {
return false;
}
return undefined;
}
};
var MSMigrationUtils = {
MIGRATION_TYPE_IE: 1,
MIGRATION_TYPE_EDGE: 2,
CtypesKernelHelpers: CtypesKernelHelpers,
getBookmarksMigrator(migrationType = this.MIGRATION_TYPE_IE) {
return new Bookmarks(migrationType);
},
getCookiesMigrator(migrationType = this.MIGRATION_TYPE_IE) {
return new Cookies(migrationType);
},
getWindowsVaultFormPasswordsMigrator() {
return new WindowsVaultFormPasswords();
},
getTypedURLs,
getEdgeLocalDataFolder,
};

File diff suppressed because it is too large Load diff

View file

@ -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]);

View file

@ -0,0 +1,650 @@
/* 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";
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
Cu.import("resource://gre/modules/AppConstants.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/osfile.jsm"); /* globals OS */
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource:///modules/MigrationUtils.jsm"); /* globals MigratorPrototype */
XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
"resource://gre/modules/Downloads.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) {
return Task.spawn(function* () {
let dict = yield new Promise(resolve =>
PropertyListUtils.read(this._file, resolve)
);
if (!dict)
throw new Error("Could not read Bookmarks.plist");
let children = dict.get("Children");
if (!children)
throw new Error("Invalid Bookmarks.plist format");
let collection = dict.get("Title") == "com.apple.ReadingList" ?
this.READING_LIST_COLLECTION : this.ROOT_COLLECTION;
yield this._migrateCollection(children, collection);
}.bind(this)).then(() => aCallback(true),
e => { Cu.reportError(e); aCallback(false) });
},
// 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: Task.async(function* (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")
yield this._migrateCollection(children, this.TOOLBAR_COLLECTION);
else if (title == "BookmarksMenu")
yield this._migrateCollection(children, this.MENU_COLLECTION);
else if (title == "com.apple.ReadingList")
yield 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 folderGuid = -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.
folderGuid = PlacesUtils.bookmarks.unfiledGuid;
break;
}
case this.MENU_COLLECTION: {
folderGuid = PlacesUtils.bookmarks.menuGuid;
if (!MigrationUtils.isStartupMigration) {
folderGuid =
yield MigrationUtils.createImportedBookmarksFolder("Safari", folderGuid);
}
break;
}
case this.TOOLBAR_COLLECTION: {
folderGuid = PlacesUtils.bookmarks.toolbarGuid;
if (!MigrationUtils.isStartupMigration) {
folderGuid =
yield MigrationUtils.createImportedBookmarksFolder("Safari", folderGuid);
}
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).
folderGuid = (yield MigrationUtils.insertBookmarkWrapper({
parentGuid: PlacesUtils.bookmarks.menuGuid,
type: PlacesUtils.bookmarks.TYPE_FOLDER,
title: MigrationUtils.getLocalizedString("importedSafariReadingList"),
})).guid;
break;
}
default:
throw new Error("Unexpected value for aCollection!");
}
if (folderGuid == -1)
throw new Error("Invalid folder GUID");
yield this._migrateEntries(entriesFiltered, folderGuid);
}),
// migrate the given array of safari bookmarks to the given places
// folder.
_migrateEntries: Task.async(function* (entries, parentGuid) {
for (let entry of entries) {
let type = entry.get("WebBookmarkType");
if (type == "WebBookmarkTypeList" && entry.has("Children")) {
let title = entry.get("Title");
let newFolderGuid = (yield MigrationUtils.insertBookmarkWrapper({
parentGuid, type: PlacesUtils.bookmarks.TYPE_FOLDER, title
})).guid;
// Empty folders may not have a children array.
if (entry.has("Children"))
yield this._migrateEntries(entry.get("Children"), newFolderGuid, false);
}
else if (type == "WebBookmarkTypeLeaf" && entry.has("URLString")) {
let title;
if (entry.has("URIDictionary"))
title = entry.get("URIDictionary").get("title");
try {
yield MigrationUtils.insertBookmarkWrapper({
parentGuid, url: entry.get("URLString"), title
});
} catch (ex) {
Cu.reportError("Invalid Safari bookmark: " + ex);
}
}
}
})
};
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"));
try {
places.push({ uri: NetUtil.newURI(entry.get("")),
title: entry.get("title"),
visits: [{ transitionType: transType,
visitDate: visitDate }] });
}
catch (ex) {
// Safari's History file may contain malformed URIs which
// will be ignored.
Cu.reportError(ex);
}
}
}
if (places.length > 0) {
MigrationUtils.insertVisitsWrapper(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(
new Uint8Array(bytes).buffer);
return this._dict;
}
};
function Preferences(aMainPreferencesPropertyListInstance) {
this._mainPreferencesPropertyList = aMainPreferencesPropertyListInstance;
}
Preferences.prototype = {
type: MigrationUtils.resourceTypes.SETTINGS,
migrate: function MPR_migrate(aCallback) {
this._mainPreferencesPropertyList.read(aDict => {
Task.spawn(function* () {
if (!aDict)
throw new Error("Could not read preferences file");
this._dict = aDict;
let invert = webkitVal => !webkitVal;
this._set("AutoFillPasswords", "signon.rememberSignons");
this._set("OpenNewTabsInFront", "browser.tabs.loadInBackground", invert);
this._set("WebKitJavaScriptCanOpenWindowsAutomatically",
"dom.disable_open_during_load", invert);
// layout.spellcheckDefault is a boolean stored as a number.
this._set("WebContinuousSpellCheckingEnabled",
"layout.spellcheckDefault", Number);
// Auto-load images
// Firefox has an elaborate set of Image preferences. The correlation is:
// Mode: Safari Firefox
// Blocked FALSE 2
// Allowed TRUE 1
// Allowed, originating site only -- 3
this._set("WebKitDisplayImagesKey", "permissions.default.image",
webkitVal => webkitVal ? 1 : 2);
this._migrateFontSettings();
yield this._migrateDownloadsFolder();
}.bind(this)).then(() => aCallback(true), ex => {
Cu.reportError(ex);
aCallback(false);
}).catch(Cu.reportError);
});
},
/**
* Attempts to migrates a preference from Safari. Returns whether the preference
* has been migrated.
* @param aSafariKey
* The dictionary key for the preference of Safari.
* @param aMozPref
* The gecko/firefox preference to which aSafariKey should be migrated
* @param [optional] aConvertFunction(aSafariValue)
* a function that converts the safari-preference value to the
* appropriate value for aMozPref. If it's not passed, then the
* Safari value is set as is.
* If aConvertFunction returns undefined, then aMozPref is not set
* at all.
* @return whether or not aMozPref was set.
*/
_set: function MPR_set(aSafariKey, aMozPref, aConvertFunction) {
if (this._dict.has(aSafariKey)) {
let safariVal = this._dict.get(aSafariKey);
let mozVal = aConvertFunction !== undefined ?
aConvertFunction(safariVal) : safariVal;
switch (typeof mozVal) {
case "string":
Services.prefs.setCharPref(aMozPref, mozVal);
break;
case "number":
Services.prefs.setIntPref(aMozPref, mozVal);
break;
case "boolean":
Services.prefs.setBoolPref(aMozPref, mozVal);
break;
case "undefined":
return false;
default:
throw new Error("Unexpected value type: " + (typeof mozVal));
}
}
return true;
},
// Fonts settings are quite problematic for migration, for a couple of
// reasons:
// (a) Every font preference in Gecko is set for a particular language.
// In Safari, each font preference applies to all languages.
// (b) The current underlying implementation of nsIFontEnumerator cannot
// really tell you anything about a font: no matter what language or type
// you try to enumerate with EnumerateFonts, you get an array of all
// fonts in the systems (This also breaks our fonts dialog).
// (c) In Gecko, each langauge has a distinct serif and sans-serif font
// preference. Safari has only one default font setting. It seems that
// it checks if it's a serif or sans serif font, and when a site
// explicitly asks to use serif/sans-serif font, it uses the default font
// only if it applies to this type.
// (d) The solution of guessing the lang-group out of the default charset (as
// done in the old Safari migrator) can only work when:
// (1) The default charset preference is set.
// (2) It's not a unicode charset.
// For now, we use the language implied by the system locale as the
// lang-group. The only exception is minimal font size, which is an
// accessibility preference in Safari (under the Advanced tab). If it is set,
// we set it for all languages.
// As for the font type of the default font (serif/sans-serif), the default
// type for the given language is used (set in font.default.LANGGROUP).
_migrateFontSettings: function MPR__migrateFontSettings() {
// If "Never use font sizes smaller than [ ] is set", migrate it for all
// languages.
if (this._dict.has("WebKitMinimumFontSize")) {
let minimumSize = this._dict.get("WebKitMinimumFontSize");
if (typeof minimumSize == "number") {
let prefs = Services.prefs.getChildList("font.minimum-size");
for (let pref of prefs) {
Services.prefs.setIntPref(pref, minimumSize);
}
}
else {
Cu.reportError("WebKitMinimumFontSize was set to an invalid value: " +
minimumSize);
}
}
// In theory, the lang group could be "x-unicode". This will result
// in setting the fonts for "Other Languages".
let lang = this._getLocaleLangGroup();
let anySet = false;
let fontType = Services.prefs.getCharPref("font.default." + lang);
anySet |= this._set("WebKitFixedFont", "font.name.monospace." + lang);
anySet |= this._set("WebKitDefaultFixedFontSize", "font.size.fixed." + lang);
anySet |= this._set("WebKitStandardFont",
"font.name." + fontType + "." + lang);
anySet |= this._set("WebKitDefaultFontSize", "font.size.variable." + lang);
// If we set font settings for a particular language, we'll also set the
// fonts dialog to open with the fonts settings for that langauge.
if (anySet)
Services.prefs.setCharPref("font.language.group", lang);
},
// Get the language group for the system locale.
_getLocaleLangGroup: function MPR__getLocaleLangGroup() {
let locale = Services.locale.getLocaleComponentForUserAgent();
// See nsLanguageAtomService::GetLanguageGroup
let localeLangGroup = "x-unicode";
let bundle = Services.strings.createBundle(
"resource://gre/res/langGroups.properties");
try {
localeLangGroup = bundle.GetStringFromName(locale);
}
catch (ex) {
let hyphenAt = locale.indexOf("-");
if (hyphenAt != -1) {
try {
localeLangGroup = bundle.GetStringFromName(locale.substr(0, hyphenAt));
}
catch (ex2) { }
}
}
return localeLangGroup;
},
_migrateDownloadsFolder: Task.async(function* () {
if (!this._dict.has("DownloadsPath"))
return;
let downloadsFolder = FileUtils.File(this._dict.get("DownloadsPath"));
// If the download folder is set to the Desktop or to ~/Downloads, set the
// folderList pref appropriately so that "Desktop"/Downloads is shown with
// pretty name in the preferences dialog.
let folderListVal = 2;
if (downloadsFolder.equals(FileUtils.getDir("Desk", []))) {
folderListVal = 0;
}
else {
let systemDownloadsPath = yield Downloads.getSystemDownloadsDirectory();
let systemDownloadsFolder = FileUtils.File(systemDownloadsPath);
if (downloadsFolder.equals(systemDownloadsFolder))
folderListVal = 1;
}
Services.prefs.setIntPref("browser.download.folderList", folderListVal);
Services.prefs.setComplexValue("browser.download.dir", Ci.nsILocalFile,
downloadsFolder);
}),
};
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 = recentSearchStrings.map((searchString) => (
{op: "add",
fieldname: "searchbar-history",
value: searchString}));
FormHistory.update(changes);
}
}
}.bind(this), aCallback));
}
};
// On OS X, the cookie-accept policy preference is stored in a separate
// property list.
function WebFoundationCookieBehavior(aWebFoundationFile) {
this._file = aWebFoundationFile;
}
WebFoundationCookieBehavior.prototype = {
type: MigrationUtils.resourceTypes.SETTINGS,
migrate: function WFPL_migrate(aCallback) {
PropertyListUtils.read(this._file, MigrationUtils.wrapMigrateFunction(
function migrateCookieBehavior(aDict) {
if (!aDict)
throw new Error("Could not read com.apple.WebFoundation.plist");
if (aDict.has("NSHTTPAcceptCookies")) {
// Setting Safari Firefox
// Always Accept always 0
// Accept from Originating current page 1
// Never Accept never 2
let acceptCookies = aDict.get("NSHTTPAcceptCookies");
let cookieValue = 0;
if (acceptCookies == "never") {
cookieValue = 2;
} else if (acceptCookies == "current page") {
cookieValue = 1;
}
Services.prefs.setIntPref("network.cookie.cookieBehavior",
cookieValue);
}
}.bind(this), aCallback));
}
};
function SafariProfileMigrator() {
}
SafariProfileMigrator.prototype = Object.create(MigratorPrototype);
SafariProfileMigrator.prototype.getResources = function SM_getResources() {
let profileDir = FileUtils.getDir("ULibDir", ["Safari"], false);
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 code is used on mac too, because
// Apple may fix this at some point.
pushProfileFileResource("ReadingList.plist", Bookmarks);
let prefs = this.mainPreferencesPropertyList;
if (prefs) {
resources.push(new Preferences(prefs));
resources.push(new SearchStrings(prefs));
}
let wfFile = FileUtils.getFile("UsrPrfs", ["com.apple.WebFoundation.plist"]);
if (wfFile.exists())
resources.push(new WebFoundationCookieBehavior(wfFile));
return resources;
};
SafariProfileMigrator.prototype.getLastUsedDate = function SM_getLastUsedDate() {
let profileDir = FileUtils.getDir("ULibDir", ["Safari"], false);
let datePromises = ["Bookmarks.plist", "History.plist"].map(file => {
let path = OS.Path.join(profileDir.path, file);
return OS.File.stat(path).catch(() => null).then(info => {
return info ? info.lastModificationDate : 0;
});
});
return Promise.all(datePromises).then(dates => {
return new Date(Math.max.apply(Math, dates));
});
};
Object.defineProperty(SafariProfileMigrator.prototype, "mainPreferencesPropertyList", {
get: function get_mainPreferencesPropertyList() {
if (this._mainPreferencesPropertyList === undefined) {
let file = FileUtils.getDir("UsrPrfs", [], false);
if (file.exists()) {
file.append("com.apple.Safari.plist");
if (file.exists()) {
this._mainPreferencesPropertyList =
new MainPreferencesPropertyList(file);
return this._mainPreferencesPropertyList;
}
}
this._mainPreferencesPropertyList = null;
return this._mainPreferencesPropertyList;
}
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]);

View file

@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-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/.
-->
<!DOCTYPE html [
<!ENTITY % htmlDTD PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
%htmlDTD;
<!ENTITY % netErrorDTD SYSTEM "chrome://global/locale/netError.dtd">
%netErrorDTD;
<!ENTITY % globalDTD SYSTEM "chrome://global/locale/global.dtd">
%globalDTD;
<!ENTITY % restorepageDTD SYSTEM "chrome://browser/locale/aboutSessionRestore.dtd">
%restorepageDTD;
]>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<head>
<title>&welcomeback2.tabtitle;</title>
<link rel="stylesheet" href="chrome://global/skin/in-content/info-pages.css" type="text/css" media="all"/>
<link rel="stylesheet" href="chrome://browser/skin/aboutWelcomeBack.css" type="text/css" media="all"/>
<link rel="icon" type="image/png" href="chrome://global/skin/icons/information-16.png"/>
<script type="application/javascript;version=1.8" src="chrome://browser/content/aboutSessionRestore.js"/>
</head>
<body dir="&locale.dir;">
<div class="container">
<div class="title">
<h1 class="title-text">&welcomeback2.pageTitle;</h1>
</div>
<div class="description">
<p>&welcomeback2.pageInfo1;</p>
<!-- Note a href in the anchor below is added by JS -->
<p>&welcomeback2.beforelink.pageInfo2;<a id="linkMoreTroubleshooting" target="_blank">&welcomeback2.link.pageInfo2;</a>&welcomeback2.afterlink.pageInfo2;</p>
<div>
<div class="radioRestoreContainer">
<input class="radioRestoreButton" id="radioRestoreAll" type="radio"
name="restore" checked="checked"/>
<label class="radioRestoreLabel" for="radioRestoreAll">&welcomeback2.label.restoreAll;</label>
</div>
<div class="radioRestoreContainer">
<input class="radioRestoreButton" id="radioRestoreChoose" type="radio"
name="restore"/>
<label class="radioRestoreLabel" for="radioRestoreChoose">&welcomeback2.label.restoreSome;</label>
</div>
</div>
</div>
<div class="tree-container">
<xul:tree id="tabList" flex="1" seltype="single" hidecolumnpicker="true"
onclick="onListClick(event);" onkeydown="onListKeyDown(event);"
_window_label="&restorepage.windowLabel;">
<xul:treecols>
<xul:treecol cycler="true" id="restore" type="checkbox" label="&restorepage.restoreHeader;"/>
<xul:splitter class="tree-splitter"/>
<xul:treecol primary="true" id="title" label="&restorepage.listHeader;" flex="1"/>
</xul:treecols>
<xul:treechildren flex="1"/>
</xul:tree>
</div>
<div class="button-container">
<xul:button class="primary"
id="errorTryAgain"
label="&welcomeback2.restoreButton;"
accesskey="&welcomeback2.restoreButton.access;"
oncommand="restoreSession();"/>
</div>
<input type="text" id="sessionData" style="display: none;"/>
</div>
</body>
</html>

View file

@ -0,0 +1,14 @@
# Automigration undo notification.
# %1$S will be replaced with the name of the browser we imported from, %2$S will be replaced with brandShortName
automigration.undo.message.all = Pick up where you left off. We’ve imported these sites and your bookmarks, history and passwords from %1$S into %2$S.
automigration.undo.message.bookmarks = Pick up where you left off. We’ve imported these sites and your bookmarks from %1$S into %2$S.
automigration.undo.message.bookmarks.logins = Pick up where you left off. We’ve imported these sites and your bookmarks and passwords from %1$S into %2$S.
automigration.undo.message.bookmarks.visits = Pick up where you left off. We’ve imported these sites and your bookmarks and history from %1$S into %2$S.
automigration.undo.message.logins = Pick up where you left off. We’ve imported your passwords from %1$S into %2$S.
automigration.undo.message.logins.visits = Pick up where you left off. We’ve imported these sites and your history and passwords from %1$S into %2$S.
automigration.undo.message.visits = Pick up where you left off. We’ve imported these sites and your history from %1$S into %2$S.
automigration.undo.keep2.label = OK, Got it
automigration.undo.keep2.accesskey = O
automigration.undo.dontkeep2.label = No Thanks
automigration.undo.dontkeep2.accesskey = N
automigration.undo.unknownbrowser = Unknown Browser

View file

@ -0,0 +1,549 @@
/* 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";
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
const kIMig = Ci.nsIBrowserProfileMigrator;
const kIPStartup = Ci.nsIProfileStartup;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource:///modules/MigrationUtils.jsm");
var MigrationWizard = { /* exported 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 ()
{
let os = Services.obs;
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;
let args = window.arguments;
let entryPointId = args[0] || MigrationUtils.MIGRATION_ENTRYPOINT_UNKNOWN;
Services.telemetry.getHistogramById("FX_MIGRATION_ENTRY_POINT").add(entryPointId);
this.isInitialMigration = entryPointId == MigrationUtils.MIGRATION_ENTRYPOINT_FIRSTRUN;
if (args.length > 1) {
this._source = args[1];
this._migrator = args[2] instanceof kIMig ? args[2] : null;
this._autoMigrate = args[3].QueryInterface(kIPStartup);
this._skipImportSourcePage = args[4];
if (this._migrator && args[5]) {
let sourceProfiles = this._migrator.sourceProfiles;
this._selectedProfile = sourceProfiles.find(profile => profile.id == args[5]);
}
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.
document.getElementById("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 ()
{
// Show warning message to close the selected browser when needed
function toggleCloseBrowserWarning() {
let visibility = "hidden";
if (group.selectedItem.id != "nothing") {
let migrator = MigrationUtils.getMigrator(group.selectedItem.id);
visibility = migrator.sourceLocked ? "visible" : "hidden";
}
document.getElementById("closeSourceBrowser").style.visibility = visibility;
}
this._wiz.canRewind = false;
var selectedMigrator = null;
this._availableMigrators = [];
// 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];
this._availableMigrators.push([migratorKey, migrator]);
} else {
// Hide this option
group.childNodes[i].hidden = true;
}
}
}
if (this.isInitialMigration) {
Services.telemetry.getHistogramById("FX_STARTUP_MIGRATION_BROWSER_COUNT")
.add(this._availableMigrators.length);
let defaultBrowser = MigrationUtils.getMigratorKeyForDefaultBrowser();
// This will record 0 for unknown default browser IDs.
defaultBrowser = MigrationUtils.getSourceIdForTelemetry(defaultBrowser);
Services.telemetry.getHistogramById("FX_STARTUP_MIGRATION_EXISTING_DEFAULT_BROWSER")
.add(defaultBrowser);
}
group.addEventListener("command", toggleCloseBrowserWarning);
if (selectedMigrator) {
group.selectedItem = selectedMigrator;
toggleCloseBrowserWarning();
} 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") {
// Need to do telemetry here because we're closing the dialog before we get to
// do actual migration. For actual migration, this doesn't happen until after
// migration takes place.
Services.telemetry.getHistogramById("FX_MIGRATION_SOURCE_BROWSER")
.add(MigrationUtils.getSourceIdForTelemetry("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;
}
return undefined;
},
// 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 ()
{
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");
var pageTitle, pageDesc, mainStr;
// These strings don't exist when not using official branding. If that's
// the case, just skip this page.
try {
pageTitle = brandBundle.getString("homePageMigrationPageTitle");
pageDesc = brandBundle.getString("homePageMigrationDescription");
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 appName = MigrationUtils.getBrowserName(this._source);
// 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 && appName) {
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);
},
onMigratingMigrate: function ()
{
this._migrator.migrate(this._itemsFlags, this._autoMigrate, this._selectedProfile);
Services.telemetry.getHistogramById("FX_MIGRATION_SOURCE_BROWSER")
.add(MigrationUtils.getSourceIdForTelemetry(this._source));
if (!this._autoMigrate) {
let hist = Services.telemetry.getKeyedHistogramById("FX_MIGRATION_USAGE");
let exp = 0;
let items = this._itemsFlags;
while (items) {
if (items & 1) {
hist.add(this._source, exp);
}
items = items >> 1;
exp++;
}
}
},
_listItems: function (aID)
{
var items = document.getElementById(aID);
while (items.hasChildNodes())
items.removeChild(items.firstChild);
var itemID;
for (var i = 0; i < 16; ++i) {
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)
{
var label;
switch (aTopic) {
case "Migration:Started":
break;
case "Migration:ItemBeforeMigrate":
label = document.getElementById(aData + "_migrated");
if (label)
label.setAttribute("style", "font-weight: bold");
break;
case "Migration:ItemAfterMigrate":
label = document.getElementById(aData + "_migrated");
if (label)
label.removeAttribute("style");
break;
case "Migration:Ended":
if (this.isInitialMigration) {
// Ensure errors in reporting data recency do not affect the rest of the migration.
try {
this.reportDataRecencyTelemetry();
} catch (ex) {
Cu.reportError(ex);
}
}
if (this._autoMigrate) {
let hasImportedHomepage = !!(this._newHomePage && this._newHomePage != "DEFAULT");
Services.telemetry.getKeyedHistogramById("FX_MIGRATION_IMPORTED_HOMEPAGE")
.add(this._source, hasImportedHomepage);
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":
let type = "undefined";
let numericType = parseInt(aData);
switch (numericType) {
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.");
Services.telemetry.getKeyedHistogramById("FX_MIGRATION_ERRORS")
.add(this._source, Math.log2(numericType));
break;
}
},
onDonePageShow: function ()
{
this._wiz.getButton("cancel").disabled = true;
this._wiz.canRewind = false;
this._listItems("doneItems");
},
reportDataRecencyTelemetry() {
let histogram = Services.telemetry.getKeyedHistogramById("FX_STARTUP_MIGRATION_DATA_RECENCY");
let lastUsedPromises = [];
for (let [key, migrator] of this._availableMigrators) {
// No block-scoped let in for...of loop conditions, so get the source:
let localKey = key;
lastUsedPromises.push(migrator.getLastUsedDate().then(date => {
const ONE_YEAR = 24 * 365;
let diffInHours = Math.round((Date.now() - date) / (60 * 60 * 1000));
if (diffInHours > ONE_YEAR) {
diffInHours = ONE_YEAR;
}
histogram.add(localKey, diffInHours);
return [localKey, diffInHours];
}));
}
Promise.all(lastUsedPromises).then(migratorUsedTimeDiff => {
// Sort low to high.
migratorUsedTimeDiff.sort(([keyA, diffA], [keyB, diffB]) => diffA - diffB); /* eslint no-unused-vars: off */
let usedMostRecentBrowser = migratorUsedTimeDiff.length && this._source == migratorUsedTimeDiff[0][0];
let usedRecentBrowser =
Services.telemetry.getKeyedHistogramById("FX_STARTUP_MIGRATION_USED_RECENT_BROWSER");
usedRecentBrowser.add(this._source, usedMostRecentBrowser);
});
},
};

View file

@ -0,0 +1,109 @@
<?xml version="1.0"?>
# 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/.
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<!DOCTYPE dialog SYSTEM "chrome://browser/locale/migration/migration.dtd" >
<wizard id="migrationWizard"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
windowtype="Browser:MigrationWizard"
title="&migrationWizard.title;"
onload="MigrationWizard.init()"
onunload="MigrationWizard.uninit()"
style="width: 40em;"
buttons="accept,cancel"
branded="true">
<script type="application/javascript" src="chrome://browser/content/migration/migration.js"/>
<stringbundle id="brandBundle" src="chrome://branding/locale/brand.properties"/>
<wizardpage id="importSource" pageid="importSource" next="selectProfile"
label="&importSource.title;"
onpageadvanced="return MigrationWizard.onImportSourcePageAdvanced();">
#ifdef XP_WIN
<description id="importAll" control="importSourceGroup">&importFrom.label;</description>
#else
<description id="importAll" control="importSourceGroup">&importFromUnix.label;</description>
#endif
<description id="importBookmarks" control="importSourceGroup" hidden="true">&importFromBookmarks.label;</description>
<radiogroup id="importSourceGroup" align="start">
# NB: if you add items to this list, please also assign them a unique migrator ID in MigrationUtils.jsm
<radio id="firefox" label="&importFromFirefox.label;" accesskey="&importFromFirefox.accesskey;"/>
#ifdef XP_WIN
<radio id="edge" label="&importFromEdge.label;" accesskey="&importFromEdge.accesskey;"/>
<radio id="ie" label="&importFromIE.label;" accesskey="&importFromIE.accesskey;"/>
<radio id="chrome" label="&importFromChrome.label;" accesskey="&importFromChrome.accesskey;"/>
<radio id="chromium" label="&importFromChromium.label;" accesskey="&importFromChromium.accesskey;"/>
<radio id="canary" label="&importFromCanary.label;" accesskey="&importFromCanary.accesskey;"/>
<radio id="360se" label="&importFrom360se.label;" accesskey="&importFrom360se.accesskey;"/>
#elifdef XP_MACOSX
<radio id="safari" label="&importFromSafari.label;" accesskey="&importFromSafari.accesskey;"/>
<radio id="chrome" label="&importFromChrome.label;" accesskey="&importFromChrome.accesskey;"/>
<radio id="chromium" label="&importFromChromium.label;" accesskey="&importFromChromium.accesskey;"/>
<radio id="canary" label="&importFromCanary.label;" accesskey="&importFromCanary.accesskey;"/>
#elifdef XP_UNIX
<radio id="chrome" label="&importFromChrome.label;" accesskey="&importFromChrome.accesskey;"/>
<radio id="chromium" label="&importFromChromium.label;" accesskey="&importFromChromium.accesskey;"/>
#endif
<radio id="nothing" label="&importFromNothing.label;" accesskey="&importFromNothing.accesskey;" hidden="true"/>
</radiogroup>
<label id="noSources" hidden="true">&noMigrationSources.label;</label>
<spacer flex="1"/>
<description class="header" id="closeSourceBrowser" style="visibility:hidden">&closeSourceBrowser.label;</description>
</wizardpage>
<wizardpage id="selectProfile" pageid="selectProfile" label="&selectProfile.title;"
next="importItems"
onpageshow="return MigrationWizard.onSelectProfilePageShow();"
onpagerewound="return MigrationWizard.onSelectProfilePageRewound();"
onpageadvanced="return MigrationWizard.onSelectProfilePageAdvanced();">
<description control="profiles">&selectProfile.label;</description>
<radiogroup id="profiles" align="left"/>
</wizardpage>
<wizardpage id="importItems" pageid="importItems" label="&importItems.title;"
next="homePageImport"
onpageshow="return MigrationWizard.onImportItemsPageShow();"
onpagerewound="return MigrationWizard.onImportItemsPageRewound();"
onpageadvanced="return MigrationWizard.onImportItemsPageAdvanced();"
oncommand="MigrationWizard.onImportItemCommand();">
<description control="dataSources">&importItems.label;</description>
<vbox id="dataSources" style="overflow: auto; -moz-appearance: listbox" align="left" flex="1" role="group"/>
</wizardpage>
<wizardpage id="homePageImport" pageid="homePageImport"
next="migrating"
onpageshow="return MigrationWizard.onHomePageMigrationPageShow();"
onpageadvanced="return MigrationWizard.onHomePageMigrationPageAdvanced();">
<description id="homePageImportDesc" control="homePageRadioGroup"/>
<radiogroup id="homePageRadiogroup">
<radio id="homePageSingleStart" selected="true" />
<radio id="oldHomePage" hidden="true" />
</radiogroup>
</wizardpage>
<wizardpage id="migrating" pageid="migrating" label="&migrating.title;"
next="done"
onpageshow="MigrationWizard.onMigratingPageShow();">
<description control="migratingItems">&migrating.label;</description>
<vbox id="migratingItems" style="overflow: auto;" align="left" role="group"/>
</wizardpage>
<wizardpage id="done" pageid="done" label="&done.title;"
onpageshow="MigrationWizard.onDonePageShow();">
<description control="doneItems">&done.label;</description>
<vbox id="doneItems" style="overflow: auto;" align="left" role="group"/>
</wizardpage>
</wizard>

View file

@ -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/migration/migration.xul (content/migration.xul)
content/browser/migration/migration.js (content/migration.js)
content/browser/migration/extra-migration-strings.properties (content/extra-migration-strings.properties)
content/browser/aboutWelcomeBack.xhtml (content/aboutWelcomeBack.xhtml)

View file

@ -0,0 +1,53 @@
# -*- Mode: python; 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 += [
'nsIBrowserProfileMigrator.idl',
]
XPIDL_MODULE = 'migration'
EXTRA_COMPONENTS += [
'ChromeProfileMigrator.js',
'FirefoxProfileMigrator.js',
'ProfileMigrator.js',
]
EXTRA_PP_COMPONENTS += [
'BrowserProfileMigrators.manifest',
]
EXTRA_JS_MODULES += [
'AutoMigrate.jsm',
'MigrationUtils.jsm',
]
if CONFIG['OS_ARCH'] == 'WINNT':
SOURCES += [
'nsIEHistoryEnumerator.cpp',
]
EXTRA_COMPONENTS += [
'360seProfileMigrator.js',
'EdgeProfileMigrator.js',
'IEProfileMigrator.js',
]
EXTRA_JS_MODULES += [
'ESEDBReader.jsm',
'MSMigrationUtils.jsm',
]
DEFINES['HAS_360SE_MIGRATOR'] = True
DEFINES['HAS_IE_MIGRATOR'] = True
DEFINES['HAS_EDGE_MIGRATOR'] = True
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
EXTRA_COMPONENTS += [
'SafariProfileMigrator.js',
]
DEFINES['HAS_SAFARI_MIGRATOR'] = True
FINAL_LIBRARY = 'browsercomps'

View file

@ -0,0 +1,77 @@
/* -*- 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/. */
#include "nsISupports.idl"
interface nsIArray;
interface nsIProfileStartup;
[scriptable, uuid(22b56ffc-3149-43c5-b5a9-b3a6b678de93)]
interface nsIBrowserProfileMigrator : nsISupports
{
/**
* profile items to migrate. use with migrate().
*/
const unsigned short ALL = 0x0000;
const unsigned short SETTINGS = 0x0001;
const unsigned short COOKIES = 0x0002;
const unsigned short HISTORY = 0x0004;
const unsigned short FORMDATA = 0x0008;
const unsigned short PASSWORDS = 0x0010;
const unsigned short BOOKMARKS = 0x0020;
const unsigned short OTHERDATA = 0x0040;
const unsigned short SESSION = 0x0080;
/**
* Copy user profile information to the current active profile.
* @param aItems list of data items to migrate. see above for values.
* @param aStartup helper interface which is non-null if called during startup.
* @param aProfile profile to migrate from, if there is more than one.
*/
void migrate(in unsigned short aItems, in nsIProfileStartup aStartup, in jsval aProfile);
/**
* A bit field containing profile items that this migrator
* offers for import.
* @param aProfile the profile that we are looking for available data
* to import
* @param aDoingStartup "true" if the profile is not currently being used.
* @return bit field containing profile items (see above)
* @note a return value of 0 represents no items rather than ALL.
*/
unsigned short getMigrateData(in jsval aProfile, in boolean aDoingStartup);
/**
* Get the last time data from this browser was modified
* @return a promise that resolves to a JS Date object
*/
jsval getLastUsedDate();
/**
* Whether or not there is any data that can be imported from this
* browser (i.e. whether or not it is installed, and there exists
* a user profile)
*/
readonly attribute boolean sourceExists;
/**
* An enumeration of available profiles. If the import source does
* not support profiles, this attribute is null.
*/
readonly attribute jsval sourceProfiles;
/**
* The import source homepage. Returns null if not present/available
*/
readonly attribute AUTF8String sourceHomePageURL;
/**
* Whether the source browser data is locked/in-use meaning migration likely
* won't succeed and the user should be warned.
*/
readonly attribute boolean sourceLocked;
};

View file

@ -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/. */
#include "nsIEHistoryEnumerator.h"
#include <urlhist.h>
#include <shlguid.h>
#include "nsArrayEnumerator.h"
#include "nsCOMArray.h"
#include "nsIVariant.h"
#include "nsNetUtil.h"
#include "nsStringAPI.h"
#include "nsWindowsMigrationUtils.h"
#include "prtime.h"
////////////////////////////////////////////////////////////////////////////////
//// nsIEHistoryEnumerator
NS_IMPL_ISUPPORTS(nsIEHistoryEnumerator, nsISimpleEnumerator)
nsIEHistoryEnumerator::nsIEHistoryEnumerator()
{
::CoInitialize(nullptr);
}
nsIEHistoryEnumerator::~nsIEHistoryEnumerator()
{
::CoUninitialize();
}
void
nsIEHistoryEnumerator::EnsureInitialized()
{
if (mURLEnumerator)
return;
HRESULT hr = ::CoCreateInstance(CLSID_CUrlHistory,
nullptr,
CLSCTX_INPROC_SERVER,
IID_IUrlHistoryStg2,
getter_AddRefs(mIEHistory));
if (FAILED(hr))
return;
hr = mIEHistory->EnumUrls(getter_AddRefs(mURLEnumerator));
if (FAILED(hr))
return;
}
NS_IMETHODIMP
nsIEHistoryEnumerator::HasMoreElements(bool* _retval)
{
*_retval = false;
EnsureInitialized();
MOZ_ASSERT(mURLEnumerator, "Should have instanced an IE History URLEnumerator");
if (!mURLEnumerator)
return NS_OK;
STATURL statURL;
ULONG fetched;
// First argument is not implemented, so doesn't matter what we pass.
HRESULT hr = mURLEnumerator->Next(1, &statURL, &fetched);
if (FAILED(hr) || fetched != 1UL) {
// Reached the last entry.
return NS_OK;
}
nsCOMPtr<nsIURI> uri;
if (statURL.pwcsUrl) {
nsDependentString url(statURL.pwcsUrl);
nsresult rv = NS_NewURI(getter_AddRefs(uri), url);
::CoTaskMemFree(statURL.pwcsUrl);
if (NS_FAILED(rv)) {
// Got a corrupt or invalid URI, continue to the next entry.
return HasMoreElements(_retval);
}
}
nsDependentString title(statURL.pwcsTitle ? statURL.pwcsTitle : L"");
bool lastVisitTimeIsValid;
PRTime lastVisited = WinMigrationFileTimeToPRTime(&(statURL.ftLastVisited), &lastVisitTimeIsValid);
mCachedNextEntry = do_CreateInstance("@mozilla.org/hash-property-bag;1");
MOZ_ASSERT(mCachedNextEntry, "Should have instanced a new property bag");
if (mCachedNextEntry) {
mCachedNextEntry->SetPropertyAsInterface(NS_LITERAL_STRING("uri"), uri);
mCachedNextEntry->SetPropertyAsAString(NS_LITERAL_STRING("title"), title);
if (lastVisitTimeIsValid) {
mCachedNextEntry->SetPropertyAsInt64(NS_LITERAL_STRING("time"), lastVisited);
}
*_retval = true;
}
if (statURL.pwcsTitle)
::CoTaskMemFree(statURL.pwcsTitle);
return NS_OK;
}
NS_IMETHODIMP
nsIEHistoryEnumerator::GetNext(nsISupports** _retval)
{
*_retval = nullptr;
if (!mCachedNextEntry)
return NS_ERROR_FAILURE;
NS_ADDREF(*_retval = mCachedNextEntry);
// Release the cached entry, so it can't be returned twice.
mCachedNextEntry = nullptr;
return NS_OK;
}

View file

@ -0,0 +1,37 @@
/* 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 iehistoryenumerator___h___
#define iehistoryenumerator___h___
#include <urlhist.h>
#include "mozilla/Attributes.h"
#include "nsCOMPtr.h"
#include "nsISimpleEnumerator.h"
#include "nsIWritablePropertyBag2.h"
class nsIEHistoryEnumerator final : public nsISimpleEnumerator
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISIMPLEENUMERATOR
nsIEHistoryEnumerator();
private:
~nsIEHistoryEnumerator();
/**
* Initializes the history reader, if needed.
*/
void EnsureInitialized();
RefPtr<IUrlHistoryStg2> mIEHistory;
RefPtr<IEnumSTATURL> mURLEnumerator;
nsCOMPtr<nsIWritablePropertyBag2> mCachedNextEntry;
};
#endif

View file

@ -0,0 +1,36 @@
/* 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 windowsmigrationutils__h__
#define windowsmigrationutils__h__
#include "prtime.h"
static
PRTime WinMigrationFileTimeToPRTime(FILETIME* filetime, bool* isValid)
{
SYSTEMTIME st;
*isValid = ::FileTimeToSystemTime(filetime, &st);
if (!*isValid) {
return 0;
}
PRExplodedTime prt;
prt.tm_year = st.wYear;
// SYSTEMTIME's day-of-month parameter is 1-based,
// PRExplodedTime's is 0-based.
prt.tm_month = st.wMonth - 1;
prt.tm_mday = st.wDay;
prt.tm_hour = st.wHour;
prt.tm_min = st.wMinute;
prt.tm_sec = st.wSecond;
prt.tm_usec = st.wMilliseconds * 1000;
prt.tm_wday = 0;
prt.tm_yday = 0;
prt.tm_params.tp_gmt_offset = 0;
prt.tm_params.tp_dst_offset = 0;
return PR_ImplodeTime(&prt);
}
#endif

View file

@ -0,0 +1,47 @@
# -*- Mode: python; 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/.
DIRS += [
'about',
'contextualidentity',
'customizableui',
'dirprovider',
'downloads',
'feeds',
'migration',
'newtab',
'places',
'preferences',
'privatebrowsing',
'search',
'sessionstore',
'shell',
'selfsupport',
'syncedtabs',
'translation',
]
if CONFIG['MOZ_WEBEXTENSIONS']:
DIRS += ['webextensions']
DIRS += ['build']
XPIDL_SOURCES += [
'nsIBrowserGlue.idl',
'nsIBrowserHandler.idl',
]
XPIDL_MODULE = 'browsercompsbase'
EXTRA_COMPONENTS += [
'BrowserComponents.manifest',
'nsBrowserContentHandler.js',
'nsBrowserGlue.js',
]
EXTRA_JS_MODULES += [
'distribution.js',
]

View file

@ -0,0 +1,2 @@
component {dfcd2adc-7867-4d3a-ba70-17501f208142} aboutNewTabService.js
contract @mozilla.org/browser/aboutnewtab-service;1 {dfcd2adc-7867-4d3a-ba70-17501f208142}

View file

@ -0,0 +1,242 @@
/* global
NewTabWebChannel,
NewTabPrefsProvider,
PlacesProvider,
PreviewProvider,
NewTabSearchProvider,
Preferences,
XPCOMUtils,
Task
*/
/* exported NewTabMessages */
"use strict";
const {utils: Cu} = Components;
Cu.import("resource://gre/modules/Preferences.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesProvider",
"resource:///modules/PlacesProvider.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PreviewProvider",
"resource:///modules/PreviewProvider.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",
"resource:///modules/NewTabPrefsProvider.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabSearchProvider",
"resource:///modules/NewTabSearchProvider.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabWebChannel",
"resource:///modules/NewTabWebChannel.jsm");
this.EXPORTED_SYMBOLS = ["NewTabMessages"];
const PREF_ENABLED = "browser.newtabpage.remote";
const CURRENT_ENGINE = "browser-search-engine-modified";
// Action names are from the content's perspective. in from chrome == out from content
// Maybe replace the ACTION objects by a bi-directional Map a bit later?
const ACTIONS = {
inboundActions: [
"REQUEST_PREFS",
"REQUEST_THUMB",
"REQUEST_FRECENT",
"REQUEST_UISTRINGS",
"REQUEST_SEARCH_SUGGESTIONS",
"REQUEST_MANAGE_ENGINES",
"REQUEST_SEARCH_STATE",
"REQUEST_REMOVE_FORM_HISTORY",
"REQUEST_PERFORM_SEARCH",
"REQUEST_CYCLE_ENGINE",
],
prefs: {
inPrefs: "REQUEST_PREFS",
outPrefs: "RECEIVE_PREFS",
},
preview: {
inThumb: "REQUEST_THUMB",
outThumb: "RECEIVE_THUMB",
},
links: {
inFrecent: "REQUEST_FRECENT",
outFrecent: "RECEIVE_FRECENT",
outPlacesChange: "RECEIVE_PLACES_CHANGE",
},
search: {
inSearch: {
UIStrings: "REQUEST_UISTRINGS",
suggestions: "REQUEST_SEARCH_SUGGESTIONS",
manageEngines: "REQUEST_MANAGE_ENGINES",
state: "REQUEST_SEARCH_STATE",
removeFormHistory: "REQUEST_REMOVE_FORM_HISTORY",
performSearch: "REQUEST_PERFORM_SEARCH",
cycleEngine: "REQUEST_CYCLE_ENGINE"
},
outSearch: {
UIStrings: "RECEIVE_UISTRINGS",
suggestions: "RECEIVE_SEARCH_SUGGESTIONS",
state: "RECEIVE_SEARCH_STATE",
currentEngine: "RECEIVE_CURRENT_ENGINE"
},
}
};
let NewTabMessages = {
_prefs: {},
/** NEWTAB EVENT HANDLERS **/
handleContentRequest(actionName, {data, target}) {
switch (actionName) {
case ACTIONS.prefs.inPrefs:
// Return to the originator all newtabpage prefs
let results = NewTabPrefsProvider.prefs.newtabPagePrefs;
NewTabWebChannel.send(ACTIONS.prefs.outPrefs, results, target);
break;
case ACTIONS.preview.inThumb:
// Return to the originator a preview URL
PreviewProvider.getThumbnail(data).then(imgData => {
NewTabWebChannel.send(ACTIONS.preview.outThumb, {url: data, imgData}, target);
});
break;
case ACTIONS.links.inFrecent:
// Return to the originator the top frecent links
PlacesProvider.links.getLinks().then(links => {
NewTabWebChannel.send(ACTIONS.links.outFrecent, links, target);
});
break;
case ACTIONS.search.inSearch.UIStrings:
// Return to the originator all search strings to display
let strings = NewTabSearchProvider.search.searchSuggestionUIStrings;
NewTabWebChannel.send(ACTIONS.search.outSearch.UIStrings, strings, target);
break;
case ACTIONS.search.inSearch.suggestions:
// Return to the originator all search suggestions
Task.spawn(function*() {
try {
let {engineName, searchString} = data;
let suggestions = yield NewTabSearchProvider.search.asyncGetSuggestions(engineName, searchString, target);
NewTabWebChannel.send(ACTIONS.search.outSearch.suggestions, suggestions, target);
} catch (e) {
Cu.reportError(e);
}
});
break;
case ACTIONS.search.inSearch.manageEngines:
// Open about:preferences to manage search state
NewTabSearchProvider.search.manageEngines(target.browser);
break;
case ACTIONS.search.inSearch.state:
// Return the state of the search component (i.e current engine and visible engine details)
Task.spawn(function*() {
try {
let state = yield NewTabSearchProvider.search.asyncGetState();
NewTabWebChannel.broadcast(ACTIONS.search.outSearch.state, state);
} catch (e) {
Cu.reportError(e);
}
});
break;
case ACTIONS.search.inSearch.removeFormHistory:
// Remove a form history entry from the search component
let suggestion = data;
NewTabSearchProvider.search.removeFormHistory(target, suggestion);
break;
case ACTIONS.search.inSearch.performSearch:
// Perform a search
NewTabSearchProvider.search.asyncPerformSearch(target, data).catch(Cu.reportError);
break;
case ACTIONS.search.inSearch.cycleEngine:
// Set the new current engine
NewTabSearchProvider.search.asyncCycleEngine(data).catch(Cu.reportError);
break;
}
},
/*
* Broadcast places change to all open newtab pages
*/
handlePlacesChange(type, data) {
NewTabWebChannel.broadcast(ACTIONS.links.outPlacesChange, {type, data});
},
/*
* Broadcast current engine has changed to all open newtab pages
*/
_handleCurrentEngineChange(name, value) { // jshint unused: false
let engine = value;
NewTabWebChannel.broadcast(ACTIONS.search.outSearch.currentEngine, engine);
},
/*
* Broadcast preference changes to all open newtab pages
*/
handlePrefChange(actionName, value) {
let prefChange = {};
prefChange[actionName] = value;
NewTabWebChannel.broadcast(ACTIONS.prefs.outPrefs, prefChange);
},
_handleEnabledChange(prefName, value) {
if (prefName === PREF_ENABLED) {
if (this._prefs.enabled && !value) {
this.uninit();
} else if (!this._prefs.enabled && value) {
this.init();
}
}
},
init() {
this.handleContentRequest = this.handleContentRequest.bind(this);
this._handleEnabledChange = this._handleEnabledChange.bind(this);
this._handleCurrentEngineChange = this._handleCurrentEngineChange.bind(this);
PlacesProvider.links.init();
NewTabPrefsProvider.prefs.init();
NewTabSearchProvider.search.init();
NewTabWebChannel.init();
this._prefs.enabled = Preferences.get(PREF_ENABLED, false);
if (this._prefs.enabled) {
for (let action of ACTIONS.inboundActions) {
NewTabWebChannel.on(action, this.handleContentRequest);
}
NewTabPrefsProvider.prefs.on(PREF_ENABLED, this._handleEnabledChange);
NewTabSearchProvider.search.on(CURRENT_ENGINE, this._handleCurrentEngineChange);
for (let pref of NewTabPrefsProvider.newtabPagePrefSet) {
NewTabPrefsProvider.prefs.on(pref, this.handlePrefChange);
}
PlacesProvider.links.on("deleteURI", this.handlePlacesChange);
PlacesProvider.links.on("clearHistory", this.handlePlacesChange);
PlacesProvider.links.on("linkChanged", this.handlePlacesChange);
PlacesProvider.links.on("manyLinksChanged", this.handlePlacesChange);
}
},
uninit() {
this._prefs.enabled = Preferences.get(PREF_ENABLED, false);
if (this._prefs.enabled) {
NewTabPrefsProvider.prefs.off(PREF_ENABLED, this._handleEnabledChange);
NewTabSearchProvider.search.off(CURRENT_ENGINE, this._handleCurrentEngineChange);
for (let action of ACTIONS.inboundActions) {
NewTabWebChannel.off(action, this.handleContentRequest);
}
for (let pref of NewTabPrefsProvider.newtabPagePrefSet) {
NewTabPrefsProvider.prefs.off(pref, this.handlePrefChange);
}
}
NewTabPrefsProvider.prefs.uninit();
NewTabSearchProvider.search.uninit();
NewTabWebChannel.uninit();
}
};

View file

@ -0,0 +1,114 @@
/* global Services, Preferences, EventEmitter, XPCOMUtils */
/* exported NewTabPrefsProvider */
"use strict";
this.EXPORTED_SYMBOLS = ["NewTabPrefsProvider"];
const {interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Preferences.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyGetter(this, "EventEmitter", function() {
const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {});
return EventEmitter;
});
// Supported prefs and data type
const gPrefsMap = new Map([
["browser.newtabpage.remote", "bool"],
["browser.newtabpage.remote.mode", "str"],
["browser.newtabpage.remote.version", "str"],
["browser.newtabpage.enabled", "bool"],
["browser.newtabpage.enhanced", "bool"],
["browser.newtabpage.introShown", "bool"],
["browser.newtabpage.updateIntroShown", "bool"],
["browser.newtabpage.pinned", "str"],
["browser.newtabpage.blocked", "str"],
["intl.locale.matchOS", "bool"],
["general.useragent.locale", "localized"],
["browser.search.hiddenOneOffs", "str"],
]);
// prefs that are important for the newtab page
const gNewtabPagePrefs = new Set([
"browser.newtabpage.enabled",
"browser.newtabpage.enhanced",
"browser.newtabpage.pinned",
"browser.newtabpage.blocked",
"browser.newtabpage.introShown",
"browser.newtabpage.updateIntroShown",
"browser.search.hiddenOneOffs",
]);
let PrefsProvider = function PrefsProvider() {
EventEmitter.decorate(this);
};
PrefsProvider.prototype = {
observe(subject, topic, data) { // jshint ignore:line
if (topic === "nsPref:changed") {
if (gPrefsMap.has(data)) {
switch (gPrefsMap.get(data)) {
case "bool":
this.emit(data, Preferences.get(data, false));
break;
case "str":
this.emit(data, Preferences.get(data, ""));
break;
case "localized":
try {
this.emit(data, Preferences.get(data, "", Ci.nsIPrefLocalizedString));
} catch (e) {
this.emit(data, Preferences.get(data, ""));
}
break;
default:
this.emit(data);
break;
}
}
} else {
Cu.reportError(new Error("NewTabPrefsProvider observing unknown topic"));
}
},
/*
* Return the preferences that are important to the newtab page
*/
get newtabPagePrefs() {
let results = {};
for (let pref of gNewtabPagePrefs) {
results[pref] = Preferences.get(pref, null);
}
return results;
},
get prefsMap() {
return gPrefsMap;
},
init() {
for (let pref of gPrefsMap.keys()) {
Services.prefs.addObserver(pref, this, false);
}
},
uninit() {
for (let pref of gPrefsMap.keys()) {
Services.prefs.removeObserver(pref, this, false);
}
}
};
/**
* Singleton that serves as the default new tab pref provider for the grid.
*/
const gPrefs = new PrefsProvider();
let NewTabPrefsProvider = {
prefs: gPrefs,
newtabPagePrefSet: gNewtabPagePrefs,
};

View file

@ -0,0 +1,15 @@
/* exported NewTabRemoteResources */
"use strict";
this.EXPORTED_SYMBOLS = ["NewTabRemoteResources"];
const NewTabRemoteResources = {
MODE_CHANNEL_MAP: {
production: {origin: "https://content.cdn.mozilla.net"},
staging: {origin: "https://s3_proxy_tiles.stage.mozaws.net"},
test: {origin: "https://example.com"},
test2: {origin: "http://mochi.test:8888"},
dev: {origin: "http://localhost:8888"}
}
};

View file

@ -0,0 +1,103 @@
/* global XPCOMUtils, ContentSearch, Task, Services, EventEmitter */
/* exported NewTabSearchProvider */
"use strict";
this.EXPORTED_SYMBOLS = ["NewTabSearchProvider"];
const {utils: Cu, interfaces: Ci} = Components;
const CURRENT_ENGINE = "browser-search-engine-modified";
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ContentSearch",
"resource:///modules/ContentSearch.jsm");
XPCOMUtils.defineLazyGetter(this, "EventEmitter", function() {
const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {});
return EventEmitter;
});
function SearchProvider() {
EventEmitter.decorate(this);
}
SearchProvider.prototype = {
observe(subject, topic, data) { // jshint unused:false
// all other topics are not relevant to content searches and can be
// ignored by NewTabSearchProvider
if (data === "engine-current" && topic === CURRENT_ENGINE) {
Task.spawn(function* () {
try {
let state = yield ContentSearch.currentStateObj(true);
let engine = state.currentEngine;
this.emit(CURRENT_ENGINE, engine);
} catch (e) {
Cu.reportError(e);
}
}.bind(this));
}
},
init() {
try {
Services.obs.addObserver(this, CURRENT_ENGINE, true);
} catch (e) {
Cu.reportError(e);
}
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference
]),
uninit() {
try {
Services.obs.removeObserver(this, CURRENT_ENGINE, true);
} catch (e) {
Cu.reportError(e);
}
},
get searchSuggestionUIStrings() {
return ContentSearch.searchSuggestionUIStrings;
},
removeFormHistory({browser}, suggestion) {
ContentSearch.removeFormHistoryEntry({target: browser}, suggestion);
},
manageEngines(browser) {
const browserWin = browser.ownerGlobal;
browserWin.openPreferences("paneSearch");
},
asyncGetState: Task.async(function*() {
let state = yield ContentSearch.currentStateObj(true);
return state;
}),
asyncPerformSearch: Task.async(function*({browser}, searchData) {
ContentSearch.performSearch({target: browser}, searchData);
yield ContentSearch.addFormHistoryEntry({target: browser}, searchData.searchString);
}),
asyncCycleEngine: Task.async(function*(engineName) {
Services.search.currentEngine = Services.search.getEngineByName(engineName);
let state = yield ContentSearch.currentStateObj(true);
let newEngine = state.currentEngine;
this.emit(CURRENT_ENGINE, newEngine);
}),
asyncGetSuggestions: Task.async(function*(engineName, searchString, target) {
let suggestions = ContentSearch.getSuggestions(engineName, searchString, target.browser);
return suggestions;
}),
};
const NewTabSearchProvider = {
search: new SearchProvider(),
};

View file

@ -0,0 +1,36 @@
/* 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/. */
/* globals XPCOMUtils, aboutNewTabService*/
/* exported NewTabURL */
"use strict";
const {utils: Cu} = Components;
this.EXPORTED_SYMBOLS = ["NewTabURL"];
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService",
"@mozilla.org/browser/aboutnewtab-service;1",
"nsIAboutNewTabService");
this.NewTabURL = {
get: function() {
return aboutNewTabService.newTabURL;
},
get overridden() {
return aboutNewTabService.overridden;
},
override: function(newURL) {
aboutNewTabService.newTabURL = newURL;
},
reset: function() {
aboutNewTabService.resetNewTabURL();
}
};

View file

@ -0,0 +1,299 @@
/* global
NewTabPrefsProvider,
Services,
EventEmitter,
Preferences,
XPCOMUtils,
WebChannel,
NewTabRemoteResources
*/
/* exported NewTabWebChannel */
"use strict";
this.EXPORTED_SYMBOLS = ["NewTabWebChannel"];
const {utils: Cu} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Preferences.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",
"resource:///modules/NewTabPrefsProvider.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabRemoteResources",
"resource:///modules/NewTabRemoteResources.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "WebChannel",
"resource://gre/modules/WebChannel.jsm");
XPCOMUtils.defineLazyGetter(this, "EventEmitter", function() {
const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {});
return EventEmitter;
});
const CHAN_ID = "newtab";
const PREF_ENABLED = "browser.newtabpage.remote";
const PREF_MODE = "browser.newtabpage.remote.mode";
/**
* NewTabWebChannel is the conduit for all communication with unprivileged newtab instances.
*
* It allows for the ability to broadcast to all newtab browsers.
* If the browser.newtab.remote pref is false, the object will be in an uninitialized state.
*
* Mode choices:
* 'production': pages from our production CDN
* 'staging': pages from our staging CDN
* 'test': intended for tests
* 'test2': intended for tests
* 'dev': intended for development
*
* An unknown mode will result in 'production' mode, which is the default
*
* Incoming messages are expected to be JSON-serialized and in the format:
*
* {
* type: "REQUEST_SCREENSHOT",
* data: {
* url: "https://example.com"
* }
* }
*
* Or:
*
* {
* type: "REQUEST_SCREENSHOT",
* }
*
* Outgoing messages are expected to be objects serializable by structured cloning, in a similar format:
* {
* type: "RECEIVE_SCREENSHOT",
* data: {
* "url": "https://example.com",
* "image": "dataURi:....."
* }
* }
*/
let NewTabWebChannelImpl = function NewTabWebChannelImpl() {
EventEmitter.decorate(this);
this._handlePrefChange = this._handlePrefChange.bind(this);
this._incomingMessage = this._incomingMessage.bind(this);
};
NewTabWebChannelImpl.prototype = {
_prefs: {},
_channel: null,
// a WeakMap containing browsers as keys and a weak ref to their principal
// as value
_principals: null,
// a Set containing weak refs to browsers
_browsers: null,
/*
* Returns current channel's ID
*/
get chanId() {
return CHAN_ID;
},
/*
* Returns the number of browsers currently tracking
*/
get numBrowsers() {
return this._getBrowserRefs().length;
},
/*
* Returns current channel's origin
*/
get origin() {
if (!(this._prefs.mode in NewTabRemoteResources.MODE_CHANNEL_MAP)) {
this._prefs.mode = "production";
}
return NewTabRemoteResources.MODE_CHANNEL_MAP[this._prefs.mode].origin;
},
/*
* Unloads all browsers and principals
*/
_unloadAll() {
if (this._principals != null) {
this._principals = new WeakMap();
}
this._browsers = new Set();
this.emit("targetUnloadAll");
},
/*
* Checks if a browser is known
*
* This will cause an iteration through all known browsers.
* That's ok, we don't expect a lot of browsers
*/
_isBrowserKnown(browser) {
for (let bRef of this._getBrowserRefs()) {
let b = bRef.get();
if (b && b.permanentKey === browser.permanentKey) {
return true;
}
}
return false;
},
/*
* Obtains all known browser refs
*/
_getBrowserRefs() {
// Some code may try to emit messages after teardown.
if (!this._browsers) {
return [];
}
let refs = [];
for (let bRef of this._browsers) {
/*
* even though we hold a weak ref to browser, it seems that browser
* objects aren't gc'd immediately after a tab closes. They stick around
* in memory, but thankfully they don't have a documentURI in that case
*/
let browser = bRef.get();
if (browser && browser.documentURI) {
refs.push(bRef);
} else {
// need to clean up principals because the browser object is not gc'ed
// immediately
this._principals.delete(browser);
this._browsers.delete(bRef);
this.emit("targetUnload");
}
}
return refs;
},
/*
* Receives a message from content.
*
* Keeps track of browsers for broadcast, relays messages to listeners.
*/
_incomingMessage(id, message, target) {
if (this.chanId !== id) {
Cu.reportError(new Error("NewTabWebChannel unexpected message destination"));
}
/*
* need to differentiate by browser, because event targets are created each
* time a message is sent.
*/
if (!this._isBrowserKnown(target.browser)) {
this._browsers.add(Cu.getWeakReference(target.browser));
this._principals.set(target.browser, Cu.getWeakReference(target.principal));
this.emit("targetAdd");
}
try {
let msg = JSON.parse(message);
this.emit(msg.type, {data: msg.data, target: target});
} catch (err) {
Cu.reportError(err);
}
},
/*
* Sends a message to all known browsers
*/
broadcast(actionType, message) {
for (let bRef of this._getBrowserRefs()) {
let browser = bRef.get();
try {
let principal = this._principals.get(browser).get();
if (principal && browser && browser.documentURI) {
this._channel.send({type: actionType, data: message}, {browser, principal});
}
} catch (e) {
Cu.reportError(new Error("NewTabWebChannel WeakRef is dead"));
this._principals.delete(browser);
}
}
},
/*
* Sends a message to a specific target
*/
send(actionType, message, target) {
try {
this._channel.send({type: actionType, data: message}, target);
} catch (e) {
// Web Channel might be dead
Cu.reportError(e);
}
},
/*
* Pref change observer callback
*/
_handlePrefChange(prefName, newState, forceState) { // eslint-disable-line no-unused-vars
switch (prefName) {
case PREF_ENABLED:
if (!this._prefs.enabled && newState) {
// changing state from disabled to enabled
this.setupState();
} else if (this._prefs.enabled && !newState) {
// changing state from enabled to disabled
this.tearDownState();
}
break;
case PREF_MODE:
if (this._prefs.mode !== newState) {
// changing modes
this.tearDownState();
this.setupState();
}
break;
}
},
/*
* Sets up the internal state
*/
setupState() {
this._prefs.enabled = Preferences.get(PREF_ENABLED, false);
let mode = Preferences.get(PREF_MODE, "production");
if (!(mode in NewTabRemoteResources.MODE_CHANNEL_MAP)) {
mode = "production";
}
this._prefs.mode = mode;
this._principals = new WeakMap();
this._browsers = new Set();
if (this._prefs.enabled) {
this._channel = new WebChannel(this.chanId, Services.io.newURI(this.origin, null, null));
this._channel.listen(this._incomingMessage);
}
},
tearDownState() {
if (this._channel) {
this._channel.stopListening();
}
this._prefs = {};
this._unloadAll();
this._channel = null;
this._principals = null;
this._browsers = null;
},
init() {
this.setupState();
NewTabPrefsProvider.prefs.on(PREF_ENABLED, this._handlePrefChange);
NewTabPrefsProvider.prefs.on(PREF_MODE, this._handlePrefChange);
},
uninit() {
this.tearDownState();
NewTabPrefsProvider.prefs.off(PREF_ENABLED, this._handlePrefChange);
NewTabPrefsProvider.prefs.off(PREF_MODE, this._handlePrefChange);
}
};
let NewTabWebChannel = new NewTabWebChannelImpl();

View file

@ -0,0 +1,211 @@
/* 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/. */
/* global XPCOMUtils, Services, PlacesUtils, EventEmitter */
/* global gLinks */
/* exported PlacesProvider */
"use strict";
this.EXPORTED_SYMBOLS = ["PlacesProvider"];
const {interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyGetter(this, "EventEmitter", function() {
const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {});
return EventEmitter;
});
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabUtils",
"resource://gre/modules/NewTabUtils.jsm");
// The maximum number of results PlacesProvider retrieves from history.
const HISTORY_RESULTS_LIMIT = 100;
/* Queries history to retrieve the most visited sites. Emits events when the
* history changes.
* Implements the EventEmitter interface.
*/
let Links = function Links() {
EventEmitter.decorate(this);
};
Links.prototype = {
/**
* Set this to change the maximum number of links the provider will provide.
*/
get maxNumLinks() {
// getter, so it can't be replaced dynamically
return HISTORY_RESULTS_LIMIT;
},
/**
* A set of functions called by @mozilla.org/browser/nav-historyservice
* All history events are emitted from this object.
*/
historyObserver: {
onDeleteURI: function historyObserver_onDeleteURI(aURI) {
// let observers remove sensetive data associated with deleted visit
gLinks.emit("deleteURI", {
url: aURI.spec,
});
},
onClearHistory: function historyObserver_onClearHistory() {
gLinks.emit("clearHistory");
},
onFrecencyChanged: function historyObserver_onFrecencyChanged(aURI,
aNewFrecency, aGUID, aHidden, aLastVisitDate) { // jshint ignore:line
// The implementation of the query in getLinks excludes hidden and
// unvisited pages, so it's important to exclude them here, too.
if (!aHidden && aLastVisitDate &&
NewTabUtils.linkChecker.checkLoadURI(aURI.spec)) {
gLinks.emit("linkChanged", {
url: aURI.spec,
frecency: aNewFrecency,
lastVisitDate: aLastVisitDate,
type: "history",
});
}
},
onManyFrecenciesChanged: function historyObserver_onManyFrecenciesChanged() {
// Called when frecencies are invalidated and also when clearHistory is called
// See toolkit/components/places/tests/unit/test_frecency_observers.js
gLinks.emit("manyLinksChanged");
},
onTitleChanged: function historyObserver_onTitleChanged(aURI, aNewTitle) {
if (NewTabUtils.linkChecker.checkLoadURI(aURI.spec)) {
gLinks.emit("linkChanged", {
url: aURI.spec,
title: aNewTitle
});
}
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver,
Ci.nsISupportsWeakReference])
},
/**
* Must be called before the provider is used.
* Makes it easy to disable under pref
*/
init: function PlacesProvider_init() {
try {
PlacesUtils.history.addObserver(this.historyObserver, true);
} catch (e) {
Cu.reportError(e);
}
},
/**
* Gets the current set of links delivered by this provider.
*
* @returns {Promise} Returns a promise with the array of links as payload.
*/
getLinks: Task.async(function*() {
// Select a single page per host with highest frecency, highest recency.
// Choose N top such pages. Note +rev_host, to turn off optimizer per :mak
// suggestion.
let sqlQuery = `SELECT url, title, frecency,
last_visit_date as lastVisitDate,
"history" as type
FROM moz_places
WHERE frecency in (
SELECT MAX(frecency) as frecency
FROM moz_places
WHERE hidden = 0 AND last_visit_date NOTNULL
GROUP BY +rev_host
ORDER BY frecency DESC
LIMIT :limit
)
GROUP BY rev_host HAVING MAX(lastVisitDate)
ORDER BY frecency DESC, lastVisitDate DESC, url`;
let links = yield this.executePlacesQuery(sqlQuery, {
columns: ["url", "title", "lastVisitDate", "frecency", "type"],
params: {limit: this.maxNumLinks}
});
return links.filter(link => NewTabUtils.linkChecker.checkLoadURI(link.url));
}),
/**
* Executes arbitrary query against places database
*
* @param {String} aSql
* SQL query to execute
* @param {Object} [optional] aOptions
* aOptions.columns - an array of column names. if supplied the returned
* items will consist of objects keyed on column names. Otherwise
* an array of raw values is returned in the select order
* aOptions.param - an object of SQL binding parameters
* aOptions.callback - a callback to handle query rows
*
* @returns {Promise} Returns a promise with the array of retrieved items
*/
executePlacesQuery: Task.async(function*(aSql, aOptions={}) {
let {columns, params, callback} = aOptions;
let items = [];
let queryError = null;
let conn = yield PlacesUtils.promiseDBConnection();
yield conn.executeCached(aSql, params, aRow => {
try {
// check if caller wants to handle query raws
if (callback) {
callback(aRow);
}
// otherwise fill in the item and add items array
else {
let item = null;
// if columns array is given construct an object
if (columns && Array.isArray(columns)) {
item = {};
columns.forEach(column => {
item[column] = aRow.getResultByName(column);
});
} else {
// if no columns - make an array of raw values
item = [];
for (let i = 0; i < aRow.numEntries; i++) {
item.push(aRow.getResultByIndex(i));
}
}
items.push(item);
}
} catch (e) {
queryError = e;
throw StopIteration;
}
});
if (queryError) {
throw new Error(queryError);
}
return items;
}),
};
/**
* Singleton that serves as the default link provider for the grid.
*/
const gLinks = new Links(); // jshint ignore:line
let PlacesProvider = {
links: gLinks,
};
// Kept only for backwards-compatibility
XPCOMUtils.defineLazyGetter(PlacesProvider, "LinkChecker",
() => NewTabUtils.linkChecker);

View file

@ -0,0 +1,49 @@
/* global XPCOMUtils, BackgroundPageThumbs, FileUtils, PageThumbsStorage, Task, MIMEService */
/* exported PreviewProvider */
"use strict";
this.EXPORTED_SYMBOLS = ["PreviewProvider"];
const {utils: Cu} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/PageThumbs.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
const {OS} = Cu.import("resource://gre/modules/osfile.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "BackgroundPageThumbs",
"resource://gre/modules/BackgroundPageThumbs.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "MIMEService",
"@mozilla.org/mime;1", "nsIMIMEService");
let PreviewProvider = {
/**
* Returns a thumbnail as a data URI for a url, creating it if necessary
*
* @param {String} url
* a url to obtain a thumbnail for
* @return {Promise} A Promise that resolves with a base64 encoded thumbnail
*/
getThumbnail: Task.async(function* PreviewProvider_getThumbnail(url) {
try {
yield BackgroundPageThumbs.captureIfMissing(url);
let imgPath = PageThumbsStorage.getFilePathForURL(url);
// OS.File object used to easily read off-thread
let file = yield OS.File.open(imgPath, {read: true, existing: true});
// nsIFile object needed for MIMEService
let nsFile = FileUtils.File(imgPath);
let contentType = MIMEService.getTypeFromFile(nsFile);
let bytes = yield file.read();
let encodedData = btoa(String.fromCharCode.apply(null, bytes));
file.close();
return `data:${contentType};base64,${encodedData}`;
} catch (err) {
Cu.reportError(`PreviewProvider_getThumbnail error: ${err}`);
throw err;
}
})
};

View file

@ -0,0 +1,289 @@
/*
* 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/.
*/
/* globals XPCOMUtils, NewTabPrefsProvider, Services,
Locale, UpdateUtils, NewTabRemoteResources
*/
"use strict";
const {utils: Cu, interfaces: Ci} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils",
"resource://gre/modules/UpdateUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",
"resource:///modules/NewTabPrefsProvider.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Locale",
"resource://gre/modules/Locale.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabRemoteResources",
"resource:///modules/NewTabRemoteResources.jsm");
const LOCAL_NEWTAB_URL = "chrome://browser/content/newtab/newTab.xhtml";
const REMOTE_NEWTAB_PATH = "/newtab/v%VERSION%/%CHANNEL%/%LOCALE%/index.html";
const ABOUT_URL = "about:newtab";
// Pref that tells if remote newtab is enabled
const PREF_REMOTE_ENABLED = "browser.newtabpage.remote";
// Pref branch necesssary for testing
const PREF_REMOTE_CS_TEST = "browser.newtabpage.remote.content-signing-test";
// The preference that tells whether to match the OS locale
const PREF_MATCH_OS_LOCALE = "intl.locale.matchOS";
// The preference that tells what locale the user selected
const PREF_SELECTED_LOCALE = "general.useragent.locale";
// The preference that tells what remote mode is enabled.
const PREF_REMOTE_MODE = "browser.newtabpage.remote.mode";
// The preference that tells which remote version is expected.
const PREF_REMOTE_VERSION = "browser.newtabpage.remote.version";
const VALID_CHANNELS = new Set(["esr", "release", "beta", "aurora", "nightly"]);
function AboutNewTabService() {
NewTabPrefsProvider.prefs.on(PREF_REMOTE_ENABLED, this._handleToggleEvent.bind(this));
this._updateRemoteMaybe = this._updateRemoteMaybe.bind(this);
// trigger remote change if needed, according to pref
this.toggleRemote(Services.prefs.getBoolPref(PREF_REMOTE_ENABLED));
}
/*
* A service that allows for the overriding, at runtime, of the newtab page's url.
* Additionally, the service manages pref state between a remote and local newtab page.
*
* There is tight coupling with browser/about/AboutRedirector.cpp.
*
* 1. Browser chrome access:
*
* When the user issues a command to open a new tab page, usually clicking a button
* in the browser chrome or using shortcut keys, the browser chrome code invokes the
* service to obtain the newtab URL. It then loads that URL in a new tab.
*
* When not overridden, the default URL emitted by the service is "about:newtab".
* When overridden, it returns the overriden URL.
*
* 2. Redirector Access:
*
* When the URL loaded is about:newtab, the default behavior, or when entered in the
* URL bar, the redirector is hit. The service is then called to return either of
* two URLs, a chrome or remote one, based on the browser.newtabpage.remote pref.
*
* NOTE: "about:newtab" will always result in a default newtab page, and never an overridden URL.
*
* Access patterns:
*
* The behavior is different when accessing the service via browser chrome or via redirector
* largely to maintain compatibility with expectations of add-on developers.
*
* Loading a chrome resource, or an about: URL in the redirector with either the
* LOAD_NORMAL or LOAD_REPLACE flags yield unexpected behaviors, so a roundtrip
* to the redirector from browser chrome is avoided.
*/
AboutNewTabService.prototype = {
_newTabURL: ABOUT_URL,
_remoteEnabled: false,
_remoteURL: null,
_overridden: false,
classID: Components.ID("{dfcd2adc-7867-4d3a-ba70-17501f208142}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutNewTabService]),
_xpcom_categories: [{
service: true
}],
_handleToggleEvent(prefName, stateEnabled, forceState) { // jshint unused:false
if (this.toggleRemote(stateEnabled, forceState)) {
Services.obs.notifyObservers(null, "newtab-url-changed", ABOUT_URL);
}
},
/**
* React to changes to the remote newtab pref.
*
* If browser.newtabpage.remote is true, this will change the default URL to the
* remote newtab page URL. If browser.newtabpage.remote is false, the default URL
* will be a local chrome URL.
*
* This will only act if there is a change of state and if not overridden.
*
* @returns {Boolean} Returns if there has been a state change
*
* @param {Boolean} stateEnabled remote state to set to
* @param {Boolean} forceState force state change
*/
toggleRemote(stateEnabled, forceState) {
if (!forceState && (this._overriden || stateEnabled === this._remoteEnabled)) {
// exit there is no change of state
return false;
}
let csTest = Services.prefs.getBoolPref(PREF_REMOTE_CS_TEST);
if (stateEnabled) {
if (!csTest) {
this._remoteURL = this.generateRemoteURL();
} else {
this._remoteURL = this._newTabURL;
}
NewTabPrefsProvider.prefs.on(
PREF_SELECTED_LOCALE,
this._updateRemoteMaybe);
NewTabPrefsProvider.prefs.on(
PREF_MATCH_OS_LOCALE,
this._updateRemoteMaybe);
NewTabPrefsProvider.prefs.on(
PREF_REMOTE_MODE,
this._updateRemoteMaybe);
NewTabPrefsProvider.prefs.on(
PREF_REMOTE_VERSION,
this._updateRemoteMaybe);
this._remoteEnabled = true;
} else {
NewTabPrefsProvider.prefs.off(PREF_SELECTED_LOCALE, this._updateRemoteMaybe);
NewTabPrefsProvider.prefs.off(PREF_MATCH_OS_LOCALE, this._updateRemoteMaybe);
NewTabPrefsProvider.prefs.off(PREF_REMOTE_MODE, this._updateRemoteMaybe);
NewTabPrefsProvider.prefs.off(PREF_REMOTE_VERSION, this._updateRemoteMaybe);
this._remoteEnabled = false;
}
if (!csTest) {
this._newTabURL = ABOUT_URL;
}
return true;
},
/*
* Generate a default url based on remote mode, version, locale and update channel
*/
generateRemoteURL() {
let releaseName = this.releaseFromUpdateChannel(UpdateUtils.UpdateChannel);
let path = REMOTE_NEWTAB_PATH
.replace("%VERSION%", this.remoteVersion)
.replace("%LOCALE%", Locale.getLocale())
.replace("%CHANNEL%", releaseName);
let mode = Services.prefs.getCharPref(PREF_REMOTE_MODE, "production");
if (!(mode in NewTabRemoteResources.MODE_CHANNEL_MAP)) {
mode = "production";
}
return NewTabRemoteResources.MODE_CHANNEL_MAP[mode].origin + path;
},
/*
* Returns the default URL.
*
* This URL only depends on the browser.newtabpage.remote pref. Overriding
* the newtab page has no effect on the result of this function.
*
* The result is also the remote URL if this is in a test (PREF_REMOTE_CS_TEST)
*
* @returns {String} the default newtab URL, remote or local depending on browser.newtabpage.remote
*/
get defaultURL() {
let csTest = Services.prefs.getBoolPref(PREF_REMOTE_CS_TEST);
if (this._remoteEnabled || csTest) {
return this._remoteURL;
}
return LOCAL_NEWTAB_URL;
},
/*
* Updates the remote location when the page is not overriden.
*
* Useful when there is a dependent pref change
*/
_updateRemoteMaybe() {
if (!this._remoteEnabled || this._overridden) {
return;
}
let url = this.generateRemoteURL();
if (url !== this._remoteURL) {
this._remoteURL = url;
Services.obs.notifyObservers(null, "newtab-url-changed",
this._remoteURL);
}
},
/**
* Returns the release name from an Update Channel name
*
* @returns {String} a release name based on the update channel. Defaults to nightly
*/
releaseFromUpdateChannel(channelName) {
return VALID_CHANNELS.has(channelName) ? channelName : "nightly";
},
get newTabURL() {
return this._newTabURL;
},
get remoteVersion() {
return Services.prefs.getCharPref(PREF_REMOTE_VERSION, "1");
},
get remoteReleaseName() {
return this.releaseFromUpdateChannel(UpdateUtils.UpdateChannel);
},
set newTabURL(aNewTabURL) {
let csTest = Services.prefs.getBoolPref(PREF_REMOTE_CS_TEST);
aNewTabURL = aNewTabURL.trim();
if (aNewTabURL === ABOUT_URL) {
// avoid infinite redirects in case one sets the URL to about:newtab
this.resetNewTabURL();
return;
} else if (aNewTabURL === "") {
aNewTabURL = "about:blank";
}
let remoteURL = this.generateRemoteURL();
let prefRemoteEnabled = Services.prefs.getBoolPref(PREF_REMOTE_ENABLED);
let isResetLocal = !prefRemoteEnabled && aNewTabURL === LOCAL_NEWTAB_URL;
let isResetRemote = prefRemoteEnabled && aNewTabURL === remoteURL;
if (isResetLocal || isResetRemote) {
if (this._overriden && !csTest) {
// only trigger a reset if previously overridden and this is no test
this.resetNewTabURL();
}
return;
}
// turn off remote state if needed
if (!csTest) {
this.toggleRemote(false);
} else {
// if this is a test, we want the remoteURL to be set
this._remoteURL = aNewTabURL;
}
this._newTabURL = aNewTabURL;
this._overridden = true;
Services.obs.notifyObservers(null, "newtab-url-changed", this._newTabURL);
},
get overridden() {
return this._overridden;
},
get remoteEnabled() {
return this._remoteEnabled;
},
resetNewTabURL() {
this._overridden = false;
this._newTabURL = ABOUT_URL;
this.toggleRemote(Services.prefs.getBoolPref(PREF_REMOTE_ENABLED), true);
Services.obs.notifyObservers(null, "newtab-url-changed", this._newTabURL);
}
};
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([AboutNewTabService]);

View file

@ -0,0 +1,27 @@
# -*- Mode: python; 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/.
EXTRA_JS_MODULES += [
'NewTabMessages.jsm',
'NewTabPrefsProvider.jsm',
'NewTabRemoteResources.jsm',
'NewTabSearchProvider.jsm',
'NewTabURL.jsm',
'NewTabWebChannel.jsm',
'PlacesProvider.jsm',
'PreviewProvider.jsm'
]
XPIDL_SOURCES += [
'nsIAboutNewTabService.idl',
]
XPIDL_MODULE = 'browser-newtab'
EXTRA_COMPONENTS += [
'aboutNewTabService.js',
'NewTabComponents.manifest',
]

View file

@ -0,0 +1,63 @@
/* 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"
/**
* Allows to override about:newtab to point to a different location
* than the one specified within AboutRedirector.cpp
*/
[scriptable, uuid(dfcd2adc-7867-4d3a-ba70-17501f208142)]
interface nsIAboutNewTabService : nsISupports
{
/**
* Returns the url of the resource for the newtab page if not overridden,
* otherwise a string represenation of the new URL.
*/
attribute ACString newTabURL;
/**
* Returns the default URL (remote or local depending on pref)
*/
attribute ACString defaultURL;
/**
* Returns true if the default resource got overridden.
*/
readonly attribute bool overridden;
/**
* Returns true if the default resource is remotely hosted and isn't
* overridden
*/
readonly attribute bool remoteEnabled;
/**
* Returns the version of the remote newtab page expected
*/
readonly attribute ACString remoteVersion;
/**
* Returns the expected channel for the remote the newtab page
*/
readonly attribute ACString remoteReleaseName;
/**
* Generates and returns the remote newtab page url
*/
ACString generateRemoteURL();
/**
* Returns a remote new tab release name given an update channel name
*/
ACString releaseFromUpdateChannel(in ACString channelName);
/**
* Resets to the default resource and also resets the
* overridden attribute to false.
*/
void resetNewTabURL();
};

View file

@ -0,0 +1,805 @@
/* 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/. */
/* eslint no-undef:2 */
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/AppConstants.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "LaterRun",
"resource:///modules/LaterRun.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
"resource://gre/modules/PrivateBrowsingUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "RecentWindow",
"resource:///modules/RecentWindow.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ShellService",
"resource:///modules/ShellService.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "WindowsUIUtils",
"@mozilla.org/windows-ui-utils;1", "nsIWindowsUIUtils");
const nsISupports = Components.interfaces.nsISupports;
const nsIBrowserDOMWindow = Components.interfaces.nsIBrowserDOMWindow;
const nsIBrowserHandler = Components.interfaces.nsIBrowserHandler;
const nsIBrowserHistory = Components.interfaces.nsIBrowserHistory;
const nsIChannel = Components.interfaces.nsIChannel;
const nsICommandLine = Components.interfaces.nsICommandLine;
const nsICommandLineHandler = Components.interfaces.nsICommandLineHandler;
const nsIContentHandler = Components.interfaces.nsIContentHandler;
const nsIDocShellTreeItem = Components.interfaces.nsIDocShellTreeItem;
const nsIDOMChromeWindow = Components.interfaces.nsIDOMChromeWindow;
const nsIDOMWindow = Components.interfaces.nsIDOMWindow;
const nsIFileURL = Components.interfaces.nsIFileURL;
const nsIInterfaceRequestor = Components.interfaces.nsIInterfaceRequestor;
const nsINetUtil = Components.interfaces.nsINetUtil;
const nsIPrefLocalizedString = Components.interfaces.nsIPrefLocalizedString;
const nsISupportsString = Components.interfaces.nsISupportsString;
const nsIWebNavigation = Components.interfaces.nsIWebNavigation;
const nsIWebNavigationInfo = Components.interfaces.nsIWebNavigationInfo;
const nsICommandLineValidator = Components.interfaces.nsICommandLineValidator;
const NS_BINDING_ABORTED = Components.results.NS_BINDING_ABORTED;
const NS_ERROR_WONT_HANDLE_CONTENT = 0x805d0001;
const NS_ERROR_ABORT = Components.results.NS_ERROR_ABORT;
function shouldLoadURI(aURI) {
if (aURI && !aURI.schemeIs("chrome"))
return true;
dump("*** Preventing external load of chrome: URI into browser window\n");
dump(" Use --chrome <uri> instead\n");
return false;
}
function resolveURIInternal(aCmdLine, aArgument) {
var uri = aCmdLine.resolveURI(aArgument);
var uriFixup = Services.uriFixup;
if (!(uri instanceof nsIFileURL)) {
return uriFixup.createFixupURI(aArgument,
uriFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS);
}
try {
if (uri.file.exists())
return uri;
}
catch (e) {
Components.utils.reportError(e);
}
// We have interpreted the argument as a relative file URI, but the file
// doesn't exist. Try URI fixup heuristics: see bug 290782.
try {
uri = uriFixup.createFixupURI(aArgument, 0);
}
catch (e) {
Components.utils.reportError(e);
}
return uri;
}
var gFirstWindow = false;
const OVERRIDE_NONE = 0;
const OVERRIDE_NEW_PROFILE = 1;
const OVERRIDE_NEW_MSTONE = 2;
const OVERRIDE_NEW_BUILD_ID = 3;
/**
* Determines whether a home page override is needed.
* Returns:
* OVERRIDE_NEW_PROFILE if this is the first run with a new profile.
* OVERRIDE_NEW_MSTONE if this is the first run with a build with a different
* Gecko milestone (i.e. right after an upgrade).
* OVERRIDE_NEW_BUILD_ID if this is the first run with a new build ID of the
* same Gecko milestone (i.e. after a nightly upgrade).
* OVERRIDE_NONE otherwise.
*/
function needHomepageOverride(prefb) {
var savedmstone = null;
try {
savedmstone = prefb.getCharPref("browser.startup.homepage_override.mstone");
} catch (e) {}
if (savedmstone == "ignore")
return OVERRIDE_NONE;
var mstone = Services.appinfo.platformVersion;
var savedBuildID = null;
try {
savedBuildID = prefb.getCharPref("browser.startup.homepage_override.buildID");
} catch (e) {}
var buildID = Services.appinfo.platformBuildID;
if (mstone != savedmstone) {
// Bug 462254. Previous releases had a default pref to suppress the EULA
// agreement if the platform's installer had already shown one. Now with
// about:rights we've removed the EULA stuff and default pref, but we need
// a way to make existing profiles retain the default that we removed.
if (savedmstone)
prefb.setBoolPref("browser.rights.3.shown", true);
prefb.setCharPref("browser.startup.homepage_override.mstone", mstone);
prefb.setCharPref("browser.startup.homepage_override.buildID", buildID);
return (savedmstone ? OVERRIDE_NEW_MSTONE : OVERRIDE_NEW_PROFILE);
}
if (buildID != savedBuildID) {
prefb.setCharPref("browser.startup.homepage_override.buildID", buildID);
return OVERRIDE_NEW_BUILD_ID;
}
return OVERRIDE_NONE;
}
/**
* Gets the override page for the first run after the application has been
* updated.
* @param defaultOverridePage
* The default override page.
* @return The override page.
*/
function getPostUpdateOverridePage(defaultOverridePage) {
var um = Components.classes["@mozilla.org/updates/update-manager;1"]
.getService(Components.interfaces.nsIUpdateManager);
try {
// If the updates.xml file is deleted then getUpdateAt will throw.
var update = um.getUpdateAt(0)
.QueryInterface(Components.interfaces.nsIPropertyBag);
} catch (e) {
// This should never happen.
Components.utils.reportError("Unable to find update: " + e);
return defaultOverridePage;
}
let actions = update.getProperty("actions");
// When the update doesn't specify actions fallback to the original behavior
// of displaying the default override page.
if (!actions)
return defaultOverridePage;
// The existence of silent or the non-existence of showURL in the actions both
// mean that an override page should not be displayed.
if (actions.indexOf("silent") != -1 || actions.indexOf("showURL") == -1)
return "";
return update.getProperty("openURL") || defaultOverridePage;
}
// Flag used to indicate that the arguments to openWindow can be passed directly.
const NO_EXTERNAL_URIS = 1;
function openWindow(parent, url, target, features, args, noExternalArgs) {
if (noExternalArgs == NO_EXTERNAL_URIS) {
// Just pass in the defaultArgs directly
var argstring;
if (args) {
argstring = Components.classes["@mozilla.org/supports-string;1"]
.createInstance(nsISupportsString);
argstring.data = args;
}
return Services.ww.openWindow(parent, url, target, features, argstring);
}
// Pass an array to avoid the browser "|"-splitting behavior.
var argArray = Components.classes["@mozilla.org/array;1"]
.createInstance(Components.interfaces.nsIMutableArray);
// add args to the arguments array
var stringArgs = null;
if (args instanceof Array) // array
stringArgs = args;
else if (args) // string
stringArgs = [args];
if (stringArgs) {
// put the URIs into argArray
var uriArray = Components.classes["@mozilla.org/array;1"]
.createInstance(Components.interfaces.nsIMutableArray);
stringArgs.forEach(function (uri) {
var sstring = Components.classes["@mozilla.org/supports-string;1"]
.createInstance(nsISupportsString);
sstring.data = uri;
uriArray.appendElement(sstring, /* weak = */ false);
});
argArray.appendElement(uriArray, /* weak =*/ false);
} else {
argArray.appendElement(null, /* weak =*/ false);
}
// Pass these as null to ensure that we always trigger the "single URL"
// behavior in browser.js's gBrowserInit.onLoad (which handles the window
// arguments)
argArray.appendElement(null, /* weak =*/ false); // charset
argArray.appendElement(null, /* weak =*/ false); // referer
argArray.appendElement(null, /* weak =*/ false); // postData
argArray.appendElement(null, /* weak =*/ false); // allowThirdPartyFixup
return Services.ww.openWindow(parent, url, target, features, argArray);
}
function openPreferences() {
var args = Components.classes["@mozilla.org/array;1"]
.createInstance(Components.interfaces.nsIMutableArray);
var wuri = Components.classes["@mozilla.org/supports-string;1"]
.createInstance(Components.interfaces.nsISupportsString);
wuri.data = "about:preferences";
args.appendElement(wuri, /* weak = */ false);
Services.ww.openWindow(null, gBrowserContentHandler.chromeURL,
"_blank",
"chrome,dialog=no,all",
args);
}
function logSystemBasedSearch(engine) {
var countId = (engine.identifier || ("other-" + engine.name)) + ".system";
var count = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS");
count.add(countId);
}
function doSearch(searchTerm, cmdLine) {
var engine = Services.search.defaultEngine;
logSystemBasedSearch(engine);
var submission = engine.getSubmission(searchTerm, null, "system");
// fill our nsIMutableArray with uri-as-wstring, null, null, postData
var args = Components.classes["@mozilla.org/array;1"]
.createInstance(Components.interfaces.nsIMutableArray);
var wuri = Components.classes["@mozilla.org/supports-string;1"]
.createInstance(Components.interfaces.nsISupportsString);
wuri.data = submission.uri.spec;
args.appendElement(wuri, /* weak =*/ false);
args.appendElement(null, /* weak =*/ false);
args.appendElement(null, /* weak =*/ false);
args.appendElement(submission.postData, /* weak =*/ false);
// XXXbsmedberg: use handURIToExistingBrowser to obey tabbed-browsing
// preferences, but need nsIBrowserDOMWindow extensions
return Services.ww.openWindow(null, gBrowserContentHandler.chromeURL,
"_blank",
"chrome,dialog=no,all" +
gBrowserContentHandler.getFeatures(cmdLine),
args);
}
function nsBrowserContentHandler() {
}
nsBrowserContentHandler.prototype = {
classID: Components.ID("{5d0ce354-df01-421a-83fb-7ead0990c24e}"),
_xpcom_factory: {
createInstance: function bch_factory_ci(outer, iid) {
if (outer)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return gBrowserContentHandler.QueryInterface(iid);
}
},
/* helper functions */
mChromeURL : null,
get chromeURL() {
if (this.mChromeURL) {
return this.mChromeURL;
}
this.mChromeURL = Services.prefs.getCharPref("browser.chromeURL");
return this.mChromeURL;
},
/* nsISupports */
QueryInterface : XPCOMUtils.generateQI([nsICommandLineHandler,
nsIBrowserHandler,
nsIContentHandler,
nsICommandLineValidator]),
/* nsICommandLineHandler */
handle : function bch_handle(cmdLine) {
if (cmdLine.handleFlag("browser", false)) {
// Passing defaultArgs, so use NO_EXTERNAL_URIS
openWindow(null, this.chromeURL, "_blank",
"chrome,dialog=no,all" + this.getFeatures(cmdLine),
this.defaultArgs, NO_EXTERNAL_URIS);
cmdLine.preventDefault = true;
}
// In the past, when an instance was not already running, the -remote
// option returned an error code. Any script or application invoking the
// -remote option is expected to be handling this case, otherwise they
// wouldn't be doing anything when there is no Firefox already running.
// Making the -remote option always return an error code makes those
// scripts or applications handle the situation as if Firefox was not
// already running.
if (cmdLine.handleFlag("remote", true)) {
throw NS_ERROR_ABORT;
}
var uriparam;
try {
while ((uriparam = cmdLine.handleFlagWithParam("new-window", false))) {
let uri = resolveURIInternal(cmdLine, uriparam);
if (!shouldLoadURI(uri))
continue;
openWindow(null, this.chromeURL, "_blank",
"chrome,dialog=no,all" + this.getFeatures(cmdLine),
uri.spec);
cmdLine.preventDefault = true;
}
}
catch (e) {
Components.utils.reportError(e);
}
try {
while ((uriparam = cmdLine.handleFlagWithParam("new-tab", false))) {
let uri = resolveURIInternal(cmdLine, uriparam);
handURIToExistingBrowser(uri, nsIBrowserDOMWindow.OPEN_NEWTAB, cmdLine);
cmdLine.preventDefault = true;
}
}
catch (e) {
Components.utils.reportError(e);
}
var chromeParam = cmdLine.handleFlagWithParam("chrome", false);
if (chromeParam) {
// Handle old preference dialog URLs.
if (chromeParam == "chrome://browser/content/pref/pref.xul" ||
chromeParam == "chrome://browser/content/preferences/preferences.xul") {
openPreferences();
cmdLine.preventDefault = true;
} else try {
let resolvedURI = resolveURIInternal(cmdLine, chromeParam);
let isLocal = uri => {
let localSchemes = new Set(["chrome", "file", "resource"]);
if (uri instanceof Components.interfaces.nsINestedURI) {
uri = uri.QueryInterface(Components.interfaces.nsINestedURI).innerMostURI;
}
return localSchemes.has(uri.scheme);
};
if (isLocal(resolvedURI)) {
// If the URI is local, we are sure it won't wrongly inherit chrome privs
var features = "chrome,dialog=no,all" + this.getFeatures(cmdLine);
openWindow(null, resolvedURI.spec, "_blank", features);
cmdLine.preventDefault = true;
} else {
dump("*** Preventing load of web URI as chrome\n");
dump(" If you're trying to load a webpage, do not pass --chrome.\n");
}
}
catch (e) {
Components.utils.reportError(e);
}
}
if (cmdLine.handleFlag("preferences", false)) {
openPreferences();
cmdLine.preventDefault = true;
}
if (cmdLine.handleFlag("silent", false))
cmdLine.preventDefault = true;
try {
var privateWindowParam = cmdLine.handleFlagWithParam("private-window", false);
if (privateWindowParam) {
let resolvedURI = resolveURIInternal(cmdLine, privateWindowParam);
handURIToExistingBrowser(resolvedURI, nsIBrowserDOMWindow.OPEN_NEWTAB, cmdLine, true);
cmdLine.preventDefault = true;
}
} catch (e) {
if (e.result != Components.results.NS_ERROR_INVALID_ARG) {
throw e;
}
// NS_ERROR_INVALID_ARG is thrown when flag exists, but has no param.
if (cmdLine.handleFlag("private-window", false)) {
openWindow(null, this.chromeURL, "_blank",
"chrome,dialog=no,private,all" + this.getFeatures(cmdLine),
"about:privatebrowsing");
cmdLine.preventDefault = true;
}
}
var searchParam = cmdLine.handleFlagWithParam("search", false);
if (searchParam) {
doSearch(searchParam, cmdLine);
cmdLine.preventDefault = true;
}
// The global PB Service consumes this flag, so only eat it in per-window
// PB builds.
if (cmdLine.handleFlag("private", false)) {
PrivateBrowsingUtils.enterTemporaryAutoStartMode();
}
var fileParam = cmdLine.handleFlagWithParam("file", false);
if (fileParam) {
var file = cmdLine.resolveFile(fileParam);
var fileURI = Services.io.newFileURI(file);
openWindow(null, this.chromeURL, "_blank",
"chrome,dialog=no,all" + this.getFeatures(cmdLine),
fileURI.spec);
cmdLine.preventDefault = true;
}
if (AppConstants.platform == "win") {
// Handle "? searchterm" for Windows Vista start menu integration
for (var i = cmdLine.length - 1; i >= 0; --i) {
var param = cmdLine.getArgument(i);
if (param.match(/^\? /)) {
cmdLine.removeArguments(i, i);
cmdLine.preventDefault = true;
searchParam = param.substr(2);
doSearch(searchParam, cmdLine);
}
}
}
},
get helpInfo() {
let info =
" --browser Open a browser window.\n" +
" --new-window <url> Open <url> in a new window.\n" +
" --new-tab <url> Open <url> in a new tab.\n" +
" --private-window <url> Open <url> in a new private window.\n";
if (AppConstants.platform == "win") {
info += " --preferences Open Options dialog.\n";
} else {
info += " --preferences Open Preferences dialog.\n";
}
info += " --search <term> Search <term> with your default search engine.\n";
return info;
},
/* nsIBrowserHandler */
get defaultArgs() {
var prefb = Services.prefs;
if (!gFirstWindow) {
gFirstWindow = true;
if (PrivateBrowsingUtils.isInTemporaryAutoStartMode) {
return "about:privatebrowsing";
}
}
var override;
var overridePage = "";
var additionalPage = "";
var willRestoreSession = false;
try {
// Read the old value of homepage_override.mstone before
// needHomepageOverride updates it, so that we can later add it to the
// URL if we do end up showing an overridePage. This makes it possible
// to have the overridePage's content vary depending on the version we're
// upgrading from.
let old_mstone = "unknown";
try {
old_mstone = Services.prefs.getCharPref("browser.startup.homepage_override.mstone");
} catch (ex) {}
override = needHomepageOverride(prefb);
if (override != OVERRIDE_NONE) {
switch (override) {
case OVERRIDE_NEW_PROFILE:
// New profile.
overridePage = Services.urlFormatter.formatURLPref("startup.homepage_welcome_url");
additionalPage = Services.urlFormatter.formatURLPref("startup.homepage_welcome_url.additional");
// Turn on 'later run' pages for new profiles.
LaterRun.enabled = true;
break;
case OVERRIDE_NEW_MSTONE:
// Check whether we will restore a session. If we will, we assume
// that this is an "update" session. This does not take crashes
// into account because that requires waiting for the session file
// to be read. If a crash occurs after updating, before restarting,
// we may open the startPage in addition to restoring the session.
var ss = Components.classes["@mozilla.org/browser/sessionstartup;1"]
.getService(Components.interfaces.nsISessionStartup);
willRestoreSession = ss.isAutomaticRestoreEnabled();
overridePage = Services.urlFormatter.formatURLPref("startup.homepage_override_url");
if (prefb.prefHasUserValue("app.update.postupdate"))
overridePage = getPostUpdateOverridePage(overridePage);
overridePage = overridePage.replace("%OLD_VERSION%", old_mstone);
break;
}
}
} catch (ex) {}
// formatURLPref might return "about:blank" if getting the pref fails
if (overridePage == "about:blank")
overridePage = "";
if (!additionalPage) {
additionalPage = LaterRun.getURL() || "";
}
if (additionalPage && additionalPage != "about:blank") {
if (overridePage) {
overridePage += "|" + additionalPage;
} else {
overridePage = additionalPage;
}
}
var startPage = "";
try {
var choice = prefb.getIntPref("browser.startup.page");
if (choice == 1 || choice == 3)
startPage = this.startPage;
} catch (e) {
Components.utils.reportError(e);
}
if (startPage == "about:blank")
startPage = "";
let skipStartPage = override == OVERRIDE_NEW_PROFILE &&
prefb.getBoolPref("browser.startup.firstrunSkipsHomepage");
// Only show the startPage if we're not restoring an update session and are
// not set to skip the start page on this profile
if (overridePage && startPage && !willRestoreSession && !skipStartPage)
return overridePage + "|" + startPage;
return overridePage || startPage || "about:blank" || "about:logopage";
},
get startPage() {
var uri = Services.prefs.getComplexValue("browser.startup.homepage",
nsIPrefLocalizedString).data;
if (!uri) {
Services.prefs.clearUserPref("browser.startup.homepage");
uri = Services.prefs.getComplexValue("browser.startup.homepage",
nsIPrefLocalizedString).data;
}
return uri;
},
mFeatures : null,
getFeatures : function bch_features(cmdLine) {
if (this.mFeatures === null) {
this.mFeatures = "";
try {
var width = cmdLine.handleFlagWithParam("width", false);
var height = cmdLine.handleFlagWithParam("height", false);
if (width)
this.mFeatures += ",width=" + width;
if (height)
this.mFeatures += ",height=" + height;
}
catch (e) {
}
// The global PB Service consumes this flag, so only eat it in per-window
// PB builds.
if (PrivateBrowsingUtils.isInTemporaryAutoStartMode) {
this.mFeatures = ",private";
}
}
return this.mFeatures;
},
/* nsIContentHandler */
handleContent : function bch_handleContent(contentType, context, request) {
try {
var webNavInfo = Components.classes["@mozilla.org/webnavigation-info;1"]
.getService(nsIWebNavigationInfo);
if (!webNavInfo.isTypeSupported(contentType, null)) {
throw NS_ERROR_WONT_HANDLE_CONTENT;
}
} catch (e) {
throw NS_ERROR_WONT_HANDLE_CONTENT;
}
request.QueryInterface(nsIChannel);
handURIToExistingBrowser(request.URI,
nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW, null);
request.cancel(NS_BINDING_ABORTED);
},
/* nsICommandLineValidator */
validate : function bch_validate(cmdLine) {
// Other handlers may use osint so only handle the osint flag if the url
// flag is also present and the command line is valid.
var osintFlagIdx = cmdLine.findFlag("osint", false);
var urlFlagIdx = cmdLine.findFlag("url", false);
if (urlFlagIdx > -1 && (osintFlagIdx > -1 ||
cmdLine.state == nsICommandLine.STATE_REMOTE_EXPLICIT)) {
var urlParam = cmdLine.getArgument(urlFlagIdx + 1);
if (cmdLine.length != urlFlagIdx + 2 || /firefoxurl:/.test(urlParam))
throw NS_ERROR_ABORT;
var isDefault = false;
try {
var url = Services.urlFormatter.formatURLPref("app.support.baseURL") +
"win10-default-browser";
if (urlParam == url) {
isDefault = ShellService.isDefaultBrowser(false, false);
}
} catch (ex) {}
if (isDefault) {
// Firefox is already the default HTTP handler.
// We don't have to show the instruction page.
throw NS_ERROR_ABORT;
}
cmdLine.handleFlag("osint", false)
}
},
};
var gBrowserContentHandler = new nsBrowserContentHandler();
function handURIToExistingBrowser(uri, location, cmdLine, forcePrivate)
{
if (!shouldLoadURI(uri))
return;
// Unless using a private window is forced, open external links in private
// windows only if we're in perma-private mode.
var allowPrivate = forcePrivate || PrivateBrowsingUtils.permanentPrivateBrowsing;
var navWin = RecentWindow.getMostRecentBrowserWindow({private: allowPrivate});
if (!navWin) {
// if we couldn't load it in an existing window, open a new one
var features = "chrome,dialog=no,all" + gBrowserContentHandler.getFeatures(cmdLine);
if (forcePrivate) {
features += ",private";
}
openWindow(null, gBrowserContentHandler.chromeURL, "_blank", features, uri.spec);
return;
}
var navNav = navWin.QueryInterface(nsIInterfaceRequestor)
.getInterface(nsIWebNavigation);
var rootItem = navNav.QueryInterface(nsIDocShellTreeItem).rootTreeItem;
var rootWin = rootItem.QueryInterface(nsIInterfaceRequestor)
.getInterface(nsIDOMWindow);
var bwin = rootWin.QueryInterface(nsIDOMChromeWindow).browserDOMWindow;
bwin.openURI(uri, null, location,
nsIBrowserDOMWindow.OPEN_EXTERNAL);
}
function nsDefaultCommandLineHandler() {
}
nsDefaultCommandLineHandler.prototype = {
classID: Components.ID("{47cd0651-b1be-4a0f-b5c4-10e5a573ef71}"),
/* nsISupports */
QueryInterface : function dch_QI(iid) {
if (!iid.equals(nsISupports) &&
!iid.equals(nsICommandLineHandler))
throw Components.results.NS_ERROR_NO_INTERFACE;
return this;
},
_haveProfile: false,
/* nsICommandLineHandler */
handle : function dch_handle(cmdLine) {
// The -url flag is inserted by the operating system when the default
// application handler is used. We check for default browser to remove
// instances where users explicitly decide to "open with" the browser.
// Note that users who launch firefox manually with the -url flag will
// get erroneously counted.
try {
if (cmdLine.findFlag("url", false) &&
ShellService.isDefaultBrowser(false, false)) {
Services.telemetry.getHistogramById("FX_STARTUP_EXTERNAL_CONTENT_HANDLER").add();
}
} catch (e) {}
var urilist = [];
if (AppConstants.platform == "win") {
// If we don't have a profile selected yet (e.g. the Profile Manager is
// displayed) we will crash if we open an url and then select a profile. To
// prevent this handle all url command line flags and set the command line's
// preventDefault to true to prevent the display of the ui. The initial
// command line will be retained when nsAppRunner calls LaunchChild though
// urls launched after the initial launch will be lost.
if (!this._haveProfile) {
try {
// This will throw when a profile has not been selected.
Services.dirsvc.get("ProfD", Components.interfaces.nsILocalFile);
this._haveProfile = true;
}
catch (e) {
while ((ar = cmdLine.handleFlagWithParam("url", false)));
cmdLine.preventDefault = true;
}
}
}
try {
var ar;
while ((ar = cmdLine.handleFlagWithParam("url", false))) {
var uri = resolveURIInternal(cmdLine, ar);
urilist.push(uri);
}
}
catch (e) {
Components.utils.reportError(e);
}
for (let i = 0; i < cmdLine.length; ++i) {
var curarg = cmdLine.getArgument(i);
if (curarg.match(/^-/)) {
Components.utils.reportError("Warning: unrecognized command line flag " + curarg + "\n");
// To emulate the pre-nsICommandLine behavior, we ignore
// the argument after an unrecognized flag.
++i;
} else {
try {
urilist.push(resolveURIInternal(cmdLine, curarg));
}
catch (e) {
Components.utils.reportError("Error opening URI '" + curarg + "' from the command line: " + e + "\n");
}
}
}
if (urilist.length) {
if (cmdLine.state != nsICommandLine.STATE_INITIAL_LAUNCH &&
urilist.length == 1) {
// Try to find an existing window and load our URI into the
// current tab, new tab, or new window as prefs determine.
try {
handURIToExistingBrowser(urilist[0], nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW, cmdLine);
return;
}
catch (e) {
}
}
var URLlist = urilist.filter(shouldLoadURI).map(u => u.spec);
if (URLlist.length) {
openWindow(null, gBrowserContentHandler.chromeURL, "_blank",
"chrome,dialog=no,all" + gBrowserContentHandler.getFeatures(cmdLine),
URLlist);
}
}
else if (!cmdLine.preventDefault) {
if (AppConstants.isPlatformAndVersionAtLeast("win", "10") &&
cmdLine.state != nsICommandLine.STATE_INITIAL_LAUNCH &&
WindowsUIUtils.inTabletMode) {
// In windows 10 tablet mode, do not create a new window, but reuse the existing one.
let win = RecentWindow.getMostRecentBrowserWindow();
if (win) {
win.focus();
return;
}
}
// Passing defaultArgs, so use NO_EXTERNAL_URIS
openWindow(null, gBrowserContentHandler.chromeURL, "_blank",
"chrome,dialog=no,all" + gBrowserContentHandler.getFeatures(cmdLine),
gBrowserContentHandler.defaultArgs, NO_EXTERNAL_URIS);
}
},
helpInfo : "",
};
var components = [nsBrowserContentHandler, nsDefaultCommandLineHandler];
this.NSGetFactory = XPCOMUtils.generateNSGetFactory(components);

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,37 @@
/* 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 nsIDOMWindow;
/**
* nsIBrowserGlue is a dirty and rather fluid interface to host shared utility
* methods used by browser UI code, but which are not local to a browser window.
* The component implementing this interface is meant to be a singleton
* (service) and should progressively replace some of the shared "glue" code
* scattered in browser/base/content (e.g. bits of utilOverlay.js,
* contentAreaUtils.js, globalOverlay.js, browser.js), avoiding dynamic
* inclusion and initialization of a ton of JS code for *each* window.
* Dued to its nature and origin, this interface won't probably be the most
* elegant or stable in the mozilla codebase, but its aim is rather pragmatic:
* 1) reducing the performance overhead which affects browser window load;
* 2) allow global hooks (e.g. startup and shutdown observers) which survive
* browser windows to accomplish browser-related activities, such as shutdown
* sanitization (see bug #284086)
*
*/
[scriptable, uuid(b0e7c156-d00c-4605-a77d-27c7418f23ae)]
interface nsIBrowserGlue : nsISupports
{
/**
* Deletes privacy sensitive data according to user preferences
*
* @param aParentWindow an optionally null window which is the parent of the
* sanitization dialog
*
*/
void sanitize(in nsIDOMWindow aParentWindow);
};

View file

@ -0,0 +1,20 @@
/* 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 nsICommandLine;
[scriptable, uuid(8D3F5A9D-118D-4548-A137-CF7718679069)]
interface nsIBrowserHandler : nsISupports
{
attribute AUTF8String startPage;
attribute AUTF8String defaultArgs;
/**
* Extract the width and height specified on the command line, if present.
* @return A feature string with a prepended comma, e.g. ",width=500,height=400"
*/
AUTF8String getFeatures(in nsICommandLine aCmdLine);
};

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more