Merge from mozilla-central.

This commit is contained in:
David Anderson 2012-04-04 13:40:49 -07:00
commit a007e37c01
191 changed files with 10292 additions and 1909 deletions

View File

@ -330,12 +330,14 @@ ToNSString(id aValue)
return (lineNumber >= 0) ? [NSNumber numberWithInt:lineNumber] : nil;
}
- (void)setText:(NSString*)newString
- (void)setText:(NSString*)aNewString
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
if (mGeckoEditableTextAccessible) {
mGeckoEditableTextAccessible->SetTextContents(NS_ConvertUTF8toUTF16([newString UTF8String]));
nsString text;
nsCocoaUtils::GetStringForNSString(aNewString, text);
mGeckoEditableTextAccessible->SetTextContents(text);
}
NS_OBJC_END_TRY_ABORT_BLOCK;
@ -347,12 +349,11 @@ ToNSString(id aValue)
return nil;
nsAutoString text;
nsresult rv =
mGeckoTextAccessible->GetText(0, nsIAccessibleText::TEXT_OFFSET_END_OF_TEXT,
text);
NS_ENSURE_SUCCESS(rv, nil);
nsresult rv = mGeckoTextAccessible->
GetText(0, nsIAccessibleText::TEXT_OFFSET_END_OF_TEXT, text);
NS_ENSURE_SUCCESS(rv, @"");
return text.IsEmpty() ? nil : nsCocoaUtils::ToNSString(text);
return nsCocoaUtils::ToNSString(text);
}
- (long)textLength
@ -392,7 +393,7 @@ ToNSString(id aValue)
if (start != end) {
nsAutoString selText;
mGeckoTextAccessible->GetText(start, end, selText);
return selText.IsEmpty() ? nil : [NSString stringWithCharacters:selText.BeginReading() length:selText.Length()];
return nsCocoaUtils::ToNSString(selText);
}
}
return nil;

View File

@ -1,40 +1,8 @@
#! /bin/sh
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1999
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
# 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/.
# allmakefiles.sh - List of all makefiles.
# Appends the list of makefiles to the variable, MAKEFILES.
@ -67,7 +35,6 @@ config/autoconf.mk
config/nspr/Makefile
config/doxygen.cfg
config/expandlibs_config.py
config/tests/src-simple/Makefile
mfbt/Makefile
probes/Makefile
extensions/Makefile
@ -140,6 +107,9 @@ fi
if [ "$ENABLE_TESTS" ]; then
add_makefiles "
build/autoconf/test/Makefile
config/makefiles/test/Makefile
config/tests/makefiles/autodeps/Makefile
config/tests/src-simple/Makefile
"
if [ ! "$LIBXUL_SDK" ]; then
add_makefiles "

View File

@ -127,10 +127,14 @@ else
APPFILES = MacOS
endif
libs repackage::
mkdir -p $(DIST)/$(APP_NAME).app/Contents/MacOS
libs-preqs = \
$(call mkdir_deps,$(DIST)/$(APP_NAME).app/Contents/MacOS) \
$(call mkdir_deps,$(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj) \
$(NULL)
.PHONY: repackage
libs repackage:: $(libs-preqs)
rsync -a --exclude "*.in" $(srcdir)/macbuild/Contents $(DIST)/$(APP_NAME).app --exclude English.lproj
mkdir -p $(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj
rsync -a --exclude "*.in" $(srcdir)/macbuild/Contents/Resources/English.lproj/ $(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj
sed -e "s/%MOZ_APP_VERSION%/$(MOZ_APP_VERSION)/" -e "s/%MOZ_APP_NAME%/$(MOZ_APP_NAME)/" -e "s/%APP_VERSION%/$(APP_VERSION)/" -e "s/%APP_NAME%/$(APP_NAME)/" -e "s/%APP_BINARY%/$(APP_BINARY)/" $(srcdir)/macbuild/Contents/Info.plist.in > $(DIST)/$(APP_NAME).app/Contents/Info.plist
sed -e "s/%APP_VERSION%/$(APP_VERSION)/" -e "s/%APP_NAME%/$(APP_NAME)/" $(srcdir)/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in | iconv -f UTF-8 -t UTF-16 > $(DIST)/$(APP_NAME).app/Contents/Resources/$(AB).lproj/InfoPlist.strings
@ -140,7 +144,7 @@ ifdef LIBXUL_SDK
cp $(LIBXUL_DIST)/bin/xulrunner$(BIN_SUFFIX) $(DIST)/$(APP_NAME).app/Contents/MacOS/$(APP_BINARY)
rsync -a --exclude nsinstall --copy-unsafe-links $(LIBXUL_DIST)/XUL.framework $(DIST)/$(APP_NAME).app/Contents/Frameworks
else
rm -f $(DIST)/$(APP_NAME).app/Contents/MacOS/$(PROGRAM)
$(RM) $(DIST)/$(APP_NAME).app/Contents/MacOS/$(PROGRAM)
rsync -aL $(PROGRAM) $(DIST)/$(APP_NAME).app/Contents/MacOS
endif
printf "APPLMOZB" > $(DIST)/$(APP_NAME).app/Contents/PkgInfo

View File

@ -412,11 +412,6 @@ pref("security.fileuri.strict_origin_policy", false);
// compositing isn't default disabled in widget/android.
pref("layers.acceleration.force-enabled", true);
// screen.enabled and screen.brightness properties.
pref("dom.screenEnabledProperty.enabled", true);
pref("dom.screenBrightnessProperty.enabled", true);
pref("dom.mozScreenWhitelist", "http://homescreen.gaiamobile.org,http://settings.gaiamobile.org");
// handle links targeting new windows
// 1=current window/tab, 2=new window, 3=new tab in most recent window
pref("browser.link.open_newwindow", 3);

View File

@ -285,7 +285,7 @@ var shell = {
let idleHandler = function idleHandler(subject, topic, time) {
if (topic === "idle") {
if (power.getWakeLockState("screen") != "locked-foreground") {
screen.mozEnabled = false;
navigator.mozPower.screenEnabled = false;
}
}
}
@ -298,10 +298,10 @@ var shell = {
if (topic == "screen") {
if (state != "locked-foreground") {
if (Services.idle.idleTime > idleTimeout*1000) {
screen.mozEnabled = false;
navigator.mozPower.screenEnabled = false;
}
} else {
screen.mozEnabled = true;
navigator.mozPower.screenEnabled = true;
}
}
}

View File

@ -56,6 +56,7 @@ _BROWSER_TEST_FILES = \
browser_privatebrowsing_geoprompt.js \
browser_privatebrowsing_geoprompt_page.html \
browser_privatebrowsing_import.js \
browser_privatebrowsing_lastpbcontextexited.js \
browser_privatebrowsing_localStorage.js \
browser_privatebrowsing_localStorage_page1.html \
browser_privatebrowsing_localStorage_page2.html \

View File

@ -0,0 +1,66 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Private Browsing Tests.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2012
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
function test() {
// We need to open a new window for this so that its docshell would get destroyed
// when clearing the PB mode flag.
let newWin = window.openDialog("chrome://browser/content/", "_blank", "chrome,all,dialog=no");
waitForExplicitFinish();
SimpleTest.waitForFocus(function() {
let notificationCount = 0;
let observer = {
observe: function(aSubject, aTopic, aData) {
is(aTopic, "last-pb-context-exited", "Correct topic should be dispatched");
++notificationCount;
}
};
Services.obs.addObserver(observer, "last-pb-context-exited", false);
newWin.gPrivateBrowsingUI.privateWindow = true;
SimpleTest.is(notificationCount, 0, "last-pb-context-exited should not be fired yet");
newWin.gPrivateBrowsingUI.privateWindow = false;
newWin.close();
newWin = null;
window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils)
.garbageCollect(); // Make sure that the docshell is destroyed
SimpleTest.is(notificationCount, 1, "last-pb-context-exited should be fired once");
Services.obs.removeObserver(observer, "last-pb-context-exited", false);
// cleanup
gPrefService.clearUserPref("browser.privatebrowsing.keep_current_session");
finish();
}, newWin);
}

View File

@ -82,3 +82,49 @@ if test "$GNU_CC" -a "$GCC_USE_GNU_LD" -a -n "$MOZ_DEBUG_FLAGS"; then
fi
])
dnl GCC and clang will fail if given an unknown warning option like -Wfoobar.
dnl But later versions won't fail if given an unknown negated warning option
dnl like -Wno-foobar. So when we are check for support of negated warning
dnl options, we actually test the positive form, but add the negated form to
dnl the flags variable.
AC_DEFUN([MOZ_C_SUPPORTS_WARNING],
[
AC_CACHE_CHECK(whether the C compiler supports $1$2, $3,
[
AC_LANG_SAVE
AC_LANG_C
_SAVE_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS -Werror -W$2"
AC_TRY_COMPILE([],
[return(0);],
$3="yes",
$3="no")
CFLAGS="$_SAVE_CFLAGS"
AC_LANG_RESTORE
])
if test "${$3}" = "yes"; then
_WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} $1$2"
fi
])
AC_DEFUN([MOZ_CXX_SUPPORTS_WARNING],
[
AC_CACHE_CHECK(whether the C++ compiler supports $1$2, $3,
[
AC_LANG_SAVE
AC_LANG_CPLUSPLUS
_SAVE_CXXFLAGS="$CXXFLAGS"
CXXFLAGS="$CXXFLAGS -Werror -W$2"
AC_TRY_COMPILE([],
[return(0);],
$3="yes",
$3="no")
CXXFLAGS="$_SAVE_CXXFLAGS"
AC_LANG_RESTORE
])
if test "${$3}" = "yes"; then
_WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} $1$2"
fi
])

View File

@ -199,17 +199,17 @@ class DeviceManagerSUT(DeviceManager):
if self.debug >= 1:
print "reconnecting socket"
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
except socket.error, msg:
self._sock = None
raise AgentError("unable to create socket")
raise AgentError("unable to create socket: "+str(msg))
try:
self._sock.connect((self.host, int(self.port)))
self._sock.recv(1024)
except:
except socket.error, msg:
self._sock.close()
self._sock = None
raise AgentError("unable to connect socket")
raise AgentError("unable to connect socket: "+str(msg))
for cmd in cmdlist:
if newline: cmd += '\r\n'
@ -220,9 +220,11 @@ class DeviceManagerSUT(DeviceManager):
raise AgentError("ERROR: our cmd was %s bytes and we only sent %s" % (len(cmd),
numbytes))
if (self.debug >= 4): print "send cmd: " + str(cmd)
except:
except socket.error, msg:
self._sock.close()
self._sock = None
if self.debug >= 1:
print "Error sending data to socket. cmd="+str(cmd)+"; err="+str(msg)
return False
# Check if the command should close the socket
@ -242,10 +244,10 @@ class DeviceManagerSUT(DeviceManager):
try:
temp = self._sock.recv(1024)
if (self.debug >= 4): print "response: " + str(temp)
except:
except socket.error, msg:
self._sock.close()
self._sock = None
raise AgentError("Error receiving data from socket")
raise AgentError("Error receiving data from socket. cmd="+str(cmd)+"; err="+str(msg))
data += temp

View File

@ -35,10 +35,10 @@
#
# ***** END LICENSE BLOCK *****
DEPTH = ../..
DEPTH = ../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
@ -102,8 +102,11 @@ REDIST_FILES = \
endif
ifdef REDIST_FILES
libs::
mkdir -p $(FINAL_TARGET)
libs-preqs = \
$(call mkdir_deps,$(FINAL_TARGET)) \
$(NULL)
libs:: $(libs-preqs)
install --preserve-timestamps $(foreach f,$(REDIST_FILES),"$(WIN32_REDIST_DIR)"/$(f)) $(FINAL_TARGET)
endif

View File

@ -101,7 +101,6 @@ ifeq (,$(strip $(AUTOCONF)))
AUTOCONF=$(error Could not find autoconf 2.13)
endif
MKDIR := mkdir
SH := /bin/sh
PERL ?= perl
PYTHON ?= python
@ -181,6 +180,9 @@ OBJDIR_TARGETS = install export libs clean realclean distclean alldep maybe_clob
build::
$(MAKE) -f $(TOPSRCDIR)/client.mk $(if $(MOZ_PGO),profiledbuild,realbuild)
# Define mkdir
include $(TOPSRCDIR)/config/makefiles/makeutils.mk
include $(TOPSRCDIR)/config/makefiles/autotargets.mk
# Print out any options loaded from mozconfig.
all realbuild clean depend distclean export libs install realclean::
@ -316,11 +318,13 @@ endif
configure-files: $(CONFIGURES)
configure:: configure-files
ifdef MOZ_BUILD_PROJECTS
@if test ! -d $(MOZ_OBJDIR); then $(MKDIR) $(MOZ_OBJDIR); else true; fi
endif
@if test ! -d $(OBJDIR); then $(MKDIR) $(OBJDIR); else true; fi
configure-preqs = \
configure-files \
$(call mkdir_deps,$(OBJDIR)) \
$(if $(MOZ_BUILD_PROJECTS),$(call mkdir_deps,$(MOZ_OBJDIR))) \
$(NULL)
configure:: $(configure-preqs)
@echo cd $(OBJDIR);
@echo $(CONFIGURE) $(CONFIGURE_ARGS)
@cd $(OBJDIR) && $(BUILD_PROJECT_ARG) $(CONFIGURE_ENV_ARGS) $(CONFIGURE) $(CONFIGURE_ARGS) \

View File

@ -7,6 +7,9 @@ NSS_DIRS = (('dbm', 'mozilla/dbm'),
('security/dbm', 'mozilla/security/dbm'))
NSSCKBI_DIRS = (('security/nss/lib/ckfw/builtins', 'mozilla/security/nss/lib/ckfw/builtins'),)
LIBFFI_DIRS = (('js/ctypes/libffi', 'libffi'),)
WEBIDLPARSER_DIR = 'dom/bindings/parser'
WEBIDLPARSER_REPO = 'https://hg.mozilla.org/users/khuey_mozilla.com/webidl-parser'
WEBIDLPARSER_EXCLUSIONS = ['.hgignore', '.gitignore', '.hg', 'ply']
CVSROOT_MOZILLA = ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot'
CVSROOT_LIBFFI = ':pserver:anoncvs@sources.redhat.com:/cvs/libffi'
@ -15,6 +18,7 @@ import os
import sys
import datetime
import shutil
import glob
from optparse import OptionParser
from subprocess import check_call
@ -30,7 +34,6 @@ def do_hg_pull(dir, repository, hg):
fulldir = os.path.join(topsrcdir, dir)
# clone if the dir doesn't exist, pull if it does
if not os.path.exists(fulldir):
fulldir = os.path.join(topsrcdir, dir)
check_call_noisy([hg, 'clone', repository, fulldir])
else:
cmd = [hg, 'pull', '-u', '-R', fulldir]
@ -40,6 +43,25 @@ def do_hg_pull(dir, repository, hg):
check_call([hg, 'parent', '-R', fulldir,
'--template=Updated to revision {node}.\n'])
def do_hg_replace(dir, repository, tag, exclusions, hg):
"""
Replace the contents of dir with the contents of repository, except for
files matching exclusions.
"""
fulldir = os.path.join(topsrcdir, dir)
if os.path.exists(fulldir):
shutil.rmtree(fulldir)
assert not os.path.exists(fulldir)
check_call_noisy([hg, 'clone', '-u', tag, repository, fulldir])
for thing in exclusions:
for excluded in glob.iglob(os.path.join(fulldir, thing)):
if os.path.isdir(excluded):
shutil.rmtree(excluded)
else:
os.remove(excluded)
def do_cvs_export(modules, tag, cvsroot, cvs):
"""Check out a CVS directory without CVS metadata, using "export"
modules is a list of directories to check out and the corresponding
@ -60,7 +82,7 @@ def do_cvs_export(modules, tag, cvsroot, cvs):
cwd=os.path.join(topsrcdir, parent))
print "CVS export end: " + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
o = OptionParser(usage="client.py [options] update_nspr tagname | update_nss tagname | update_libffi tagname")
o = OptionParser(usage="client.py [options] update_nspr tagname | update_nss tagname | update_libffi tagname | update_webidlparser tagname")
o.add_option("--skip-mozilla", dest="skip_mozilla",
action="store_true", default=False,
help="Obsolete")
@ -69,6 +91,8 @@ o.add_option("--cvs", dest="cvs", default=os.environ.get('CVS', 'cvs'),
help="The location of the cvs binary")
o.add_option("--cvsroot", dest="cvsroot",
help="The CVSROOT (default for mozilla checkouts: %s)" % CVSROOT_MOZILLA)
o.add_option("--hg", dest="hg", default=os.environ.get('HG', 'hg'),
help="The location of the hg binary")
try:
options, args = o.parse_args()
@ -104,6 +128,9 @@ elif action in ('update_libffi'):
if not options.cvsroot:
options.cvsroot = CVSROOT_LIBFFI
do_cvs_export(LIBFFI_DIRS, tag, options.cvsroot, options.cvs)
elif action in ('update_webidlparser'):
tag, = args[1:]
do_hg_replace(WEBIDLPARSER_DIR, WEBIDLPARSER_REPO, tag, WEBIDLPARSER_EXCLUSIONS, options.hg)
else:
o.print_help()
sys.exit(2)

View File

@ -1,3 +1,4 @@
# -*- Makefile -*-
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
@ -117,8 +118,11 @@ else
endif
ifdef WRAP_SYSTEM_INCLUDES
export::
if test ! -d system_wrappers; then mkdir system_wrappers; fi
export-preqs = \
$(call mkdir_deps,system_wrappers) \
$(NULL)
export:: $(export-preqs)
$(PYTHON) $(topsrcdir)/config/Preprocessor.py $(DEFINES) $(ACDEFINES) \
-DMOZ_TREE_CAIRO=$(MOZ_TREE_CAIRO) \
-DMOZ_TREE_PIXMAN=$(MOZ_TREE_PIXMAN) \
@ -190,7 +194,13 @@ PYUNITS := \
unit-writemozinfo.py \
$(NULL)
check:: check-python-modules check-jar-mn
check-preqs = \
check-python-modules \
check-jar-mn \
check-makefiles \
$(NULL)
check:: $(check-preqs)
check-python-modules::
@$(EXIT_ON_ERROR) \
@ -205,3 +215,6 @@ check-jar-mn::
ifneq (,$(filter-out WINNT OS2,$(OS_ARCH)))
$(MAKE) -C tests/src-simple check-symlink
endif
check-makefiles:
$(MAKE) -C tests/makefiles/autodeps check

View File

@ -46,7 +46,7 @@
# Define an include-at-most-once flag
ifdef INCLUDED_CONFIG_MK
$(error Don't include config.mk twice!)
$(error Do not include config.mk twice!)
endif
INCLUDED_CONFIG_MK = 1

View File

@ -0,0 +1,45 @@
# -*- makefile -*-
# vim:set ts=8 sw=8 sts=8 noet:
#
# 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/.
#
###########################################################################
# AUTO_DEPS - A list of deps/targets drived from other macros.
# *_DEPS - Make dependencies derived from a given macro.
###########################################################################
MKDIR ?= mkdir -p
TOUCH ?= touch
###########################################################################
# Threadsafe directory creation
# GENERATED_DIRS - Automated creation of these directories.
###########################################################################
mkdir_deps =$(foreach dir,$(getargv),$(dir)/.mkdir.done)
ifneq (,$(GENERATED_DIRS))
tmpauto :=$(call mkdir_deps,GENERATED_DIRS)
GENERATED_DIRS_DEPS +=$(tmpauto)
GARBAGE_DIRS +=$(tmpauto)
endif
%/.mkdir.done:
$(subst $(SPACE)-p,$(null),$(MKDIR)) -p $(dir $@)
@$(TOUCH) $@
#################################################################
# One ring/dep to rule them all:
# config/rules.mk::all target is available by default
# Add $(AUTO_DEPS) as an explicit target dependency when needed.
#################################################################
AUTO_DEPS +=$(GENERATED_DIRS_DEPS)
# Complain loudly if deps have not loaded so getargv != $(NULL)
ifndef getargv
$(error config/makefiles/makeutil.mk has not been included)
endif

View File

@ -0,0 +1,36 @@
# -*- makefile -*-
# vim:set ts=8 sw=8 sts=8 noet:
#
# 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/.
# Usage: $(call banner,foo bar tans)
banner =\
$(info )\
$(info ***************************************************************************)\
$(info ** BANNER: $(1) $(2) $(3) $(4) $(5) $(6) $(7) $(8) $(9))\
$(info ***************************************************************************)\
## Identify function argument types
istype =$(if $(value ${1}),list,scalar)
isval =$(if $(filter-out list,$(call istype,${1})),true)
isvar =$(if $(filter-out scalar,$(call istype,${1})),true)
# Access up to 9 arguments passed, option needed to emulate $*
# Inline for function expansion, do not use $(call )
argv =$(strip
argv +=$(if $(1), $(1))$(if $(2), $(2))$(if $(3), $(3))$(if $(4), $(4))
argv +=$(if $(5), $(5))$(if $(6), $(6))$(if $(7), $(7))$(if $(8), $(8))
argv +=$(if $(9), $(9))
argv +=$(if $(10), $(error makeutils.mk::argv can only handle 9 arguments))
argv +=)
###########################################################################
## Access function args as a simple list, inline within user functions.
## Usage: $(info ** $(call banner,$(getargv)))
## $(call banner,scalar)
## $(call banner,list0 list1 list2)
## $(call banner,ref) ; ref=foo bar tans
## getarglist() would be a more accurate name but is longer to type
getargv = $(if $(call isvar,$(1)),$($(1)),$(argv))

View File

@ -0,0 +1,95 @@
# -*- makefile -*-
#
# 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/.
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
include $(topsrcdir)/config/makefiles/makeutils.mk
##------------------_##
##---] TARGETS [---##
##------------------_##
all::
###########################################################################
## This test target should really depend on a timestamp to only perform
## work when makeutils.mk is modified. That answer would require using a
## 2nd makefile imposing more shell overhead. Separate makefiles would be
## very handy for testing when pwd==$src/ but for now avoid the overhead.
##
## Test logic will be interpreted at compile time, 'fast' and 'required' so
## the test will always be run when testing is enabled.
###########################################################################
check::
@true
## Logic processed at compile time so be selective about when to test
ifneq ($(NULL),$(findstring check,$(MAKECMDGOALS)))
$(info ===========================================================================)
$(info Running test: $(MAKECMDGOALS): pwd=$(CURDIR))
$(info ===========================================================================)
## Silent errors are oh so much fun
ifndef istype
$(error makeutils.mk was not included)
endif
# arg_scalar = [scalar|literal]
arg_list = foo bar
arg_ref = arg_list
## Identify type of function argument(s)
########################################
ifneq (scalar,$(call istype,arg_scalar))
$(error istype(arg_scalar)=scalar, found [$(call istype,arg_scalar)])
endif
ifneq (list,$(call istype,arg_list))
$(error istype(arg_list)=list, found [$(call istype,arg_list)])
endif
ifneq (list,$(call istype,arg_ref))
$(error istype(arg_ref)=list, found [$(call istype,arg_ref)])
endif
## Type == scalar or a list of values
#####################################
ifneq (true,$(call isval,scalar))
$(error isval(scalar)=true, found [$(call isval,scalar)])
endif
ifneq ($(NULL),$(call isval,arg_list))
$(error isval(arg_list)=null, found [$(call isval,arg_list)])
endif
## type == reference: macro=>macro => $($(1))
#############################################
ifneq ($(NULL),$(call isvar,scalar))
$(error isvar(scalar)=$(NULL), found [$(call isvar,scalar)])
endif
ifneq (true,$(call isvar,arg_list))
$(error isvar(arg_list)=true, found [$(call isvar,arg_list)])
endif
ifneq (true,$(call isvar,arg_ref))
$(error isvar(arg_ref)=true, found [$(call isvar,arg_ref)])
endif
# Verify getargv expansion
##########################
ifneq (scalar,$(call getargv,scalar))
$(error getargv(scalar)=scalar, found [$(call getargv,scalar)])
endif
ifneq ($(arg_list),$(call getargv,arg_list))
$(error getargv(arg_list)=list, found [$(call getargv,arg_list)])
endif
ifneq (arg_list,$(call getargv,arg_ref))
$(error getargv(arg_ref)=list, found [$(call getargv,arg_ref)])
endif
endif # check in MAKECMDGOALS

View File

@ -1,45 +1,10 @@
# -*- makefile -*-
# vim:set ts=8 sw=8 sts=8 noet:
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Chase Phillips <chase@mozilla.org>
# Benjamin Smedberg <benjamin@smedbergs.us>
# Jeff Walden <jwalden+code@mit.edu>
# Joey Armstrong <joey@mozilla.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either of the GNU General Public License Version 2 or later (the "GPL"),
# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
ifndef topsrcdir
$(error topsrcdir was not set))
@ -57,6 +22,9 @@ ifndef INCLUDED_VERSION_MK
include $(topsrcdir)/config/version.mk
endif
include $(topsrcdir)/config/makefiles/makeutils.mk
include $(topsrcdir)/config/makefiles/autotargets.mk
ifdef SDK_XPIDLSRCS
XPIDLSRCS += $(SDK_XPIDLSRCS)
endif
@ -512,8 +480,8 @@ endif
# A Makefile that needs $(MDDEPDIR) created but doesn't set any of these
# variables we know to check can just set NEED_MDDEPDIR explicitly.
ifneq (,$(OBJS)$(XPIDLSRCS)$(SIMPLE_PROGRAMS)$(NEED_MDDEPDIR))
MAKE_DIRS += $(CURDIR)/$(MDDEPDIR)
GARBAGE_DIRS += $(MDDEPDIR)
MAKE_DIRS += $(CURDIR)/$(MDDEPDIR)
GARBAGE_DIRS += $(CURDIR)/$(MDDEPDIR)
endif
#
@ -1461,12 +1429,6 @@ endif
# generate .h files from into $(XPIDL_GEN_DIR), then export to $(DIST)/include;
# warn against overriding existing .h file.
$(XPIDL_GEN_DIR)/.done:
$(MKDIR) -p $(XPIDL_GEN_DIR)
@$(TOUCH) $@
# don't depend on $(XPIDL_GEN_DIR), because the modification date changes
# with any addition to the directory, regenerating all .h files -> everything.
XPIDL_DEPS = \
$(topsrcdir)/xpcom/idl-parser/header.py \
@ -1474,7 +1436,12 @@ XPIDL_DEPS = \
$(topsrcdir)/xpcom/idl-parser/xpidl.py \
$(NULL)
$(XPIDL_GEN_DIR)/%.h: %.idl $(XPIDL_DEPS) $(XPIDL_GEN_DIR)/.done
xpidl-preqs = \
$(call mkdir_deps,$(XPIDL_GEN_DIR)) \
$(call mkdir_deps,$(MDDEPDIR)) \
$(NULL)
$(XPIDL_GEN_DIR)/%.h: %.idl $(XPIDL_DEPS) $(xpidl-preqs)
$(REPORT_BUILD)
$(PYTHON_PATH) \
-I$(topsrcdir)/other-licenses/ply \
@ -1486,7 +1453,7 @@ $(XPIDL_GEN_DIR)/%.h: %.idl $(XPIDL_DEPS) $(XPIDL_GEN_DIR)/.done
ifndef NO_GEN_XPT
# generate intermediate .xpt files into $(XPIDL_GEN_DIR), then link
# into $(XPIDL_MODULE).xpt and export it to $(FINAL_TARGET)/components.
$(XPIDL_GEN_DIR)/%.xpt: %.idl $(XPIDL_DEPS) $(XPIDL_GEN_DIR)/.done
$(XPIDL_GEN_DIR)/%.xpt: %.idl $(XPIDL_DEPS) $(xpidl-preqs)
$(REPORT_BUILD)
$(PYTHON_PATH) \
-I$(topsrcdir)/other-licenses/ply \
@ -2028,8 +1995,18 @@ $(foreach var,$(FREEZE_VARIABLES),$(eval $(var)_FROZEN := '$($(var))'))
CHECK_FROZEN_VARIABLES = $(foreach var,$(FREEZE_VARIABLES), \
$(if $(subst $($(var)_FROZEN),,'$($(var))'),$(error Makefile variable '$(var)' changed value after including rules.mk. Was $($(var)_FROZEN), now $($(var)).)))
libs export libs::
libs export::
$(CHECK_FROZEN_VARIABLES)
default all::
if test -d $(DIST)/bin ; then touch $(DIST)/bin/.purgecaches ; fi
#############################################################################
# Derived targets and dependencies
include $(topsrcdir)/config/makefiles/autotargets.mk
ifneq ($(NULL),$(AUTO_DEPS))
default all libs tools export:: $(AUTO_DEPS)
endif

2035
config/rules.mk.orig Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
# -*- makefile -*-
#
# 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/.
#
PYTHON ?= python
PYTEST = $(PYTHON) -E
# python -B not supported by older interpreters
export PYTHONDONTWRITEBYTECODE=1
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk
autotgt_tests = .deps/autotargets.mk.ts
tgts =\
.deps/.mkdir.done\
$(autotgt_tests)
$(NULL)
##------------------_##
##---] TARGETS [---##
##------------------_##
all::
check:: $(tgts)
# Only run unit test when autotargets.mk is modified
$(autotgt_tests): $(topsrcdir)/config/makefiles/autotargets.mk
MAKECMD=$(MAKE) $(PYTEST) $(srcdir)/check_mkdir.tpy
@$(TOUCH) $@

View File

@ -0,0 +1,271 @@
#!/usr/bin/env 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/.
#
import os
import sys
import tempfile
from subprocess import call
from shutil import rmtree
import logging
import unittest
def banner():
"""
Display interpreter and system info for the test env
"""
print '*' * 75
cmd = os.path.basename(__file__)
print "%s: python version is %s" % (cmd, sys.version)
print '*' * 75
def myopts(vals):
"""
Storage for extra command line args passed.
Returns:
hash - argparse::Namespace object values
"""
if not hasattr(myopts, 'vals'):
if 'argparse' in sys.modules:
tmp = { } # key existance enables unittest module debug
else:
tmp = { 'debug': False, 'verbose': False }
for k in dir(vals):
if k[0:1] == '_':
continue
tmp[k] = getattr(vals, k)
myopts.vals = tmp
return myopts.vals
def path2posix(src):
"""
Normalize directory path syntax
Keyword arguments:
src - path to normalize
Returns:
scalar - a file path with drive separators and windows slashes removed
Todo:
move to {build,config,tools,toolkit}/python for use in a library
"""
## (drive, tail) = os.path.splitdrive(src)
## Support path testing on all platforms
drive = ''
winpath = src.find(':')
if -1 != winpath and 10 > winpath:
(drive, tail) = src.split(':', 2)
if drive:
todo = [ '', drive.rstrip(':').lstrip('/').lstrip('\\') ]
todo.extend( tail.lstrip('/').lstrip('\\').split('\\') ) # c:\a => [a]
else: # os.name == 'posix'
todo = src.split('\\')
dst = '/'.join(todo)
return dst
def checkMkdir(work, debug=False):
"""
Verify arg permutations for directory mutex creation.
Keyword arguments:
None
Returns:
Exception on error
Note:
Exception() rather than self.assertTrue() is used in this test
function to enable scatch cleanup on test exit/failure conditions.
Not guaranteed by python closures on early exit.
"""
logging.debug("Testing: checkMkdir")
if False:
path = os.path.abspath(__file__).split(os.sep)
else:
path = path2posix(os.path.abspath(__file__)).split('/')
root = os.path.join(os.sep, *path[:-5])
src = os.path.join(os.sep, *path[:-1])
rootP = path2posix(root)
srcP = path2posix(src)
workP = path2posix(work)
# C:\foo -vs- /c/foo
# [0] command paths use /c/foo
# [1] os.path.exists() on mingw() requires C:\
paths = [
[ # function generated
"%s/mkdir_bycall" % (workP),
"%s/mkdir_bycall" % (work),
],
[ # explicit dependency
"%s/mkdir_bydep" % (workP),
"%s/mkdir_bydep" % (work),
],
[ # by GENERATED_DIRS macro
"%s/mkdir_bygen" % (workP),
"%s/mkdir_bygen" % (work),
]
]
## Use make from the parent "make check" call when available
cmd = { 'make': 'make' }
shell0 = os.environ.get('MAKECMD')
if shell0:
shell = os.path.splitext(shell0)[0] # strip: .exe, .py
if -1 != shell.find('make'):
print "MAKE COMMAND FOUND: %s" % (shell0)
cmd['make'] = path2posix(shell0)
args = []
args.append('%s' % (cmd['make']))
args.append('-C %s' % (workP))
args.append("-f %s/testor.tmpl" % (srcP))
args.append('topsrcdir=%s' % (rootP))
args.append('deps_mkdir_bycall=%s' % paths[0][0])
args.append('deps_mkdir_bydep=%s' % paths[1][0])
args.append('deps_mkdir_bygen=%s' % paths[2][0])
args.append('checkup') # target
# Call will fail on mingw with output redirected ?!?
if debug:
pass
if False: # if not debug:
args.append('>/dev/null')
cmd = '%s' % (' '.join(args))
logging.debug("Running: %s" % (cmd))
rc = call(cmd, shell=True)
if rc:
raise Exception("make failed ($?=%s): cmd=%s" % (rc, cmd))
for i in paths:
logging.debug("Did testing mkdir(%s) succeed?" % (i[1]))
if not os.path.exists(i[1]):
raise Exception("Test path %s does not exist" % (i[1]))
def parseargs():
"""
Support additional command line arguments for testing
Returns:
hash - arguments of interested parsed from the command line
"""
opts = None
try:
import argparse2
parser = argparse.ArgumentParser()
parser.add_argument('--debug',
action="store_true",
default=False,
help='Enable debug mode')
# Cannot overload verbose, Verbose: False enables debugging
parser.add_argument('--verbose',
action="store_true",
default=False,
help='Enable verbose mode')
parser.add_argument('unittest_args',
nargs='*'
# help='Slurp/pass remaining args to unittest'
)
opts = parser.parse_args()
except ImportError:
pass
return opts
class TestMakeLogic(unittest.TestCase):
"""
Test suite used to validate makefile library rules and macros
"""
def setUp(self):
opts = myopts(None) # NameSpace object not hash
self.debug = opts['debug']
self.verbose = opts['verbose']
if self.debug:
logging.basicConfig(level=logging.DEBUG)
if self.verbose:
print
print "ENVIRONMENT DUMP:"
print '=' * 75
for k,v in os.environ.items():
print "env{%s} => %s" % (k, v)
print
def test_path2posix(self):
todo = {
'/dev/null' : '/dev/null',
'A:\\a\\b\\c' : '/A/a/b/c',
'B:/x/y' : '/B/x/y',
'C:/x\\y/z' : '/C/x/y/z',
'//FOO/bar/tans': '//FOO/bar/tans',
'//X\\a/b\\c/d' : '//X/a/b/c/d',
'\\c:mozilla\\sandbox': '/c/mozilla/sandbox',
}
for val,exp in todo.items():
found = path2posix(val)
tst = "posix2path(%s): %s != %s)" % (val, exp, found)
self.assertEqual(exp, found, "%s: invalid path detected" % (tst))
def test_mkdir(self):
"""
Verify directory creation rules and macros
"""
failed = True
# Exception handling is used to cleanup scratch space on error
try:
work = tempfile.mkdtemp()
checkMkdir(work, self.debug)
failed = False
finally:
if os.path.exists(work):
rmtree(work)
self.assertFalse(failed, "Unit test failure detected")
if __name__ == '__main__':
banner()
opts = parseargs()
myopts(opts)
if opts:
if hasattr(opts, 'unittest_args'):
sys.argv[1:] = opts.unittest_args
else:
sys.argv[1:] = []
unittest.main()

View File

@ -0,0 +1,63 @@
# -*- makefile -*-
#
# 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/.
#
###########################################################################
## Intent: Standalone unit tests for makefile rules and target logic
###########################################################################
deps =$(NULL)
tgts =$(NULL)
ifdef VERBOSE
tgts += show
endif
# Define macros
include $(topsrcdir)/config/makefiles/makeutils.mk
include $(topsrcdir)/config/makefiles/autotargets.mk
##########################
## Verify threadsafe mkdir
##########################
ifdef deps_mkdir_bycall
deps += $(call mkdir_deps,deps_mkdir_bycall)
tgts += check_mkdir
endif
ifdef deps_mkdir_bydep
deps += $(foreach dir,$(deps_mkdir_bydep),$(dir)/.mkdir.done)
tgts += check_mkdir
endif
ifdef deps_mkdir_bygen
GENERATED_DIRS += $(deps_mkdir_bygen)
tgts += check_mkdir
endif
###########################
## Minimal environment load
###########################
MKDIR ?= mkdir -p
TOUCH ?= touch
INCLUDED_CONFIG_MK = 1
include $(topsrcdir)/config/rules.mk
##-------------------##
##---] TARGETS [---##
##-------------------##
all::
# Quarks:
# o Use of 'all' would trigger export target processing
checkup: $(tgts)
# AUTO_DEPS - verify GENERATED_DIRS
check_mkdir: $(deps) $(AUTO_DEPS)
show:
@echo "tgts=[$(tgts)]"
@echo "deps=[$(deps)]"
find $(dir $(deps)) -print

View File

@ -1707,15 +1707,27 @@ if test "$GNU_CC"; then
_MOZ_RTTI_FLAGS_ON=-frtti
_MOZ_RTTI_FLAGS_OFF=-fno-rtti
# Turn on GNU specific features
# -Wall - turn on all warnings
# -pedantic - make compiler warn about non-ANSI stuff, and
# be a little bit stricter
# Turn on GNU-specific warnings:
# -Wall - turn on a lot of warnings
# -pedantic - this is turned on below
# -Wpointer-arith - enabled with -pedantic, but good to have even if not
# -Wdeclaration-after-statement - MSVC doesn't like these
# Warnings slamm took out for now (these were giving more noise than help):
# -Wbad-function-cast - warns when casting a function to a new return type
# -Wshadow - removed because it generates more noise than help --pete
_WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -W -Wno-unused -Wpointer-arith -Wdeclaration-after-statement"
# -Werror=return-type - catches missing returns, zero false positives
# -Wtype-limits - catches overflow bugs, few false positives
# -Wempty-body - catches bugs, e.g. "if (c); foo();", few false positives
#
_WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wall -Wpointer-arith -Wdeclaration-after-statement"
MOZ_C_SUPPORTS_WARNING(-W, error=return-type, ac_c_has_werror_return_type)
MOZ_C_SUPPORTS_WARNING(-W, type-limits, ac_c_has_wtype_limits)
MOZ_C_SUPPORTS_WARNING(-W, empty-body, ac_c_has_wempty_body)
# Turn off the following warnings that -Wall/-pedantic turn on:
# -Wno-unused - lots of violations in third-party code
# -Wno-overlength-strings - we exceed the minimum maximum length frequently
#
_WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -Wno-unused"
MOZ_C_SUPPORTS_WARNING(-Wno-, overlength-strings, ac_c_has_wno_overlength_strings)
if test -z "$INTEL_CC" -a -z "$CLANG_CC"; then
# Don't use -Wcast-align with ICC or clang
case "$CPU_ARCH" in
@ -1731,12 +1743,9 @@ if test "$GNU_CC"; then
dnl Turn pedantic on but disable the warnings for long long
_PEDANTIC=1
if test -z "$INTEL_CC"; then
_WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} -W"
fi
_DEFINES_CFLAGS='-include $(DEPTH)/mozilla-config.h -DMOZILLA_CLIENT'
_USE_CPP_INCLUDE_FLAG=1
elif test "$SOLARIS_SUNPRO_CC"; then
DSO_CFLAGS=''
if test "$CPU_ARCH" = "sparc"; then
@ -1764,8 +1773,32 @@ fi
if test "$GNU_CXX"; then
# FIXME: Let us build with strict aliasing. bug 414641.
CXXFLAGS="$CXXFLAGS -fno-exceptions -fno-strict-aliasing"
# Turn on GNU specific features
_WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wall -Wpointer-arith -Woverloaded-virtual -Wsynth -Wno-ctor-dtor-privacy -Wno-non-virtual-dtor"
# Turn on GNU-specific warnings:
# -Wall - turn on a lot of warnings
# -pedantic - this is turned on below
# -Wpointer-arith - enabled with -pedantic, but good to have even if not
# -Woverloaded-virtual - ???
# -Werror=return-type - catches missing returns, zero false positives
# -Wtype-limits - catches overflow bugs, few false positives
# -Wempty-body - catches bugs, e.g. "if (c); foo();", few false positives
#
_WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wall -Wpointer-arith -Woverloaded-virtual"
MOZ_CXX_SUPPORTS_WARNING(-W, error=return-type, ac_cxx_has_werror_return_type)
MOZ_CXX_SUPPORTS_WARNING(-W, type-limits, ac_cxx_has_wtype_limits)
MOZ_CXX_SUPPORTS_WARNING(-W, empty-body, ac_cxx_has_wempty_body)
# Turn off the following warnings that -Wall/-pedantic turn on:
# -Wno-ctor-dtor-privacy - ???
# -Wno-overlength-strings - we exceed the minimum maximum length frequently
# -Wno-invalid-offsetof - we use offsetof on non-POD types frequently
# -Wno-variadic-macros - ???
#
_WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-ctor-dtor-privacy"
MOZ_CXX_SUPPORTS_WARNING(-Wno-, overlength-strings, ac_cxx_has_wno_overlength_strings)
MOZ_CXX_SUPPORTS_WARNING(-Wno-, invalid-offsetof, ac_cxx_has_wno_invalid_offsetof)
MOZ_CXX_SUPPORTS_WARNING(-Wno-, variadic-macros, ac_cxx_has_wno_variadic_macros)
if test -z "$INTEL_CXX" -a -z "$CLANG_CXX"; then
# Don't use -Wcast-align with ICC or clang
case "$CPU_ARCH" in
@ -1789,81 +1822,7 @@ if test "$GNU_CXX"; then
# deleted function syntax.
if test "$CLANG_CXX"; then
_WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-c++0x-extensions"
fi
AC_CACHE_CHECK(whether the compiler supports -Wno-extended-offsetof,
ac_has_wno_extended_offsetof,
[
AC_LANG_SAVE
AC_LANG_CPLUSPLUS
_SAVE_CXXFLAGS="$CXXFLAGS"
CXXFLAGS="$CXXFLAGS -Wno-extended-offsetof"
AC_TRY_COMPILE([$configure_static_assert_macros
#ifndef __has_warning
#define __has_warning(x) 0
#endif],
[CONFIGURE_STATIC_ASSERT(__has_warning("-Wextended-offsetof"))],
ac_has_wno_extended_offsetof="yes",
ac_has_wno_extended_offsetof="no")
CXXFLAGS="$_SAVE_CXXFLAGS"
AC_LANG_RESTORE
])
if test "$ac_has_wno_extended_offsetof" = "yes"; then
_WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-extended-offsetof"
fi
AC_CACHE_CHECK(whether the compiler supports -Wno-invalid-offsetof,
ac_has_wno_invalid_offsetof,
[
AC_LANG_SAVE
AC_LANG_CPLUSPLUS
_SAVE_CXXFLAGS="$CXXFLAGS"
CXXFLAGS="$CXXFLAGS -Wno-invalid-offsetof"
AC_TRY_COMPILE([],
[return(0);],
ac_has_wno_invalid_offsetof="yes",
ac_has_wno_invalid_offsetof="no")
CXXFLAGS="$_SAVE_CXXFLAGS"
AC_LANG_RESTORE
])
if test "$ac_has_wno_invalid_offsetof" = "yes"; then
_WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-invalid-offsetof"
fi
AC_CACHE_CHECK(whether the compiler supports -Wno-variadic-macros,
ac_has_wno_variadic_macros,
[
AC_LANG_SAVE
AC_LANG_CPLUSPLUS
_SAVE_CXXFLAGS="$CXXFLAGS"
CXXFLAGS="$CXXFLAGS -Wno-variadic-macros"
AC_TRY_COMPILE([],
[return(0);],
ac_has_wno_variadic_macros="yes",
ac_has_wno_variadic_macros="no")
CXXFLAGS="$_SAVE_CXXFLAGS"
AC_LANG_RESTORE
])
if test "$ac_has_wno_variadic_macros" = "yes"; then
_WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-variadic-macros"
fi
AC_CACHE_CHECK(whether the compiler supports -Werror=return-type,
ac_has_werror_return_type,
[
AC_LANG_SAVE
AC_LANG_CPLUSPLUS
_SAVE_CXXFLAGS="$CXXFLAGS"
CXXFLAGS="$CXXFLAGS -Werror=return-type"
AC_TRY_COMPILE([],
[return(0);],
ac_has_werror_return_type="yes",
ac_has_werror_return_type="no")
CXXFLAGS="$_SAVE_CXXFLAGS"
AC_LANG_RESTORE
])
if test "$ac_has_werror_return_type" = "yes"; then
_WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Werror=return-type"
MOZ_CXX_SUPPORTS_WARNING(-Wno-, extended-offsetof, ac_cxx_has_wno_extended_offsetof)
fi
else

View File

@ -145,12 +145,35 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsMutationReceiver)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsMutationReceiver)
tmp->Disconnect();
tmp->Disconnect(false);
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsMutationReceiver)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
void
nsMutationReceiver::Disconnect(bool aRemoveFromObserver)
{
if (mRegisterTarget) {
mRegisterTarget->RemoveMutationObserver(this);
mRegisterTarget = nsnull;
}
mParent = nsnull;
nsINode* target = mTarget;
mTarget = nsnull;
nsIDOMMozMutationObserver* observer = mObserver;
mObserver = nsnull;
RemoveClones();
if (target && observer) {
if (aRemoveFromObserver) {
static_cast<nsDOMMutationObserver*>(observer)->RemoveReceiver(this);
}
// UnbindObject may delete 'this'!
target->UnbindObject(observer);
}
}
void
nsMutationReceiver::AttributeWillChange(nsIDocument* aDocument,
@ -382,7 +405,7 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMMutationObserver)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mScriptContext)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOwner)
for (PRInt32 i = 0; i < tmp->mReceivers.Count(); ++i) {
tmp->mReceivers[i]->Disconnect();
tmp->mReceivers[i]->Disconnect(false);
}
tmp->mReceivers.Clear();
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMARRAY(mPendingMutations)
@ -420,6 +443,12 @@ nsDOMMutationObserver::GetReceiverFor(nsINode* aNode, bool aMayCreate)
return r;
}
void
nsDOMMutationObserver::RemoveReceiver(nsMutationReceiver* aReceiver)
{
mReceivers.RemoveObject(aReceiver);
}
void
nsDOMMutationObserver::GetAllSubtreeObserversFor(nsINode* aNode,
nsTArray<nsMutationReceiver*>&
@ -527,6 +556,14 @@ nsDOMMutationObserver::Observe(nsIDOMNode* aTarget,
r->SetAttributeFilter(filters);
r->SetAllAttributes(allAttrs);
r->RemoveClones();
#ifdef DEBUG
for (PRInt32 i = 0; i < mReceivers.Count(); ++i) {
NS_WARN_IF_FALSE(mReceivers[i]->Target(),
"All the receivers should have a target!");
}
#endif
return NS_OK;
}
@ -534,7 +571,7 @@ NS_IMETHODIMP
nsDOMMutationObserver::Disconnect()
{
for (PRInt32 i = 0; i < mReceivers.Count(); ++i) {
mReceivers[i]->Disconnect();
mReceivers[i]->Disconnect(false);
}
mReceivers.Clear();
mCurrentMutations.Clear();
@ -837,8 +874,10 @@ nsAutoMutationBatch::Done()
m->mAddedNodes = addedList;
m->mPreviousSibling = mPrevSibling;
m->mNextSibling = mNextSibling;
ob->ScheduleForRun();
}
// Always schedule the observer so that transient receivers are
// removed correctly.
ob->ScheduleForRun();
}
nsDOMMutationObserver::LeaveMutationHandling();
}

View File

@ -151,7 +151,8 @@ protected:
nsMutationReceiverBase(nsINode* aRegisterTarget,
nsMutationReceiverBase* aParent)
: mObserver(nsnull), mParent(aParent), mRegisterTarget(aRegisterTarget)
: mTarget(nsnull), mObserver(nsnull), mParent(aParent),
mRegisterTarget(aRegisterTarget)
{
NS_ASSERTION(mParent->Subtree(), "Should clone a non-subtree observer!");
mRegisterTarget->AddMutationObserver(this);
@ -228,7 +229,7 @@ public:
aParent->AddClone(this);
}
virtual ~nsMutationReceiver() { Disconnect(); }
virtual ~nsMutationReceiver() { Disconnect(false); }
nsMutationReceiver* GetParent()
{
@ -240,12 +241,12 @@ public:
for (PRInt32 i = 0; i < mTransientReceivers.Count(); ++i) {
nsMutationReceiver* r =
static_cast<nsMutationReceiver*>(mTransientReceivers[i]);
r->Disconnect();
r->DisconnectTransientReceiver();
}
mTransientReceivers.Clear();
}
void DisconnectTransientReceivers()
void DisconnectTransientReceiver()
{
if (mRegisterTarget) {
mRegisterTarget->RemoveMutationObserver(this);
@ -253,23 +254,11 @@ public:
}
mParent = nsnull;
NS_ASSERTION(!mTarget, "Should not have mTarget");
NS_ASSERTION(!mObserver, "Should not have mObserver");
}
void Disconnect()
{
if (mRegisterTarget) {
mRegisterTarget->RemoveMutationObserver(this);
mRegisterTarget = nsnull;
}
if (mTarget && mObserver) {
mTarget->UnbindObject(mObserver);
}
mParent = nsnull;
mTarget = nsnull;
mObserver = nsnull;
RemoveClones();
}
void Disconnect(bool aRemoveFromObserver);
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IMUTATION_OBSERVER_IID)
NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
@ -300,7 +289,8 @@ public:
virtual void NodeWillBeDestroyed(const nsINode *aNode)
{
Disconnect();
NS_ASSERTION(!mParent, "Shouldn't have mParent here!");
Disconnect(true);
}
};
@ -347,6 +337,8 @@ protected:
friend class nsMutationReceiver;
friend class nsAutoMutationBatch;
nsMutationReceiver* GetReceiverFor(nsINode* aNode, bool aMayCreate);
void RemoveReceiver(nsMutationReceiver* aReceiver);
void GetAllSubtreeObserversFor(nsINode* aNode,
nsTArray<nsMutationReceiver*>& aObservers);
void ScheduleForRun();

View File

@ -61,24 +61,11 @@ nsScriptElement::ScriptAvailable(nsresult aResult,
nsCOMPtr<nsIContent> cont =
do_QueryInterface((nsIScriptElement*) this);
nsRefPtr<nsPresContext> presContext =
nsContentUtils::GetContextForContent(cont);
nsEventStatus status = nsEventStatus_eIgnore;
nsScriptErrorEvent event(true, NS_LOAD_ERROR);
event.lineNr = aLineNo;
NS_NAMED_LITERAL_STRING(errorString, "Error loading script");
event.errorMsg = errorString.get();
nsCAutoString spec;
aURI->GetSpec(spec);
NS_ConvertUTF8toUTF16 fileName(spec);
event.fileName = fileName.get();
nsEventDispatcher::Dispatch(cont, presContext, &event, nsnull, &status);
return nsContentUtils::DispatchTrustedEvent(cont->OwnerDoc(),
cont,
NS_LITERAL_STRING("error"),
false /* bubbles */,
false /* cancelable */);
}
return NS_OK;

View File

@ -286,6 +286,7 @@ _TEST_FILES1 = \
file_XHRDocURI.text^headers^ \
test_DOMException.html \
test_mutationobservers.html \
mutationobserver_dialog.html \
$(NULL)
_TEST_FILES2 = \
@ -575,6 +576,7 @@ _TEST_FILES2 = \
file_bug650386_content.sjs \
file_bug650386_report.sjs \
test_bug719533.html \
test_bug737087.html \
$(NULL)
_CHROME_FILES = \

View File

@ -0,0 +1,62 @@
<html>
<head>
<title></title>
<script>
var div = document.createElement("div");
var M;
if ("MozMutationObserver" in window) {
M = window.MozMutationObserver;
} else if ("WebKitMutationObserver" in window) {
M = window.WebKitMutationObserver;
} else {
M = window.MutationObserver;
}
var didCall1 = false;
var didCall2 = false;
function testMutationObserverInDialog() {
div.innerHTML = "<span>1</span><span>2</span>";
m = new M(function(records, observer) {
opener.is(records[0].type, "childList", "Should have got childList");
opener.is(records[0].removedNodes.length, 2, "Should have got removedNodes");
opener.is(records[0].addedNodes.length, 1, "Should have got addedNodes");
observer.disconnect();
m = null;
didCall1 = true;
});
m.observe(div, { childList: true });
div.innerHTML = "<span><span>foo</span></span>";
}
function testMutationObserverInDialog2() {
div.innerHTML = "<span>1</span><span>2</span>";
m = new M(function(records, observer) {
opener.is(records[0].type, "childList", "Should have got childList");
opener.is(records[0].removedNodes.length, 2, "Should have got removedNodes");
opener.is(records[0].addedNodes.length, 1, "Should have got addedNodes");
observer.disconnect();
m = null;
didCall2 = true;
});
m.observe(div, { childList: true });
div.innerHTML = "<span><span>foo</span></span>";
}
window.addEventListener("load", testMutationObserverInDialog);
window.addEventListener("load", testMutationObserverInDialog2);
window.addEventListener("load",
function() {
opener.ok(didCall1, "Should have called 1st mutation callback");
opener.ok(didCall2, "Should have called 2nd mutation callback");
window.close();
});
</script>
<style>
</style>
</head>
<body>
<input type="button" onclick="window.close()" value="close">
</body>
</html>

View File

@ -63,6 +63,22 @@ ok(false, "NOT REACHED");
ok(true, "an undefined options member should throw");
}
/** Test for dictionary initialization order **/
(function() {
var o = {};
var p = {type: "text/plain", endings: "transparent"};
var called = [];
function add_to_called(n) {
called.push(n);
return p[n];
}
["type", "endings"].forEach(function(n) {
Object.defineProperty(o, n, { get: add_to_called.bind(null, n) });
});
var b = new Blob([], o);
is(JSON.stringify(called), JSON.stringify(["endings", "type"]), "dictionary members should be get in lexicographical order");
})();
let blob1 = Blob(["squiggle"]);
ok(blob1 instanceof Blob, "Blob constructor should produce Blobs");
ok(!(blob1 instanceof File), "Blob constructor should not produce Files");

View File

@ -56,14 +56,14 @@ window.onerror = function(message, uri, line) {
<script type="application/javascript">
errorFired = false;
global = "";
window.onerror = function(message, uri, line) {
is(message, "Error loading script", "Should have correct error message");
is(uri,
"http://example.com/tests/content/base/test/bug696301-script-2.js",
"Should still have correct script URI even when failing CORS");
is(line, 1, "Load failures seem to count as line 1");
window.addEventListener("error", function(e) {
is(Object.getPrototypeOf(e), Event.prototype,
"Object prototype should be Event");
var externalScripts = document.querySelectorAll("script[src]");
is(e.target, externalScripts[externalScripts.length - 1],
"Event's target should be the right <script>");
errorFired = true;
}
}, true);
</script>
<script src="http://example.com/tests/content/base/test/bug696301-script-2.js"
crossorigin></script>

View File

@ -58,14 +58,14 @@ window.onerror = function(message, uri, line) {
<script type="application/javascript">
errorFired = false;
global = "";
window.onerror = function(message, uri, line) {
is(message, "Error loading script", "Should have correct error message");
is(uri,
"http://example.com/tests/content/base/test/bug696301-script-2.js",
"Should still have correct script URI even when failing CORS");
is(line, 1, "Load failures seem to count as line 1");
window.addEventListener("error", function(e) {
is(Object.getPrototypeOf(e), Event.prototype,
"Object prototype should be Event");
var scripts = document.querySelectorAll("script");
is(e.target, scripts[scripts.length - 1],
"Event's target should be the right &lt;script>");
errorFired = true;
}
}, true);
</script>
<script xlink:href="http://example.com/tests/content/base/test/bug696301-script-2.js"
crossorigin></script>

View File

@ -0,0 +1,37 @@
<!DOCTYPE HTML>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=737087
-->
<title>Test for Bug 737087</title>
<script src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" href="/tests/SimpleTest/test.css"/>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=737087">Mozilla Bug 737087</a>
<script>
/** Test for Bug 737087 **/
SimpleTest.waitForExplicitFinish();
var bubbled = false;
var capturedEvent = null;
var inlineFiredEvent = null;
addEventListener("error", function() { bubbled = true });
addEventListener("error", function(e) {
capturedEvent = e;
is(typeof e, "object", "Error event must be object");
is(Object.getPrototypeOf(e), Event.prototype, "Error event must be Event");
is(e.bubbles, false, "e.bubbles must be false");
is(e.cancelable, false, "e.cancelable must be false");
}, true);
addLoadEvent(function() {
is(bubbled, false, "Error event must not bubble");
isnot(capturedEvent, null, "Error event must be captured");
isnot(inlineFiredEvent, null, "Inline error handler must fire");
is(capturedEvent, inlineFiredEvent,
"Same event must be handled by both handlers");
SimpleTest.finish();
});
</script>
<script src=nonexistent
onerror="inlineFiredEvent = event"></script>

View File

@ -293,6 +293,11 @@ function testChildList4() {
});
m.observe(df, { childList: true, characterData: true, characterDataOldValue: true, subtree: true });
m.observe(div, { childList: true });
// Make sure transient observers aren't leaked.
var leakTest = new MozMutationObserver(function(){});
leakTest.observe(div, { characterData: true, subtree: true });
div.insertBefore(df, s2);
s1.firstChild.data = "bar"; // This should *not* create a record.
t1.data = "Hello the whole "; // This should create a record.
@ -454,6 +459,24 @@ function testSyncXHR() {
function testSyncXHR2() {
ok(callbackHandled, "Should have called the mutation callback!");
then(testModalDialog);
}
function testModalDialog() {
var didHandleCallback = false;
div.innerHTML = "<span>1</span><span>2</span>";
m = new M(function(records, observer) {
is(records[0].type, "childList", "Should have got childList");
is(records[0].removedNodes.length, 2, "Should have got removedNodes");
is(records[0].addedNodes.length, 1, "Should have got addedNodes");
observer.disconnect();
m = null;
didHandleCallback = true;
});
m.observe(div, { childList: true });
div.innerHTML = "<span><span>foo</span></span>";
window.showModalDialog("mutationobserver_dialog.html");
ok(didHandleCallback, "Should have called the callback while showing modal dialog!");
then();
}

View File

@ -127,9 +127,10 @@ struct WebGLTexelPremultiplicationOp {
int GetWebGLTexelFormat(GLenum format, GLenum type);
// Zero is not an integer power of two.
inline bool is_pot_assuming_nonnegative(WebGLsizei x)
{
return (x & (x-1)) == 0;
return x && (x & (x-1)) == 0;
}
/* Each WebGL object class WebGLFoo wants to:
@ -585,6 +586,7 @@ public:
nsresult ErrorOutOfMemory(const char *fmt = 0, ...);
const char *ErrorName(GLenum error);
bool IsTextureFormatCompressed(GLenum format);
nsresult DummyFramebufferOperation(const char *info);
@ -1247,14 +1249,26 @@ public:
class ImageInfo : public WebGLRectangleObject {
public:
ImageInfo() : mFormat(0), mType(0), mIsDefined(false) {}
ImageInfo()
: mFormat(0)
, mType(0)
, mIsDefined(false)
{}
ImageInfo(WebGLsizei width, WebGLsizei height,
WebGLenum format, WebGLenum type)
: WebGLRectangleObject(width, height), mFormat(format), mType(type), mIsDefined(true) {}
: WebGLRectangleObject(width, height)
, mFormat(format)
, mType(type)
, mIsDefined(true)
{}
bool operator==(const ImageInfo& a) const {
return mWidth == a.mWidth && mHeight == a.mHeight &&
mFormat == a.mFormat && mType == a.mType;
return mIsDefined == a.mIsDefined &&
mWidth == a.mWidth &&
mHeight == a.mHeight &&
mFormat == a.mFormat &&
mType == a.mType;
}
bool operator!=(const ImageInfo& a) const {
return !(*this == a);

View File

@ -1911,15 +1911,20 @@ WebGLContext::GenerateMipmap(WebGLenum target)
WebGLTexture *tex = activeBoundTextureForTarget(target);
if (!tex)
return ErrorInvalidOperation("generateMipmap: no texture is bound to this target");
return ErrorInvalidOperation("generateMipmap: No texture is bound to this target.");
if (!tex->IsFirstImagePowerOfTwo()) {
return ErrorInvalidOperation("generateMipmap: the width or height of this texture is not a power of two");
}
if (!tex->HasImageInfoAt(0, 0))
return ErrorInvalidOperation("generateMipmap: Level zero of texture is not defined.");
if (!tex->AreAllLevel0ImageInfosEqual()) {
return ErrorInvalidOperation("generateMipmap: the six faces of this cube map have different dimensions, format, or type.");
}
if (!tex->IsFirstImagePowerOfTwo())
return ErrorInvalidOperation("generateMipmap: Level zero of texture does not have power-of-two width and height.");
GLenum format = tex->ImageInfoAt(0, 0).Format();
if (IsTextureFormatCompressed(format))
return ErrorInvalidOperation("generateMipmap: Texture data at level zero is compressed.");
if (!tex->AreAllLevel0ImageInfosEqual())
return ErrorInvalidOperation("generateMipmap: The six faces of this cube map have different dimensions, format, or type.");
tex->SetGeneratedMipmap();

View File

@ -239,4 +239,27 @@ WebGLContext::ErrorName(GLenum error)
NS_ABORT();
return "[unknown WebGL error!]";
}
};
}
bool
WebGLContext::IsTextureFormatCompressed(GLenum format)
{
switch(format) {
case LOCAL_GL_RGB:
case LOCAL_GL_RGBA:
case LOCAL_GL_ALPHA:
case LOCAL_GL_LUMINANCE:
case LOCAL_GL_LUMINANCE_ALPHA:
return false;
case LOCAL_GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case LOCAL_GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case LOCAL_GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
case LOCAL_GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return true;
}
NS_NOTREACHED("Invalid WebGL texture format?");
NS_ABORT();
return false;
}

View File

@ -0,0 +1,9 @@
<input form="f" id="x" xmlns="http://www.w3.org/1999/xhtml">
<form id="f"></form>
<script>
window.addEventListener("load", function() {
var x = document.getElementById("x");
x.appendChild(x.cloneNode(true));
}, false);
</script>
</input>

View File

@ -34,3 +34,4 @@ load 682058.xhtml
load 682460.html
load 673853.html
load 738744.xhtml
load 741250.xhtml

View File

@ -2366,7 +2366,10 @@ nsFormControlList::AddElementToTable(nsGenericHTMLFormElement* aChild,
// the list in the hash
nsSimpleContentList *list = new nsSimpleContentList(mForm);
NS_ASSERTION(content->GetParent(), "Item in list without parent");
// If an element has a @form, we can assume it *might* be able to not have
// a parent and still be in the form.
NS_ASSERTION(content->HasAttr(kNameSpaceID_None, nsGkAtoms::form) ||
content->GetParent(), "Item in list without parent");
// Determine the ordering between the new and old element.
bool newFirst = nsContentUtils::PositionIsBefore(aChild, content);

View File

@ -90,7 +90,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=408231
["removeformat", "exception"],
["selectall", "exception"],
["strikethrough", "false"],
["styleWithCSS", "exception"],
["styleWithCSS", "false"],
["subscript", "false"],
["superscript", "false"],
["underline", "false"],
@ -130,7 +130,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=408231
["removeformat", ""],
["selectall", ""],
["strikethrough", ""],
["styleWithCSS", "exception"],
["styleWithCSS", ""],
["subscript", ""],
["superscript", ""],
["underline", ""],

View File

@ -3233,6 +3233,13 @@ nsHTMLDocument::QueryCommandState(const nsAString & commandID, bool *_retval)
if (!window)
return NS_ERROR_FAILURE;
if (commandID.LowerCaseEqualsLiteral("usecss")) {
// Per spec, state is supported for styleWithCSS but not useCSS, so we just
// return false always.
*_retval = false;
return NS_OK;
}
nsCAutoString cmdToDispatch, paramToCheck;
bool dummy, dummy2;
if (!ConvertToMidasInternalCommand(commandID, commandID,

View File

@ -671,7 +671,7 @@ nsSMILAnimationFunction::ScaleSimpleProgress(double aProgress,
return aProgress;
PRUint32 i = 0;
for (; i < numTimes - 2 && aProgress >= mKeyTimes[i+1]; ++i);
for (; i < numTimes - 2 && aProgress >= mKeyTimes[i+1]; ++i) { }
if (aCalcMode == CALC_DISCRETE) {
// discrete calcMode behaviour differs in that each keyTime defines the time

View File

@ -1767,7 +1767,7 @@ nsSMILTimedElement::GetNextGreater(const InstanceTimeList& aList,
{
nsSMILInstanceTime* result = nsnull;
while ((result = GetNextGreaterOrEqual(aList, aBase, aPosition)) &&
result->Time() == aBase);
result->Time() == aBase) { }
return result;
}

View File

@ -102,8 +102,7 @@ protected:
const txExpandedName key()
{
NS_ASSERTION(mCurrentPos >= 0 &&
mCurrentPos < mMap.mItems.Length(),
NS_ASSERTION(mCurrentPos < mMap.mItems.Length(),
"invalid position in txExpandedNameMap::iterator");
return txExpandedName(mMap.mItems[mCurrentPos].mNamespaceID,
mMap.mItems[mCurrentPos].mLocalName);
@ -112,8 +111,7 @@ protected:
protected:
void* itemValue()
{
NS_ASSERTION(mCurrentPos >= 0 &&
mCurrentPos < mMap.mItems.Length(),
NS_ASSERTION(mCurrentPos < mMap.mItems.Length(),
"invalid position in txExpandedNameMap::iterator");
return mMap.mItems[mCurrentPos].mValue;
}

View File

@ -218,6 +218,23 @@ nsXULTemplateBuilder::InitGlobals()
return mPool.Init("nsXULTemplateBuilder", bucketsizes, 1, 256);
}
void
nsXULTemplateBuilder::CleanUp(bool aIsFinal)
{
for (PRInt32 q = mQuerySets.Length() - 1; q >= 0; q--) {
nsTemplateQuerySet* qs = mQuerySets[q];
delete qs;
}
mQuerySets.Clear();
mMatchMap.Enumerate(DestroyMatchList, &mPool);
// Setting mQueryProcessor to null will close connections. This would be
// handled by the cycle collector, but we want to close them earlier.
if (aIsFinal)
mQueryProcessor = nsnull;
}
void
nsXULTemplateBuilder::Uninit(bool aIsFinal)
@ -232,14 +249,7 @@ nsXULTemplateBuilder::Uninit(bool aIsFinal)
if (mQueryProcessor)
mQueryProcessor->Done();
for (PRInt32 q = mQuerySets.Length() - 1; q >= 0; q--) {
nsTemplateQuerySet* qs = mQuerySets[q];
delete qs;
}
mQuerySets.Clear();
mMatchMap.Enumerate(DestroyMatchList, &mPool);
CleanUp(aIsFinal);
mRootResult = nsnull;
mRefVariable = nsnull;
@ -1188,6 +1198,8 @@ nsXULTemplateBuilder::ContentRemoved(nsIDocument* aDocument,
if (xulcontent)
xulcontent->ClearTemplateGenerated();
CleanUp(true);
mDB = nsnull;
mCompDB = nsnull;
mDataSource = nsnull;

View File

@ -81,6 +81,8 @@ class nsXULTemplateBuilder : public nsIXULTemplateBuilder,
public nsIObserver,
public nsStubDocumentObserver
{
void CleanUp(bool aIsFinal);
public:
nsXULTemplateBuilder();
virtual ~nsXULTemplateBuilder();

View File

@ -1919,6 +1919,9 @@ nsXULTreeBuilder::CompareResults(nsIXULTemplateResult* aLeft, nsIXULTemplateResu
}
PRInt32 sortorder;
if (!mQueryProcessor)
return 0;
mQueryProcessor->CompareResults(aLeft, aRight, mSortVariable, mSortHints, &sortorder);
if (sortorder)

View File

@ -148,7 +148,6 @@
#include "nsIJSContextStack.h"
#include "nsIJSRuntimeService.h"
#include "nsIMarkupDocumentViewer.h"
#include "nsIPrefBranch.h"
#include "nsIPresShell.h"
#include "nsIPrivateDOMEvent.h"
#include "nsIProgrammingLanguage.h"
@ -7154,6 +7153,8 @@ nsGlobalWindow::ShowModalDialog(const nsAString& aURI, nsIVariant *aArgs,
options.AppendLiteral(",scrollbars=1,centerscreen=1,resizable=0");
nsCOMPtr<nsIDOMWindow> callerWin = EnterModalState();
PRUint32 oldMicroTaskLevel = nsContentUtils::MicroTaskLevel();
nsContentUtils::SetMicroTaskLevel(0);
nsresult rv = OpenInternal(aURI, EmptyString(), options,
false, // aDialog
true, // aContentModal
@ -7163,6 +7164,7 @@ nsGlobalWindow::ShowModalDialog(const nsAString& aURI, nsIVariant *aArgs,
GetPrincipal(), // aCalleePrincipal
nsnull, // aJSCallerContext
getter_AddRefs(dlgWin));
nsContentUtils::SetMicroTaskLevel(oldMicroTaskLevel);
LeaveModalState(callerWin);
NS_ENSURE_SUCCESS(rv, rv);

View File

@ -42,20 +42,13 @@
#include "nsPresContext.h"
#include "nsCOMPtr.h"
#include "nsDOMClassInfoID.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIDocShellTreeItem.h"
#include "nsLayoutUtils.h"
#include "nsContentUtils.h"
#include "mozilla/Preferences.h"
#include "nsDOMEvent.h"
using namespace mozilla;
using namespace mozilla::dom;
/* static */ bool nsScreen::sInitialized = false;
/* static */ bool nsScreen::sAllowScreenEnabledProperty = false;
/* static */ bool nsScreen::sAllowScreenBrightnessProperty = false;
namespace {
bool
@ -73,26 +66,11 @@ IsChromeType(nsIDocShell *aDocShell)
} // anonymous namespace
/* static */ void
nsScreen::Initialize()
{
MOZ_ASSERT(!sInitialized);
sInitialized = true;
Preferences::AddBoolVarCache(&sAllowScreenEnabledProperty,
"dom.screenEnabledProperty.enabled");
Preferences::AddBoolVarCache(&sAllowScreenBrightnessProperty,
"dom.screenBrightnessProperty.enabled");
}
/* static */ already_AddRefed<nsScreen>
nsScreen::Create(nsPIDOMWindow* aWindow)
{
MOZ_ASSERT(aWindow);
if (!sInitialized) {
Initialize();
}
if (!aWindow->GetDocShell()) {
return nsnull;
}
@ -103,7 +81,6 @@ nsScreen::Create(nsPIDOMWindow* aWindow)
nsRefPtr<nsScreen> screen = new nsScreen();
screen->BindToOwner(aWindow);
screen->mIsChrome = IsChromeType(aWindow->GetDocShell());
hal::RegisterScreenOrientationObserver(screen);
hal::GetCurrentScreenOrientation(&(screen->mOrientation));
@ -148,28 +125,6 @@ NS_IMPL_RELEASE_INHERITED(nsScreen, nsDOMEventTargetHelper)
NS_IMPL_EVENT_HANDLER(nsScreen, mozorientationchange)
bool
nsScreen::IsWhiteListed() {
if (mIsChrome) {
return true;
}
if (!GetOwner()) {
return false;
}
nsCOMPtr<nsIDocument> doc = do_GetInterface(GetOwner()->GetDocShell());
if (!doc) {
return false;
}
nsIPrincipal *principal = doc->NodePrincipal();
nsCOMPtr<nsIURI> principalURI;
principal->GetURI(getter_AddRefs(principalURI));
return nsContentUtils::URIIsChromeOrInPref(principalURI,
"dom.mozScreenWhitelist");
}
NS_IMETHODIMP
nsScreen::GetTop(PRInt32* aTop)
{
@ -329,55 +284,6 @@ nsScreen::GetAvailRect(nsRect& aRect)
return NS_OK;
}
nsresult
nsScreen::GetMozEnabled(bool *aEnabled)
{
if (!sAllowScreenEnabledProperty || !IsWhiteListed()) {
*aEnabled = true;
return NS_OK;
}
*aEnabled = hal::GetScreenEnabled();
return NS_OK;
}
nsresult
nsScreen::SetMozEnabled(bool aEnabled)
{
if (!sAllowScreenEnabledProperty || !IsWhiteListed()) {
return NS_OK;
}
// TODO bug 707589: When the screen's state changes, all visible windows
// should fire a visibility change event.
hal::SetScreenEnabled(aEnabled);
return NS_OK;
}
nsresult
nsScreen::GetMozBrightness(double *aBrightness)
{
if (!sAllowScreenEnabledProperty || !IsWhiteListed()) {
*aBrightness = 1;
return NS_OK;
}
*aBrightness = hal::GetScreenBrightness();
return NS_OK;
}
nsresult
nsScreen::SetMozBrightness(double aBrightness)
{
if (!sAllowScreenEnabledProperty || !IsWhiteListed()) {
return NS_OK;
}
NS_ENSURE_TRUE(0 <= aBrightness && aBrightness <= 1, NS_ERROR_INVALID_ARG);
hal::SetScreenBrightness(aBrightness);
return NS_OK;
}
void
nsScreen::Notify(const ScreenOrientationWrapper& aOrientation)
{

View File

@ -74,8 +74,6 @@ protected:
nsresult GetRect(nsRect& aRect);
nsresult GetAvailRect(nsRect& aRect);
bool mIsChrome;
mozilla::dom::ScreenOrientation mOrientation;
private:
@ -91,14 +89,6 @@ private:
nsScreen();
virtual ~nsScreen();
static bool sInitialized;
static bool sAllowScreenEnabledProperty;
static bool sAllowScreenBrightnessProperty;
static void Initialize();
bool IsWhiteListed();
nsRefPtr<FullScreenEventListener> mEventListener;
NS_DECL_EVENT_HANDLER(mozorientationchange)

View File

@ -69,14 +69,16 @@ def parseInt(literal):
# Magic for creating enums
def M_add_class_attribs(attribs):
def foo(name, bases, dict_):
for v, k in attribs:
for v, k in enumerate(attribs):
dict_[k] = v
assert 'length' not in dict_
dict_['length'] = len(attribs)
return type(name, bases, dict_)
return foo
def enum(*names):
class Foo(object):
__metaclass__ = M_add_class_attribs(enumerate(names))
__metaclass__ = M_add_class_attribs(names)
def __setattr__(self, name, value): # this makes it read-only
raise NotImplementedError
return Foo()
@ -93,9 +95,8 @@ class WebIDLError(Exception):
self.location)
class Location(object):
_line = None
def __init__(self, lexer, lineno, lexpos, filename):
self._line = None
self._lineno = lineno
self._lexpos = lexpos
self._lexdata = lexer.lexdata
@ -105,36 +106,47 @@ class Location(object):
return self._lexpos == other._lexpos and \
self._file == other._file
def filename(self):
return self.filename
def resolve(self):
if self._line:
return
startofline = self._lexdata.rfind('\n', 0, self._lexpos) + 1
endofline = self._lexdata.find('\n', self._lexpos, self._lexpos + 80)
self._line = self._lexdata[startofline:endofline]
if endofline != -1:
self._line = self._lexdata[startofline:endofline]
else:
self._line = self._lexdata[startofline:]
self._colno = self._lexpos - startofline
def pointerline(self):
def i():
for i in xrange(0, self._colno):
yield " "
yield "^"
return "".join(i())
def get(self):
self.resolve()
return "%s line %s:%s" % (self._file, self._lineno, self._colno)
def _pointerline(self):
return " " * self._colno + "^"
def __str__(self):
self.resolve()
return "%s line %s:%s\n%s\n%s" % (self._file, self._lineno, self._colno,
self._line, self.pointerline())
self._line, self._pointerline())
class BuiltinLocation(object):
def __init__(self, text):
self.msg = text
def __eq__(self, other):
return isinstance(other, BuiltinLocation) and \
self.msg == other.msg
def filename(self):
return '<builtin>'
def resolve(self):
pass
def get(self):
return self.msg
@ -150,7 +162,7 @@ class IDLObject(object):
self.userData = dict()
def filename(self):
return self.location._file
return self.location.filename()
def isInterface(self):
return False
@ -198,6 +210,11 @@ class IDLScope(IDLObject):
return "::"
def ensureUnique(self, identifier, object):
"""
Ensure that there is at most one 'identifier' in scope ('self').
Note that object can be None. This occurs if we end up here for an
interface type we haven't seen yet.
"""
assert isinstance(identifier, IDLUnresolvedIdentifier)
assert not object or isinstance(object, IDLObjectWithIdentifier)
assert not object or object.identifier == identifier
@ -300,6 +317,9 @@ class IDLUnresolvedIdentifier(IDLObject):
object.identifier = identifier
return identifier
def finish(self):
assert False # Should replace with a resolved identifier first.
class IDLObjectWithIdentifier(IDLObject):
def __init__(self, location, parentScope, identifier):
IDLObject.__init__(self, location)
@ -368,9 +388,8 @@ class IDLInterface(IDLObjectWithScope):
self.parent = parent
self._callback = False
self._finished = False
self.members = list(members) # clone the list
assert iter(self.members) # Assert it's iterable
IDLObjectWithScope.__init__(self, location, parentScope, name)
@ -404,7 +423,7 @@ class IDLInterface(IDLObjectWithScope):
return retval
def finish(self, scope):
if hasattr(self, "_finished"):
if self._finished:
return
self._finished = True
@ -416,7 +435,6 @@ class IDLInterface(IDLObjectWithScope):
self.parent = parent
assert iter(self.members)
members = None
if self.parent:
self.parent.finish(scope)
@ -427,19 +445,6 @@ class IDLInterface(IDLObjectWithScope):
else:
members = list(self.members)
SpecialType = enum(
'NamedGetter',
'NamedSetter',
'NamedCreator',
'NamedDeleter',
'IndexedGetter',
'IndexedSetter',
'IndexedCreator',
'IndexedDeleter'
)
specialMembersSeen = [False for i in range(8)]
def memberNotOnParentChain(member, iface):
assert iface
@ -451,59 +456,39 @@ class IDLInterface(IDLObjectWithScope):
return False
return memberNotOnParentChain(member, iface.parent)
# Ensure that there's at most one of each {named,indexed}
# {getter,setter,creator,deleter}.
specialMembersSeen = set()
for member in members:
if memberNotOnParentChain(member, self):
member.resolve(self)
if member.tag == IDLInterfaceMember.Tags.Method:
if member.isGetter():
if member.isNamed():
if specialMembersSeen[SpecialType.NamedGetter]:
raise WebIDLError("Multiple named getters on %s" % (self),
self.location)
specialMembersSeen[SpecialType.NamedGetter] = True
else:
assert member.isIndexed()
if specialMembersSeen[SpecialType.IndexedGetter]:
raise WebIDLError("Multiple indexed getters on %s" % (self),
self.location)
specialMembersSeen[SpecialType.IndexedGetter] = True
if member.isSetter():
if member.isNamed():
if specialMembersSeen[SpecialType.NamedSetter]:
raise WebIDLError("Multiple named setters on %s" % (self),
self.location)
specialMembersSeen[SpecialType.NamedSetter] = True
else:
assert member.isIndexed()
if specialMembersSeen[SpecialType.IndexedSetter]:
raise WebIDLError("Multiple indexed setters on %s" % (self),
self.location)
specialMembersSeen[SpecialType.IndexedSetter] = True
if member.isCreator():
if member.isNamed():
if specialMembersSeen[SpecialType.NamedCreator]:
raise WebIDLError("Multiple named creators on %s" % (self),
self.location)
specialMembersSeen[SpecialType.NamedCreator] = True
else:
assert member.isIndexed()
if specialMembersSeen[SpecialType.IndexedCreator]:
raise WebIDLError("Multiple indexed creators on %s" % (self),
self.location)
specialMembersSeen[SpecialType.IndexedCreator] = True
if member.isDeleter():
if member.isNamed():
if specialMembersSeen[SpecialType.NamedDeleter]:
raise WebIDLError("Multiple named deleters on %s" % (self),
self.location)
specialMembersSeen[SpecialType.NamedDeleter] = True
else:
assert member.isIndexed()
if specialMembersSeen[SpecialType.IndexedDeleter]:
raise WebIDLError("Multiple indexed Deleters on %s" % (self),
self.location)
specialMembersSeen[SpecialType.IndexedDeleter] = True
if member.tag != IDLInterfaceMember.Tags.Method:
continue
if member.isGetter():
memberType = "getters"
elif member.isSetter():
memberType = "setters"
elif member.isCreator():
memberType = "creators"
elif member.isDeleter():
memberType = "deleters"
else:
continue
if member.isNamed():
memberType = "named " + memberType
elif member.isIndexed():
memberType = "indexed " + memberType
else:
continue
if memberType in specialMembersSeen:
raise WebIDLError("Multiple " + memberType + " on %s" % (self),
self.location)
specialMembersSeen.add(memberType)
for member in self.members:
member.finish(scope)
@ -529,7 +514,7 @@ class IDLInterface(IDLObjectWithScope):
return depth
def hasConstants(self):
return reduce(lambda b, m: b or m.isConst(), self.members, False)
return any(m.isConst() for m in self.members)
def hasInterfaceObject(self):
if self.isCallback():
@ -567,10 +552,7 @@ class IDLInterface(IDLObjectWithScope):
identifier = IDLUnresolvedIdentifier(self.location, "constructor",
allowForbidden=True)
method = IDLMethod(self.location, identifier, retType, args,
False, False, False, False, False, False,
False, False)
method = IDLMethod(self.location, identifier, retType, args)
method.resolve(self)
self._extendedAttrDict[identifier] = attrlist if len(attrlist) else True
@ -763,6 +745,12 @@ class IDLNullableType(IDLType):
def isString(self):
return self.inner.isString()
def isFloat(self):
return self.inner.isFloat()
def isInteger(self):
return self.inner.isInteger()
def isVoid(self):
return False
@ -772,6 +760,9 @@ class IDLNullableType(IDLType):
def isArray(self):
return self.inner.isArray()
def isArrayBuffer(self):
return self.inner.isArrayBuffer()
def isDictionary(self):
return self.inner.isDictionary()
@ -797,7 +788,7 @@ class IDLNullableType(IDLType):
return self
def unroll(self):
return self.inner
return self.inner.unroll()
def isDistinguishableFrom(self, other):
if other.nullable():
@ -835,18 +826,19 @@ class IDLSequenceType(IDLType):
return True
def isArray(self):
return self.inner.isArray()
return False
def isDictionary(self):
return self.inner.isDictionary()
return False
def isInterface(self):
return self.inner.isInterface()
return False
def isEnum(self):
return self.inner.isEnum();
return False
def tag(self):
# XXXkhuey this is probably wrong.
return self.inner.tag()
def resolveType(self, parentScope):
@ -858,10 +850,11 @@ class IDLSequenceType(IDLType):
def complete(self, scope):
self.inner = self.inner.complete(scope)
self.name = self.inner.name
return self
def unroll(self):
return self.inner
return self.inner.unroll()
def isDistinguishableFrom(self, other):
return (other.isPrimitive() or other.isString() or other.isEnum() or
@ -895,32 +888,33 @@ class IDLArrayType(IDLType):
return False
def isPrimitive(self):
return self.inner.isPrimitive()
return False
def isString(self):
return self.inner.isString()
return False
def isVoid(self):
return False
def isSequence(self):
assert not self.inner.isSequence()
return self.inner.isSequence()
return False
def isArray(self):
return True
def isDictionary(self):
assert not self.inner.isDictionary()
return self.inner.isDictionary()
return False
def isInterface(self):
return self.inner.isInterface()
return False
def isEnum(self):
return self.inner.isEnum()
return False
def tag(self):
# XXXkhuey this is probably wrong.
return self.inner.tag()
def resolveType(self, parentScope):
@ -932,10 +926,11 @@ class IDLArrayType(IDLType):
def complete(self, scope):
self.inner = self.inner.complete(scope)
self.name = self.inner.name
return self
def unroll(self):
return self.inner
return self.inner.unroll()
def isDistinguishableFrom(self, other):
return (other.isPrimitive() or other.isString() or other.isEnum() or
@ -995,7 +990,7 @@ class IDLTypedefType(IDLType, IDLObjectWithIdentifier):
return self.inner.tag()
def unroll(self):
return self.inner
return self.inner.unroll()
def isDistinguishableFrom(self, other):
return self.inner.isDistinguishableFrom(other)
@ -1041,6 +1036,10 @@ class IDLWrapperType(IDLType):
def isEnum(self):
return isinstance(self.inner, IDLEnum)
def resolveType(self, parentScope):
assert isinstance(parentScope, IDLScope)
self.inner.resolve(parentScope)
def isComplete(self):
return True
@ -1122,32 +1121,32 @@ class IDLBuiltinType(IDLType):
def __init__(self, location, name, type):
IDLType.__init__(self, location, name)
self.builtin = True
self.type = type
self._typeTag = type
def isPrimitive(self):
return self.type <= IDLBuiltinType.Types.double
return self._typeTag <= IDLBuiltinType.Types.double
def isString(self):
return self.type == IDLBuiltinType.Types.domstring
return self._typeTag == IDLBuiltinType.Types.domstring
def isInteger(self):
return self.type <= IDLBuiltinType.Types.unsigned_long_long
return self._typeTag <= IDLBuiltinType.Types.unsigned_long_long
def isArrayBuffer(self):
return self.type == IDLBuiltinType.Types.ArrayBuffer
return self._typeTag == IDLBuiltinType.Types.ArrayBuffer
def isInterface(self):
# ArrayBuffers are interface types per the TypedArray spec,
# but we handle them as builtins because SpiderMonkey implements
# ArrayBuffers.
return self.type == IDLBuiltinType.Types.ArrayBuffer
return self._typeTag == IDLBuiltinType.Types.ArrayBuffer
def isFloat(self):
return self.type == IDLBuiltinType.Types.float or \
self.type == IDLBuiltinType.Types.double
return self._typeTag == IDLBuiltinType.Types.float or \
self._typeTag == IDLBuiltinType.Types.double
def tag(self):
return IDLBuiltinType.TagLookup[self.type]
return IDLBuiltinType.TagLookup[self._typeTag]
def isDistinguishableFrom(self, other):
if self.isPrimitive() or self.isString():
@ -1280,7 +1279,7 @@ class IDLValue(IDLObject):
# We're both integer types. See if we fit.
(min, max) = integerTypeSizes[type.type]
(min, max) = integerTypeSizes[type._typeTag]
if self.value <= max and self.value >= min:
# Promote
return IDLValue(self.location, type, self.value)
@ -1492,8 +1491,10 @@ class IDLMethod(IDLInterfaceMember, IDLScope):
)
def __init__(self, location, identifier, returnType, arguments,
static, getter, setter, creator, deleter, specialType, legacycaller,
stringifier):
static=False, getter=False, setter=False, creator=False,
deleter=False, specialType=NamedOrIndexed.Neither,
legacycaller=False, stringifier=False):
# REVIEW: specialType is NamedOrIndexed -- wow, this is messed up.
IDLInterfaceMember.__init__(self, location, identifier,
IDLInterfaceMember.Tags.Method)
@ -1678,6 +1679,7 @@ class Tokenizer(object):
def t_INTEGER(self, t):
r'-?(0([0-7]+|[Xx][0-9A-Fa-f]+)?|[1-9][0-9]*)'
try:
# Can't use int(), because that doesn't handle octal properly.
t.value = parseInt(t.value)
except:
raise WebIDLError("Invalid integer literal",
@ -2261,8 +2263,9 @@ class Parser(Tokenizer):
"legacycaller" if legacycaller else ""), allowDoubleUnderscore=True)
method = IDLMethod(self.getLocation(p, 2), identifier, returnType, arguments,
static, getter, setter, creator, deleter, specialType,
legacycaller, False)
static=static, getter=getter, setter=setter, creator=creator,
deleter=deleter, specialType=specialType,
legacycaller=legacycaller, stringifier=False)
p[0] = method
def p_QualifiersStatic(self, p):
@ -2861,7 +2864,14 @@ class Parser(Tokenizer):
for production in self._productions:
production.finish(self.globalScope())
return set(self._productions)
# De-duplicate self._productions, without modifying its order.
seen = set()
result = []
for p in self._productions:
if p not in seen:
seen.add(p)
result.append(p)
return result
def reset(self):
return Parser()

View File

@ -1 +0,0 @@
__all__ = ['WebIDL']

View File

@ -37,36 +37,76 @@
import os, sys
import glob
import optparse
import traceback
import WebIDL
class TestHarness(object):
def __init__(self, test, verbose):
self.test = test
self.verbose = verbose
self.printed_intro = False
def start(self):
if self.verbose:
self.maybe_print_intro()
def finish(self):
if self.verbose or self.printed_intro:
print "Finished test %s" % self.test
def maybe_print_intro(self):
if not self.printed_intro:
print "Starting test %s" % self.test
self.printed_intro = True
def test_pass(self, msg):
if self.verbose:
print "TEST-PASS | %s" % msg
def test_fail(self, msg):
self.maybe_print_intro()
print "TEST-UNEXPECTED-FAIL | %s" % msg
def ok(self, condition, msg):
if condition:
print "TEST-PASS | %s" % msg
self.test_pass(msg)
else:
print "TEST-UNEXPECTED-FAIL | %s" % msg
self.test_fail(msg)
def check(self, a, b, msg):
if a == b:
print "TEST-PASS | %s" % msg
self.test_pass(msg)
else:
print "TEST-UNEXPECTED-FAIL | %s" % msg
self.test_fail(msg)
print "\tGot %s expected %s" % (a, b)
def run_tests():
harness = TestHarness()
def run_tests(tests, verbose):
testdir = os.path.join(os.path.dirname(__file__), 'tests')
if not tests:
tests = glob.iglob(os.path.join(testdir, "*.py"))
sys.path.append(testdir)
tests = glob.iglob("tests/*.py")
sys.path.append("./tests")
for test in tests:
(testpath, ext) = os.path.splitext(os.path.basename(test))
_test = __import__(testpath, globals(), locals(), ['WebIDLTest'])
#try:
_test.WebIDLTest.__call__(WebIDL.Parser(), harness)
#except:
# print "TEST-UNEXPECTED-FAIL | Unhandled exception in Test %s" % testpath
# print sys.exc_info()[0]
print "Test %s Complete\n" % testpath
harness = TestHarness(test, verbose)
harness.start()
try:
_test.WebIDLTest.__call__(WebIDL.Parser(), harness)
except:
print "TEST-UNEXPECTED-FAIL | Unhandled exception in test %s" % testpath
traceback.print_exc()
finally:
harness.finish()
if __name__ == '__main__':
run_tests()
usage = """%prog [OPTIONS] [TESTS]
Where TESTS are relative to the tests directory."""
parser = optparse.OptionParser(usage=usage)
parser.add_option('-q', '--quiet', action='store_false', dest='verbose', default=True,
help="Don't print passing tests.")
options, tests = parser.parse_args()
run_tests(tests, verbose=options.verbose)

View File

@ -0,0 +1,13 @@
import WebIDL
def WebIDLTest(parser, harness):
parser.parse("""
interface A {
attribute long a;
};
interface B {
attribute A[] b;
};
""");
parser.finish()

View File

@ -0,0 +1,11 @@
import WebIDL
def WebIDLTest(parser, harness):
parser.parse("""
interface Test {
attribute long b;
};
""");
attr = parser.finish()[0].members[0]
harness.check(attr.type.filename(), '<builtin>', 'Filename on builtin type')

View File

@ -62,14 +62,14 @@ def WebIDLTest(parser, harness):
"Should be an IDLInterface")
checkMethod(results[0].ctor(), "::TestConstructorNoArgs::constructor",
"constructor", [("TestConstructorNoArgs", [])])
"constructor", [("TestConstructorNoArgs (Wrapper)", [])])
checkMethod(results[1].ctor(), "::TestConstructorWithArgs::constructor",
"constructor",
[("TestConstructorWithArgs",
[("TestConstructorWithArgs (Wrapper)",
[("::TestConstructorWithArgs::constructor::name", "name", "String", False, False)])])
checkMethod(results[2].ctor(), "::TestConstructorOverloads::constructor",
"constructor",
[("TestConstructorOverloads",
[("TestConstructorOverloads (Wrapper)",
[("::TestConstructorOverloads::constructor::foo", "foo", "Object", False, False)]),
("TestConstructorOverloads",
("TestConstructorOverloads (Wrapper)",
[("::TestConstructorOverloads::constructor::bar", "bar", "Boolean", False, False)])])

View File

@ -0,0 +1,15 @@
import WebIDL
def WebIDLTest(parser, harness):
parser.parse("""
interface Foo;
interface Bar;
interface Foo;
""");
results = parser.finish()
# There should be no duplicate interfaces in the result.
expectedNames = sorted(['Foo', 'Bar'])
actualNames = sorted(map(lambda iface: iface.identifier.name, results))
harness.check(actualNames, expectedNames, "Parser shouldn't output duplicate names.")

View File

@ -47,7 +47,7 @@ def WebIDLTest(parser, harness):
harness.check(len(signatures), 1, "Expect one signature")
(returnType, arguments) = signatures[0]
harness.check(str(returnType), "TestEnum", "Method type is the correct name")
harness.check(str(returnType), "TestEnum (Wrapper)", "Method type is the correct name")
harness.check(len(arguments), 1, "Method has the right number of arguments")
arg = arguments[0]
harness.ok(isinstance(arg, WebIDL.IDLArgument), "Should be an IDLArgument")
@ -58,4 +58,4 @@ def WebIDLTest(parser, harness):
"Attr has correct QName")
harness.check(attr.identifier.name, "foo", "Attr has correct name")
harness.check(str(attr.type), "TestEnum", "Attr type is the correct name")
harness.check(str(attr.type), "TestEnum (Wrapper)", "Attr type is the correct name")

View File

@ -0,0 +1,20 @@
import WebIDL
def WebIDLTest(parser, harness):
# Check that error messages put the '^' in the right place.
threw = False
input = 'interface ?'
try:
parser.parse(input)
results = parser.finish()
except WebIDL.WebIDLError as e:
threw = True
lines = str(e).split('\n')
harness.check(len(lines), 3, 'Expected number of lines in error message')
harness.check(lines[1], input, 'Second line shows error')
harness.check(lines[2], ' ' * (len(input) - 1) + '^',
'Correct column pointer in error message')
harness.ok(threw, "Should have thrown.")

View File

@ -0,0 +1,134 @@
import WebIDL
def WebIDLTest(parser, harness):
parser.parse("""
interface TestNullableEquivalency1 {
attribute long a;
attribute long? b;
};
interface TestNullableEquivalency2 {
attribute ArrayBuffer a;
attribute ArrayBuffer? b;
};
/* Not implemented */
/*dictionary TestNullableEquivalency3Dict {
long foo = 42;
};
interface TestNullableEquivalency3 {
attribute Test3Dict a;
attribute Test3Dict? b;
};*/
enum TestNullableEquivalency4Enum {
"Foo",
"Bar"
};
interface TestNullableEquivalency4 {
attribute TestNullableEquivalency4Enum a;
attribute TestNullableEquivalency4Enum? b;
};
interface TestNullableEquivalency5 {
attribute TestNullableEquivalency4 a;
attribute TestNullableEquivalency4? b;
};
interface TestNullableEquivalency6 {
attribute boolean a;
attribute boolean? b;
};
interface TestNullableEquivalency7 {
attribute DOMString a;
attribute DOMString? b;
};
/* Not implemented. */
/*interface TestNullableEquivalency8 {
attribute float a;
attribute float? b;
};*/
interface TestNullableEquivalency8 {
attribute double a;
attribute double? b;
};
interface TestNullableEquivalency9 {
attribute object a;
attribute object? b;
};
interface TestNullableEquivalency10 {
attribute double[] a;
attribute double[]? b;
};
interface TestNullableEquivalency11 {
attribute TestNullableEquivalency9[] a;
attribute TestNullableEquivalency9[]? b;
};
""")
for decl in parser.finish():
if decl.isInterface():
checkEquivalent(decl, harness)
def checkEquivalent(iface, harness):
type1 = iface.members[0].type
type2 = iface.members[1].type
harness.check(type1.nullable(), False, 'attr1 should not be nullable')
harness.check(type2.nullable(), True, 'attr2 should be nullable')
# We don't know about type1, but type2, the nullable type, definitely
# shouldn't be builtin.
harness.check(type2.builtin, False, 'attr2 should not be builtin')
# Ensure that all attributes of type2 match those in type1, except for:
# - names on an ignore list,
# - names beginning with '_',
# - functions which throw when called with no args, and
# - class-level non-callables ("static variables").
#
# Yes, this is an ugly, fragile hack. But it finds bugs...
for attr in dir(type1):
if attr.startswith('_') or \
attr in ['nullable', 'builtin', 'filename', 'location',
'inner', 'QName'] or \
(hasattr(type(type1), attr) and not callable(getattr(type1, attr))):
continue
a1 = getattr(type1, attr)
if callable(a1):
try:
v1 = a1()
except:
# Can't call a1 with no args, so skip this attriute.
continue
try:
a2 = getattr(type2, attr)
except:
harness.ok(False, 'Missing %s attribute on type %s in %s' % (attr, type2, iface))
continue
if not callable(a2):
harness.ok(False, "%s attribute on type %s in %s wasn't callable" % (attr, type2, iface))
continue
v2 = a2()
harness.check(v2, v1, '%s method return value' % attr)
else:
try:
a2 = getattr(type2, attr)
except:
harness.ok(False, 'Missing %s attribute on type %s in %s' % (attr, type2, iface))
continue
harness.check(a2, a1, '%s attribute should match' % attr)

View File

@ -39,7 +39,7 @@
#include "nsIDOMEventTarget.idl"
[scriptable, uuid(8a66b30c-9a32-4b17-ab4e-ca8b7b588243)]
[scriptable, uuid(9b978f58-5bfe-409d-aa3f-946ca934e51d)]
interface nsIDOMScreen : nsIDOMEventTarget
{
readonly attribute long top;
@ -53,29 +53,6 @@ interface nsIDOMScreen : nsIDOMEventTarget
readonly attribute long availLeft;
readonly attribute long availTop;
/**
* Is the device's screen currently enabled? This attribute controls the
* device's screen, so setting it to false will turn off the screen.
*/
attribute boolean mozEnabled;
/**
* How bright is the screen's backlight, on a scale from 0 (very dim) to 1
* (full brightness)? Setting this attribute modifies the screen's
* brightness.
*
* You can read and write this attribute even when the screen is disabled,
* but the backlight is off while the screen is disabled.
*
* If you write a value of X into this attribute, the attribute may not have
* the same value X when you later read it. Most screens don't support as
* many different brightness levels as there are doubles between 0 and 1, so
* we may reduce the value's precision before storing it.
*
* @throw NS_ERROR_INVALID_ARG if brightness is not in the range [0, 1].
*/
attribute double mozBrightness;
/**
* Returns the current screen orientation.
* Can be: landscape-primary, landscape-secondary,

View File

@ -49,8 +49,6 @@
#include "nsIFilePicker.h"
#include "nsIWindowWatcher.h"
#include "nsIDOMWindow.h"
#include "nsIPrefBranch.h"
#include "nsIPrefLocalizedString.h"
#include "nsIObserverService.h"
#include "nsContentUtils.h"
#include "nsAutoPtr.h"
@ -216,10 +214,7 @@ ContentParent::Init()
obs->AddObserver(this, "a11y-init-or-shutdown", false);
#endif
}
nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
if (prefs) {
prefs->AddObserver("", this, false);
}
Preferences::AddStrongObserver(this, "");
nsCOMPtr<nsIThreadInternal>
threadInt(do_QueryInterface(NS_GetCurrentThread()));
if (threadInt) {
@ -249,13 +244,8 @@ ContentParent::OnChannelConnected(int32 pid)
SetOtherProcess(handle);
#if defined(ANDROID) || defined(LINUX)
EnsurePrefService();
nsCOMPtr<nsIPrefBranch> branch;
branch = do_QueryInterface(mPrefService);
// Check nice preference
PRInt32 nice = 0;
branch->GetIntPref("dom.ipc.content.nice", &nice);
PRInt32 nice = Preferences::GetInt("dom.ipc.content.nice", 0);
// Environment variable overrides preference
char* relativeNicenessStr = getenv("MOZ_CHILD_PROCESS_RELATIVE_NICENESS");
@ -329,11 +319,7 @@ ContentParent::ActorDestroy(ActorDestroyReason why)
SetChildMemoryReporters(empty);
// remove the global remote preferences observers
nsCOMPtr<nsIPrefBranch> prefs
(do_GetService(NS_PREFSERVICE_CONTRACTID));
if (prefs) {
prefs->RemoveObserver("", this);
}
Preferences::RemoveObserver(this, "");
RecvRemoveGeolocationListener();
@ -464,7 +450,6 @@ ContentParent::IsAlive()
bool
ContentParent::RecvReadPrefsArray(InfallibleTArray<PrefTuple> *prefs)
{
EnsurePrefService();
Preferences::MirrorPreferences(prefs);
return true;
}
@ -478,18 +463,6 @@ ContentParent::RecvReadFontList(InfallibleTArray<FontListEntry>* retValue)
return true;
}
void
ContentParent::EnsurePrefService()
{
nsresult rv;
if (!mPrefService) {
mPrefService = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
NS_ASSERTION(NS_SUCCEEDED(rv),
"We lost prefService in the Chrome process !");
}
}
bool
ContentParent::RecvReadPermissions(InfallibleTArray<IPC::Permission>* aPermissions)
{

View File

@ -48,7 +48,6 @@
#include "nsIObserver.h"
#include "nsIThreadInternal.h"
#include "nsNetUtil.h"
#include "nsIPrefService.h"
#include "nsIPermissionManager.h"
#include "nsIDOMGeoPositionCallback.h"
#include "nsIMemoryReporter.h"
@ -167,8 +166,6 @@ private:
virtual bool RecvReadPrefsArray(InfallibleTArray<PrefTuple> *retValue);
virtual bool RecvReadFontList(InfallibleTArray<FontListEntry>* retValue);
void EnsurePrefService();
virtual bool RecvReadPermissions(InfallibleTArray<IPC::Permission>* aPermissions);
virtual bool RecvGetIndexedDBDirectory(nsString* aDirectory);
@ -238,8 +235,6 @@ private:
nsCOMArray<nsIMemoryReporter> mMemoryReporters;
bool mIsAlive;
nsCOMPtr<nsIPrefService> mPrefService;
bool mSendPermissionUpdates;
nsRefPtr<nsFrameMessageManager> mMessageManager;

View File

@ -55,12 +55,11 @@
#include "nsIServiceManager.h"
#include "nsThreadUtils.h"
#include "nsIPrivateBrowsingService.h"
#include "mozilla/Preferences.h"
#include "nsIPluginStreamListener.h"
#include "nsPluginsDir.h"
#include "nsPluginSafety.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsPluginLogging.h"
#include "nsIJSContextStack.h"
@ -352,7 +351,7 @@ nsNPAPIPlugin::RunPluginOOP(const nsPluginTag *aPluginTag)
}
#endif
nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
nsIPrefBranch* prefs = Preferences::GetRootBranch();
if (!prefs) {
return false;
}
@ -385,8 +384,7 @@ nsNPAPIPlugin::RunPluginOOP(const nsPluginTag *aPluginTag)
// so use the mime type (mIsJavaPlugin) and a special pref.
bool javaIsEnabled;
if (aPluginTag->mIsJavaPlugin &&
NS_SUCCEEDED(prefs->GetBoolPref("dom.ipc.plugins.java.enabled", &javaIsEnabled)) &&
!javaIsEnabled) {
!Preferences::GetBool("dom.ipc.plugins.java.enabled", true)) {
return false;
}
@ -417,8 +415,8 @@ nsNPAPIPlugin::RunPluginOOP(const nsPluginTag *aPluginTag)
match = (NS_WildCardMatch(prefFile.get(), maskStart, 0) == MATCH);
}
if (match && NS_SUCCEEDED(prefs->GetBoolPref(prefNames[currentPref],
&oopPluginsEnabled))) {
if (match && NS_SUCCEEDED(Preferences::GetBool(prefNames[currentPref],
&oopPluginsEnabled))) {
prefSet = true;
break;
}
@ -427,17 +425,17 @@ nsNPAPIPlugin::RunPluginOOP(const nsPluginTag *aPluginTag)
}
if (!prefSet) {
oopPluginsEnabled = false;
oopPluginsEnabled =
#ifdef XP_MACOSX
#if defined(__i386__)
prefs->GetBoolPref("dom.ipc.plugins.enabled.i386", &oopPluginsEnabled);
Preferences::GetBool("dom.ipc.plugins.enabled.i386", false);
#elif defined(__x86_64__)
prefs->GetBoolPref("dom.ipc.plugins.enabled.x86_64", &oopPluginsEnabled);
Preferences::GetBool("dom.ipc.plugins.enabled.x86_64", false);
#elif defined(__ppc__)
prefs->GetBoolPref("dom.ipc.plugins.enabled.ppc", &oopPluginsEnabled);
Preferences::GetBool("dom.ipc.plugins.enabled.ppc", false);
#endif
#else
prefs->GetBoolPref("dom.ipc.plugins.enabled", &oopPluginsEnabled);
Preferences::GetBool("dom.ipc.plugins.enabled", false);
#endif
}
@ -2061,12 +2059,10 @@ _getvalue(NPP npp, NPNVariable variable, void *result)
case NPNVjavascriptEnabledBool: {
*(NPBool*)result = false;
nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
if (prefs) {
bool js = false;;
res = prefs->GetBoolPref("javascript.enabled", &js);
if (NS_SUCCEEDED(res))
*(NPBool*)result = js;
bool js = false;
res = Preferences::GetBool("javascript.enabled", &js);
if (NS_SUCCEEDED(res)) {
*(NPBool*)result = js;
}
return NPERR_NO_ERROR;
}

View File

@ -61,6 +61,8 @@
#include "nsNetCID.h"
#include "nsIContent.h"
#include "mozilla/Preferences.h"
#ifdef MOZ_WIDGET_ANDROID
#include "ANPBase.h"
#include <android/log.h>
@ -105,13 +107,8 @@ nsNPAPIPluginInstance::nsNPAPIPluginInstance()
mNPP.pdata = NULL;
mNPP.ndata = this;
nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
if (prefs) {
bool useLayersPref;
nsresult rv = prefs->GetBoolPref("plugins.use_layers", &useLayersPref);
if (NS_SUCCEEDED(rv))
mUsePluginLayersPref = useLayersPref;
}
mUsePluginLayersPref =
Preferences::GetBool("plugins.use_layers", mUsePluginLayersPref);
PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance ctor: this=%p\n",this));
}

View File

@ -41,16 +41,16 @@
#include "nsCRT.h"
#include "nsILocalFile.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsDependentString.h"
#include "nsXPIDLString.h"
#include "prmem.h"
#include "nsArrayEnumerator.h"
#include "mozilla/Preferences.h"
#include <windows.h>
#include "nsIWindowsRegKey.h"
using namespace mozilla;
typedef struct structVer
{
WORD wMajor;
@ -231,18 +231,15 @@ nsPluginDirServiceProvider::GetFile(const char *charProp, bool *persistant,
*_retval = nsnull;
*persistant = false;
nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
if (!prefs)
return NS_ERROR_FAILURE;
nsCOMPtr<nsIWindowsRegKey> regKey =
do_CreateInstance("@mozilla.org/windows-registry-key;1");
NS_ENSURE_TRUE(regKey, NS_ERROR_FAILURE);
if (nsCRT::strcmp(charProp, NS_WIN_JRE_SCAN_KEY) == 0) {
nsXPIDLCString strVer;
if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer))))
nsAdoptingCString strVer = Preferences::GetCString(charProp);
if (!strVer) {
return NS_ERROR_FAILURE;
}
verBlock minVer;
TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);
@ -332,9 +329,10 @@ nsPluginDirServiceProvider::GetFile(const char *charProp, bool *persistant,
}
}
} else if (nsCRT::strcmp(charProp, NS_WIN_QUICKTIME_SCAN_KEY) == 0) {
nsXPIDLCString strVer;
if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer))))
nsAdoptingCString strVer = Preferences::GetCString(charProp);
if (!strVer) {
return NS_ERROR_FAILURE;
}
verBlock minVer;
TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);
@ -371,9 +369,10 @@ nsPluginDirServiceProvider::GetFile(const char *charProp, bool *persistant,
}
}
} else if (nsCRT::strcmp(charProp, NS_WIN_WMP_SCAN_KEY) == 0) {
nsXPIDLCString strVer;
if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer))))
nsAdoptingCString strVer = Preferences::GetCString(charProp);
if (!strVer) {
return NS_ERROR_FAILURE;
}
verBlock minVer;
TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);
@ -409,8 +408,8 @@ nsPluginDirServiceProvider::GetFile(const char *charProp, bool *persistant,
}
}
} else if (nsCRT::strcmp(charProp, NS_WIN_ACROBAT_SCAN_KEY) == 0) {
nsXPIDLCString strVer;
if (NS_FAILED(prefs->GetCharPref(charProp, getter_Copies(strVer)))) {
nsAdoptingCString strVer = Preferences::GetCString(charProp);
if (!strVer) {
return NS_ERROR_FAILURE;
}

View File

@ -80,7 +80,6 @@
#include "nsHashtable.h"
#include "nsIProxyInfo.h"
#include "nsPluginLogging.h"
#include "nsIPrefBranch.h"
#include "nsIScriptChannel.h"
#include "nsIBlocklistService.h"
#include "nsVersionComparator.h"
@ -88,6 +87,7 @@
#include "nsIObjectLoadingContent.h"
#include "nsIWritablePropertyBag2.h"
#include "nsPluginStreamListenerPeer.h"
#include "mozilla/Preferences.h"
#include "nsEnumeratorUtils.h"
#include "nsXPCOM.h"
@ -336,17 +336,7 @@ NS_IMETHODIMP nsPluginDocReframeEvent::Run() {
static bool UnloadPluginsASAP()
{
nsresult rv;
nsCOMPtr<nsIPrefBranch> pref(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
if (NS_SUCCEEDED(rv)) {
bool unloadPluginsASAP = false;
rv = pref->GetBoolPref("dom.ipc.plugins.unloadASAP", &unloadPluginsASAP);
if (NS_SUCCEEDED(rv)) {
return unloadPluginsASAP;
}
}
return false;
return Preferences::GetBool("dom.ipc.plugins.unloadASAP", false);
}
nsPluginHost::nsPluginHost()
@ -355,20 +345,10 @@ nsPluginHost::nsPluginHost()
{
// check to see if pref is set at startup to let plugins take over in
// full page mode for certain image mime types that we handle internally
mPrefService = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (mPrefService) {
bool tmp;
nsresult rv = mPrefService->GetBoolPref("plugin.override_internal_types",
&tmp);
if (NS_SUCCEEDED(rv)) {
mOverrideInternalTypes = tmp;
}
mOverrideInternalTypes =
Preferences::GetBool("plugin.override_internal_types", false);
rv = mPrefService->GetBoolPref("plugin.disable", &tmp);
if (NS_SUCCEEDED(rv)) {
mPluginsDisabled = tmp;
}
}
mPluginsDisabled = Preferences::GetBool("plugin.disable", false);
nsCOMPtr<nsIObserverService> obsService =
mozilla::services::GetObserverService();
@ -428,16 +408,16 @@ nsPluginHost::GetInst()
return sInst;
}
bool nsPluginHost::IsRunningPlugin(nsPluginTag * plugin)
bool nsPluginHost::IsRunningPlugin(nsPluginTag * aPluginTag)
{
if (!plugin || !plugin->mEntryPoint) {
if (!aPluginTag || !aPluginTag->mPlugin) {
return false;
}
for (PRUint32 i = 0; i < mInstances.Length(); i++) {
nsNPAPIPluginInstance *instance = mInstances[i].get();
if (instance &&
instance->GetPlugin() == plugin->mEntryPoint &&
instance->GetPlugin() == aPluginTag->mPlugin &&
instance->IsRunning()) {
return true;
}
@ -866,8 +846,6 @@ nsresult nsPluginHost::Destroy()
}
#endif /* XP_WIN */
mPrefService = nsnull; // release prefs service to avoid leaks!
return NS_OK;
}
@ -1198,7 +1176,7 @@ nsPluginHost::TagForPlugin(nsNPAPIPlugin* aPlugin)
{
nsPluginTag* pluginTag;
for (pluginTag = mPlugins; pluginTag; pluginTag = pluginTag->mNext) {
if (pluginTag->mEntryPoint == aPlugin) {
if (pluginTag->mPlugin == aPlugin) {
return pluginTag;
}
}
@ -1213,37 +1191,31 @@ nsresult nsPluginHost::SetUpPluginInstance(const char *aMimeType,
{
NS_ENSURE_ARG_POINTER(aOwner);
nsresult rv = NS_OK;
rv = TrySetUpPluginInstance(aMimeType, aURL, aOwner);
// if we fail, refresh plugin list just in case the plugin has been
// just added and try to instantiate plugin instance again, see bug 143178
if (NS_FAILED(rv)) {
// we should also make sure not to do this more than once per page
// so if there are a few embed tags with unknown plugins,
// we don't get unnecessary overhead
// let's cache document to decide whether this is the same page or not
nsCOMPtr<nsIDocument> document;
aOwner->GetDocument(getter_AddRefs(document));
nsCOMPtr<nsIDocument> currentdocument = do_QueryReferent(mCurrentDocument);
if (document == currentdocument)
return rv;
mCurrentDocument = do_GetWeakReference(document);
// ReloadPlugins will do the job smartly: nothing will be done
// if no changes detected, in such a case just return
if (NS_ERROR_PLUGINS_PLUGINSNOTCHANGED == ReloadPlugins(false))
return rv;
// other failure return codes may be not fatal, so we can still try
aOwner->SetInstance(nsnull); // avoid assert about setting it twice
rv = TrySetUpPluginInstance(aMimeType, aURL, aOwner);
nsresult rv = TrySetUpPluginInstance(aMimeType, aURL, aOwner);
if (NS_SUCCEEDED(rv)) {
return rv;
}
return rv;
// If we failed to load a plugin instance we'll try again after
// reloading our plugin list. Only do that once per document to
// avoid redundant high resource usage on pages with multiple
// unkown instance types. We'll do that by caching the document.
nsCOMPtr<nsIDocument> document;
aOwner->GetDocument(getter_AddRefs(document));
nsCOMPtr<nsIDocument> currentdocument = do_QueryReferent(mCurrentDocument);
if (document == currentdocument) {
return rv;
}
mCurrentDocument = do_GetWeakReference(document);
// Don't try to set up an instance again if nothing changed.
if (ReloadPlugins(false) == NS_ERROR_PLUGINS_PLUGINSNOTCHANGED) {
return rv;
}
return TrySetUpPluginInstance(aMimeType, aURL, aOwner);
}
nsresult
@ -1460,11 +1432,7 @@ public:
NS_METHOD GetFilename(nsAString& aFilename)
{
bool bShowPath;
nsCOMPtr<nsIPrefBranch> prefService = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (prefService &&
NS_SUCCEEDED(prefService->GetBoolPref("plugin.expose_full_path", &bShowPath)) &&
bShowPath) {
if (Preferences::GetBool("plugin.expose_full_path", false)) {
CopyUTF8toUTF16(mPluginTag.mFullPath, aFilename);
} else {
CopyUTF8toUTF16(mPluginTag.mFileName, aFilename);
@ -1658,15 +1626,15 @@ static nsresult CreateNPAPIPlugin(nsPluginTag *aPluginTag,
return rv;
}
nsresult nsPluginHost::EnsurePluginLoaded(nsPluginTag* plugin)
nsresult nsPluginHost::EnsurePluginLoaded(nsPluginTag* aPluginTag)
{
nsRefPtr<nsNPAPIPlugin> entrypoint = plugin->mEntryPoint;
if (!entrypoint) {
nsresult rv = CreateNPAPIPlugin(plugin, getter_AddRefs(entrypoint));
nsRefPtr<nsNPAPIPlugin> plugin = aPluginTag->mPlugin;
if (!plugin) {
nsresult rv = CreateNPAPIPlugin(aPluginTag, getter_AddRefs(plugin));
if (NS_FAILED(rv)) {
return rv;
}
plugin->mEntryPoint = entrypoint;
aPluginTag->mPlugin = plugin;
}
return NS_OK;
}
@ -1699,7 +1667,7 @@ nsresult nsPluginHost::GetPlugin(const char *aMimeType, nsNPAPIPlugin** aPlugin)
return rv;
}
NS_ADDREF(*aPlugin = pluginTag->mEntryPoint);
NS_ADDREF(*aPlugin = pluginTag->mPlugin);
return NS_OK;
}
@ -1823,7 +1791,7 @@ nsPluginHost::ClearSiteData(nsIPluginTag* plugin, const nsACString& domain,
// We only ensure support for clearing Flash site data for now.
// We will also attempt to clear data for any plugin that happens
// to be loaded already.
if (!tag->mIsFlashPlugin && !tag->mEntryPoint) {
if (!tag->mIsFlashPlugin && !tag->mPlugin) {
return NS_ERROR_FAILURE;
}
@ -1833,7 +1801,7 @@ nsPluginHost::ClearSiteData(nsIPluginTag* plugin, const nsACString& domain,
return rv;
}
PluginLibrary* library = tag->mEntryPoint->GetLibrary();
PluginLibrary* library = tag->mPlugin->GetLibrary();
// If 'domain' is the null string, clear everything.
if (domain.IsVoid()) {
@ -1874,7 +1842,7 @@ nsPluginHost::SiteHasData(nsIPluginTag* plugin, const nsACString& domain,
// We only ensure support for clearing Flash site data for now.
// We will also attempt to clear data for any plugin that happens
// to be loaded already.
if (!tag->mIsFlashPlugin && !tag->mEntryPoint) {
if (!tag->mIsFlashPlugin && !tag->mPlugin) {
return NS_ERROR_FAILURE;
}
@ -1884,7 +1852,7 @@ nsPluginHost::SiteHasData(nsIPluginTag* plugin, const nsACString& domain,
return rv;
}
PluginLibrary* library = tag->mEntryPoint->GetLibrary();
PluginLibrary* library = tag->mPlugin->GetLibrary();
// Get the list of sites from the plugin.
InfallibleTArray<nsCString> sites;
@ -2225,7 +2193,7 @@ nsresult nsPluginHost::ScanPluginsDirectory(nsIFile *pluginsDir,
}
if (warnOutdated) {
mPrefService->SetBoolPref("plugins.update.notifyUser", true);
Preferences::SetBool("plugins.update.notifyUser", true);
}
return NS_OK;
@ -2354,10 +2322,7 @@ nsresult nsPluginHost::FindPlugins(bool aCreatePluginList, bool * aPluginsChange
// the rest is optional
#ifdef XP_WIN
bool bScanPLIDs = false;
if (mPrefService)
mPrefService->GetBoolPref("plugin.scan.plid.all", &bScanPLIDs);
bool bScanPLIDs = Preferences::GetBool("plugin.scan.plid.all", false);
// Now lets scan any PLID directories
if (bScanPLIDs && mPrivateDirServiceProvider) {
@ -3239,13 +3204,9 @@ nsPluginHost::StopPluginInstance(nsNPAPIPluginInstance* aInstance)
bool doCache = aInstance->ShouldCache();
if (doCache) {
// try to get the max cached instances from a pref or use default
PRUint32 cachedInstanceLimit;
nsresult rv = NS_ERROR_FAILURE;
if (mPrefService)
rv = mPrefService->GetIntPref(NS_PREF_MAX_NUM_CACHED_INSTANCES, (int*)&cachedInstanceLimit);
if (NS_FAILED(rv))
cachedInstanceLimit = DEFAULT_NUMBER_OF_STOPPED_INSTANCES;
PRUint32 cachedInstanceLimit =
Preferences::GetUint(NS_PREF_MAX_NUM_CACHED_INSTANCES,
DEFAULT_NUMBER_OF_STOPPED_INSTANCES);
if (StoppedInstanceCount() >= cachedInstanceLimit) {
nsNPAPIPluginInstance *oldestInstance = FindOldestStoppedInstance();
if (oldestInstance) {
@ -3984,10 +3945,10 @@ nsPluginHost::PluginCrashed(nsNPAPIPlugin* aPlugin,
}
// Only after all instances have been invalidated is it safe to null
// out nsPluginTag.mEntryPoint. The next time we try to create an
// out nsPluginTag.mPlugin. The next time we try to create an
// instance of this plugin we reload it (launch a new plugin process).
crashedPluginTag->mEntryPoint = nsnull;
crashedPluginTag->mPlugin = nsnull;
#ifdef XP_WIN
CheckForDisabledWindows();

View File

@ -53,7 +53,6 @@
#include "nsWeakPtr.h"
#include "nsIPrompt.h"
#include "nsISupportsArray.h"
#include "nsIPrefBranch.h"
#include "nsWeakReference.h"
#include "nsThreadUtils.h"
#include "nsTArray.h"
@ -275,9 +274,9 @@ private:
bool aCreatePluginList,
bool *aPluginsChanged);
nsresult EnsurePluginLoaded(nsPluginTag* plugin);
nsresult EnsurePluginLoaded(nsPluginTag* aPluginTag);
bool IsRunningPlugin(nsPluginTag * plugin);
bool IsRunningPlugin(nsPluginTag * aPluginTag);
// Stores all plugins info into the registry
nsresult WritePluginInfo();
@ -322,7 +321,6 @@ private:
nsTArray< nsRefPtr<nsNPAPIPluginInstance> > mInstances;
nsCOMPtr<nsIFile> mPluginRegFile;
nsCOMPtr<nsIPrefBranch> mPrefService;
#ifdef XP_WIN
nsRefPtr<nsPluginDirServiceProvider> mPrivateDirServiceProvider;
#endif

View File

@ -40,8 +40,6 @@
#include "npapi.h"
#include "nsPluginHost.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include <prinrval.h>
#if defined(XP_WIN)
@ -52,14 +50,15 @@ void NS_NotifyPluginCall(PRIntervalTime);
#ifdef CALL_SAFETY_ON
#include "mozilla/Preferences.h"
extern bool gSkipPluginSafeCalls;
#define NS_INIT_PLUGIN_SAFE_CALLS \
PR_BEGIN_MACRO \
nsresult res; \
nsCOMPtr<nsIPrefBranch> pref(do_GetService(NS_PREFSERVICE_CONTRACTID, &res)); \
if(NS_SUCCEEDED(res) && pref) \
res = pref->GetBoolPref("plugin.dont_try_safe_calls", &gSkipPluginSafeCalls);\
#define NS_INIT_PLUGIN_SAFE_CALLS \
PR_BEGIN_MACRO \
gSkipPluginSafeCalls = \
::mozilla::Preferences::GetBool("plugin.dont_try_safe_calls", \
gSkipPluginSafeCalls); \
PR_END_MACRO
#define NS_TRY_SAFE_CALL_RETURN(ret, fun, pluginInst) \

View File

@ -45,8 +45,6 @@
#include "nsIPluginInstanceOwner.h"
#include "nsIDocument.h"
#include "nsServiceManagerUtils.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsPluginsDir.h"
#include "nsPluginHost.h"
#include "nsIUnicodeDecoder.h"
@ -56,7 +54,9 @@
#include "nsICategoryManager.h"
#include "nsNPAPIPlugin.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Preferences.h"
using namespace mozilla;
using mozilla::TimeStamp;
inline char* new_str(const char* str)
@ -388,10 +388,6 @@ nsPluginTag::RegisterWithCategoryManager(bool aOverrideInternalTypes,
const char *contractId = "@mozilla.org/content/plugin/document-loader-factory;1";
nsCOMPtr<nsIPrefBranch> psvc(do_GetService(NS_PREFSERVICE_CONTRACTID));
if (!psvc)
return; // NS_ERROR_OUT_OF_MEMORY
// A preference controls whether or not the full page plugin is disabled for
// a particular type. The string must be in the form:
// type1,type2,type3,type4
@ -399,11 +395,11 @@ nsPluginTag::RegisterWithCategoryManager(bool aOverrideInternalTypes,
// (and other plugin host settings) so applications can reliably disable
// plugins - without relying on implementation details such as prefs/category
// manager entries.
nsXPIDLCString overrideTypes;
nsCAutoString overrideTypesFormatted;
if (aType != ePluginUnregister) {
psvc->GetCharPref("plugin.disable_full_page_plugin_for_types", getter_Copies(overrideTypes));
overrideTypesFormatted.Assign(',');
nsAdoptingCString overrideTypes =
Preferences::GetCString("plugin.disable_full_page_plugin_for_types");
overrideTypesFormatted += overrideTypes;
overrideTypesFormatted.Append(',');
}
@ -514,8 +510,8 @@ void nsPluginTag::TryUnloadPlugin(bool inShutdown)
return;
}
if (mEntryPoint) {
mEntryPoint->Shutdown();
mEntryPoint = nsnull;
if (mPlugin) {
mPlugin->Shutdown();
mPlugin = nsnull;
}
}

View File

@ -108,7 +108,7 @@ public:
nsTArray<nsCString> mMimeDescriptions; // UTF-8
nsTArray<nsCString> mExtensions; // UTF-8
PRLibrary *mLibrary;
nsRefPtr<nsNPAPIPlugin> mEntryPoint;
nsRefPtr<nsNPAPIPlugin> mPlugin;
bool mIsJavaPlugin;
bool mIsNPRuntimeEnabledJavaPlugin;
bool mIsFlashPlugin;

View File

@ -41,8 +41,6 @@
#elif XP_MACOSX
#include "PluginInterposeOSX.h"
#include "PluginUtilsOSX.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#endif
#ifdef MOZ_WIDGET_QT
#include <QtCore/QCoreApplication>
@ -1163,15 +1161,8 @@ PluginModuleParent::RecvGetNativeCursorsSupported(bool* supported)
{
PLUGIN_LOG_DEBUG(("%s", FULLFUNCTION));
#if defined(XP_MACOSX)
bool nativeCursorsSupported = false;
nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (prefs) {
if (NS_FAILED(prefs->GetBoolPref("dom.ipc.plugins.nativeCursorSupport",
&nativeCursorsSupported))) {
nativeCursorsSupported = false;
}
}
*supported = nativeCursorsSupported;
*supported =
Preferences::GetBool("dom.ipc.plugins.nativeCursorSupport", false);
return true;
#else
NS_NOTREACHED(

View File

@ -35,6 +35,7 @@
*
* ***** END LICENSE BLOCK ***** */
#include "mozilla/Hal.h"
#include "PowerManager.h"
#include "WakeLock.h"
#include "nsContentUtils.h"
@ -87,33 +88,32 @@ PowerManager::Shutdown()
return NS_OK;
}
nsresult
bool
PowerManager::CheckPermission()
{
if (nsContentUtils::IsCallerChrome()) {
return NS_OK;
return true;
}
nsCOMPtr<nsPIDOMWindow> win = do_QueryReferent(mWindow);
NS_ENSURE_STATE(win);
NS_ENSURE_TRUE(win, false);
nsCOMPtr<nsIDocument> doc = do_QueryInterface(win->GetExtantDocument());
NS_ENSURE_STATE(doc);
NS_ENSURE_TRUE(doc, false);
nsCOMPtr<nsIURI> uri;
doc->NodePrincipal()->GetURI(getter_AddRefs(uri));
if (!nsContentUtils::URIIsChromeOrInPref(uri, "dom.power.whitelist")) {
return NS_ERROR_DOM_SECURITY_ERR;
return false;
}
return NS_OK;
return true;
}
NS_IMETHODIMP
PowerManager::Reboot()
{
nsresult rv = CheckPermission();
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
nsCOMPtr<nsIPowerManagerService> pmService =
do_GetService(POWERMANAGERSERVICE_CONTRACTID);
@ -127,8 +127,7 @@ PowerManager::Reboot()
NS_IMETHODIMP
PowerManager::PowerOff()
{
nsresult rv = CheckPermission();
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
nsCOMPtr<nsIPowerManagerService> pmService =
do_GetService(POWERMANAGERSERVICE_CONTRACTID);
@ -142,8 +141,7 @@ PowerManager::PowerOff()
NS_IMETHODIMP
PowerManager::AddWakeLockListener(nsIDOMMozWakeLockListener *aListener)
{
nsresult rv = CheckPermission();
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
// already added? bail out.
if (mListeners.Contains(aListener))
@ -156,8 +154,7 @@ PowerManager::AddWakeLockListener(nsIDOMMozWakeLockListener *aListener)
NS_IMETHODIMP
PowerManager::RemoveWakeLockListener(nsIDOMMozWakeLockListener *aListener)
{
nsresult rv = CheckPermission();
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
mListeners.RemoveElement(aListener);
return NS_OK;
@ -166,8 +163,7 @@ PowerManager::RemoveWakeLockListener(nsIDOMMozWakeLockListener *aListener)
NS_IMETHODIMP
PowerManager::GetWakeLockState(const nsAString &aTopic, nsAString &aState)
{
nsresult rv = CheckPermission();
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
nsCOMPtr<nsIPowerManagerService> pmService =
do_GetService(POWERMANAGERSERVICE_CONTRACTID);
@ -195,6 +191,51 @@ PowerManager::Callback(const nsAString &aTopic, const nsAString &aState)
return NS_OK;
}
NS_IMETHODIMP
PowerManager::GetScreenEnabled(bool *aEnabled)
{
if (!CheckPermission()) {
*aEnabled = true;
return NS_OK;
}
*aEnabled = hal::GetScreenEnabled();
return NS_OK;
}
NS_IMETHODIMP
PowerManager::SetScreenEnabled(bool aEnabled)
{
NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
// TODO bug 707589: When the screen's state changes, all visible windows
// should fire a visibility change event.
hal::SetScreenEnabled(aEnabled);
return NS_OK;
}
NS_IMETHODIMP
PowerManager::GetScreenBrightness(double *aBrightness)
{
if (!CheckPermission()) {
*aBrightness = 1;
return NS_OK;
}
*aBrightness = hal::GetScreenBrightness();
return NS_OK;
}
NS_IMETHODIMP
PowerManager::SetScreenBrightness(double aBrightness)
{
NS_ENSURE_TRUE(CheckPermission(), NS_ERROR_DOM_SECURITY_ERR);
NS_ENSURE_TRUE(0 <= aBrightness && aBrightness <= 1, NS_ERROR_INVALID_ARG);
hal::SetScreenBrightness(aBrightness);
return NS_OK;
}
} // power
} // dom
} // mozilla

View File

@ -64,7 +64,7 @@ public:
nsresult Shutdown();
private:
nsresult CheckPermission();
bool CheckPermission();
nsWeakPtr mWindow;
nsTArray<nsCOMPtr<nsIDOMMozWakeLockListener> > mListeners;

View File

@ -42,7 +42,7 @@ interface nsIDOMMozWakeLockListener;
/**
* This interface implements navigator.mozPower
*/
[scriptable, uuid(abf4b2b1-139d-4eff-998d-8f24616910ae)]
[scriptable, uuid(4586bed1-cf78-4436-b503-88277d645b68)]
interface nsIDOMMozPowerManager : nsISupports
{
void powerOff();
@ -73,4 +73,27 @@ interface nsIDOMMozPowerManager : nsISupports
* @param aTopic The resource name related to the wake lock.
*/
DOMString getWakeLockState(in DOMString aTopic);
/**
* Is the device's screen currently enabled? This attribute controls the
* device's screen, so setting it to false will turn off the screen.
*/
attribute boolean screenEnabled;
/**
* How bright is the screen's backlight, on a scale from 0 (very dim) to 1
* (full brightness)? Setting this attribute modifies the screen's
* brightness.
*
* You can read and write this attribute even when the screen is disabled,
* but the backlight is off while the screen is disabled.
*
* If you write a value of X into this attribute, the attribute may not have
* the same value X when you later read it. Most screens don't support as
* many different brightness levels as there are doubles between 0 and 1, so
* we may reduce the value's precision before storing it.
*
* @throw NS_ERROR_INVALID_ARG if brightness is not in the range [0, 1].
*/
attribute double screenBrightness;
};

View File

@ -66,8 +66,6 @@
#include "nsIURI.h"
#include "nsIPermissionManager.h"
#include "nsIObserverService.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsIJSContextStack.h"
#include "nsThreadUtils.h"
#include "mozilla/Services.h"

View File

@ -61,7 +61,6 @@ using mozilla::dom::StorageChild;
#include "nsReadableUtils.h"
#include "nsIObserverService.h"
#include "nsNetUtil.h"
#include "nsIPrefBranch.h"
#include "nsICookiePermission.h"
#include "nsIPermission.h"
#include "nsIPermissionManager.h"

View File

@ -48,7 +48,8 @@
#include "nsIServiceManager.h"
#include "nsIPrivateDOMEvent.h"
#include "nsIServiceManager.h"
#include "nsIPrefService.h"
#include "mozilla/Preferences.h"
using namespace mozilla;
using namespace hal;
@ -122,17 +123,9 @@ NS_IMETHODIMP nsDeviceSensorData::GetZ(double *aZ)
NS_IMPL_ISUPPORTS1(nsDeviceSensors, nsIDeviceSensors)
nsDeviceSensors::nsDeviceSensors()
: mEnabled(true)
{
mLastDOMMotionEventTime = TimeStamp::Now();
nsCOMPtr<nsIPrefBranch> prefSrv = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (prefSrv) {
bool bvalue;
nsresult rv = prefSrv->GetBoolPref("device.motion.enabled", &bvalue);
if (NS_SUCCEEDED(rv) && bvalue == false)
mEnabled = false;
}
mEnabled = Preferences::GetBool("device.motion.enabled", true);
for (int i = 0; i < NUM_SENSOR_TYPE; i++) {
nsTArray<nsIDOMWindow*> *windows = new nsTArray<nsIDOMWindow*>();

View File

@ -41,10 +41,11 @@
#include "MaemoLocationProvider.h"
#include "nsIClassInfo.h"
#include "nsDOMClassInfoID.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsIServiceManager.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/Preferences.h"
using namespace mozilla;
NS_IMPL_ISUPPORTS2(MaemoLocationProvider, nsIGeolocationProvider, nsITimerCallback)
@ -192,31 +193,31 @@ NS_IMETHODIMP MaemoLocationProvider::Startup()
{
nsresult rv(NS_OK);
nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (!prefs)
return NS_ERROR_FAILURE;
rv = StartControl();
NS_ENSURE_SUCCESS(rv, rv);
rv = StartDevice();
NS_ENSURE_SUCCESS(rv, rv);
prefs->GetBoolPref("geo.herror.ignore.big", &mIgnoreBigHErr);
mIgnoreBigHErr =
Preferences::GetBool("geo.herror.ignore.big", mIgnoreBigHErr);
if (mIgnoreBigHErr)
prefs->GetIntPref("geo.herror.max.value", &mMaxHErr);
if (mIgnoreBigHErr) {
mMaxHErr = Preferences::GetInt("geo.herror.max.value", mMaxHErr);
}
prefs->GetBoolPref("geo.verror.ignore.big", &mIgnoreBigVErr);
mIgnoreBigVErr =
Preferences::GetBool("geo.verror.ignore.big", mIgnoreBigVErr);
if (mIgnoreBigVErr)
prefs->GetIntPref("geo.verror.max.value", &mMaxVErr);
if (mIgnoreBigVErr) {
mMaxVErr = Preferences::GetInt("geo.verror.max.value", mMaxVErr);
}
if (mUpdateTimer)
return NS_OK;
PRInt32 update = 0; //0 second no timer created
prefs->GetIntPref("geo.default.update", &update);
// 0 second no timer created
PRInt32 update = Preferences::GetInt("geo.default.update", 0);
if (!update)
return NS_OK;

View File

@ -52,8 +52,9 @@ DIST_FILES = \
TEST_EXTENSIONS_DIR = $(DEPTH)/_tests/testing/mochitest/extensions
GENERATED_DIRS = $(TEST_EXTENSIONS_DIR)
include $(topsrcdir)/config/rules.mk
libs::
$(MKDIR) -p $(TEST_EXTENSIONS_DIR)
@(cd $(DIST)/xpi-stage && tar $(TAR_CREATE_FLAGS) - $(XPI_NAME)) | (cd $(TEST_EXTENSIONS_DIR) && tar -xf -)

View File

@ -61,8 +61,9 @@ DIST_FILES = \
TEST_EXTENSIONS_DIR = $(DEPTH)/_tests/testing/mochitest/extensions
GENERATED_DIRS = $(TEST_EXTENSIONS_DIR)
include $(topsrcdir)/config/rules.mk
libs::
$(MKDIR) -p $(TEST_EXTENSIONS_DIR)
@(cd $(DIST)/xpi-stage && tar $(TAR_CREATE_FLAGS) - $(XPI_NAME)) | (cd $(TEST_EXTENSIONS_DIR) && tar -xf -)

View File

@ -16,7 +16,7 @@
<script type="text/javascript">
const workerCount = 3;
const errorMessage = "expectedError";
const errorMessage = "Error: expectedError";
const errorFilename = "http://mochi.test:8888/tests/dom/workers/test/" +
"errorPropagation_worker.js";
const errorLineno = 48;

View File

@ -20,7 +20,7 @@
}
worker.onerror = function(event) {
is(event.message, "foo!", "Got wrong error message!");
is(event.message, "Error: foo!", "Got wrong error message!");
event.preventDefault();
SimpleTest.finish();
}

View File

@ -14,8 +14,8 @@
const filename = "http://mochi.test:8888/tests/dom/workers/test/" +
"recursiveOnerror_worker.js";
const errors = [
{ message: "2", lineno: 6 },
{ message: "1", lineno: 10 }
{ message: "Error: 2", lineno: 6 },
{ message: "Error: 1", lineno: 10 }
]
var errorCount = 0;

View File

@ -63,6 +63,7 @@
//defines
#define STATE_ENABLED "state_enabled"
#define STATE_ALL "state_all"
#define STATE_ATTRIBUTE "state_attribute"
#define STATE_DATA "state_data"
@ -378,7 +379,7 @@ nsSetDocumentStateCommand::GetCommandStateParams(const char *aCommandName,
bool isCSS;
htmleditor->GetIsCSSEnabled(&isCSS);
return aParams->SetBooleanValue(STATE_ATTRIBUTE, isCSS);
return aParams->SetBooleanValue(STATE_ALL, isCSS);
}
if (!nsCRT::strcmp(aCommandName, "cmd_insertBrOnReturn"))

View File

@ -50,6 +50,7 @@ _TEST_FILES = \
test_bug389350.html \
test_bug519928.html \
bug678842_subframe.html \
test_bug738440.html \
$(NULL)
_CHROME_TEST_FILES = \

View File

@ -0,0 +1,37 @@
<!doctype html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=738440
-->
<title>Test for Bug 738440</title>
<script src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" href="/tests/SimpleTest/test.css" />
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=738440">Mozilla Bug 738440</a>
<div contenteditable></div>
<script>
/** Test for Bug 738440 **/
document.execCommand("stylewithcss", false, "true");
is(document.queryCommandState("stylewithcss"), true,
"setting stylewithcss to true should cause its state to be true");
is(document.queryCommandState("usecss"), false,
"usecss state should always be false");
document.execCommand("stylewithcss", false, "false");
is(document.queryCommandState("stylewithcss"), false,
"setting stylewithcss to false should cause its state to be false");
is(document.queryCommandState("usecss"), false,
"usecss state should always be false");
document.execCommand("usecss", false, "true");
is(document.queryCommandState("stylewithcss"), false,
"setting usecss to true should cause stylewithcss state to be false");
is(document.queryCommandState("usecss"), false,
"usecss state should always be false");
document.execCommand("usecss", false, "false");
is(document.queryCommandState("stylewithcss"), true,
"setting usecss to false should cause stylewithcss state to be true");
is(document.queryCommandState("usecss"), false,
"usecss state should always be false");
</script>

View File

@ -9,12 +9,22 @@ function boom()
{
document.getElementById("i").focus();
try { document.execCommand("stylewithcss", false, "true") } catch(e) { }
try { document.execCommand("inserthtml", false, "<x>X</x>"); } catch(e) { }
try { document.execCommand("underline", false, null); } catch(e) { }
try { document.execCommand("justifyfull", false, null); } catch(e) { }
try { document.execCommand("underline", false, null); } catch(e) { }
try { document.execCommand("insertParagraph", false, null); } catch(e) { }
try { document.execCommand("delete", false, null); } catch(e) { }
try { document.execCommand("stylewithcss", false, "false") } catch(e) { }
try { document.execCommand("inserthtml", false, "<x>X</x>"); } catch(e) { }
try { document.execCommand("underline", false, null); } catch(e) { }
try { document.execCommand("justifyfull", false, null); } catch(e) { }
try { document.execCommand("underline", false, null); } catch(e) { }
try { document.execCommand("insertParagraph", false, null); } catch(e) { }
try { document.execCommand("delete", false, null); } catch(e) { }
document.documentElement.removeAttribute("class");
}

View File

@ -6,7 +6,7 @@ load 407256-1.html
load 430624-1.html
load 459613.html
load 475132-1.xhtml
asserts-if(!Android,1) load 633709.xhtml # Bug 695364
asserts-if(!Android,2) load 633709.xhtml # Bug 695364 and bug 671153
asserts-if(!Android,6) load 636074-1.html # Bug 439258, charged to the wrong test due to bug 635550
load 713427-1.html
load 713427-2.xhtml

View File

@ -299,7 +299,7 @@ const nsHTMLCSSUtils::CSSEquivTable hrAlignEquivTable[] = {
nsHTMLCSSUtils::nsHTMLCSSUtils(nsHTMLEditor* aEditor)
: mHTMLEditor(aEditor)
, mIsCSSPrefChecked(false)
, mIsCSSPrefChecked(true)
{
// let's retrieve the value of the "CSS editing" pref
mIsCSSPrefChecked = Preferences::GetBool("editor.use_css", mIsCSSPrefChecked);

View File

@ -1624,6 +1624,9 @@ NS_IMETHODIMP nsHTMLEditor::PasteTransferable(nsITransferable *aTransferable)
//
NS_IMETHODIMP nsHTMLEditor::PasteNoFormatting(PRInt32 aSelectionType)
{
if (!FireClipboardEvent(NS_PASTE))
return NS_OK;
ForceCompositionEnd();
// Get Clipboard Service

View File

@ -102,6 +102,7 @@ _TEST_FILES = \
test_select_all_without_body.html \
file_select_all_without_body.html \
test_root_element_replacement.html \
test_bug738366.html \
$(NULL)
ifneq (mobile,$(MOZ_BUILD_APP))

View File

@ -25,7 +25,7 @@ editor.innerHTML = '<p></p><ul><li>Item 1</li><li>Item 2</li></ul><p></p>';
editor.focus();
addLoadEvent(function() {
document.execCommand("stylewithcss", false, "true");
var sel = window.getSelection();
sel.removeAllRanges();
var lis = document.getElementsByTagName("li");

View File

@ -21,6 +21,11 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=410986
/** Test for Bug 410986 **/
var gPasteEvents = 0;
document.getElementById("editor").addEventListener("paste", function() {
++gPasteEvents;
}, false);
SimpleTest.waitForExplicitFinish();
SimpleTest.waitForFocus(function() {
getSelection().selectAllChildren(document.getElementById("contents"));
@ -37,6 +42,7 @@ SimpleTest.waitForFocus(function() {
synthesizeKey("V", {accelKey: true, shiftKey: true});
}
is(ed.innerHTML, "green text", "Content should be pasted in plaintext format");
is(gPasteEvents, 1, "One paste event must be fired");
ed.innerHTML = "";
ed.blur();
@ -51,6 +57,7 @@ SimpleTest.waitForFocus(function() {
synthesizeKey("V", {accelKey: true});
isnot(ed.innerHTML.indexOf("<span style=\"color: green;\">green text</span>"), -1,
"Content should be pasted in HTML format");
is(gPasteEvents, 2, "Two paste events must be fired");
SimpleTest.finish();
},

View File

@ -54,6 +54,8 @@ function justify(textNode, pos) {
}
function runTests() {
document.execCommand("stylewithcss", false, "true");
const test1 = document.getElementById("test1");
const test2 = document.getElementById("test2");
const test3 = document.getElementById("test3");

View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=738366
-->
<title>Test for Bug 738366</title>
<script src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" href="/tests/SimpleTest/test.css"/>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=738366">Mozilla Bug 738366</a>
<div id="display" contenteditable>foobarbaz</div>
<script>
/** Test for Bug 738366 **/
getSelection().collapse(document.getElementById("display").firstChild, 3);
getSelection().extend(document.getElementById("display").firstChild, 6);
document.execCommand("bold");
is(document.getElementById("display").innerHTML, "foo<b>bar</b>baz",
"styleWithCSS must default to false");
document.execCommand("stylewithcss", false, "true");
document.execCommand("bold");
document.execCommand("bold");
is(document.getElementById("display").innerHTML,
'foo<span style="font-weight: bold;">bar</span>baz',
"styleWithCSS must be settable to true");
</script>

View File

@ -31,6 +31,7 @@ const kIsLinux = navigator.platform.indexOf("Linux") == 0 || navigator.platform.
function runTests()
{
document.execCommand("stylewithcss", false, "true");
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var fm = Components.classes["@mozilla.org/focus-manager;1"].

View File

@ -829,6 +829,11 @@ public:
#ifdef WIN32
static TemporaryRef<DrawTarget> CreateDrawTargetForD3D10Texture(ID3D10Texture2D *aTexture, SurfaceFormat aFormat);
static TemporaryRef<DrawTarget>
CreateDualDrawTargetForD3D10Textures(ID3D10Texture2D *aTextureA,
ID3D10Texture2D *aTextureB,
SurfaceFormat aFormat);
static void SetDirect3D10Device(ID3D10Device1 *aDevice);
static ID3D10Device1 *GetDirect3D10Device();

213
gfx/2d/DrawTargetDual.cpp Normal file
View File

@ -0,0 +1,213 @@
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Corporation code.
*
* The Initial Developer of the Original Code is Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bas Schouten <bschouten@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "DrawTargetDual.h"
#include "Tools.h"
namespace mozilla {
namespace gfx {
class DualSurface
{
public:
inline DualSurface(SourceSurface *aSurface)
{
if (aSurface->GetType() != SURFACE_DUAL_DT) {
mA = mB = aSurface;
return;
}
SourceSurfaceDual *ssDual =
static_cast<SourceSurfaceDual*>(aSurface);
mA = ssDual->mA;
mB = ssDual->mB;
}
SourceSurface *mA;
SourceSurface *mB;
};
/* This only needs to split patterns up for SurfacePatterns. Only in that
* case can we be dealing with a 'dual' source (SourceSurfaceDual) and do
* we need to pass separate patterns into our destination DrawTargets.
*/
class DualPattern
{
public:
inline DualPattern(const Pattern &aPattern)
: mPatternsInitialized(false)
{
if (aPattern.GetType() != PATTERN_SURFACE) {
mA = mB = &aPattern;
return;
}
const SurfacePattern *surfPat =
static_cast<const SurfacePattern*>(&aPattern);
if (surfPat->mSurface->GetType() != SURFACE_DUAL_DT) {
mA = mB = &aPattern;
return;
}
const SourceSurfaceDual *ssDual =
static_cast<const SourceSurfaceDual*>(surfPat->mSurface.get());
mA = new (mSurfPatA.addr()) SurfacePattern(ssDual->mA, surfPat->mExtendMode,
surfPat->mMatrix, surfPat->mFilter);
mB = new (mSurfPatB.addr()) SurfacePattern(ssDual->mB, surfPat->mExtendMode,
surfPat->mMatrix, surfPat->mFilter);
mPatternsInitialized = true;
}
inline ~DualPattern()
{
if (mPatternsInitialized) {
mA->~Pattern();
mB->~Pattern();
}
}
ClassStorage<SurfacePattern> mSurfPatA;
ClassStorage<SurfacePattern> mSurfPatB;
const Pattern *mA;
const Pattern *mB;
bool mPatternsInitialized;
};
void
DrawTargetDual::DrawSurface(SourceSurface *aSurface, const Rect &aDest, const Rect &aSource,
const DrawSurfaceOptions &aSurfOptions, const DrawOptions &aOptions)
{
DualSurface surface(aSurface);
mA->DrawSurface(surface.mA, aDest, aSource, aSurfOptions, aOptions);
mB->DrawSurface(surface.mB, aDest, aSource, aSurfOptions, aOptions);
}
void
DrawTargetDual::DrawSurfaceWithShadow(SourceSurface *aSurface, const Point &aDest,
const Color &aColor, const Point &aOffset,
Float aSigma, CompositionOp aOp)
{
DualSurface surface(aSurface);
mA->DrawSurfaceWithShadow(surface.mA, aDest, aColor, aOffset, aSigma, aOp);
mB->DrawSurfaceWithShadow(surface.mB, aDest, aColor, aOffset, aSigma, aOp);
}
void
DrawTargetDual::CopySurface(SourceSurface *aSurface, const IntRect &aSourceRect,
const IntPoint &aDestination)
{
DualSurface surface(aSurface);
mA->CopySurface(surface.mA, aSourceRect, aDestination);
mB->CopySurface(surface.mB, aSourceRect, aDestination);
}
void
DrawTargetDual::FillRect(const Rect &aRect, const Pattern &aPattern, const DrawOptions &aOptions)
{
DualPattern pattern(aPattern);
mA->FillRect(aRect, *pattern.mA, aOptions);
mB->FillRect(aRect, *pattern.mB, aOptions);
}
void
DrawTargetDual::StrokeRect(const Rect &aRect, const Pattern &aPattern,
const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions)
{
DualPattern pattern(aPattern);
mA->StrokeRect(aRect, *pattern.mA, aStrokeOptions, aOptions);
mB->StrokeRect(aRect, *pattern.mB, aStrokeOptions, aOptions);
}
void
DrawTargetDual::StrokeLine(const Point &aStart, const Point &aEnd, const Pattern &aPattern,
const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions)
{
DualPattern pattern(aPattern);
mA->StrokeLine(aStart, aEnd, *pattern.mA, aStrokeOptions, aOptions);
mB->StrokeLine(aStart, aEnd, *pattern.mB, aStrokeOptions, aOptions);
}
void
DrawTargetDual::Stroke(const Path *aPath, const Pattern &aPattern,
const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions)
{
DualPattern pattern(aPattern);
mA->Stroke(aPath, *pattern.mA, aStrokeOptions, aOptions);
mB->Stroke(aPath, *pattern.mB, aStrokeOptions, aOptions);
}
void
DrawTargetDual::Fill(const Path *aPath, const Pattern &aPattern, const DrawOptions &aOptions)
{
DualPattern pattern(aPattern);
mA->Fill(aPath, *pattern.mA, aOptions);
mB->Fill(aPath, *pattern.mB, aOptions);
}
void
DrawTargetDual::FillGlyphs(ScaledFont *aScaledFont, const GlyphBuffer &aBuffer,
const Pattern &aPattern, const DrawOptions &aOptions,
const GlyphRenderingOptions *aRenderingOptions)
{
DualPattern pattern(aPattern);
mA->FillGlyphs(aScaledFont, aBuffer, *pattern.mA, aOptions, aRenderingOptions);
mB->FillGlyphs(aScaledFont, aBuffer, *pattern.mB, aOptions, aRenderingOptions);
}
void
DrawTargetDual::Mask(const Pattern &aSource, const Pattern &aMask, const DrawOptions &aOptions)
{
DualPattern source(aSource);
DualPattern mask(aMask);
mA->Mask(*source.mA, *mask.mA, aOptions);
mB->Mask(*source.mB, *mask.mB, aOptions);
}
TemporaryRef<DrawTarget>
DrawTargetDual::CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const
{
RefPtr<DrawTarget> dtA = mA->CreateSimilarDrawTarget(aSize, aFormat);
RefPtr<DrawTarget> dtB = mB->CreateSimilarDrawTarget(aSize, aFormat);
return new DrawTargetDual(dtA, dtB);
}
}
}

170
gfx/2d/DrawTargetDual.h Normal file
View File

@ -0,0 +1,170 @@
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Corporation code.
*
* The Initial Developer of the Original Code is Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bas Schouten <bschouten@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef MOZILLA_GFX_DRAWTARGETDUAL_H_
#define MOZILLA_GFX_DRAWTARGETDUAL_H_
#include <vector>
#include <sstream>
#include "SourceSurfaceDual.h"
#include "2D.h"
namespace mozilla {
namespace gfx {
#define FORWARD_FUNCTION(funcName) \
virtual void funcName() { mA->funcName(); mB->funcName(); }
#define FORWARD_FUNCTION1(funcName, var1Type, var1Name) \
virtual void funcName(var1Type var1Name) { mA->funcName(var1Name); mB->funcName(var1Name); }
/* This is a special type of DrawTarget. It duplicates all drawing calls
* accross two drawtargets. An exception to this is when a snapshot of another
* dual DrawTarget is used as the source for any surface data. In this case
* the snapshot of the first source DrawTarget is used as a source for the call
* to the first destination DrawTarget (mA) and the snapshot of the second
* source DrawTarget is used at the source for the second destination
* DrawTarget (mB). This class facilitates black-background/white-background
* drawing for per-component alpha extraction for backends which do not support
* native component alpha.
*/
class DrawTargetDual : public DrawTarget
{
public:
DrawTargetDual(DrawTarget *aA, DrawTarget *aB)
: mA(aA)
, mB(aB)
{
mFormat = aA->GetFormat();
}
virtual BackendType GetType() const { return mA->GetType(); }
virtual TemporaryRef<SourceSurface> Snapshot() { return new SourceSurfaceDual(mA, mB); }
virtual IntSize GetSize() { return mA->GetSize(); }
FORWARD_FUNCTION(Flush)
FORWARD_FUNCTION1(PushClip, const Path *, aPath)
FORWARD_FUNCTION1(PushClipRect, const Rect &, aRect)
FORWARD_FUNCTION(PopClip)
FORWARD_FUNCTION1(ClearRect, const Rect &, aRect)
virtual void SetTransform(const Matrix &aTransform) {
mTransform = aTransform;
mA->SetTransform(aTransform);
mB->SetTransform(aTransform);
}
virtual void DrawSurface(SourceSurface *aSurface, const Rect &aDest, const Rect & aSource,
const DrawSurfaceOptions &aSurfOptions, const DrawOptions &aOptions);
virtual void DrawSurfaceWithShadow(SourceSurface *aSurface, const Point &aDest,
const Color &aColor, const Point &aOffset,
Float aSigma, CompositionOp aOp);
virtual void CopySurface(SourceSurface *aSurface, const IntRect &aSourceRect,
const IntPoint &aDestination);
virtual void FillRect(const Rect &aRect, const Pattern &aPattern, const DrawOptions &aOptions);
virtual void StrokeRect(const Rect &aRect, const Pattern &aPattern,
const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions);
virtual void StrokeLine(const Point &aStart, const Point &aEnd, const Pattern &aPattern,
const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions);
virtual void Stroke(const Path *aPath, const Pattern &aPattern,
const StrokeOptions &aStrokeOptions, const DrawOptions &aOptions);
virtual void Fill(const Path *aPath, const Pattern &aPattern, const DrawOptions &aOptions);
virtual void FillGlyphs(ScaledFont *aScaledFont, const GlyphBuffer &aBuffer,
const Pattern &aPattern, const DrawOptions &aOptions,
const GlyphRenderingOptions *aRenderingOptions);
virtual void Mask(const Pattern &aSource, const Pattern &aMask, const DrawOptions &aOptions);
virtual TemporaryRef<SourceSurface>
CreateSourceSurfaceFromData(unsigned char *aData,
const IntSize &aSize,
int32_t aStride,
SurfaceFormat aFormat) const
{
return mA->CreateSourceSurfaceFromData(aData, aSize, aStride, aFormat);
}
virtual TemporaryRef<SourceSurface> OptimizeSourceSurface(SourceSurface *aSurface) const
{
return mA->OptimizeSourceSurface(aSurface);
}
virtual TemporaryRef<SourceSurface>
CreateSourceSurfaceFromNativeSurface(const NativeSurface &aSurface) const
{
return mA->CreateSourceSurfaceFromNativeSurface(aSurface);
}
virtual TemporaryRef<DrawTarget>
CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const;
virtual TemporaryRef<PathBuilder> CreatePathBuilder(FillRule aFillRule = FILL_WINDING) const
{
return mA->CreatePathBuilder(aFillRule);
}
virtual TemporaryRef<GradientStops>
CreateGradientStops(GradientStop *aStops,
uint32_t aNumStops,
ExtendMode aExtendMode = EXTEND_CLAMP) const
{
return mA->CreateGradientStops(aStops, aNumStops, aExtendMode);
}
virtual void *GetNativeSurface(NativeSurfaceType aType)
{
return NULL;
}
private:
RefPtr<DrawTarget> mA;
RefPtr<DrawTarget> mB;
};
}
}
#endif /* MOZILLA_GFX_DRAWTARGETDUAL_H_ */

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