diff options
author | Simon Hausmann <simon.hausmann@digia.com> | 2012-11-29 12:18:48 +0100 |
---|---|---|
committer | Simon Hausmann <simon.hausmann@digia.com> | 2012-11-29 12:18:57 +0100 |
commit | 4c01d0526ba4dd8cff0c0ff22a6f0ab5eb973064 (patch) | |
tree | bed2fe914fe0f7ec70abfb47d2d84af8a3604d09 | |
parent | 01485457c9a5da3f1121015afd25bb53af77662e (diff) |
Imported WebKit commit c60cfe0fc09efd257aa0111d7b133b02deb8a63e (http://svn.webkit.org/repository/webkit/trunk@136119)
New snapshot that includes the fix for installing the QtWebProcess into libexec
Change-Id: I01344e079cbdac5678c4cba6ffcc05f4597cf0d7
Reviewed-by: Simon Hausmann <simon.hausmann@digia.com>
838 files changed, 21040 insertions, 6299 deletions
@@ -1,3 +1,57 @@ +2012-11-28 Michael Pruett <michael@68k.org> + + IndexedDB: Remove duplicate toWireString() and createFromWire() methods in JSC SerializedScriptValue + https://bugs.webkit.org/show_bug.cgi?id=103554 + + Reviewed by Kentaro Hara. + + In r135022, duplicate createFromWire() and toWireString() methods + were added to the JSC version of SerializedScriptValue. In + order to allow the JSC SerializedScriptValue to compile when + ENABLE(INDEXED_DATABASE) is turned on, these new methods have + been removed and the old methods have been moved outside the + ENABLE(INDEXED_DATABASE) guard. + + * Source/autotools/symbols.filter: + +2012-11-28 Shinya Kawanaka <shinyak@chromium.org> + + [Shadow] Move Distribution stuffs from ShadowRoot + https://bugs.webkit.org/show_bug.cgi?id=103481 + + Reviewed by Hajime Morita. + + * Source/autotools/symbols.filter: + +2012-11-26 Halton Huo <halton.huo@intel.com> + + [EFL] CMake shows ENABLE_3D_RENDERING and ENABLE_WEBGL is still OFF when AC is enabled + https://bugs.webkit.org/show_bug.cgi?id=100829 + + Reviewed by Gyuyoung Kim. + + In WebKitFeatures.cmake, only use ${_name} for condition to print + a option as ON will prevent the overridden ones in OptionsXXX.cmake, + should use ${_WEBKIT_AVAILABLE_OPTIONS_INITALVALUE_${_name}} instead. + + * Source/cmake/OptionsEfl.cmake: Turn on ENABLE_3D_RENDERING and + ENABLE_WEBGL + * Source/cmake/WebKitFeatures.cmake: Use + ${_WEBKIT_AVAILABLE_OPTIONS_INITALVALUE_${_name}} to as value of + a feature is enabled. Adjust options in lexicographical order. + +2012-11-26 Kalev Lember <kalevlember@gmail.com> + + [GTK] Explicitly link against librt + https://bugs.webkit.org/show_bug.cgi?id=103194 + + Reviewed by Martin Robinson. + + Fixes broken build with undefined references to shm_open / shm_unlink + symbols. SharedMemoryUnix.cpp uses these so we need to link with -lrt. + + * configure.ac: + 2012-11-26 Laszlo Gombos <l.gombos@samsung.com> [CMake] Allow user specified compiler flags to take precedence diff --git a/Source/JavaScriptCore/CMakeLists.txt b/Source/JavaScriptCore/CMakeLists.txt index a77e9e451..7e5656025 100644 --- a/Source/JavaScriptCore/CMakeLists.txt +++ b/Source/JavaScriptCore/CMakeLists.txt @@ -100,6 +100,7 @@ SET(JavaScriptCore_SOURCES dfg/DFGStructureCheckHoistingPhase.cpp dfg/DFGThunks.cpp dfg/DFGValueSource.cpp + dfg/DFGVariableAccessDataDump.cpp dfg/DFGVariableEvent.cpp dfg/DFGVariableEventStream.cpp dfg/DFGValidate.cpp diff --git a/Source/JavaScriptCore/ChangeLog b/Source/JavaScriptCore/ChangeLog index ba2979bc2..9ab660ba2 100644 --- a/Source/JavaScriptCore/ChangeLog +++ b/Source/JavaScriptCore/ChangeLog @@ -1,3 +1,420 @@ +2012-11-28 Filip Pizlo <fpizlo@apple.com> + + SpeculatedType dumping should not use the static char buffer[thingy] idiom + https://bugs.webkit.org/show_bug.cgi?id=103584 + + Reviewed by Michael Saboff. + + Changed SpeculatedType to be "dumpable" by saying things like: + + dataLog("thingy = ", SpeculationDump(thingy)) + + Removed the old stringification functions, and changed all code that referred to them + to use the new dataLog()/print() style. + + * CMakeLists.txt: + * GNUmakefile.list.am: + * JavaScriptCore.xcodeproj/project.pbxproj: + * Target.pri: + * bytecode/SpeculatedType.cpp: + (JSC::dumpSpeculation): + (JSC::speculationToAbbreviatedString): + (JSC::dumpSpeculationAbbreviated): + * bytecode/SpeculatedType.h: + * bytecode/ValueProfile.h: + (JSC::ValueProfileBase::dump): + * bytecode/VirtualRegister.h: + (WTF::printInternal): + * dfg/DFGAbstractValue.h: + (JSC::DFG::AbstractValue::dump): + * dfg/DFGByteCodeParser.cpp: + (JSC::DFG::ByteCodeParser::injectLazyOperandSpeculation): + (JSC::DFG::ByteCodeParser::getPredictionWithoutOSRExit): + * dfg/DFGGraph.cpp: + (JSC::DFG::Graph::dump): + (JSC::DFG::Graph::predictArgumentTypes): + * dfg/DFGGraph.h: + (Graph): + * dfg/DFGStructureAbstractValue.h: + * dfg/DFGVariableAccessDataDump.cpp: Added. + (JSC::DFG::VariableAccessDataDump::VariableAccessDataDump): + (JSC::DFG::VariableAccessDataDump::dump): + * dfg/DFGVariableAccessDataDump.h: Added. + (VariableAccessDataDump): + +2012-11-28 Michael Saboff <msaboff@apple.com> + + Change Bytecompiler s_dumpsGeneratedCode to an Options value + https://bugs.webkit.org/show_bug.cgi?id=103588 + + Reviewed by Filip Pizlo. + + Moved the control of dumping bytecodes to Options::dumpGeneratedBytecodes. + + * bytecode/CodeBlock.cpp: + (JSC::CodeBlock::CodeBlock): + * bytecompiler/BytecodeGenerator.cpp: + * bytecompiler/BytecodeGenerator.h: + * jsc.cpp: + (runWithScripts): + * runtime/Options.h: + +2012-11-28 Mark Hahnenberg <mhahnenberg@apple.com> + + Copying phase should use work lists + https://bugs.webkit.org/show_bug.cgi?id=101390 + + Reviewed by Filip Pizlo. + + * JavaScriptCore.xcodeproj/project.pbxproj: + * heap/BlockAllocator.cpp: + (JSC::BlockAllocator::BlockAllocator): + * heap/BlockAllocator.h: New RegionSet for CopyWorkListSegments. + (BlockAllocator): + (JSC::CopyWorkListSegment): + * heap/CopiedBlock.h: Added a per-block CopyWorkList to keep track of the JSCells that need to be revisited during the copying + phase to copy their backing stores. + (CopiedBlock): + (JSC::CopiedBlock::CopiedBlock): + (JSC::CopiedBlock::didSurviveGC): + (JSC::CopiedBlock::didEvacuateBytes): There is now a one-to-one relationship between GCThreads and the CopiedBlocks they're + responsible for evacuating, we no longer need any of that fancy compare and swap stuff. + (JSC::CopiedBlock::pin): + (JSC::CopiedBlock::hasWorkList): + (JSC::CopiedBlock::workList): + * heap/CopiedBlockInlines.h: Added. + (JSC::CopiedBlock::reportLiveBytes): Since we now have to grab a SpinLock to perform operations on the CopyWorkList during marking, + we don't need to do any of that fancy compare and swap stuff we were doing for tracking live bytes. + * heap/CopiedSpace.h: + (CopiedSpace): + * heap/CopiedSpaceInlines.h: + (JSC::CopiedSpace::pin): + * heap/CopyVisitor.cpp: + (JSC::CopyVisitor::copyFromShared): We now iterate over a range of CopiedBlocks rather than MarkedBlocks and revisit the cells in those + blocks' CopyWorkLists. + * heap/CopyVisitor.h: + (CopyVisitor): + * heap/CopyVisitorInlines.h: + (JSC::CopyVisitor::visitCell): The function responsible for calling the correct copyBackingStore() function for each JSCell from + a CopiedBlock's CopyWorkList. + (JSC::CopyVisitor::didCopy): We no longer need to check if the block is empty here because we know exactly when we're done + evacuating a CopiedBlock, which is when we've gone through all of the CopiedBlock's CopyWorkList. + * heap/CopyWorkList.h: Added. + (CopyWorkListSegment): Individual chunk of a CopyWorkList that is allocated from the BlockAllocator. + (JSC::CopyWorkListSegment::create): + (JSC::CopyWorkListSegment::size): + (JSC::CopyWorkListSegment::isFull): + (JSC::CopyWorkListSegment::get): + (JSC::CopyWorkListSegment::append): + (JSC::CopyWorkListSegment::CopyWorkListSegment): + (JSC::CopyWorkListSegment::data): + (JSC::CopyWorkListSegment::endOfBlock): + (CopyWorkListIterator): Responsible for giving CopyVisitors a contiguous notion of access across the separate CopyWorkListSegments + that make up each CopyWorkList. + (JSC::CopyWorkListIterator::get): + (JSC::CopyWorkListIterator::operator*): + (JSC::CopyWorkListIterator::operator->): + (JSC::CopyWorkListIterator::operator++): + (JSC::CopyWorkListIterator::operator==): + (JSC::CopyWorkListIterator::operator!=): + (JSC::CopyWorkListIterator::CopyWorkListIterator): + (CopyWorkList): Data structure that keeps track of the JSCells that need copying in a particular CopiedBlock. + (JSC::CopyWorkList::CopyWorkList): + (JSC::CopyWorkList::~CopyWorkList): + (JSC::CopyWorkList::append): + (JSC::CopyWorkList::begin): + (JSC::CopyWorkList::end): + * heap/GCThreadSharedData.cpp: + (JSC::GCThreadSharedData::GCThreadSharedData): We no longer use the m_blockSnapshot from the Heap during the copying phase. + (JSC::GCThreadSharedData::didStartCopying): We now copy the set of all blocks in the CopiedSpace to a separate vector for + iterating over during the copying phase since the set stored in the CopiedSpace will change as blocks are evacuated and + recycled throughout the copying phase. + * heap/GCThreadSharedData.h: + (GCThreadSharedData): + * heap/Heap.h: + (Heap): + * heap/SlotVisitor.h: We now need to know the object who is being marked that has a backing store so that we can store it + in a CopyWorkList to revisit later during the copying phase. + * heap/SlotVisitorInlines.h: + (JSC::SlotVisitor::copyLater): + * runtime/JSObject.cpp: + (JSC::JSObject::visitButterfly): + +2012-11-28 Filip Pizlo <fpizlo@apple.com> + + Disassembly methods should be able to disassemble to any PrintStream& rather than always using WTF::dataFile() + https://bugs.webkit.org/show_bug.cgi?id=103492 + + Reviewed by Mark Hahnenberg. + + Switched disassembly code to use PrintStream&, and to use print() rather than printf(). + + * dfg/DFGDisassembler.cpp: + (JSC::DFG::Disassembler::dump): + (DFG): + (JSC::DFG::Disassembler::dumpDisassembly): + * dfg/DFGDisassembler.h: + (Disassembler): + * dfg/DFGGraph.cpp: + (JSC::DFG::printWhiteSpace): + (JSC::DFG::Graph::dumpCodeOrigin): + (JSC::DFG::Graph::printNodeWhiteSpace): + (JSC::DFG::Graph::dump): + (DFG): + (JSC::DFG::Graph::dumpBlockHeader): + * dfg/DFGGraph.h: + (Graph): + * jit/JITDisassembler.cpp: + (JSC::JITDisassembler::dump): + (JSC::JITDisassembler::dumpForInstructions): + (JSC::JITDisassembler::dumpDisassembly): + * jit/JITDisassembler.h: + (JITDisassembler): + +2012-11-28 Filip Pizlo <fpizlo@apple.com> + + It should be possible to say dataLog("count = ", count, "\n") instead of dataLogF("count = %d\n", count) + https://bugs.webkit.org/show_bug.cgi?id=103009 + + Reviewed by Michael Saboff. + + Instead of converting all of JSC to use the new dataLog()/print() methods, I just changed + one place: dumping of abstract values. This is mainly just to ensure that the code I + added to WTF is actually doing things. + + * bytecode/CodeBlock.cpp: + (JSC::CodeBlock::dump): + * dfg/DFGAbstractValue.h: + (JSC::DFG::AbstractValue::dump): + (WTF): + (WTF::printInternal): + * dfg/DFGStructureAbstractValue.h: + (JSC::DFG::StructureAbstractValue::dump): + (WTF): + (WTF::printInternal): + +2012-11-28 Oliver Hunt <oliver@apple.com> + + Make source cache include more information about the function extent. + https://bugs.webkit.org/show_bug.cgi?id=103552 + + Reviewed by Gavin Barraclough. + + Add a bit more information to the source cache. + + * parser/Parser.cpp: + (JSC::::parseFunctionInfo): + Store the function start offset + * parser/SourceProviderCacheItem.h: + (JSC::SourceProviderCacheItem::SourceProviderCacheItem): + (SourceProviderCacheItem): + Add additional field for the start of the real function string, and re-arrange + fields to avoid growing the struct. + +2012-11-27 Filip Pizlo <fpizlo@apple.com> + + Convert some remaining uses of FILE* to PrintStream&. + + Rubber stamped by Mark Hahnenberg. + + * bytecode/ValueProfile.h: + (JSC::ValueProfileBase::dump): + * bytecode/ValueRecovery.h: + (JSC::ValueRecovery::dump): + * dfg/DFGByteCodeParser.cpp: + (JSC::DFG::ByteCodeParser::parseCodeBlock): + * dfg/DFGNode.h: + (JSC::DFG::Node::dumpChildren): + +2012-11-27 Filip Pizlo <fpizlo@apple.com> + + Fix indentation in JSValue.h + + Rubber stamped by Mark Hahnenberg. + + * runtime/JSValue.h: + +2012-11-26 Filip Pizlo <fpizlo@apple.com> + + DFG SetLocal should use forwardSpeculationCheck instead of its own half-baked version of same + https://bugs.webkit.org/show_bug.cgi?id=103353 + + Reviewed by Oliver Hunt and Gavin Barraclough. + + Made it possible to use forward speculations for most of the operand classes. Changed the conditional + direction parameter from being 'bool isForward' to an enum (SpeculationDirection). Changed SetLocal + to use forward speculations and got rid of its half-baked version of same. + + Also added the ability to force the DFG's disassembler to dump all nodes, even ones that are dead. + + * dfg/DFGByteCodeParser.cpp: + (JSC::DFG::ByteCodeParser::parseBlock): + * dfg/DFGDisassembler.cpp: + (JSC::DFG::Disassembler::dump): + * dfg/DFGDriver.cpp: + (JSC::DFG::compile): + * dfg/DFGSpeculativeJIT.cpp: + (JSC::DFG::SpeculativeJIT::speculationCheck): + (DFG): + (JSC::DFG::SpeculativeJIT::convertLastOSRExitToForward): + (JSC::DFG::SpeculativeJIT::speculationWatchpoint): + (JSC::DFG::SpeculativeJIT::terminateSpeculativeExecution): + (JSC::DFG::SpeculativeJIT::fillStorage): + * dfg/DFGSpeculativeJIT.h: + (SpeculativeJIT): + (JSC::DFG::SpeculateIntegerOperand::SpeculateIntegerOperand): + (JSC::DFG::SpeculateIntegerOperand::gpr): + (SpeculateIntegerOperand): + (JSC::DFG::SpeculateDoubleOperand::SpeculateDoubleOperand): + (JSC::DFG::SpeculateDoubleOperand::fpr): + (SpeculateDoubleOperand): + (JSC::DFG::SpeculateCellOperand::SpeculateCellOperand): + (JSC::DFG::SpeculateCellOperand::gpr): + (SpeculateCellOperand): + (JSC::DFG::SpeculateBooleanOperand::SpeculateBooleanOperand): + (JSC::DFG::SpeculateBooleanOperand::gpr): + (SpeculateBooleanOperand): + * dfg/DFGSpeculativeJIT32_64.cpp: + (JSC::DFG::SpeculativeJIT::fillSpeculateIntInternal): + (JSC::DFG::SpeculativeJIT::fillSpeculateInt): + (JSC::DFG::SpeculativeJIT::fillSpeculateIntStrict): + (JSC::DFG::SpeculativeJIT::fillSpeculateDouble): + (JSC::DFG::SpeculativeJIT::fillSpeculateCell): + (JSC::DFG::SpeculativeJIT::fillSpeculateBoolean): + (JSC::DFG::SpeculativeJIT::compile): + * dfg/DFGSpeculativeJIT64.cpp: + (JSC::DFG::SpeculativeJIT::fillSpeculateIntInternal): + (JSC::DFG::SpeculativeJIT::fillSpeculateInt): + (JSC::DFG::SpeculativeJIT::fillSpeculateIntStrict): + (JSC::DFG::SpeculativeJIT::fillSpeculateDouble): + (JSC::DFG::SpeculativeJIT::fillSpeculateCell): + (JSC::DFG::SpeculativeJIT::fillSpeculateBoolean): + (JSC::DFG::SpeculativeJIT::compile): + * runtime/Options.h: + (JSC): + +2012-11-26 Daniel Bates <dbates@webkit.org> + + Substitute "allSeparators8Bit" for "allSeperators8Bit" in JSC::jsSpliceSubstringsWithSeparators() + <https://bugs.webkit.org/show_bug.cgi?id=103303> + + Reviewed by Simon Fraser. + + Fix misspelled word, "Seperators" [sic], in a local variable name in JSC::jsSpliceSubstringsWithSeparators(). + + * runtime/StringPrototype.cpp: + (JSC::jsSpliceSubstringsWithSeparators): + +2012-11-26 Daniel Bates <dbates@webkit.org> + + JavaScript fails to handle String.replace() with large replacement string + https://bugs.webkit.org/show_bug.cgi?id=102956 + <rdar://problem/12738012> + + Reviewed by Oliver Hunt. + + Fix an issue where we didn't check for overflow when computing the length + of the result of String.replace() with a large replacement string. + + * runtime/StringPrototype.cpp: + (JSC::jsSpliceSubstringsWithSeparators): + +2012-11-26 Zeno Albisser <zeno@webkit.org> + + [Qt] Fix the LLInt build on Mac + https://bugs.webkit.org/show_bug.cgi?id=97587 + + Reviewed by Simon Hausmann. + + * DerivedSources.pri: + * JavaScriptCore.pro: + +2012-11-26 Oliver Hunt <oliver@apple.com> + + 32-bit build fix. Move the method decalration outside of the X86_64 only section. + + * assembler/MacroAssembler.h: + (MacroAssembler): + (JSC::MacroAssembler::shouldConsiderBlinding): + +2012-11-26 Oliver Hunt <oliver@apple.com> + + Don't blind all the things. + https://bugs.webkit.org/show_bug.cgi?id=102572 + + Reviewed by Gavin Barraclough. + + No longer blind all the constants in the instruction stream. We use a + simple non-deterministic filter to avoid blinding everything. Also modified + the basic integer blinding logic to avoid blinding small negative values. + + * assembler/MacroAssembler.h: + (MacroAssembler): + (JSC::MacroAssembler::shouldConsiderBlinding): + (JSC::MacroAssembler::shouldBlind): + +2012-11-26 Mark Hahnenberg <mhahnenberg@apple.com> + + JSObject::copyButterfly doesn't handle undecided indexing types correctly + https://bugs.webkit.org/show_bug.cgi?id=102573 + + Reviewed by Filip Pizlo. + + We don't do any copying into the newly allocated vector and we don't zero-initialize CopiedBlocks + during the copying phase, so we end up with uninitialized memory in arrays which have undecided indexing + types. We should just do the actual memcpy from the old block to the new one. + + * runtime/JSObject.cpp: + (JSC::JSObject::copyButterfly): Just do the same thing that we do for other contiguous indexing types. + +2012-11-26 Julien BRIANCEAU <jbrianceau@nds.com> + + [sh4] JavaScriptCore JIT build is broken since r135330 + Add missing implementation for sh4 arch. + https://bugs.webkit.org/show_bug.cgi?id=103145 + + Reviewed by Oliver Hunt. + + * assembler/MacroAssemblerSH4.h: + (JSC::MacroAssemblerSH4::canJumpReplacePatchableBranchPtrWithPatch): + (MacroAssemblerSH4): + (JSC::MacroAssemblerSH4::startOfBranchPtrWithPatchOnRegister): + (JSC::MacroAssemblerSH4::revertJumpReplacementToBranchPtrWithPatch): + (JSC::MacroAssemblerSH4::startOfPatchableBranchPtrWithPatchOnAddress): + (JSC::MacroAssemblerSH4::revertJumpReplacementToPatchableBranchPtrWithPatch): + * assembler/SH4Assembler.h: + (JSC::SH4Assembler::revertJump): + (SH4Assembler): + (JSC::SH4Assembler::printInstr): + +2012-11-26 Yuqiang Xian <yuqiang.xian@intel.com> + + Use load64 instead of loadPtr to load a JSValue on JSVALUE64 platforms + https://bugs.webkit.org/show_bug.cgi?id=100909 + + Reviewed by Brent Fulgham. + + This is a (trivial) fix after r132701. + + * dfg/DFGOSRExitCompiler64.cpp: + (JSC::DFG::OSRExitCompiler::compileExit): + +2012-11-26 Gabor Ballabas <gaborb@inf.u-szeged.hu> + + [Qt][ARM] REGRESSION(r130826): It made 33 JSC test and 466 layout tests crash + https://bugs.webkit.org/show_bug.cgi?id=98857 + + Reviewed by Zoltan Herczeg. + + Implement a new version of patchableBranch32 to fix crashing JSC + tests. + + * assembler/MacroAssembler.h: + (MacroAssembler): + * assembler/MacroAssemblerARM.h: + (JSC::MacroAssemblerARM::patchableBranch32): + (MacroAssemblerARM): + 2012-11-21 Filip Pizlo <fpizlo@apple.com> Any function that can log things should be able to easily log them to a memory buffer as well diff --git a/Source/JavaScriptCore/DerivedSources.pri b/Source/JavaScriptCore/DerivedSources.pri index f9bbbf67c..8bbc29d2a 100644 --- a/Source/JavaScriptCore/DerivedSources.pri +++ b/Source/JavaScriptCore/DerivedSources.pri @@ -102,15 +102,13 @@ for(dir, DIRS) { exists($$file): LLINT_FILES += $$file } -if(linux-*|win32) { - #GENERATOR: LLInt - llint.output = ${QMAKE_FILE_IN_PATH}$${QMAKE_DIR_SEP}LLIntAssembly.h - llint.script = $$PWD/offlineasm/asm.rb - llint.input = LLINT_FILES - llint.depends = $$LLINT_DEPENDENCY - llint.commands = ruby $$llint.script $$LLINT_ASSEMBLER ${QMAKE_FILE_IN} ${QMAKE_FILE_OUT} - GENERATORS += llint -} +#GENERATOR: LLInt +llint.output = ${QMAKE_FILE_IN_PATH}$${QMAKE_DIR_SEP}LLIntAssembly.h +llint.script = $$PWD/offlineasm/asm.rb +llint.input = LLINT_FILES +llint.depends = $$LLINT_DEPENDENCY +llint.commands = ruby $$llint.script $$LLINT_ASSEMBLER ${QMAKE_FILE_IN} ${QMAKE_FILE_OUT} +GENERATORS += llint linux-*:if(isEqual(QT_ARCH, "i386")|isEqual(QT_ARCH, "x86_64")) { # GENERATOR: disassembler diff --git a/Source/JavaScriptCore/GNUmakefile.list.am b/Source/JavaScriptCore/GNUmakefile.list.am index d7afaf18a..c42ee7dfe 100644 --- a/Source/JavaScriptCore/GNUmakefile.list.am +++ b/Source/JavaScriptCore/GNUmakefile.list.am @@ -250,6 +250,8 @@ javascriptcore_sources += \ Source/JavaScriptCore/dfg/DFGValidate.cpp \ Source/JavaScriptCore/dfg/DFGValidate.h \ Source/JavaScriptCore/dfg/DFGVariableAccessData.h \ + Source/JavaScriptCore/dfg/DFGVariableAccessDataDump.cpp \ + Source/JavaScriptCore/dfg/DFGVariableAccessDataDump.h \ Source/JavaScriptCore/dfg/DFGVirtualRegisterAllocationPhase.cpp \ Source/JavaScriptCore/dfg/DFGVirtualRegisterAllocationPhase.h \ Source/JavaScriptCore/disassembler/Disassembler.cpp \ diff --git a/Source/JavaScriptCore/JavaScriptCore.pro b/Source/JavaScriptCore/JavaScriptCore.pro index 924261d4f..13130b87f 100644 --- a/Source/JavaScriptCore/JavaScriptCore.pro +++ b/Source/JavaScriptCore/JavaScriptCore.pro @@ -7,18 +7,16 @@ TEMPLATE = subdirs CONFIG += ordered -if(linux-*|win32*) { - LLIntOffsetsExtractor.file = LLIntOffsetsExtractor.pro - LLIntOffsetsExtractor.makefile = Makefile.LLIntOffsetsExtractor - SUBDIRS += LLIntOffsetsExtractor -} +LLIntOffsetsExtractor.file = LLIntOffsetsExtractor.pro +LLIntOffsetsExtractor.makefile = Makefile.LLIntOffsetsExtractor +SUBDIRS += LLIntOffsetsExtractor derived_sources.file = DerivedSources.pri target.file = Target.pri SUBDIRS += derived_sources target -if(linux-*|win32*):addStrictSubdirOrderBetween(LLIntOffsetsExtractor, derived_sources) +addStrictSubdirOrderBetween(LLIntOffsetsExtractor, derived_sources) addStrictSubdirOrderBetween(derived_sources, target) jsc.file = jsc.pro diff --git a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj b/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj index bda9b27ff..a2c4b5f52 100644 --- a/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj +++ b/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj @@ -237,6 +237,8 @@ 0FD82E56141DAF0800179C94 /* DFGOSREntry.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FD82E52141DAEDE00179C94 /* DFGOSREntry.cpp */; }; 0FD82E57141DAF1000179C94 /* DFGOSREntry.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FD82E53141DAEDE00179C94 /* DFGOSREntry.h */; settings = {ATTRIBUTES = (Private, ); }; }; 0FD82E86141F3FF100179C94 /* SpeculatedType.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FD82E84141F3FDA00179C94 /* SpeculatedType.cpp */; }; + 0FDDBFB51666EED800C55FEF /* DFGVariableAccessDataDump.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FDDBFB21666EED500C55FEF /* DFGVariableAccessDataDump.cpp */; }; + 0FDDBFB61666EEDA00C55FEF /* DFGVariableAccessDataDump.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FDDBFB31666EED500C55FEF /* DFGVariableAccessDataDump.h */; settings = {ATTRIBUTES = (Private, ); }; }; 0FE228ED1436AB2700196C48 /* Options.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FE228EB1436AB2300196C48 /* Options.h */; settings = {ATTRIBUTES = (Private, ); }; }; 0FE228EE1436AB2C00196C48 /* Options.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FE228EA1436AB2300196C48 /* Options.cpp */; }; 0FEB3ECD16237F4D00AB67AD /* TypedArrayDescriptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FEB3ECB16237F4700AB67AD /* TypedArrayDescriptor.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -721,6 +723,7 @@ C21122E215DD9AB300790E3A /* GCThreadSharedData.h in Headers */ = {isa = PBXBuildFile; fileRef = C21122DF15DD9AB300790E3A /* GCThreadSharedData.h */; settings = {ATTRIBUTES = (Private, ); }; }; C21122E315DD9AB300790E3A /* MarkStackInlines.h in Headers */ = {isa = PBXBuildFile; fileRef = C21122E015DD9AB300790E3A /* MarkStackInlines.h */; settings = {ATTRIBUTES = (Private, ); }; }; C2160FE715F7E95E00942DFC /* SlotVisitorInlines.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FCB408515C0A3C30048932B /* SlotVisitorInlines.h */; settings = {ATTRIBUTES = (Private, ); }; }; + C218D1401655CFD50062BB81 /* CopyWorkList.h in Headers */ = {isa = PBXBuildFile; fileRef = C218D13F1655CFD50062BB81 /* CopyWorkList.h */; settings = {ATTRIBUTES = (Private, ); }; }; C2239D1716262BDD005AC5FD /* CopyVisitor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C2239D1216262BDD005AC5FD /* CopyVisitor.cpp */; }; C2239D1816262BDD005AC5FD /* CopyVisitor.h in Headers */ = {isa = PBXBuildFile; fileRef = C2239D1316262BDD005AC5FD /* CopyVisitor.h */; settings = {ATTRIBUTES = (Private, ); }; }; C2239D1916262BDD005AC5FD /* CopyVisitorInlines.h in Headers */ = {isa = PBXBuildFile; fileRef = C2239D1416262BDD005AC5FD /* CopyVisitorInlines.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -744,6 +747,7 @@ C2E526BE1590EF000054E48D /* HeapTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = C2E526BC1590EF000054E48D /* HeapTimer.h */; settings = {ATTRIBUTES = (Private, ); }; }; C2EAA3FA149A835E00FCE112 /* CopiedSpace.h in Headers */ = {isa = PBXBuildFile; fileRef = C2EAA3F8149A830800FCE112 /* CopiedSpace.h */; settings = {ATTRIBUTES = (Private, ); }; }; C2EAD2FC14F0249800A4B159 /* CopiedAllocator.h in Headers */ = {isa = PBXBuildFile; fileRef = C2EAD2FB14F0249800A4B159 /* CopiedAllocator.h */; settings = {ATTRIBUTES = (Private, ); }; }; + C2FC9BD316644DFB00810D33 /* CopiedBlockInlines.h in Headers */ = {isa = PBXBuildFile; fileRef = C2FC9BD216644DFB00810D33 /* CopiedBlockInlines.h */; settings = {ATTRIBUTES = (Private, ); }; }; DDF7ABD411F60ED200108E36 /* GCActivityCallback.h in Headers */ = {isa = PBXBuildFile; fileRef = DDF7ABD211F60ED200108E36 /* GCActivityCallback.h */; settings = {ATTRIBUTES = (Private, ); }; }; E124A8F70E555775003091F1 /* OpaqueJSString.h in Headers */ = {isa = PBXBuildFile; fileRef = E124A8F50E555775003091F1 /* OpaqueJSString.h */; settings = {ATTRIBUTES = (Private, ); }; }; E124A8F80E555775003091F1 /* OpaqueJSString.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E124A8F60E555775003091F1 /* OpaqueJSString.cpp */; }; @@ -1034,6 +1038,8 @@ 0FD82E52141DAEDE00179C94 /* DFGOSREntry.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = DFGOSREntry.cpp; path = dfg/DFGOSREntry.cpp; sourceTree = "<group>"; }; 0FD82E53141DAEDE00179C94 /* DFGOSREntry.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DFGOSREntry.h; path = dfg/DFGOSREntry.h; sourceTree = "<group>"; }; 0FD82E84141F3FDA00179C94 /* SpeculatedType.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SpeculatedType.cpp; sourceTree = "<group>"; }; + 0FDDBFB21666EED500C55FEF /* DFGVariableAccessDataDump.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = DFGVariableAccessDataDump.cpp; path = dfg/DFGVariableAccessDataDump.cpp; sourceTree = "<group>"; }; + 0FDDBFB31666EED500C55FEF /* DFGVariableAccessDataDump.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DFGVariableAccessDataDump.h; path = dfg/DFGVariableAccessDataDump.h; sourceTree = "<group>"; }; 0FE228EA1436AB2300196C48 /* Options.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Options.cpp; sourceTree = "<group>"; }; 0FE228EB1436AB2300196C48 /* Options.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Options.h; sourceTree = "<group>"; }; 0FEB3ECB16237F4700AB67AD /* TypedArrayDescriptor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TypedArrayDescriptor.h; sourceTree = "<group>"; }; @@ -1518,6 +1524,7 @@ C21122DE15DD9AB300790E3A /* GCThreadSharedData.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GCThreadSharedData.cpp; sourceTree = "<group>"; }; C21122DF15DD9AB300790E3A /* GCThreadSharedData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCThreadSharedData.h; sourceTree = "<group>"; }; C21122E015DD9AB300790E3A /* MarkStackInlines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MarkStackInlines.h; sourceTree = "<group>"; }; + C218D13F1655CFD50062BB81 /* CopyWorkList.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CopyWorkList.h; sourceTree = "<group>"; }; C2239D1216262BDD005AC5FD /* CopyVisitor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CopyVisitor.cpp; sourceTree = "<group>"; }; C2239D1316262BDD005AC5FD /* CopyVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CopyVisitor.h; sourceTree = "<group>"; }; C2239D1416262BDD005AC5FD /* CopyVisitorInlines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CopyVisitorInlines.h; sourceTree = "<group>"; }; @@ -1540,6 +1547,7 @@ C2E526BC1590EF000054E48D /* HeapTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HeapTimer.h; sourceTree = "<group>"; }; C2EAA3F8149A830800FCE112 /* CopiedSpace.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CopiedSpace.h; sourceTree = "<group>"; }; C2EAD2FB14F0249800A4B159 /* CopiedAllocator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CopiedAllocator.h; sourceTree = "<group>"; }; + C2FC9BD216644DFB00810D33 /* CopiedBlockInlines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CopiedBlockInlines.h; sourceTree = "<group>"; }; D21202280AD4310C00ED79B6 /* DateConversion.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = DateConversion.cpp; sourceTree = "<group>"; }; D21202290AD4310C00ED79B6 /* DateConversion.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DateConversion.h; sourceTree = "<group>"; }; DDF7ABD211F60ED200108E36 /* GCActivityCallback.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCActivityCallback.h; sourceTree = "<group>"; }; @@ -1936,6 +1944,8 @@ 14150132154BB13F005D8C98 /* WeakSetInlines.h */, 0FC8150814043BCA00CFA603 /* WriteBarrierSupport.cpp */, 0FC8150914043BD200CFA603 /* WriteBarrierSupport.h */, + C218D13F1655CFD50062BB81 /* CopyWorkList.h */, + C2FC9BD216644DFB00810D33 /* CopiedBlockInlines.h */, ); path = heap; sourceTree = "<group>"; @@ -2464,6 +2474,8 @@ 0F2BDC4E15228BE700CD8910 /* DFGValueSource.cpp */, 0F2BDC401522801700CD8910 /* DFGValueSource.h */, 0F620172143FCD2F0068B77C /* DFGVariableAccessData.h */, + 0FDDBFB21666EED500C55FEF /* DFGVariableAccessDataDump.cpp */, + 0FDDBFB31666EED500C55FEF /* DFGVariableAccessDataDump.h */, 0F2BDC5015228FFA00CD8910 /* DFGVariableEvent.cpp */, 0F2BDC411522801700CD8910 /* DFGVariableEvent.h */, 0F2BDC421522801700CD8910 /* DFGVariableEventStream.cpp */, @@ -2638,6 +2650,8 @@ 86ADD1450FDDEA980006EEC2 /* ARMv7Assembler.h in Headers */, C2EAD2FC14F0249800A4B159 /* CopiedAllocator.h in Headers */, C2B916C214DA014E00CBAC86 /* MarkedAllocator.h in Headers */, + C218D1401655CFD50062BB81 /* CopyWorkList.h in Headers */, + C2FC9BD316644DFB00810D33 /* CopiedBlockInlines.h in Headers */, FE4A332015BD2E07006F54F3 /* VMInspector.h in Headers */, C2239D1816262BDD005AC5FD /* CopyVisitor.h in Headers */, C2239D1916262BDD005AC5FD /* CopyVisitorInlines.h in Headers */, @@ -3039,6 +3053,7 @@ A77F1825164192C700640A47 /* ParserModes.h in Headers */, 0FAF7EFE165BA91F000C8455 /* JITDisassembler.h in Headers */, 0F73D7AF165A143000ACAB71 /* ClosureCallStubRoutine.h in Headers */, + 0FDDBFB61666EEDA00C55FEF /* DFGVariableAccessDataDump.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -3621,6 +3636,7 @@ 0FAF7EFD165BA91B000C8455 /* JITDisassembler.cpp in Sources */, 0F73D7AE165A142D00ACAB71 /* ClosureCallStubRoutine.cpp in Sources */, 0F9D3370165DBB90005AD387 /* Disassembler.cpp in Sources */, + 0FDDBFB51666EED800C55FEF /* DFGVariableAccessDataDump.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Source/JavaScriptCore/Target.pri b/Source/JavaScriptCore/Target.pri index e15b21dae..e1caa725f 100644 --- a/Source/JavaScriptCore/Target.pri +++ b/Source/JavaScriptCore/Target.pri @@ -136,6 +136,7 @@ SOURCES += \ dfg/DFGStructureCheckHoistingPhase.cpp \ dfg/DFGThunks.cpp \ dfg/DFGValueSource.cpp \ + dfg/DFGVariableAccessDataDump.cpp \ dfg/DFGVariableEvent.cpp \ dfg/DFGVariableEventStream.cpp \ dfg/DFGValidate.cpp \ diff --git a/Source/JavaScriptCore/assembler/MacroAssembler.h b/Source/JavaScriptCore/assembler/MacroAssembler.h index 642b5ca6b..3d57340f9 100644 --- a/Source/JavaScriptCore/assembler/MacroAssembler.h +++ b/Source/JavaScriptCore/assembler/MacroAssembler.h @@ -266,12 +266,14 @@ public: { return PatchableJump(branchTest32(cond, reg, mask)); } - +#endif // !CPU(ARM_THUMB2) + +#if !CPU(ARM) PatchableJump patchableBranch32(RelationalCondition cond, RegisterID reg, TrustedImm32 imm) { return PatchableJump(branch32(cond, reg, imm)); } -#endif +#endif // !(CPU(ARM) void jump(Label target) { @@ -306,7 +308,12 @@ public: ASSERT(condition == Equal || condition == NotEqual); return condition; } - + + static const unsigned BlindingModulus = 64; + bool shouldConsiderBlinding() + { + return !(random() & (BlindingModulus - 1)); + } // Ptr methods // On 32-bit platforms (i.e. x86), these methods directly map onto their 32-bit equivalents. @@ -837,26 +844,25 @@ public: using MacroAssemblerBase::and64; using MacroAssemblerBase::convertInt32ToDouble; using MacroAssemblerBase::store64; - bool shouldBlindDouble(double value) { // Don't trust NaN or +/-Infinity if (!isfinite(value)) - return true; + return shouldConsiderBlinding(); // Try to force normalisation, and check that there's no change // in the bit pattern if (bitwise_cast<uint64_t>(value * 1.0) != bitwise_cast<uint64_t>(value)) - return true; + return shouldConsiderBlinding(); value = abs(value); // Only allow a limited set of fractional components double scaledValue = value * 8; if (scaledValue / 8 != value) - return true; + return shouldConsiderBlinding(); double frac = scaledValue - floor(scaledValue); if (frac != 0.0) - return true; + return shouldConsiderBlinding(); return value > 0xff; } @@ -885,8 +891,14 @@ public: default: { if (value <= 0xff) return false; + if (~value <= 0xff) + return false; } } + + if (!shouldConsiderBlinding()) + return false; + return shouldBlindForSpecificArch(value); } @@ -938,6 +950,9 @@ public: default: { if (value <= 0xff) return false; + if (~value <= 0xff) + return false; + JSValue jsValue = JSValue::decode(value); if (jsValue.isInt32()) return shouldBlind(Imm32(jsValue.asInt32())); @@ -948,6 +963,10 @@ public: return false; } } + + if (!shouldConsiderBlinding()) + return false; + return shouldBlindForSpecificArch(value); } @@ -1066,7 +1085,13 @@ public: default: if (value <= 0xff) return false; + if (~value <= 0xff) + return false; } + + if (!shouldConsiderBlinding()) + return false; + return shouldBlindForSpecificArch(value); #endif } diff --git a/Source/JavaScriptCore/assembler/MacroAssemblerARM.h b/Source/JavaScriptCore/assembler/MacroAssemblerARM.h index 9c77e9349..e6b5ad383 100644 --- a/Source/JavaScriptCore/assembler/MacroAssemblerARM.h +++ b/Source/JavaScriptCore/assembler/MacroAssemblerARM.h @@ -570,11 +570,7 @@ public: Jump branch32(RelationalCondition cond, RegisterID left, TrustedImm32 right, int useConstantPool = 0) { - ARMWord tmp = (static_cast<unsigned>(right.m_value) == 0x80000000) ? ARMAssembler::InvalidImmediate : m_assembler.getOp2(-right.m_value); - if (tmp != ARMAssembler::InvalidImmediate) - m_assembler.cmn(left, tmp); - else - m_assembler.cmp(left, m_assembler.getImm(right.m_value, ARMRegisters::S0)); + internalCompare32(left, right); return Jump(m_assembler.jmp(ARMCondition(cond), useConstantPool)); } @@ -807,6 +803,14 @@ public: return Jump(m_assembler.jmp(ARMCondition(cond))); } + PatchableJump patchableBranch32(RelationalCondition cond, RegisterID reg, TrustedImm32 imm) + { + internalCompare32(reg, imm); + Jump jump(m_assembler.loadBranchTarget(ARMRegisters::S1, ARMCondition(cond), true)); + m_assembler.bx(ARMRegisters::S1, ARMCondition(cond)); + return PatchableJump(jump); + } + void breakpoint() { m_assembler.bkpt(0); @@ -1320,6 +1324,15 @@ private: friend class LinkBuffer; friend class RepatchBuffer; + void internalCompare32(RegisterID left, TrustedImm32 right) + { + ARMWord tmp = (static_cast<unsigned>(right.m_value) == 0x80000000) ? ARMAssembler::InvalidImmediate : m_assembler.getOp2(-right.m_value); + if (tmp != ARMAssembler::InvalidImmediate) + m_assembler.cmn(left, tmp); + else + m_assembler.cmp(left, m_assembler.getImm(right.m_value, ARMRegisters::S0)); + } + static void linkCall(void* code, Call call, FunctionPtr function) { ARMAssembler::linkCall(code, call.m_label, function.value()); diff --git a/Source/JavaScriptCore/assembler/MacroAssemblerSH4.h b/Source/JavaScriptCore/assembler/MacroAssemblerSH4.h index b6f3e6d57..ec025cec3 100644 --- a/Source/JavaScriptCore/assembler/MacroAssemblerSH4.h +++ b/Source/JavaScriptCore/assembler/MacroAssemblerSH4.h @@ -2216,6 +2216,29 @@ void or32(TrustedImm32 imm, RegisterID src, RegisterID dest) return 0; } + static bool canJumpReplacePatchableBranchPtrWithPatch() { return false; } + + static CodeLocationLabel startOfBranchPtrWithPatchOnRegister(CodeLocationDataLabelPtr label) + { + return label.labelAtOffset(0); + } + + static void revertJumpReplacementToBranchPtrWithPatch(CodeLocationLabel instructionStart, RegisterID, void* initialValue) + { + SH4Assembler::revertJump(instructionStart.dataLocation(), reinterpret_cast<uintptr_t>(initialValue) & 0xffff); + } + + static CodeLocationLabel startOfPatchableBranchPtrWithPatchOnAddress(CodeLocationDataLabelPtr) + { + UNREACHABLE_FOR_PLATFORM(); + return CodeLocationLabel(); + } + + static void revertJumpReplacementToPatchableBranchPtrWithPatch(CodeLocationLabel instructionStart, Address, void* initialValue) + { + UNREACHABLE_FOR_PLATFORM(); + } + protected: SH4Assembler::Condition SH4Condition(RelationalCondition cond) { diff --git a/Source/JavaScriptCore/assembler/SH4Assembler.h b/Source/JavaScriptCore/assembler/SH4Assembler.h index 2cd0aa82e..39f5585be 100644 --- a/Source/JavaScriptCore/assembler/SH4Assembler.h +++ b/Source/JavaScriptCore/assembler/SH4Assembler.h @@ -1462,6 +1462,20 @@ public: // Linking & patching + static void revertJump(void* instructionStart, SH4Word imm) + { + SH4Word *insn = reinterpret_cast<SH4Word*>(instructionStart); + SH4Word disp; + + ASSERT((insn[0] & 0xf000) == MOVL_READ_OFFPC_OPCODE); + + disp = insn[0] & 0x00ff; + insn += 2 + (disp << 1); // PC += 4 + (disp*4) + insn = (SH4Word *) ((unsigned) insn & (~3)); + insn[0] = imm; + cacheFlush(insn, sizeof(SH4Word)); + } + void linkJump(AssemblerLabel from, AssemblerLabel to, JumpType type = JumpFar) { ASSERT(to.isSet()); @@ -1755,6 +1769,9 @@ public: case FCNVDS_DRM_FPUL_OPCODE: format = " FCNVDS FR%d, FPUL\n"; break; + case FCNVSD_FPUL_DRN_OPCODE: + format = " FCNVSD FPUL, FR%d\n"; + break; } if (format) { if (isdoubleInst) diff --git a/Source/JavaScriptCore/bytecode/CodeBlock.cpp b/Source/JavaScriptCore/bytecode/CodeBlock.cpp index 206d281a2..6e1edaa0e 100644 --- a/Source/JavaScriptCore/bytecode/CodeBlock.cpp +++ b/Source/JavaScriptCore/bytecode/CodeBlock.cpp @@ -497,7 +497,7 @@ void CodeBlock::dump() static_cast<unsigned long>(instructions().size() * sizeof(Instruction)), this, codeTypeToString(codeType()), m_numParameters, m_numCalleeRegisters, m_numVars); - if (symbolTable()->captureCount()) + if (symbolTable() && symbolTable()->captureCount()) dataLogF("; %d captured var(s)", symbolTable()->captureCount()); if (usesArguments()) { dataLogF( @@ -1891,7 +1891,7 @@ CodeBlock::CodeBlock(ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlin } m_instructions = WTF::RefCountedArray<Instruction>(instructions); - if (BytecodeGenerator::dumpsGeneratedCode()) + if (Options::dumpGeneratedBytecodes()) dump(); m_globalData->finishedCompiling(this); } diff --git a/Source/JavaScriptCore/bytecode/SpeculatedType.cpp b/Source/JavaScriptCore/bytecode/SpeculatedType.cpp index 399ab29c8..a07ca2b22 100644 --- a/Source/JavaScriptCore/bytecode/SpeculatedType.cpp +++ b/Source/JavaScriptCore/bytecode/SpeculatedType.cpp @@ -34,144 +34,143 @@ #include "JSFunction.h" #include "ValueProfile.h" #include <wtf/BoundsCheckedPointer.h> +#include <wtf/StringPrintStream.h> namespace JSC { -const char* speculationToString(SpeculatedType value) +void dumpSpeculation(PrintStream& out, SpeculatedType value) { - if (value == SpecNone) - return "None"; + if (value == SpecNone) { + out.print("None"); + return; + } - static const int size = 256; - static char description[size]; - BoundsCheckedPointer<char> ptr(description, size); + StringPrintStream myOut; bool isTop = true; if (value & SpecCellOther) - ptr.strcat("Othercell"); + myOut.print("Othercell"); else isTop = false; if (value & SpecObjectOther) - ptr.strcat("Otherobj"); + myOut.print("Otherobj"); else isTop = false; if (value & SpecFinalObject) - ptr.strcat("Final"); + myOut.print("Final"); else isTop = false; if (value & SpecArray) - ptr.strcat("Array"); + myOut.print("Array"); else isTop = false; if (value & SpecInt8Array) - ptr.strcat("Int8array"); + myOut.print("Int8array"); else isTop = false; if (value & SpecInt16Array) - ptr.strcat("Int16array"); + myOut.print("Int16array"); else isTop = false; if (value & SpecInt32Array) - ptr.strcat("Int32array"); + myOut.print("Int32array"); else isTop = false; if (value & SpecUint8Array) - ptr.strcat("Uint8array"); + myOut.print("Uint8array"); else isTop = false; if (value & SpecUint8ClampedArray) - ptr.strcat("Uint8clampedarray"); + myOut.print("Uint8clampedarray"); else isTop = false; if (value & SpecUint16Array) - ptr.strcat("Uint16array"); + myOut.print("Uint16array"); else isTop = false; if (value & SpecUint32Array) - ptr.strcat("Uint32array"); + myOut.print("Uint32array"); else isTop = false; if (value & SpecFloat32Array) - ptr.strcat("Float32array"); + myOut.print("Float32array"); else isTop = false; if (value & SpecFloat64Array) - ptr.strcat("Float64array"); + myOut.print("Float64array"); else isTop = false; if (value & SpecFunction) - ptr.strcat("Function"); + myOut.print("Function"); else isTop = false; if (value & SpecMyArguments) - ptr.strcat("Myarguments"); + myOut.print("Myarguments"); else isTop = false; if (value & SpecForeignArguments) - ptr.strcat("Foreignarguments"); + myOut.print("Foreignarguments"); else isTop = false; if (value & SpecString) - ptr.strcat("String"); + myOut.print("String"); else isTop = false; if (value & SpecInt32) - ptr.strcat("Int"); + myOut.print("Int"); else isTop = false; if (value & SpecDoubleReal) - ptr.strcat("Doublereal"); + myOut.print("Doublereal"); else isTop = false; if (value & SpecDoubleNaN) - ptr.strcat("Doublenan"); + myOut.print("Doublenan"); else isTop = false; if (value & SpecBoolean) - ptr.strcat("Bool"); + myOut.print("Bool"); else isTop = false; if (value & SpecOther) - ptr.strcat("Other"); + myOut.print("Other"); else isTop = false; - if (isTop) { - ptr = description; - ptr.strcat("Top"); - } + if (isTop) + out.print("Top"); + else + out.print(myOut.toCString()); if (value & SpecEmpty) - ptr.strcat("Empty"); - - *ptr++ = 0; - - return description; + out.print("Empty"); } -const char* speculationToAbbreviatedString(SpeculatedType prediction) +// We don't expose this because we don't want anyone relying on the fact that this method currently +// just returns string constants. +static const char* speculationToAbbreviatedString(SpeculatedType prediction) { if (isFinalObjectSpeculation(prediction)) return "<Final>"; @@ -218,6 +217,11 @@ const char* speculationToAbbreviatedString(SpeculatedType prediction) return ""; } +void dumpSpeculationAbbreviated(PrintStream& out, SpeculatedType value) +{ + out.print(speculationToAbbreviatedString(value)); +} + SpeculatedType speculationFromClassInfo(const ClassInfo* classInfo) { if (classInfo == &JSFinalObject::s_info) diff --git a/Source/JavaScriptCore/bytecode/SpeculatedType.h b/Source/JavaScriptCore/bytecode/SpeculatedType.h index 656bc79ee..261a26b0e 100644 --- a/Source/JavaScriptCore/bytecode/SpeculatedType.h +++ b/Source/JavaScriptCore/bytecode/SpeculatedType.h @@ -289,8 +289,11 @@ inline bool isEmptySpeculation(SpeculatedType value) return value == SpecEmpty; } -const char* speculationToString(SpeculatedType value); -const char* speculationToAbbreviatedString(SpeculatedType value); +void dumpSpeculation(PrintStream&, SpeculatedType); +void dumpSpeculationAbbreviated(PrintStream&, SpeculatedType); + +MAKE_PRINT_ADAPTOR(SpeculationDump, SpeculatedType, dumpSpeculation); +MAKE_PRINT_ADAPTOR(AbbreviatedSpeculationDump, SpeculatedType, dumpSpeculationAbbreviated); // Merge two predictions. Note that currently this just does left | right. It may // seem tempting to do so directly, but you would be doing so at your own peril, diff --git a/Source/JavaScriptCore/bytecode/ValueProfile.h b/Source/JavaScriptCore/bytecode/ValueProfile.h index 31e76842f..e56e6eb6e 100644 --- a/Source/JavaScriptCore/bytecode/ValueProfile.h +++ b/Source/JavaScriptCore/bytecode/ValueProfile.h @@ -38,6 +38,7 @@ #include "SpeculatedType.h" #include "Structure.h" #include "WriteBarrier.h" +#include <wtf/PrintStream.h> namespace JSC { @@ -109,27 +110,24 @@ struct ValueProfileBase { return false; } - void dump(FILE* out) + void dump(PrintStream& out) { - fprintf(out, - "samples = %u, prediction = %s", - totalNumberOfSamples(), - speculationToString(m_prediction)); - fprintf(out, ", value = "); + out.print("samples = ", totalNumberOfSamples(), " prediction = ", SpeculationDump(m_prediction)); + out.printf(", value = "); if (m_singletonValueIsTop) - fprintf(out, "TOP"); + out.printf("TOP"); else - fprintf(out, "%s", m_singletonValue.description()); + out.printf("%s", m_singletonValue.description()); bool first = true; for (unsigned i = 0; i < totalNumberOfBuckets; ++i) { JSValue value = JSValue::decode(m_buckets[i]); if (!!value) { if (first) { - fprintf(out, ": "); + out.printf(": "); first = false; } else - fprintf(out, ", "); - fprintf(out, "%s", value.description()); + out.printf(", "); + out.printf("%s", value.description()); } } } diff --git a/Source/JavaScriptCore/bytecode/ValueRecovery.h b/Source/JavaScriptCore/bytecode/ValueRecovery.h index 93ad221d8..fc991a413 100644 --- a/Source/JavaScriptCore/bytecode/ValueRecovery.h +++ b/Source/JavaScriptCore/bytecode/ValueRecovery.h @@ -274,70 +274,70 @@ public: return JSValue::decode(m_source.constant); } - void dump(FILE* out) const + void dump(PrintStream& out) const { switch (technique()) { case AlreadyInJSStack: - fprintf(out, "-"); + out.printf("-"); break; case AlreadyInJSStackAsUnboxedInt32: - fprintf(out, "(int32)"); + out.printf("(int32)"); break; case AlreadyInJSStackAsUnboxedCell: - fprintf(out, "(cell)"); + out.printf("(cell)"); break; case AlreadyInJSStackAsUnboxedBoolean: - fprintf(out, "(bool)"); + out.printf("(bool)"); break; case AlreadyInJSStackAsUnboxedDouble: - fprintf(out, "(double)"); + out.printf("(double)"); break; case InGPR: - fprintf(out, "%%r%d", gpr()); + out.printf("%%r%d", gpr()); break; case UnboxedInt32InGPR: - fprintf(out, "int32(%%r%d)", gpr()); + out.printf("int32(%%r%d)", gpr()); break; case UnboxedBooleanInGPR: - fprintf(out, "bool(%%r%d)", gpr()); + out.printf("bool(%%r%d)", gpr()); break; case UInt32InGPR: - fprintf(out, "uint32(%%r%d)", gpr()); + out.printf("uint32(%%r%d)", gpr()); break; case InFPR: - fprintf(out, "%%fr%d", fpr()); + out.printf("%%fr%d", fpr()); break; #if USE(JSVALUE32_64) case InPair: - fprintf(out, "pair(%%r%d, %%r%d)", tagGPR(), payloadGPR()); + out.printf("pair(%%r%d, %%r%d)", tagGPR(), payloadGPR()); break; #endif case DisplacedInJSStack: - fprintf(out, "*%d", virtualRegister()); + out.printf("*%d", virtualRegister()); break; case Int32DisplacedInJSStack: - fprintf(out, "*int32(%d)", virtualRegister()); + out.printf("*int32(%d)", virtualRegister()); break; case DoubleDisplacedInJSStack: - fprintf(out, "*double(%d)", virtualRegister()); + out.printf("*double(%d)", virtualRegister()); break; case CellDisplacedInJSStack: - fprintf(out, "*cell(%d)", virtualRegister()); + out.printf("*cell(%d)", virtualRegister()); break; case BooleanDisplacedInJSStack: - fprintf(out, "*bool(%d)", virtualRegister()); + out.printf("*bool(%d)", virtualRegister()); break; case ArgumentsThatWereNotCreated: - fprintf(out, "arguments"); + out.printf("arguments"); break; case Constant: - fprintf(out, "[%s]", constant().description()); + out.printf("[%s]", constant().description()); break; case DontKnow: - fprintf(out, "!"); + out.printf("!"); break; default: - fprintf(out, "?%d", technique()); + out.printf("?%d", technique()); break; } } diff --git a/Source/JavaScriptCore/bytecode/VirtualRegister.h b/Source/JavaScriptCore/bytecode/VirtualRegister.h index b95f8b8fa..a6dc8d565 100644 --- a/Source/JavaScriptCore/bytecode/VirtualRegister.h +++ b/Source/JavaScriptCore/bytecode/VirtualRegister.h @@ -27,6 +27,7 @@ #define VirtualRegister_h #include <wtf/Platform.h> +#include <wtf/PrintStream.h> namespace JSC { @@ -37,4 +38,13 @@ COMPILE_ASSERT(sizeof(VirtualRegister) == sizeof(int), VirtualRegister_is_32bit) } // namespace JSC +namespace WTF { + +inline void printInternal(PrintStream& out, JSC::VirtualRegister value) +{ + out.print(static_cast<int>(value)); +} + +} // namespace WTF + #endif // VirtualRegister_h diff --git a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp b/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp index c6f81f3c3..35976257b 100644 --- a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp +++ b/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp @@ -38,6 +38,7 @@ #include "JSFunction.h" #include "JSNameScope.h" #include "LowLevelInterpreter.h" +#include "Options.h" #include "StrongInlines.h" #include <wtf/text/WTFString.h> @@ -146,18 +147,6 @@ void ResolveResult::checkValidity() } #endif -static bool s_dumpsGeneratedCode = false; - -void BytecodeGenerator::setDumpsGeneratedCode(bool dumpsGeneratedCode) -{ - s_dumpsGeneratedCode = dumpsGeneratedCode; -} - -bool BytecodeGenerator::dumpsGeneratedCode() -{ - return s_dumpsGeneratedCode; -} - ParserError BytecodeGenerator::generate() { SamplingRegion samplingRegion("Bytecode Generation"); diff --git a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h b/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h index 2e7aa2035..a5bb95b6c 100644 --- a/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h +++ b/Source/JavaScriptCore/bytecompiler/BytecodeGenerator.h @@ -209,9 +209,6 @@ namespace JSC { typedef DeclarationStacks::VarStack VarStack; typedef DeclarationStacks::FunctionStack FunctionStack; - JS_EXPORT_PRIVATE static void setDumpsGeneratedCode(bool dumpsGeneratedCode); - static bool dumpsGeneratedCode(); - BytecodeGenerator(JSGlobalData&, ProgramNode*, UnlinkedProgramCodeBlock*, DebuggerMode, ProfilerMode); BytecodeGenerator(JSGlobalData&, FunctionBodyNode*, UnlinkedFunctionCodeBlock*, DebuggerMode, ProfilerMode); BytecodeGenerator(JSGlobalData&, EvalNode*, UnlinkedEvalCodeBlock*, DebuggerMode, ProfilerMode); diff --git a/Source/JavaScriptCore/dfg/DFGAbstractValue.h b/Source/JavaScriptCore/dfg/DFGAbstractValue.h index fd3220494..0ce01ab56 100644 --- a/Source/JavaScriptCore/dfg/DFGAbstractValue.h +++ b/Source/JavaScriptCore/dfg/DFGAbstractValue.h @@ -373,13 +373,12 @@ struct AbstractValue { void dump(PrintStream& out) const { - out.printf("(%s, %s, ", speculationToString(m_type), arrayModesToString(m_arrayModes)); - m_currentKnownStructure.dump(out); - out.printf(", "); - m_futurePossibleStructure.dump(out); + out.print( + "(", SpeculationDump(m_type), ", ", arrayModesToString(m_arrayModes), ", ", + m_currentKnownStructure, ", ", m_futurePossibleStructure); if (!!m_value) - out.printf(", %s", m_value.description()); - out.printf(")"); + out.print(", ", m_value.description()); + out.print(")"); } // A great way to think about the difference between m_currentKnownStructure and diff --git a/Source/JavaScriptCore/dfg/DFGByteCodeParser.cpp b/Source/JavaScriptCore/dfg/DFGByteCodeParser.cpp index 9b879b9e3..c5ffb1fc6 100644 --- a/Source/JavaScriptCore/dfg/DFGByteCodeParser.cpp +++ b/Source/JavaScriptCore/dfg/DFGByteCodeParser.cpp @@ -247,6 +247,17 @@ private: setDirect(m_inlineStackTop->remapOperand(operand), value, setMode); } + void setPair(int operand1, NodeIndex value1, int operand2, NodeIndex value2) + { + // First emit dead SetLocals for the benefit of OSR. + set(operand1, value1); + set(operand2, value2); + + // Now emit the real SetLocals. + set(operand1, value1); + set(operand2, value2); + } + NodeIndex injectLazyOperandSpeculation(NodeIndex nodeIndex) { Node& node = m_graph[nodeIndex]; @@ -256,8 +267,7 @@ private: m_inlineStackTop->m_lazyOperands.prediction( LazyOperandValueProfileKey(m_currentIndex, node.local())); #if DFG_ENABLE(DEBUG_VERBOSE) - dataLogF("Lazy operand [@%u, bc#%u, r%d] prediction: %s\n", - nodeIndex, m_currentIndex, node.local(), speculationToString(prediction)); + dataLog("Lazy operand [@", nodeIndex, ", bc#", m_currentIndex, ", r", node.local(), "] prediction: ", SpeculationDump(prediction), "\n"); #endif node.variableAccessData()->predict(prediction); return nodeIndex; @@ -876,7 +886,7 @@ private: SpeculatedType prediction = m_inlineStackTop->m_profiledBlock->valueProfilePredictionForBytecodeOffset(bytecodeIndex); #if DFG_ENABLE(DEBUG_VERBOSE) - dataLogF("Dynamic [@%u, bc#%u] prediction: %s\n", nodeIndex, bytecodeIndex, speculationToString(prediction)); + dataLog("Dynamic [@", nodeIndex, ", bc#", bytecodeIndex, "] prediction: ", SpeculationDump(prediction), "\n"); #endif return prediction; @@ -2299,8 +2309,7 @@ bool ByteCodeParser::parseBlock(unsigned limit) unsigned srcDst = currentInstruction[2].u.operand; ASSERT(result != srcDst); // Required for assumptions we make during OSR. NodeIndex op = get(srcDst); - set(result, op); - set(srcDst, makeSafe(addToGraph(ArithAdd, op, one()))); + setPair(result, op, srcDst, makeSafe(addToGraph(ArithAdd, op, one()))); NEXT_OPCODE(op_post_inc); } @@ -2315,8 +2324,7 @@ bool ByteCodeParser::parseBlock(unsigned limit) unsigned result = currentInstruction[1].u.operand; unsigned srcDst = currentInstruction[2].u.operand; NodeIndex op = get(srcDst); - set(result, op); - set(srcDst, makeSafe(addToGraph(ArithSub, op, one()))); + setPair(result, op, srcDst, makeSafe(addToGraph(ArithSub, op, one()))); NEXT_OPCODE(op_post_dec); } @@ -3115,21 +3123,11 @@ bool ByteCodeParser::parseBlock(unsigned limit) NodeIndex base = 0; NodeIndex value = 0; - if (parseResolveOperations(prediction, identifier, operations, putToBaseOperation, &base, &value)) { - // First create OSR hints only. - set(baseDst, base); - set(valueDst, value); - - // If we try to hoist structure checks into here, then we're guaranteed that they will occur - // *after* we have already set up the values for OSR. - - // Then do the real SetLocals. - set(baseDst, base); - set(valueDst, value); - } else { + if (parseResolveOperations(prediction, identifier, operations, putToBaseOperation, &base, &value)) + setPair(baseDst, base, valueDst, value); + else { addToGraph(ForceOSRExit); - set(baseDst, addToGraph(GarbageValue)); - set(valueDst, addToGraph(GarbageValue)); + setPair(baseDst, addToGraph(GarbageValue), valueDst, addToGraph(GarbageValue)); } NEXT_OPCODE(op_resolve_with_base); @@ -3143,21 +3141,11 @@ bool ByteCodeParser::parseBlock(unsigned limit) NodeIndex base = 0; NodeIndex value = 0; - if (parseResolveOperations(prediction, identifier, operations, 0, &base, &value)) { - // First create OSR hints only. - set(baseDst, base); - set(valueDst, value); - - // If we try to hoist structure checks into here, then we're guaranteed that they will occur - // *after* we have already set up the values for OSR. - - // Then do the real SetLocals. - set(baseDst, base); - set(valueDst, value); - } else { + if (parseResolveOperations(prediction, identifier, operations, 0, &base, &value)) + setPair(baseDst, base, valueDst, value); + else { addToGraph(ForceOSRExit); - set(baseDst, addToGraph(GarbageValue)); - set(valueDst, addToGraph(GarbageValue)); + setPair(baseDst, addToGraph(GarbageValue), valueDst, addToGraph(GarbageValue)); } NEXT_OPCODE(op_resolve_with_this); @@ -3664,7 +3652,7 @@ void ByteCodeParser::parseCodeBlock() codeBlock->needsFullScopeChain()?"true":"false", codeBlock->ownerExecutable()->needsActivation()?"true":"false", codeBlock->ownerExecutable()->isStrictMode()?"true":"false"); - codeBlock->baselineVersion()->dump(m_exec); + codeBlock->baselineVersion()->dump(); #endif for (unsigned jumpTargetIndex = 0; jumpTargetIndex <= codeBlock->numberOfJumpTargets(); ++jumpTargetIndex) { diff --git a/Source/JavaScriptCore/dfg/DFGDisassembler.cpp b/Source/JavaScriptCore/dfg/DFGDisassembler.cpp index 654824196..f09b974a5 100644 --- a/Source/JavaScriptCore/dfg/DFGDisassembler.cpp +++ b/Source/JavaScriptCore/dfg/DFGDisassembler.cpp @@ -39,12 +39,12 @@ Disassembler::Disassembler(Graph& graph) m_labelForNodeIndex.resize(graph.size()); } -void Disassembler::dump(LinkBuffer& linkBuffer) +void Disassembler::dump(PrintStream& out, LinkBuffer& linkBuffer) { m_graph.m_dominators.computeIfNecessary(m_graph); - dataLogF("Generated JIT code for DFG CodeBlock %p, instruction count = %u:\n", m_graph.m_codeBlock, m_graph.m_codeBlock->instructionCount()); - dataLogF(" Code at [%p, %p):\n", linkBuffer.debugAddress(), static_cast<char*>(linkBuffer.debugAddress()) + linkBuffer.debugSize()); + out.print("Generated JIT code for DFG CodeBlock ", RawPointer(m_graph.m_codeBlock), ", instruction count = ", m_graph.m_codeBlock->instructionCount(), ":\n"); + out.print(" Code at [", RawPointer(linkBuffer.debugAddress()), ", ", RawPointer(static_cast<char*>(linkBuffer.debugAddress()) + linkBuffer.debugSize()), "):\n"); const char* prefix = " "; const char* disassemblyPrefix = " "; @@ -55,11 +55,11 @@ void Disassembler::dump(LinkBuffer& linkBuffer) BasicBlock* block = m_graph.m_blocks[blockIndex].get(); if (!block) continue; - dumpDisassembly(disassemblyPrefix, linkBuffer, previousLabel, m_labelForBlockIndex[blockIndex], lastNodeIndex); - m_graph.dumpBlockHeader(prefix, blockIndex, Graph::DumpLivePhisOnly); + dumpDisassembly(out, disassemblyPrefix, linkBuffer, previousLabel, m_labelForBlockIndex[blockIndex], lastNodeIndex); + m_graph.dumpBlockHeader(out, prefix, blockIndex, Graph::DumpLivePhisOnly); NodeIndex lastNodeIndexForDisassembly = block->at(0); for (size_t i = 0; i < block->size(); ++i) { - if (!m_graph[block->at(i)].willHaveCodeGenOrOSR()) + if (!m_graph[block->at(i)].willHaveCodeGenOrOSR() && !Options::showAllDFGNodes()) continue; MacroAssembler::Label currentLabel; if (m_labelForNodeIndex[block->at(i)].isSet()) @@ -74,19 +74,24 @@ void Disassembler::dump(LinkBuffer& linkBuffer) else currentLabel = m_endOfMainPath; } - dumpDisassembly(disassemblyPrefix, linkBuffer, previousLabel, currentLabel, lastNodeIndexForDisassembly); - m_graph.dumpCodeOrigin(prefix, lastNodeIndex, block->at(i)); - m_graph.dump(prefix, block->at(i)); + dumpDisassembly(out, disassemblyPrefix, linkBuffer, previousLabel, currentLabel, lastNodeIndexForDisassembly); + m_graph.dumpCodeOrigin(out, prefix, lastNodeIndex, block->at(i)); + m_graph.dump(out, prefix, block->at(i)); lastNodeIndex = block->at(i); lastNodeIndexForDisassembly = block->at(i); } } - dumpDisassembly(disassemblyPrefix, linkBuffer, previousLabel, m_endOfMainPath, lastNodeIndex); - dataLogF("%s(End Of Main Path)\n", prefix); - dumpDisassembly(disassemblyPrefix, linkBuffer, previousLabel, m_endOfCode, NoNode); + dumpDisassembly(out, disassemblyPrefix, linkBuffer, previousLabel, m_endOfMainPath, lastNodeIndex); + out.print(prefix, "(End Of Main Path)\n"); + dumpDisassembly(out, disassemblyPrefix, linkBuffer, previousLabel, m_endOfCode, NoNode); +} + +void Disassembler::dump(LinkBuffer& linkBuffer) +{ + dump(WTF::dataFile(), linkBuffer); } -void Disassembler::dumpDisassembly(const char* prefix, LinkBuffer& linkBuffer, MacroAssembler::Label& previousLabel, MacroAssembler::Label currentLabel, NodeIndex context) +void Disassembler::dumpDisassembly(PrintStream& out, const char* prefix, LinkBuffer& linkBuffer, MacroAssembler::Label& previousLabel, MacroAssembler::Label currentLabel, NodeIndex context) { size_t prefixLength = strlen(prefix); int amountOfNodeWhiteSpace; @@ -104,7 +109,7 @@ void Disassembler::dumpDisassembly(const char* prefix, LinkBuffer& linkBuffer, M CodeLocationLabel end = linkBuffer.locationOf(currentLabel); previousLabel = currentLabel; ASSERT(bitwise_cast<uintptr_t>(end.executableAddress()) >= bitwise_cast<uintptr_t>(start.executableAddress())); - disassemble(start, bitwise_cast<uintptr_t>(end.executableAddress()) - bitwise_cast<uintptr_t>(start.executableAddress()), prefixBuffer.get(), WTF::dataFile()); + disassemble(start, bitwise_cast<uintptr_t>(end.executableAddress()) - bitwise_cast<uintptr_t>(start.executableAddress()), prefixBuffer.get(), out); } } } // namespace JSC::DFG diff --git a/Source/JavaScriptCore/dfg/DFGDisassembler.h b/Source/JavaScriptCore/dfg/DFGDisassembler.h index 470a989ef..8cc58c666 100644 --- a/Source/JavaScriptCore/dfg/DFGDisassembler.h +++ b/Source/JavaScriptCore/dfg/DFGDisassembler.h @@ -62,10 +62,11 @@ public: m_endOfCode = label; } + void dump(PrintStream&, LinkBuffer&); void dump(LinkBuffer&); private: - void dumpDisassembly(const char* prefix, LinkBuffer&, MacroAssembler::Label& previousLabel, MacroAssembler::Label currentLabel, NodeIndex context); + void dumpDisassembly(PrintStream&, const char* prefix, LinkBuffer&, MacroAssembler::Label& previousLabel, MacroAssembler::Label currentLabel, NodeIndex context); Graph& m_graph; MacroAssembler::Label m_startOfCode; diff --git a/Source/JavaScriptCore/dfg/DFGGraph.cpp b/Source/JavaScriptCore/dfg/DFGGraph.cpp index 19587ba64..270f53b87 100644 --- a/Source/JavaScriptCore/dfg/DFGGraph.cpp +++ b/Source/JavaScriptCore/dfg/DFGGraph.cpp @@ -27,7 +27,7 @@ #include "DFGGraph.h" #include "CodeBlock.h" -#include <wtf/BoundsCheckedPointer.h> +#include "DFGVariableAccessDataDump.h" #if ENABLE(DFG_JIT) @@ -57,51 +57,13 @@ const char *Graph::opName(NodeType op) return dfgOpNames[op]; } -const char* Graph::nameOfVariableAccessData(VariableAccessData* variableAccessData) -{ - // Variables are already numbered. For readability of IR dumps, this returns - // an alphabetic name for the variable access data, so that you don't have to - // reason about two numbers (variable number and live range number), but instead - // a number and a letter. - - unsigned index = std::numeric_limits<unsigned>::max(); - for (unsigned i = 0; i < m_variableAccessData.size(); ++i) { - if (&m_variableAccessData[i] == variableAccessData) { - index = i; - break; - } - } - - ASSERT(index != std::numeric_limits<unsigned>::max()); - - if (!index) - return "A"; - - static char buf[100]; - BoundsCheckedPointer<char> ptr(buf, sizeof(buf)); - - while (index) { - *ptr++ = 'A' + (index % 26); - index /= 26; - } - - if (variableAccessData->isCaptured()) - *ptr++ = '*'; - - ptr.strcat(speculationToAbbreviatedString(variableAccessData->prediction())); - - *ptr++ = 0; - - return buf; -} - -static void printWhiteSpace(unsigned amount) +static void printWhiteSpace(PrintStream& out, unsigned amount) { while (amount-- > 0) - dataLogF(" "); + out.print(" "); } -void Graph::dumpCodeOrigin(const char* prefix, NodeIndex prevNodeIndex, NodeIndex nodeIndex) +void Graph::dumpCodeOrigin(PrintStream& out, const char* prefix, NodeIndex prevNodeIndex, NodeIndex nodeIndex) { if (prevNodeIndex == NoNode) return; @@ -124,16 +86,16 @@ void Graph::dumpCodeOrigin(const char* prefix, NodeIndex prevNodeIndex, NodeInde // Print the pops. for (unsigned i = previousInlineStack.size(); i-- > indexOfDivergence;) { - dataLogF("%s", prefix); - printWhiteSpace(i * 2); - dataLogF("<-- %p\n", previousInlineStack[i].inlineCallFrame->executable.get()); + out.print(prefix); + printWhiteSpace(out, i * 2); + out.print("<-- ", RawPointer(previousInlineStack[i].inlineCallFrame->executable.get()), "\n"); } // Print the pushes. for (unsigned i = indexOfDivergence; i < currentInlineStack.size(); ++i) { - dataLogF("%s", prefix); - printWhiteSpace(i * 2); - dataLogF("--> %p\n", currentInlineStack[i].inlineCallFrame->executable.get()); + out.print(prefix); + printWhiteSpace(out, i * 2); + out.print("--> ", RawPointer(currentInlineStack[i].inlineCallFrame->executable.get()), "\n"); } } @@ -142,12 +104,20 @@ int Graph::amountOfNodeWhiteSpace(Node& node) return (node.codeOrigin.inlineDepth() - 1) * 2; } -void Graph::printNodeWhiteSpace(Node& node) +void Graph::printNodeWhiteSpace(PrintStream& out, Node& node) { - printWhiteSpace(amountOfNodeWhiteSpace(node)); + printWhiteSpace(out, amountOfNodeWhiteSpace(node)); } -void Graph::dump(const char* prefix, NodeIndex nodeIndex) +void Graph::dump(PrintStream& out, Edge edge) +{ + out.print( + useKindToString(edge.useKind()), + "@", edge.index(), + AbbreviatedSpeculationDump(at(edge).prediction())); +} + +void Graph::dump(PrintStream& out, const char* prefix, NodeIndex nodeIndex) { Node& node = at(nodeIndex); NodeType op = node.op(); @@ -157,9 +127,9 @@ void Graph::dump(const char* prefix, NodeIndex nodeIndex) bool mustGenerate = node.mustGenerate(); if (mustGenerate) --refCount; - - dataLogF("%s", prefix); - printNodeWhiteSpace(node); + + out.print(prefix); + printNodeWhiteSpace(out, node); // Example/explanation of dataflow dump output // @@ -178,95 +148,84 @@ void Graph::dump(const char* prefix, NodeIndex nodeIndex) // $# - the index in the CodeBlock of a constant { for numeric constants the value is displayed | for integers, in both decimal and hex }. // id# - the index in the CodeBlock of an identifier { if codeBlock is passed to dump(), the string representation is displayed }. // var# - the index of a var on the global object, used by GetGlobalVar/PutGlobalVar operations. - dataLogF("% 4d:%s<%c%u:", (int)nodeIndex, skipped ? " skipped " : " ", mustGenerate ? '!' : ' ', refCount); + out.printf("% 4d:%s<%c%u:", (int)nodeIndex, skipped ? " skipped " : " ", mustGenerate ? '!' : ' ', refCount); if (node.hasResult() && !skipped && node.hasVirtualRegister()) - dataLogF("%u", node.virtualRegister()); + out.print(node.virtualRegister()); else - dataLogF("-"); - dataLogF(">\t%s(", opName(op)); + out.print("-"); + out.print(">\t", opName(op), "("); bool hasPrinted = false; if (node.flags() & NodeHasVarArgs) { for (unsigned childIdx = node.firstChild(); childIdx < node.firstChild() + node.numChildren(); childIdx++) { if (hasPrinted) - dataLogF(", "); + out.print(", "); else hasPrinted = true; if (!m_varArgChildren[childIdx]) continue; - dataLogF("%s@%u%s", - useKindToString(m_varArgChildren[childIdx].useKind()), - m_varArgChildren[childIdx].index(), - speculationToAbbreviatedString( - at(m_varArgChildren[childIdx]).prediction())); + dump(out, m_varArgChildren[childIdx]); } } else { if (!!node.child1()) { - dataLogF("%s@%u%s", - useKindToString(node.child1().useKind()), - node.child1().index(), - speculationToAbbreviatedString(at(node.child1()).prediction())); + dump(out, node.child1()); + hasPrinted = true; } if (!!node.child2()) { - dataLogF(", %s@%u%s", - useKindToString(node.child2().useKind()), - node.child2().index(), - speculationToAbbreviatedString(at(node.child2()).prediction())); + out.print(", "); // Whether or not there is a first child, we print a comma to ensure that we see a blank entry if there wasn't one. + dump(out, node.child2()); + hasPrinted = true; } if (!!node.child3()) { - dataLogF(", %s@%u%s", - useKindToString(node.child3().useKind()), - node.child3().index(), - speculationToAbbreviatedString(at(node.child3()).prediction())); + if (!node.child1() && !node.child2()) + out.print(", "); // If the third child is the first non-empty one then make sure we have two blanks preceding it. + out.print(", "); + dump(out, node.child3()); + hasPrinted = true; } - hasPrinted = !!node.child1(); } if (strlen(nodeFlagsAsString(node.flags()))) { - dataLogF("%s%s", hasPrinted ? ", " : "", nodeFlagsAsString(node.flags())); + out.print(hasPrinted ? ", " : "", nodeFlagsAsString(node.flags())); hasPrinted = true; } if (node.hasArrayMode()) { - dataLogF("%s%s", hasPrinted ? ", " : "", node.arrayMode().toString()); + out.print(hasPrinted ? ", " : "", node.arrayMode().toString()); hasPrinted = true; } if (node.hasVarNumber()) { - dataLogF("%svar%u", hasPrinted ? ", " : "", node.varNumber()); + out.print(hasPrinted ? ", " : "", "var", node.varNumber()); hasPrinted = true; } if (node.hasRegisterPointer()) { - dataLogF( - "%sglobal%u(%p)", hasPrinted ? ", " : "", - globalObjectFor(node.codeOrigin)->findRegisterIndex(node.registerPointer()), - node.registerPointer()); + out.print(hasPrinted ? ", " : "", "global", globalObjectFor(node.codeOrigin)->findRegisterIndex(node.registerPointer()), "(", RawPointer(node.registerPointer()), ")"); hasPrinted = true; } if (node.hasIdentifier()) { - dataLogF("%sid%u{%s}", hasPrinted ? ", " : "", node.identifierNumber(), m_codeBlock->identifier(node.identifierNumber()).string().utf8().data()); + out.print(hasPrinted ? ", " : "", "id", node.identifierNumber(), "{", m_codeBlock->identifier(node.identifierNumber()).string(), "}"); hasPrinted = true; } if (node.hasStructureSet()) { for (size_t i = 0; i < node.structureSet().size(); ++i) { - dataLogF("%sstruct(%p: %s)", hasPrinted ? ", " : "", node.structureSet()[i], indexingTypeToString(node.structureSet()[i]->indexingType())); + out.print(hasPrinted ? ", " : "", "struct(", RawPointer(node.structureSet()[i]), ": ", indexingTypeToString(node.structureSet()[i]->indexingType()), ")"); hasPrinted = true; } } if (node.hasStructure()) { - dataLogF("%sstruct(%p: %s)", hasPrinted ? ", " : "", node.structure(), indexingTypeToString(node.structure()->indexingType())); + out.print(hasPrinted ? ", " : "", "struct(", RawPointer(node.structure()), ": ", indexingTypeToString(node.structure()->indexingType()), ")"); hasPrinted = true; } if (node.hasStructureTransitionData()) { - dataLogF("%sstruct(%p -> %p)", hasPrinted ? ", " : "", node.structureTransitionData().previousStructure, node.structureTransitionData().newStructure); + out.print(hasPrinted ? ", " : "", "struct(", RawPointer(node.structureTransitionData().previousStructure), " -> ", RawPointer(node.structureTransitionData().newStructure), ")"); hasPrinted = true; } if (node.hasFunction()) { - dataLogF("%s%p", hasPrinted ? ", " : "", node.function()); + out.print(hasPrinted ? ", " : "", RawPointer(node.function())); hasPrinted = true; } if (node.hasStorageAccessData()) { StorageAccessData& storageAccessData = m_storageAccessData[node.storageAccessDataIndex()]; - dataLogF("%sid%u{%s}", hasPrinted ? ", " : "", storageAccessData.identifierNumber, m_codeBlock->identifier(storageAccessData.identifierNumber).string().utf8().data()); - - dataLogF(", %lu", static_cast<unsigned long>(storageAccessData.offset)); + out.print(hasPrinted ? ", " : "", "id", storageAccessData.identifierNumber, "{", m_codeBlock->identifier(storageAccessData.identifierNumber).string(), "}"); + out.print(", ", static_cast<ptrdiff_t>(storageAccessData.offset)); hasPrinted = true; } ASSERT(node.hasVariableAccessData() == node.hasLocal()); @@ -274,138 +233,139 @@ void Graph::dump(const char* prefix, NodeIndex nodeIndex) VariableAccessData* variableAccessData = node.variableAccessData(); int operand = variableAccessData->operand(); if (operandIsArgument(operand)) - dataLogF("%sarg%u(%s)", hasPrinted ? ", " : "", operandToArgument(operand), nameOfVariableAccessData(variableAccessData)); + out.print(hasPrinted ? ", " : "", "arg", operandToArgument(operand), "(", VariableAccessDataDump(*this, variableAccessData), ")"); else - dataLogF("%sr%u(%s)", hasPrinted ? ", " : "", operand, nameOfVariableAccessData(variableAccessData)); + out.print(hasPrinted ? ", " : "", "r", operand, "(", VariableAccessDataDump(*this, variableAccessData), ")"); hasPrinted = true; } if (node.hasConstantBuffer()) { if (hasPrinted) - dataLogF(", "); - dataLogF("%u:[", node.startConstant()); + out.print(", "); + out.print(node.startConstant(), ":["); for (unsigned i = 0; i < node.numConstants(); ++i) { if (i) - dataLogF(", "); - dataLogF("%s", m_codeBlock->constantBuffer(node.startConstant())[i].description()); + out.print(", "); + out.print(m_codeBlock->constantBuffer(node.startConstant())[i].description()); } - dataLogF("]"); + out.print("]"); hasPrinted = true; } if (node.hasIndexingType()) { if (hasPrinted) - dataLogF(", "); - dataLogF("%s", indexingTypeToString(node.indexingType())); + out.print(", "); + out.print(indexingTypeToString(node.indexingType())); } if (op == JSConstant) { - dataLogF("%s$%u", hasPrinted ? ", " : "", node.constantNumber()); + out.print(hasPrinted ? ", " : "", "$", node.constantNumber()); JSValue value = valueOfJSConstant(nodeIndex); - dataLogF(" = %s", value.description()); + out.print(" = ", value.description()); hasPrinted = true; } if (op == WeakJSConstant) { - dataLogF("%s%p", hasPrinted ? ", " : "", node.weakConstant()); + out.print(hasPrinted ? ", " : "", RawPointer(node.weakConstant())); hasPrinted = true; } if (node.isBranch() || node.isJump()) { - dataLogF("%sT:#%u", hasPrinted ? ", " : "", node.takenBlockIndex()); + out.print(hasPrinted ? ", " : "", "T:#", node.takenBlockIndex()); hasPrinted = true; } if (node.isBranch()) { - dataLogF("%sF:#%u", hasPrinted ? ", " : "", node.notTakenBlockIndex()); + out.print(hasPrinted ? ", " : "", "F:#", node.notTakenBlockIndex()); hasPrinted = true; } - dataLogF("%sbc#%u", hasPrinted ? ", " : "", node.codeOrigin.bytecodeIndex); + out.print(hasPrinted ? ", " : "", "bc#", node.codeOrigin.bytecodeIndex); hasPrinted = true; + (void)hasPrinted; - dataLogF(")"); + out.print(")"); if (!skipped) { if (node.hasVariableAccessData()) - dataLogF(" predicting %s%s", speculationToString(node.variableAccessData()->prediction()), node.variableAccessData()->shouldUseDoubleFormat() ? ", forcing double" : ""); + out.print(" predicting ", SpeculationDump(node.variableAccessData()->prediction()), node.variableAccessData()->shouldUseDoubleFormat() ? ", forcing double" : ""); else if (node.hasHeapPrediction()) - dataLogF(" predicting %s", speculationToString(node.getHeapPrediction())); + out.print(" predicting ", SpeculationDump(node.getHeapPrediction())); } - dataLogF("\n"); + out.print("\n"); } -void Graph::dumpBlockHeader(const char* prefix, BlockIndex blockIndex, PhiNodeDumpMode phiNodeDumpMode) +void Graph::dumpBlockHeader(PrintStream& out, const char* prefix, BlockIndex blockIndex, PhiNodeDumpMode phiNodeDumpMode) { BasicBlock* block = m_blocks[blockIndex].get(); - dataLogF("%sBlock #%u (bc#%u): %s%s\n", prefix, (int)blockIndex, block->bytecodeBegin, block->isReachable ? "" : " (skipped)", block->isOSRTarget ? " (OSR target)" : ""); - dataLogF("%s Predecessors:", prefix); + out.print(prefix, "Block #", blockIndex, " (bc#", block->bytecodeBegin, "): ", block->isReachable ? "" : "(skipped)", block->isOSRTarget ? " (OSR target)" : "", "\n"); + out.print(prefix, " Predecessors:"); for (size_t i = 0; i < block->m_predecessors.size(); ++i) - dataLogF(" #%u", block->m_predecessors[i]); - dataLogF("\n"); + out.print(" #", block->m_predecessors[i]); + out.print("\n"); if (m_dominators.isValid()) { - dataLogF("%s Dominated by:", prefix); + out.print(prefix, " Dominated by:"); for (size_t i = 0; i < m_blocks.size(); ++i) { if (!m_dominators.dominates(i, blockIndex)) continue; - dataLogF(" #%lu", static_cast<unsigned long>(i)); + out.print(" #", i); } - dataLogF("\n"); - dataLogF("%s Dominates:", prefix); + out.print("\n"); + out.print(prefix, " Dominates:"); for (size_t i = 0; i < m_blocks.size(); ++i) { if (!m_dominators.dominates(blockIndex, i)) continue; - dataLogF(" #%lu", static_cast<unsigned long>(i)); + out.print(" #", i); } - dataLogF("\n"); + out.print("\n"); } - dataLogF("%s Phi Nodes:", prefix); + out.print(prefix, " Phi Nodes:"); for (size_t i = 0; i < block->phis.size(); ++i) { NodeIndex phiNodeIndex = block->phis[i]; Node& phiNode = at(phiNodeIndex); if (!phiNode.shouldGenerate() && phiNodeDumpMode == DumpLivePhisOnly) continue; - dataLogF(" @%u->(", phiNodeIndex); + out.print(" @", phiNodeIndex, "->("); if (phiNode.child1()) { - dataLogF("@%u", phiNode.child1().index()); + out.print("@", phiNode.child1().index()); if (phiNode.child2()) { - dataLogF(", @%u", phiNode.child2().index()); + out.print(", @", phiNode.child2().index()); if (phiNode.child3()) - dataLogF(", @%u", phiNode.child3().index()); + out.print(", @", phiNode.child3().index()); } } - dataLogF(")%s", i + 1 < block->phis.size() ? "," : ""); + out.print(")", i + 1 < block->phis.size() ? "," : ""); } - dataLogF("\n"); + out.print("\n"); } -void Graph::dump() +void Graph::dump(PrintStream& out) { NodeIndex lastNodeIndex = NoNode; for (size_t b = 0; b < m_blocks.size(); ++b) { BasicBlock* block = m_blocks[b].get(); if (!block) continue; - dumpBlockHeader("", b, DumpAllPhis); - dataLogF(" vars before: "); + dumpBlockHeader(out, "", b, DumpAllPhis); + out.print(" vars before: "); if (block->cfaHasVisited) - dumpOperands(block->valuesAtHead, WTF::dataFile()); + dumpOperands(block->valuesAtHead, out); else - dataLogF("<empty>"); - dataLogF("\n"); - dataLogF(" var links: "); - dumpOperands(block->variablesAtHead, WTF::dataFile()); - dataLogF("\n"); + out.print("<empty>"); + out.print("\n"); + out.print(" var links: "); + dumpOperands(block->variablesAtHead, out); + out.print("\n"); for (size_t i = 0; i < block->size(); ++i) { - dumpCodeOrigin("", lastNodeIndex, block->at(i)); - dump("", block->at(i)); + dumpCodeOrigin(out, "", lastNodeIndex, block->at(i)); + dump(out, "", block->at(i)); lastNodeIndex = block->at(i); } - dataLogF(" vars after: "); + out.print(" vars after: "); if (block->cfaHasVisited) - dumpOperands(block->valuesAtTail, WTF::dataFile()); + dumpOperands(block->valuesAtTail, out); else - dataLogF("<empty>"); - dataLogF("\n"); - dataLogF(" var links: "); - dumpOperands(block->variablesAtTail, WTF::dataFile()); - dataLogF("\n"); + out.print("<empty>"); + out.print("\n"); + out.print(" var links: "); + dumpOperands(block->variablesAtTail, out); + out.print("\n"); } } @@ -460,7 +420,9 @@ void Graph::predictArgumentTypes() at(m_arguments[arg]).variableAccessData()->predict(profile->computeUpdatedPrediction()); #if DFG_ENABLE(DEBUG_VERBOSE) - dataLogF("Argument [%zu] prediction: %s\n", arg, speculationToString(at(m_arguments[arg]).variableAccessData()->prediction())); + dataLog( + "Argument [", arg, "] prediction: ", + SpeculationDump(at(m_arguments[arg]).variableAccessData()->prediction()), "\n"); #endif } } diff --git a/Source/JavaScriptCore/dfg/DFGGraph.h b/Source/JavaScriptCore/dfg/DFGGraph.h index 0c77b2959..d91d37394 100644 --- a/Source/JavaScriptCore/dfg/DFGGraph.h +++ b/Source/JavaScriptCore/dfg/DFGGraph.h @@ -190,16 +190,17 @@ public: } // CodeBlock is optional, but may allow additional information to be dumped (e.g. Identifier names). - void dump(); + void dump(PrintStream& = WTF::dataFile()); enum PhiNodeDumpMode { DumpLivePhisOnly, DumpAllPhis }; - void dumpBlockHeader(const char* prefix, BlockIndex, PhiNodeDumpMode); - void dump(const char* prefix, NodeIndex); + void dumpBlockHeader(PrintStream&, const char* prefix, BlockIndex, PhiNodeDumpMode); + void dump(PrintStream&, Edge); + void dump(PrintStream&, const char* prefix, NodeIndex); static int amountOfNodeWhiteSpace(Node&); - static void printNodeWhiteSpace(Node&); + static void printNodeWhiteSpace(PrintStream&, Node&); // Dump the code origin of the given node as a diff from the code origin of the // preceding node. - void dumpCodeOrigin(const char* prefix, NodeIndex, NodeIndex); + void dumpCodeOrigin(PrintStream&, const char* prefix, NodeIndex, NodeIndex); BlockIndex blockIndexForBytecodeOffset(Vector<BlockIndex>& blocks, unsigned bytecodeBegin); @@ -326,9 +327,6 @@ public: static const char *opName(NodeType); - // This is O(n), and should only be used for verbose dumps. - const char* nameOfVariableAccessData(VariableAccessData*); - void predictArgumentTypes(); StructureSet* addStructureSet(const StructureSet& structureSet) diff --git a/Source/JavaScriptCore/dfg/DFGNode.h b/Source/JavaScriptCore/dfg/DFGNode.h index 18c8ce16f..5f7890a96 100644 --- a/Source/JavaScriptCore/dfg/DFGNode.h +++ b/Source/JavaScriptCore/dfg/DFGNode.h @@ -1158,17 +1158,17 @@ struct Node { return nodeCanSpeculateInteger(arithNodeFlags()); } - void dumpChildren(FILE* out) + void dumpChildren(PrintStream& out) { if (!child1()) return; - fprintf(out, "@%u", child1().index()); + out.printf("@%u", child1().index()); if (!child2()) return; - fprintf(out, ", @%u", child2().index()); + out.printf(", @%u", child2().index()); if (!child3()) return; - fprintf(out, ", @%u", child3().index()); + out.printf(", @%u", child3().index()); } // Used to look up exception handling information (currently implemented as a bytecode index). diff --git a/Source/JavaScriptCore/dfg/DFGOSRExitCompiler64.cpp b/Source/JavaScriptCore/dfg/DFGOSRExitCompiler64.cpp index b83c0b3f5..3138daea9 100644 --- a/Source/JavaScriptCore/dfg/DFGOSRExitCompiler64.cpp +++ b/Source/JavaScriptCore/dfg/DFGOSRExitCompiler64.cpp @@ -684,7 +684,7 @@ void OSRExitCompiler::compileExit(const OSRExit& exit, const Operands<ValueRecov // 16) Load the result of the last bytecode operation into regT0. if (exit.m_lastSetOperand != std::numeric_limits<int>::max()) - m_jit.loadPtr(AssemblyHelpers::addressFor((VirtualRegister)exit.m_lastSetOperand), GPRInfo::cachedResultRegister); + m_jit.load64(AssemblyHelpers::addressFor((VirtualRegister)exit.m_lastSetOperand), GPRInfo::cachedResultRegister); // 17) Adjust the call frame pointer. diff --git a/Source/JavaScriptCore/dfg/DFGSpeculativeJIT.cpp b/Source/JavaScriptCore/dfg/DFGSpeculativeJIT.cpp index 41276d233..d7f7b2fab 100644 --- a/Source/JavaScriptCore/dfg/DFGSpeculativeJIT.cpp +++ b/Source/JavaScriptCore/dfg/DFGSpeculativeJIT.cpp @@ -147,6 +147,13 @@ void SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource speculationCheck(kind, jsValueSource, nodeUse.index(), jumpToFail, recovery); } +void SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, NodeIndex nodeIndex, MacroAssembler::Jump jumpToFail, const SpeculationRecovery& recovery, SpeculationDirection direction) +{ + speculationCheck(kind, jsValueSource, nodeIndex, jumpToFail, recovery); + if (direction == ForwardSpeculation) + convertLastOSRExitToForward(); +} + JumpReplacementWatchpoint* SpeculativeJIT::speculationWatchpoint(ExitKind kind, JSValueSource jsValueSource, NodeIndex nodeIndex) { if (!m_compileOkay) @@ -170,10 +177,13 @@ JumpReplacementWatchpoint* SpeculativeJIT::speculationWatchpoint(ExitKind kind) void SpeculativeJIT::convertLastOSRExitToForward(const ValueRecovery& valueRecovery) { if (!valueRecovery) { - // Check that the preceding node was a SetLocal with the same code origin. - Node* setLocal = &at(m_jit.graph().m_blocks[m_block]->at(m_indexInBlock - 1)); - ASSERT_UNUSED(setLocal, setLocal->op() == SetLocal); - ASSERT_UNUSED(setLocal, setLocal->codeOrigin == at(m_compileIndex).codeOrigin); + // Check that either the current node is a SetLocal, or the preceding node was a + // SetLocal with the same code origin. + if (at(m_compileIndex).op() != SetLocal) { + Node* setLocal = &at(m_jit.graph().m_blocks[m_block]->at(m_indexInBlock - 1)); + ASSERT_UNUSED(setLocal, setLocal->op() == SetLocal); + ASSERT_UNUSED(setLocal, setLocal->codeOrigin == at(m_compileIndex).codeOrigin); + } // Find the next node. unsigned indexInBlock = m_indexInBlock + 1; @@ -239,10 +249,10 @@ JumpReplacementWatchpoint* SpeculativeJIT::forwardSpeculationWatchpoint(ExitKind return result; } -JumpReplacementWatchpoint* SpeculativeJIT::speculationWatchpointWithConditionalDirection(ExitKind kind, bool isForward) +JumpReplacementWatchpoint* SpeculativeJIT::speculationWatchpoint(ExitKind kind, SpeculationDirection direction) { JumpReplacementWatchpoint* result = speculationWatchpoint(kind); - if (isForward) + if (direction == ForwardSpeculation) convertLastOSRExitToForward(); return result; } @@ -262,9 +272,9 @@ void SpeculativeJIT::forwardSpeculationCheck(ExitKind kind, JSValueSource jsValu forwardSpeculationCheck(kind, jsValueSource, nodeIndex, jumpVector[i], valueRecovery); } -void SpeculativeJIT::speculationCheckWithConditionalDirection(ExitKind kind, JSValueSource jsValueSource, NodeIndex nodeIndex, MacroAssembler::Jump jumpToFail, bool isForward) +void SpeculativeJIT::speculationCheck(ExitKind kind, JSValueSource jsValueSource, NodeIndex nodeIndex, MacroAssembler::Jump jumpToFail, SpeculationDirection direction) { - if (isForward) + if (direction == ForwardSpeculation) forwardSpeculationCheck(kind, jsValueSource, nodeIndex, jumpToFail); else speculationCheck(kind, jsValueSource, nodeIndex, jumpToFail); @@ -288,7 +298,7 @@ void SpeculativeJIT::terminateSpeculativeExecution(ExitKind kind, JSValueRegs js terminateSpeculativeExecution(kind, jsValueRegs, nodeUse.index()); } -void SpeculativeJIT::terminateSpeculativeExecutionWithConditionalDirection(ExitKind kind, JSValueRegs jsValueRegs, NodeIndex nodeIndex, bool isForward) +void SpeculativeJIT::terminateSpeculativeExecution(ExitKind kind, JSValueRegs jsValueRegs, NodeIndex nodeIndex, SpeculationDirection direction) { ASSERT(at(m_compileIndex).canExit() || m_isCheckingArgumentTypes); #if DFG_ENABLE(DEBUG_VERBOSE) @@ -296,7 +306,7 @@ void SpeculativeJIT::terminateSpeculativeExecutionWithConditionalDirection(ExitK #endif if (!m_compileOkay) return; - speculationCheckWithConditionalDirection(kind, jsValueRegs, nodeIndex, m_jit.jump(), isForward); + speculationCheck(kind, jsValueRegs, nodeIndex, m_jit.jump(), direction); m_compileOkay = false; } @@ -662,7 +672,7 @@ GPRReg SpeculativeJIT::fillStorage(NodeIndex nodeIndex) } // Must be a cell; fill it as a cell and then return the pointer. - return fillSpeculateCell(nodeIndex); + return fillSpeculateCell(nodeIndex, BackwardSpeculation); } case DataFormatStorage: { @@ -672,7 +682,7 @@ GPRReg SpeculativeJIT::fillStorage(NodeIndex nodeIndex) } default: - return fillSpeculateCell(nodeIndex); + return fillSpeculateCell(nodeIndex, BackwardSpeculation); } } diff --git a/Source/JavaScriptCore/dfg/DFGSpeculativeJIT.h b/Source/JavaScriptCore/dfg/DFGSpeculativeJIT.h index f1384e269..5f6fe842c 100644 --- a/Source/JavaScriptCore/dfg/DFGSpeculativeJIT.h +++ b/Source/JavaScriptCore/dfg/DFGSpeculativeJIT.h @@ -53,6 +53,7 @@ class SpeculateCellOperand; class SpeculateBooleanOperand; enum GeneratedOperandType { GeneratedOperandTypeUnknown, GeneratedOperandInteger, GeneratedOperandDouble, GeneratedOperandJSValue}; +enum SpeculationDirection { ForwardSpeculation, BackwardSpeculation }; // === SpeculativeJIT === // @@ -306,11 +307,11 @@ public: // Called by the speculative operand types, below, to fill operand to // machine registers, implicitly generating speculation checks as needed. - GPRReg fillSpeculateInt(NodeIndex, DataFormat& returnFormat); + GPRReg fillSpeculateInt(NodeIndex, DataFormat& returnFormat, SpeculationDirection); GPRReg fillSpeculateIntStrict(NodeIndex); - FPRReg fillSpeculateDouble(NodeIndex); - GPRReg fillSpeculateCell(NodeIndex, bool isForwardSpeculation = false); - GPRReg fillSpeculateBoolean(NodeIndex); + FPRReg fillSpeculateDouble(NodeIndex, SpeculationDirection); + GPRReg fillSpeculateCell(NodeIndex, SpeculationDirection); + GPRReg fillSpeculateBoolean(NodeIndex, SpeculationDirection); GeneratedOperandType checkGeneratedTypeForToInt32(NodeIndex); void addSlowPathGenerator(PassOwnPtr<SlowPathGenerator>); @@ -2448,15 +2449,16 @@ public: // that you've ensured that there exists a MovHint prior to your use of forwardSpeculationCheck(). void forwardSpeculationCheck(ExitKind, JSValueSource, NodeIndex, MacroAssembler::Jump jumpToFail, const ValueRecovery& = ValueRecovery()); void forwardSpeculationCheck(ExitKind, JSValueSource, NodeIndex, const MacroAssembler::JumpList& jumpsToFail, const ValueRecovery& = ValueRecovery()); - void speculationCheckWithConditionalDirection(ExitKind, JSValueSource, NodeIndex, MacroAssembler::Jump jumpToFail, bool isForward); + void speculationCheck(ExitKind, JSValueSource, NodeIndex, MacroAssembler::Jump jumpToFail, SpeculationDirection); + void speculationCheck(ExitKind, JSValueSource, NodeIndex, MacroAssembler::Jump jumpToFail, const SpeculationRecovery&, SpeculationDirection); // Called when we statically determine that a speculation will fail. void terminateSpeculativeExecution(ExitKind, JSValueRegs, NodeIndex); void terminateSpeculativeExecution(ExitKind, JSValueRegs, Edge); - void terminateSpeculativeExecutionWithConditionalDirection(ExitKind, JSValueRegs, NodeIndex, bool isForward); + void terminateSpeculativeExecution(ExitKind, JSValueRegs, NodeIndex, SpeculationDirection); // Issue a forward speculation watchpoint, which will exit to the next instruction rather // than the current one. JumpReplacementWatchpoint* forwardSpeculationWatchpoint(ExitKind = UncountableWatchpoint); - JumpReplacementWatchpoint* speculationWatchpointWithConditionalDirection(ExitKind, bool isForward); + JumpReplacementWatchpoint* speculationWatchpoint(ExitKind, SpeculationDirection); const TypedArrayDescriptor* typedArrayDescriptor(ArrayMode); @@ -2467,7 +2469,7 @@ public: void arrayify(Node&); template<bool strict> - GPRReg fillSpeculateIntInternal(NodeIndex, DataFormat& returnFormat); + GPRReg fillSpeculateIntInternal(NodeIndex, DataFormat& returnFormat, SpeculationDirection); // It is possible, during speculative generation, to reach a situation in which we // can statically determine a speculation will fail (for example, when two nodes @@ -2963,13 +2965,14 @@ private: class SpeculateIntegerOperand { public: - explicit SpeculateIntegerOperand(SpeculativeJIT* jit, Edge use) + explicit SpeculateIntegerOperand(SpeculativeJIT* jit, Edge use, SpeculationDirection direction = BackwardSpeculation) : m_jit(jit) , m_index(use.index()) , m_gprOrInvalid(InvalidGPRReg) #ifndef NDEBUG , m_format(DataFormatNone) #endif + , m_direction(direction) { ASSERT(m_jit); ASSERT(use.useKind() != DoubleUse); @@ -2998,7 +3001,7 @@ public: GPRReg gpr() { if (m_gprOrInvalid == InvalidGPRReg) - m_gprOrInvalid = m_jit->fillSpeculateInt(index(), m_format); + m_gprOrInvalid = m_jit->fillSpeculateInt(index(), m_format, m_direction); return m_gprOrInvalid; } @@ -3012,6 +3015,7 @@ private: NodeIndex m_index; GPRReg m_gprOrInvalid; DataFormat m_format; + SpeculationDirection m_direction; }; class SpeculateStrictInt32Operand { @@ -3058,10 +3062,11 @@ private: class SpeculateDoubleOperand { public: - explicit SpeculateDoubleOperand(SpeculativeJIT* jit, Edge use) + explicit SpeculateDoubleOperand(SpeculativeJIT* jit, Edge use, SpeculationDirection direction = BackwardSpeculation) : m_jit(jit) , m_index(use.index()) , m_fprOrInvalid(InvalidFPRReg) + , m_direction(direction) { ASSERT(m_jit); ASSERT(use.useKind() == DoubleUse); @@ -3083,7 +3088,7 @@ public: FPRReg fpr() { if (m_fprOrInvalid == InvalidFPRReg) - m_fprOrInvalid = m_jit->fillSpeculateDouble(index()); + m_fprOrInvalid = m_jit->fillSpeculateDouble(index(), m_direction); return m_fprOrInvalid; } @@ -3096,15 +3101,16 @@ private: SpeculativeJIT* m_jit; NodeIndex m_index; FPRReg m_fprOrInvalid; + SpeculationDirection m_direction; }; class SpeculateCellOperand { public: - explicit SpeculateCellOperand(SpeculativeJIT* jit, Edge use, bool isForwardSpeculation = false) + explicit SpeculateCellOperand(SpeculativeJIT* jit, Edge use, SpeculationDirection direction = BackwardSpeculation) : m_jit(jit) , m_index(use.index()) , m_gprOrInvalid(InvalidGPRReg) - , m_isForwardSpeculation(isForwardSpeculation) + , m_direction(direction) { ASSERT(m_jit); ASSERT(use.useKind() != DoubleUse); @@ -3126,7 +3132,7 @@ public: GPRReg gpr() { if (m_gprOrInvalid == InvalidGPRReg) - m_gprOrInvalid = m_jit->fillSpeculateCell(index(), m_isForwardSpeculation); + m_gprOrInvalid = m_jit->fillSpeculateCell(index(), m_direction); return m_gprOrInvalid; } @@ -3139,15 +3145,16 @@ private: SpeculativeJIT* m_jit; NodeIndex m_index; GPRReg m_gprOrInvalid; - bool m_isForwardSpeculation; + SpeculationDirection m_direction; }; class SpeculateBooleanOperand { public: - explicit SpeculateBooleanOperand(SpeculativeJIT* jit, Edge use) + explicit SpeculateBooleanOperand(SpeculativeJIT* jit, Edge use, SpeculationDirection direction = BackwardSpeculation) : m_jit(jit) , m_index(use.index()) , m_gprOrInvalid(InvalidGPRReg) + , m_direction(direction) { ASSERT(m_jit); ASSERT(use.useKind() != DoubleUse); @@ -3169,7 +3176,7 @@ public: GPRReg gpr() { if (m_gprOrInvalid == InvalidGPRReg) - m_gprOrInvalid = m_jit->fillSpeculateBoolean(index()); + m_gprOrInvalid = m_jit->fillSpeculateBoolean(index(), m_direction); return m_gprOrInvalid; } @@ -3182,6 +3189,7 @@ private: SpeculativeJIT* m_jit; NodeIndex m_index; GPRReg m_gprOrInvalid; + SpeculationDirection m_direction; }; } } // namespace JSC::DFG diff --git a/Source/JavaScriptCore/dfg/DFGSpeculativeJIT32_64.cpp b/Source/JavaScriptCore/dfg/DFGSpeculativeJIT32_64.cpp index 05af6962e..f5b9ec9ce 100644 --- a/Source/JavaScriptCore/dfg/DFGSpeculativeJIT32_64.cpp +++ b/Source/JavaScriptCore/dfg/DFGSpeculativeJIT32_64.cpp @@ -1087,13 +1087,13 @@ void SpeculativeJIT::emitCall(Node& node) } template<bool strict> -GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& returnFormat) +GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& returnFormat, SpeculationDirection direction) { #if DFG_ENABLE(DEBUG_VERBOSE) dataLogF("SpecInt@%d ", nodeIndex); #endif if (isKnownNotInteger(nodeIndex)) { - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); returnFormat = DataFormatInteger; return allocate(); } @@ -1121,7 +1121,7 @@ GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& // If we know this was spilled as an integer we can fill without checking. if (!isInt32Speculation(type)) - speculationCheck(BadType, JSValueSource(JITCompiler::addressFor(virtualRegister)), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::Int32Tag))); + speculationCheck(BadType, JSValueSource(JITCompiler::addressFor(virtualRegister)), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::Int32Tag)), direction); GPRReg gpr = allocate(); m_jit.load32(JITCompiler::payloadFor(virtualRegister), gpr); @@ -1139,7 +1139,7 @@ GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& m_gprs.lock(tagGPR); m_gprs.lock(payloadGPR); if (!isInt32Speculation(type)) - speculationCheck(BadType, JSValueRegs(tagGPR, payloadGPR), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, tagGPR, TrustedImm32(JSValue::Int32Tag))); + speculationCheck(BadType, JSValueRegs(tagGPR, payloadGPR), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, tagGPR, TrustedImm32(JSValue::Int32Tag)), direction); m_gprs.unlock(tagGPR); m_gprs.release(tagGPR); m_gprs.release(payloadGPR); @@ -1172,26 +1172,26 @@ GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& } } -GPRReg SpeculativeJIT::fillSpeculateInt(NodeIndex nodeIndex, DataFormat& returnFormat) +GPRReg SpeculativeJIT::fillSpeculateInt(NodeIndex nodeIndex, DataFormat& returnFormat, SpeculationDirection direction) { - return fillSpeculateIntInternal<false>(nodeIndex, returnFormat); + return fillSpeculateIntInternal<false>(nodeIndex, returnFormat, direction); } GPRReg SpeculativeJIT::fillSpeculateIntStrict(NodeIndex nodeIndex) { DataFormat mustBeDataFormatInteger; - GPRReg result = fillSpeculateIntInternal<true>(nodeIndex, mustBeDataFormatInteger); + GPRReg result = fillSpeculateIntInternal<true>(nodeIndex, mustBeDataFormatInteger, BackwardSpeculation); ASSERT(mustBeDataFormatInteger == DataFormatInteger); return result; } -FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex) +FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex, SpeculationDirection direction) { #if DFG_ENABLE(DEBUG_VERBOSE) dataLogF("SpecDouble@%d ", nodeIndex); #endif if (isKnownNotNumber(nodeIndex)) { - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return fprAllocate(); } @@ -1234,7 +1234,7 @@ FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex) if (spillFormat != DataFormatJSInteger && spillFormat != DataFormatInteger) { JITCompiler::Jump isInteger = m_jit.branch32(MacroAssembler::Equal, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::Int32Tag)); if (!isNumberSpeculation(type)) - speculationCheck(BadType, JSValueSource(JITCompiler::addressFor(virtualRegister)), nodeIndex, m_jit.branch32(MacroAssembler::AboveOrEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::LowestTag))); + speculationCheck(BadType, JSValueSource(JITCompiler::addressFor(virtualRegister)), nodeIndex, m_jit.branch32(MacroAssembler::AboveOrEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::LowestTag)), direction); m_jit.loadDouble(JITCompiler::addressFor(virtualRegister), fpr); hasUnboxedDouble = m_jit.jump(); @@ -1269,7 +1269,7 @@ FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex) FPRTemporary scratch(this); JITCompiler::Jump isInteger = m_jit.branch32(MacroAssembler::Equal, tagGPR, TrustedImm32(JSValue::Int32Tag)); if (!isNumberSpeculation(type)) - speculationCheck(BadType, JSValueRegs(tagGPR, payloadGPR), nodeIndex, m_jit.branch32(MacroAssembler::AboveOrEqual, tagGPR, TrustedImm32(JSValue::LowestTag))); + speculationCheck(BadType, JSValueRegs(tagGPR, payloadGPR), nodeIndex, m_jit.branch32(MacroAssembler::AboveOrEqual, tagGPR, TrustedImm32(JSValue::LowestTag)), direction); unboxDouble(tagGPR, payloadGPR, fpr, scratch.fpr()); hasUnboxedDouble = m_jit.jump(); isInteger.link(&m_jit); @@ -1320,13 +1320,13 @@ FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex) } } -GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpeculation) +GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, SpeculationDirection direction) { #if DFG_ENABLE(DEBUG_VERBOSE) dataLogF("SpecCell@%d ", nodeIndex); #endif if (isKnownNotCell(nodeIndex)) { - terminateSpeculativeExecutionWithConditionalDirection(Uncountable, JSValueRegs(), NoNode, isForwardSpeculation); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return allocate(); } @@ -1350,7 +1350,7 @@ GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpec ASSERT((info.spillFormat() & DataFormatJS) || info.spillFormat() == DataFormatCell); if (!isCellSpeculation(type)) - speculationCheckWithConditionalDirection(BadType, JSValueSource(JITCompiler::addressFor(virtualRegister)), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::CellTag)), isForwardSpeculation); + speculationCheck(BadType, JSValueSource(JITCompiler::addressFor(virtualRegister)), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::CellTag)), direction); GPRReg gpr = allocate(); m_jit.load32(JITCompiler::payloadFor(virtualRegister), gpr); m_gprs.retain(gpr, virtualRegister, SpillOrderSpilled); @@ -1371,7 +1371,7 @@ GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpec m_gprs.lock(tagGPR); m_gprs.lock(payloadGPR); if (!isCellSpeculation(type)) - speculationCheckWithConditionalDirection(BadType, JSValueRegs(tagGPR, payloadGPR), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, tagGPR, TrustedImm32(JSValue::CellTag)), isForwardSpeculation); + speculationCheck(BadType, JSValueRegs(tagGPR, payloadGPR), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, tagGPR, TrustedImm32(JSValue::CellTag)), direction); m_gprs.unlock(tagGPR); m_gprs.release(tagGPR); m_gprs.release(payloadGPR); @@ -1395,7 +1395,7 @@ GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpec } } -GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) +GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex, SpeculationDirection direction) { #if DFG_ENABLE(DEBUG_VERBOSE) dataLogF("SpecBool@%d ", nodeIndex); @@ -1406,7 +1406,7 @@ GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) GenerationInfo& info = m_generationInfo[virtualRegister]; if ((node.hasConstant() && !valueOfJSConstant(nodeIndex).isBoolean()) || !(info.isJSBoolean() || info.isUnknownJS())) { - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return allocate(); } @@ -1426,7 +1426,7 @@ GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) ASSERT((info.spillFormat() & DataFormatJS) || info.spillFormat() == DataFormatBoolean); if (!isBooleanSpeculation(type)) - speculationCheck(BadType, JSValueSource(JITCompiler::addressFor(virtualRegister)), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::BooleanTag))); + speculationCheck(BadType, JSValueSource(JITCompiler::addressFor(virtualRegister)), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, JITCompiler::tagFor(virtualRegister), TrustedImm32(JSValue::BooleanTag)), direction); GPRReg gpr = allocate(); m_jit.load32(JITCompiler::payloadFor(virtualRegister), gpr); @@ -1448,7 +1448,7 @@ GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) m_gprs.lock(tagGPR); m_gprs.lock(payloadGPR); if (!isBooleanSpeculation(type)) - speculationCheck(BadType, JSValueRegs(tagGPR, payloadGPR), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, tagGPR, TrustedImm32(JSValue::BooleanTag))); + speculationCheck(BadType, JSValueRegs(tagGPR, payloadGPR), nodeIndex, m_jit.branch32(MacroAssembler::NotEqual, tagGPR, TrustedImm32(JSValue::BooleanTag)), direction); m_gprs.unlock(tagGPR); m_gprs.release(tagGPR); @@ -2241,39 +2241,9 @@ void SpeculativeJIT::compile(Node& node) // stack. compileMovHint(node); - // As far as OSR is concerned, we're on the bytecode index corresponding - // to the *next* instruction, since we've already "executed" the - // SetLocal and whatever other DFG Nodes are associated with the same - // bytecode index as the SetLocal. - ASSERT(m_codeOriginForOSR == node.codeOrigin); - Node* nextNode = &at(block()->at(m_indexInBlock + 1)); - - // But even more oddly, we need to be super careful about the following - // sequence: - // - // a: Foo() - // b: SetLocal(@a) - // c: Flush(@b) - // - // This next piece of crazy takes care of this. - if (nextNode->op() == Flush && nextNode->child1() == m_compileIndex) - nextNode = &at(block()->at(m_indexInBlock + 2)); - - // Oddly, it's possible for the bytecode index for the next node to be - // equal to ours. This will happen for op_post_inc. And, even more oddly, - // this is just fine. Ordinarily, this wouldn't be fine, since if the - // next node failed OSR then we'd be OSR-ing with this SetLocal's local - // variable already set even though from the standpoint of the old JIT, - // this SetLocal should not have executed. But for op_post_inc, it's just - // fine, because this SetLocal's local (i.e. the LHS in a x = y++ - // statement) would be dead anyway - so the fact that DFG would have - // already made the assignment, and baked it into the stack during - // OSR exit, would not be visible to the old JIT in any way. - m_codeOriginForOSR = nextNode->codeOrigin; - if (!node.variableAccessData()->isCaptured() && !m_jit.graph().isCreatedThisArgument(node.local())) { if (node.variableAccessData()->shouldUseDoubleFormat()) { - SpeculateDoubleOperand value(this, node.child1()); + SpeculateDoubleOperand value(this, node.child1(), ForwardSpeculation); m_jit.storeDouble(value.fpr(), JITCompiler::addressFor(node.local())); noResult(m_compileIndex); // Indicate that it's no longer necessary to retrieve the value of @@ -2291,14 +2261,14 @@ void SpeculativeJIT::compile(Node& node) break; } if (isInt32Speculation(predictedType)) { - SpeculateIntegerOperand value(this, node.child1()); + SpeculateIntegerOperand value(this, node.child1(), ForwardSpeculation); m_jit.store32(value.gpr(), JITCompiler::payloadFor(node.local())); noResult(m_compileIndex); recordSetLocal(node.local(), ValueSource(Int32InJSStack)); break; } if (isCellSpeculation(predictedType)) { - SpeculateCellOperand cell(this, node.child1()); + SpeculateCellOperand cell(this, node.child1(), ForwardSpeculation); GPRReg cellGPR = cell.gpr(); m_jit.storePtr(cellGPR, JITCompiler::payloadFor(node.local())); noResult(m_compileIndex); @@ -2306,7 +2276,7 @@ void SpeculativeJIT::compile(Node& node) break; } if (isBooleanSpeculation(predictedType)) { - SpeculateBooleanOperand value(this, node.child1()); + SpeculateBooleanOperand value(this, node.child1(), ForwardSpeculation); m_jit.store32(value.gpr(), JITCompiler::payloadFor(node.local())); noResult(m_compileIndex); recordSetLocal(node.local(), ValueSource(BooleanInJSStack)); @@ -4172,18 +4142,19 @@ void SpeculativeJIT::compile(Node& node) break; } - SpeculateCellOperand base(this, node.child1(), node.op() == ForwardCheckStructure); + SpeculationDirection direction = node.op() == ForwardCheckStructure ? ForwardSpeculation : BackwardSpeculation; + SpeculateCellOperand base(this, node.child1(), direction); ASSERT(node.structureSet().size()); if (node.structureSet().size() == 1) { - speculationCheckWithConditionalDirection( + speculationCheck( BadCache, JSValueSource::unboxedCell(base.gpr()), NoNode, m_jit.branchWeakPtr( JITCompiler::NotEqual, JITCompiler::Address(base.gpr(), JSCell::structureOffset()), node.structureSet()[0]), - node.op() == ForwardCheckStructure); + direction); } else { GPRTemporary structure(this); @@ -4194,11 +4165,11 @@ void SpeculativeJIT::compile(Node& node) for (size_t i = 0; i < node.structureSet().size() - 1; ++i) done.append(m_jit.branchWeakPtr(JITCompiler::Equal, structure.gpr(), node.structureSet()[i])); - speculationCheckWithConditionalDirection( + speculationCheck( BadCache, JSValueSource::unboxedCell(base.gpr()), NoNode, m_jit.branchWeakPtr( JITCompiler::NotEqual, structure.gpr(), node.structureSet().last()), - node.op() == ForwardCheckStructure); + direction); done.link(&m_jit); } @@ -4216,13 +4187,16 @@ void SpeculativeJIT::compile(Node& node) // we'll just rely on the fact that when a watchpoint fires then that's // quite a hint already. + SpeculationDirection direction = node.op() == ForwardStructureTransitionWatchpoint ? ForwardSpeculation : BackwardSpeculation; + m_jit.addWeakReference(node.structure()); node.structure()->addTransitionWatchpoint( - speculationWatchpointWithConditionalDirection( - BadCache, node.op() == ForwardStructureTransitionWatchpoint)); + speculationWatchpoint( + m_jit.graph()[node.child1()].op() == WeakJSConstant ? BadWeakConstantCache : BadCache, + direction)); #if !ASSERT_DISABLED - SpeculateCellOperand op1(this, node.child1()); + SpeculateCellOperand op1(this, node.child1(), direction); JITCompiler::Jump isOK = m_jit.branchPtr(JITCompiler::Equal, JITCompiler::Address(op1.gpr(), JSCell::structureOffset()), TrustedImmPtr(node.structure())); m_jit.breakpoint(); isOK.link(&m_jit); diff --git a/Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp b/Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp index da6583c70..7b43c5cfc 100644 --- a/Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp +++ b/Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp @@ -1062,7 +1062,7 @@ void SpeculativeJIT::emitCall(Node& node) } template<bool strict> -GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& returnFormat) +GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& returnFormat, SpeculationDirection direction) { #if DFG_ENABLE(DEBUG_VERBOSE) dataLogF("SpecInt@%d ", nodeIndex); @@ -1075,7 +1075,7 @@ GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& switch (info.registerFormat()) { case DataFormatNone: { if ((node.hasConstant() && !isInt32Constant(nodeIndex)) || info.spillFormat() == DataFormatDouble) { - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); returnFormat = DataFormatInteger; return allocate(); } @@ -1126,7 +1126,7 @@ GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& GPRReg gpr = info.gpr(); m_gprs.lock(gpr); if (!isInt32Speculation(type)) - speculationCheck(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branch64(MacroAssembler::Below, gpr, GPRInfo::tagTypeNumberRegister)); + speculationCheck(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branch64(MacroAssembler::Below, gpr, GPRInfo::tagTypeNumberRegister), direction); info.fillJSValue(*m_stream, gpr, DataFormatJSInteger); // If !strict we're done, return. if (!strict) { @@ -1183,7 +1183,7 @@ GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& case DataFormatBoolean: case DataFormatJSCell: case DataFormatJSBoolean: { - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); returnFormat = DataFormatInteger; return allocate(); } @@ -1197,20 +1197,20 @@ GPRReg SpeculativeJIT::fillSpeculateIntInternal(NodeIndex nodeIndex, DataFormat& } } -GPRReg SpeculativeJIT::fillSpeculateInt(NodeIndex nodeIndex, DataFormat& returnFormat) +GPRReg SpeculativeJIT::fillSpeculateInt(NodeIndex nodeIndex, DataFormat& returnFormat, SpeculationDirection direction) { - return fillSpeculateIntInternal<false>(nodeIndex, returnFormat); + return fillSpeculateIntInternal<false>(nodeIndex, returnFormat, direction); } GPRReg SpeculativeJIT::fillSpeculateIntStrict(NodeIndex nodeIndex) { DataFormat mustBeDataFormatInteger; - GPRReg result = fillSpeculateIntInternal<true>(nodeIndex, mustBeDataFormatInteger); + GPRReg result = fillSpeculateIntInternal<true>(nodeIndex, mustBeDataFormatInteger, BackwardSpeculation); ASSERT(mustBeDataFormatInteger == DataFormatInteger); return result; } -FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex) +FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex, SpeculationDirection direction) { #if DFG_ENABLE(DEBUG_VERBOSE) dataLogF("SpecDouble@%d ", nodeIndex); @@ -1244,7 +1244,7 @@ FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex) info.fillDouble(*m_stream, fpr); return fpr; } - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return fprAllocate(); } @@ -1287,7 +1287,7 @@ FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex) ASSERT_NOT_REACHED(); case DataFormatCell: - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return fprAllocate(); case DataFormatJSCell: @@ -1301,7 +1301,7 @@ FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex) JITCompiler::Jump isInteger = m_jit.branch64(MacroAssembler::AboveOrEqual, jsValueGpr, GPRInfo::tagTypeNumberRegister); if (!isNumberSpeculation(type)) - speculationCheck(BadType, JSValueRegs(jsValueGpr), nodeIndex, m_jit.branchTest64(MacroAssembler::Zero, jsValueGpr, GPRInfo::tagTypeNumberRegister)); + speculationCheck(BadType, JSValueRegs(jsValueGpr), nodeIndex, m_jit.branchTest64(MacroAssembler::Zero, jsValueGpr, GPRInfo::tagTypeNumberRegister), direction); // First, if we get here we have a double encoded as a JSValue m_jit.move(jsValueGpr, tempGpr); @@ -1364,7 +1364,7 @@ FPRReg SpeculativeJIT::fillSpeculateDouble(NodeIndex nodeIndex) } } -GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpeculation) +GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, SpeculationDirection direction) { #if DFG_ENABLE(DEBUG_VERBOSE) dataLogF("SpecCell@%d ", nodeIndex); @@ -1377,7 +1377,7 @@ GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpec switch (info.registerFormat()) { case DataFormatNone: { if (info.spillFormat() == DataFormatInteger || info.spillFormat() == DataFormatDouble) { - terminateSpeculativeExecutionWithConditionalDirection(Uncountable, JSValueRegs(), NoNode, isForwardSpeculation); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return allocate(); } @@ -1391,7 +1391,7 @@ GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpec info.fillJSValue(*m_stream, gpr, DataFormatJSCell); return gpr; } - terminateSpeculativeExecutionWithConditionalDirection(Uncountable, JSValueRegs(), NoNode, isForwardSpeculation); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return gpr; } ASSERT(info.spillFormat() & DataFormatJS); @@ -1400,7 +1400,7 @@ GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpec info.fillJSValue(*m_stream, gpr, DataFormatJS); if (!isCellSpeculation(type)) - speculationCheckWithConditionalDirection(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branchTest64(MacroAssembler::NonZero, gpr, GPRInfo::tagMaskRegister), isForwardSpeculation); + speculationCheck(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branchTest64(MacroAssembler::NonZero, gpr, GPRInfo::tagMaskRegister), direction); info.fillJSValue(*m_stream, gpr, DataFormatJSCell); return gpr; } @@ -1416,7 +1416,7 @@ GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpec GPRReg gpr = info.gpr(); m_gprs.lock(gpr); if (!isCellSpeculation(type)) - speculationCheckWithConditionalDirection(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branchTest64(MacroAssembler::NonZero, gpr, GPRInfo::tagMaskRegister), isForwardSpeculation); + speculationCheck(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branchTest64(MacroAssembler::NonZero, gpr, GPRInfo::tagMaskRegister), direction); info.fillJSValue(*m_stream, gpr, DataFormatJSCell); return gpr; } @@ -1427,7 +1427,7 @@ GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpec case DataFormatDouble: case DataFormatJSBoolean: case DataFormatBoolean: { - terminateSpeculativeExecutionWithConditionalDirection(Uncountable, JSValueRegs(), NoNode, isForwardSpeculation); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return allocate(); } @@ -1440,7 +1440,7 @@ GPRReg SpeculativeJIT::fillSpeculateCell(NodeIndex nodeIndex, bool isForwardSpec } } -GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) +GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex, SpeculationDirection direction) { #if DFG_ENABLE(DEBUG_VERBOSE) dataLogF("SpecBool@%d ", nodeIndex); @@ -1453,7 +1453,7 @@ GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) switch (info.registerFormat()) { case DataFormatNone: { if (info.spillFormat() == DataFormatInteger || info.spillFormat() == DataFormatDouble) { - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return allocate(); } @@ -1467,7 +1467,7 @@ GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) info.fillJSValue(*m_stream, gpr, DataFormatJSBoolean); return gpr; } - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return gpr; } ASSERT(info.spillFormat() & DataFormatJS); @@ -1477,7 +1477,7 @@ GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) info.fillJSValue(*m_stream, gpr, DataFormatJS); if (!isBooleanSpeculation(type)) { m_jit.xor64(TrustedImm32(static_cast<int32_t>(ValueFalse)), gpr); - speculationCheck(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branchTest64(MacroAssembler::NonZero, gpr, TrustedImm32(static_cast<int32_t>(~1))), SpeculationRecovery(BooleanSpeculationCheck, gpr, InvalidGPRReg)); + speculationCheck(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branchTest64(MacroAssembler::NonZero, gpr, TrustedImm32(static_cast<int32_t>(~1))), SpeculationRecovery(BooleanSpeculationCheck, gpr, InvalidGPRReg), direction); m_jit.xor64(TrustedImm32(static_cast<int32_t>(ValueFalse)), gpr); } info.fillJSValue(*m_stream, gpr, DataFormatJSBoolean); @@ -1496,7 +1496,7 @@ GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) m_gprs.lock(gpr); if (!isBooleanSpeculation(type)) { m_jit.xor64(TrustedImm32(static_cast<int32_t>(ValueFalse)), gpr); - speculationCheck(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branchTest64(MacroAssembler::NonZero, gpr, TrustedImm32(static_cast<int32_t>(~1))), SpeculationRecovery(BooleanSpeculationCheck, gpr, InvalidGPRReg)); + speculationCheck(BadType, JSValueRegs(gpr), nodeIndex, m_jit.branchTest64(MacroAssembler::NonZero, gpr, TrustedImm32(static_cast<int32_t>(~1))), SpeculationRecovery(BooleanSpeculationCheck, gpr, InvalidGPRReg), direction); m_jit.xor64(TrustedImm32(static_cast<int32_t>(ValueFalse)), gpr); } info.fillJSValue(*m_stream, gpr, DataFormatJSBoolean); @@ -1509,7 +1509,7 @@ GPRReg SpeculativeJIT::fillSpeculateBoolean(NodeIndex nodeIndex) case DataFormatDouble: case DataFormatJSCell: case DataFormatCell: { - terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode); + terminateSpeculativeExecution(Uncountable, JSValueRegs(), NoNode, direction); return allocate(); } @@ -2219,39 +2219,9 @@ void SpeculativeJIT::compile(Node& node) // stack. compileMovHint(node); - // As far as OSR is concerned, we're on the bytecode index corresponding - // to the *next* instruction, since we've already "executed" the - // SetLocal and whatever other DFG Nodes are associated with the same - // bytecode index as the SetLocal. - ASSERT(m_codeOriginForOSR == node.codeOrigin); - Node* nextNode = &at(block()->at(m_indexInBlock + 1)); - - // But even more oddly, we need to be super careful about the following - // sequence: - // - // a: Foo() - // b: SetLocal(@a) - // c: Flush(@b) - // - // This next piece of crazy takes care of this. - if (nextNode->op() == Flush && nextNode->child1() == m_compileIndex) - nextNode = &at(block()->at(m_indexInBlock + 2)); - - // Oddly, it's possible for the bytecode index for the next node to be - // equal to ours. This will happen for op_post_inc. And, even more oddly, - // this is just fine. Ordinarily, this wouldn't be fine, since if the - // next node failed OSR then we'd be OSR-ing with this SetLocal's local - // variable already set even though from the standpoint of the old JIT, - // this SetLocal should not have executed. But for op_post_inc, it's just - // fine, because this SetLocal's local (i.e. the LHS in a x = y++ - // statement) would be dead anyway - so the fact that DFG would have - // already made the assignment, and baked it into the stack during - // OSR exit, would not be visible to the old JIT in any way. - m_codeOriginForOSR = nextNode->codeOrigin; - if (!node.variableAccessData()->isCaptured() && !m_jit.graph().isCreatedThisArgument(node.local())) { if (node.variableAccessData()->shouldUseDoubleFormat()) { - SpeculateDoubleOperand value(this, node.child1()); + SpeculateDoubleOperand value(this, node.child1(), ForwardSpeculation); m_jit.storeDouble(value.fpr(), JITCompiler::addressFor(node.local())); noResult(m_compileIndex); // Indicate that it's no longer necessary to retrieve the value of @@ -2263,14 +2233,14 @@ void SpeculativeJIT::compile(Node& node) SpeculatedType predictedType = node.variableAccessData()->argumentAwarePrediction(); if (isInt32Speculation(predictedType)) { - SpeculateIntegerOperand value(this, node.child1()); + SpeculateIntegerOperand value(this, node.child1(), ForwardSpeculation); m_jit.store32(value.gpr(), JITCompiler::payloadFor(node.local())); noResult(m_compileIndex); recordSetLocal(node.local(), ValueSource(Int32InJSStack)); break; } if (isCellSpeculation(predictedType)) { - SpeculateCellOperand cell(this, node.child1()); + SpeculateCellOperand cell(this, node.child1(), ForwardSpeculation); GPRReg cellGPR = cell.gpr(); m_jit.store64(cellGPR, JITCompiler::addressFor(node.local())); noResult(m_compileIndex); @@ -2278,7 +2248,7 @@ void SpeculativeJIT::compile(Node& node) break; } if (isBooleanSpeculation(predictedType)) { - SpeculateBooleanOperand boolean(this, node.child1()); + SpeculateBooleanOperand boolean(this, node.child1(), ForwardSpeculation); m_jit.store64(boolean.gpr(), JITCompiler::addressFor(node.local())); noResult(m_compileIndex); recordSetLocal(node.local(), ValueSource(BooleanInJSStack)); @@ -4110,7 +4080,8 @@ void SpeculativeJIT::compile(Node& node) break; } - SpeculateCellOperand base(this, node.child1(), node.op() == ForwardCheckStructure); + SpeculationDirection direction = node.op() == ForwardCheckStructure ? ForwardSpeculation : BackwardSpeculation; + SpeculateCellOperand base(this, node.child1(), direction); ASSERT(node.structureSet().size()); @@ -4121,13 +4092,13 @@ void SpeculativeJIT::compile(Node& node) exitKind = BadCache; if (node.structureSet().size() == 1) { - speculationCheckWithConditionalDirection( + speculationCheck( exitKind, JSValueRegs(base.gpr()), NoNode, m_jit.branchWeakPtr( JITCompiler::NotEqual, JITCompiler::Address(base.gpr(), JSCell::structureOffset()), node.structureSet()[0]), - node.op() == ForwardCheckStructure); + direction); } else { GPRTemporary structure(this); @@ -4138,11 +4109,11 @@ void SpeculativeJIT::compile(Node& node) for (size_t i = 0; i < node.structureSet().size() - 1; ++i) done.append(m_jit.branchWeakPtr(JITCompiler::Equal, structure.gpr(), node.structureSet()[i])); - speculationCheckWithConditionalDirection( + speculationCheck( exitKind, JSValueRegs(base.gpr()), NoNode, m_jit.branchWeakPtr( JITCompiler::NotEqual, structure.gpr(), node.structureSet().last()), - node.op() == ForwardCheckStructure); + direction); done.link(&m_jit); } @@ -4160,14 +4131,16 @@ void SpeculativeJIT::compile(Node& node) // we'll just rely on the fact that when a watchpoint fires then that's // quite a hint already. + SpeculationDirection direction = node.op() == ForwardStructureTransitionWatchpoint ? ForwardSpeculation : BackwardSpeculation; + m_jit.addWeakReference(node.structure()); node.structure()->addTransitionWatchpoint( - speculationWatchpointWithConditionalDirection( + speculationWatchpoint( m_jit.graph()[node.child1()].op() == WeakJSConstant ? BadWeakConstantCache : BadCache, - node.op() == ForwardStructureTransitionWatchpoint)); + direction)); #if !ASSERT_DISABLED - SpeculateCellOperand op1(this, node.child1()); + SpeculateCellOperand op1(this, node.child1(), direction); JITCompiler::Jump isOK = m_jit.branchPtr(JITCompiler::Equal, JITCompiler::Address(op1.gpr(), JSCell::structureOffset()), TrustedImmPtr(node.structure())); m_jit.breakpoint(); isOK.link(&m_jit); diff --git a/Source/JavaScriptCore/dfg/DFGStructureAbstractValue.h b/Source/JavaScriptCore/dfg/DFGStructureAbstractValue.h index 25606b9be..626a11f0b 100644 --- a/Source/JavaScriptCore/dfg/DFGStructureAbstractValue.h +++ b/Source/JavaScriptCore/dfg/DFGStructureAbstractValue.h @@ -301,14 +301,14 @@ public: void dump(PrintStream& out) const { if (isTop()) { - out.printf("TOP"); + out.print("TOP"); return; } - out.printf("["); + out.print("["); if (m_structure) - out.printf("%p", m_structure); - out.printf("]"); + out.print(RawPointer(m_structure)); + out.print("]"); } private: diff --git a/Source/JavaScriptCore/dfg/DFGVariableAccessDataDump.cpp b/Source/JavaScriptCore/dfg/DFGVariableAccessDataDump.cpp new file mode 100644 index 000000000..920858cef --- /dev/null +++ b/Source/JavaScriptCore/dfg/DFGVariableAccessDataDump.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "DFGVariableAccessDataDump.h" + +#if ENABLE(DFG_JIT) + +#include "DFGGraph.h" +#include "DFGVariableAccessData.h" + +namespace JSC { namespace DFG { + +VariableAccessDataDump::VariableAccessDataDump(Graph& graph, VariableAccessData* data) + : m_graph(graph) + , m_data(data) +{ +} + +void VariableAccessDataDump::dump(PrintStream& out) const +{ + unsigned index = std::numeric_limits<unsigned>::max(); + for (unsigned i = 0; i < m_graph.m_variableAccessData.size(); ++i) { + if (&m_graph.m_variableAccessData[i] == m_data) { + index = i; + break; + } + } + + ASSERT(index != std::numeric_limits<unsigned>::max()); + + if (!index) { + out.print("a"); + return; + } + + while (index) { + out.print(CharacterDump('A' + (index % 26))); + index /= 26; + } + + if (m_data->isCaptured()) + out.print("*"); + + out.print(AbbreviatedSpeculationDump(m_data->prediction())); +} + +} } // namespace JSC::DFG + +#endif // ENABLE(DFG_JIT) + + diff --git a/Source/JavaScriptCore/dfg/DFGVariableAccessDataDump.h b/Source/JavaScriptCore/dfg/DFGVariableAccessDataDump.h new file mode 100644 index 000000000..1422d7fac --- /dev/null +++ b/Source/JavaScriptCore/dfg/DFGVariableAccessDataDump.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef DFGVariableAccessDataDump_h +#define DFGVariableAccessDataDump_h + +#include <wtf/Platform.h> + +#if ENABLE(DFG_JIT) + +#include <wtf/PrintStream.h> + +namespace JSC { namespace DFG { + +class Graph; +class VariableAccessData; + +class VariableAccessDataDump { +public: + VariableAccessDataDump(Graph&, VariableAccessData*); + + void dump(PrintStream&) const; + +private: + Graph& m_graph; + VariableAccessData* m_data; +}; + +} } // namespace JSC::DFG + +#endif // ENABLE(DFG_JIT) + +#endif // DFGVariableAccessDataDump_h + diff --git a/Source/JavaScriptCore/heap/BlockAllocator.cpp b/Source/JavaScriptCore/heap/BlockAllocator.cpp index 2d7b57f9a..f94025c1a 100644 --- a/Source/JavaScriptCore/heap/BlockAllocator.cpp +++ b/Source/JavaScriptCore/heap/BlockAllocator.cpp @@ -27,6 +27,7 @@ #include "BlockAllocator.h" #include "CopiedBlock.h" +#include "CopyWorkList.h" #include "MarkedBlock.h" #include "WeakBlock.h" #include <wtf/CurrentTime.h> @@ -37,6 +38,7 @@ BlockAllocator::BlockAllocator() : m_copiedRegionSet(CopiedBlock::blockSize) , m_markedRegionSet(MarkedBlock::blockSize) , m_weakAndMarkStackRegionSet(WeakBlock::blockSize) + , m_workListRegionSet(CopyWorkListSegment::blockSize) , m_numberOfEmptyRegions(0) , m_isCurrentlyAllocating(false) , m_blockFreeingThreadShouldQuit(false) diff --git a/Source/JavaScriptCore/heap/BlockAllocator.h b/Source/JavaScriptCore/heap/BlockAllocator.h index 75c59b783..417f81da0 100644 --- a/Source/JavaScriptCore/heap/BlockAllocator.h +++ b/Source/JavaScriptCore/heap/BlockAllocator.h @@ -37,6 +37,7 @@ namespace JSC { class BlockAllocator; class CopiedBlock; +class CopyWorkListSegment; class MarkStackSegment; class MarkedBlock; class Region; @@ -188,6 +189,7 @@ private: RegionSet m_markedRegionSet; // WeakBlocks and MarkStackSegments use the same RegionSet since they're the same size. RegionSet m_weakAndMarkStackRegionSet; + RegionSet m_workListRegionSet; DoublyLinkedList<Region> m_emptyRegions; size_t m_numberOfEmptyRegions; @@ -327,6 +329,12 @@ inline BlockAllocator::RegionSet& BlockAllocator::regionSetFor<MarkStackSegment> } template <> +inline BlockAllocator::RegionSet& BlockAllocator::regionSetFor<CopyWorkListSegment>() +{ + return m_workListRegionSet; +} + +template <> inline BlockAllocator::RegionSet& BlockAllocator::regionSetFor<HeapBlock<CopiedBlock> >() { return m_copiedRegionSet; @@ -350,6 +358,12 @@ inline BlockAllocator::RegionSet& BlockAllocator::regionSetFor<HeapBlock<MarkSta return m_weakAndMarkStackRegionSet; } +template <> +inline BlockAllocator::RegionSet& BlockAllocator::regionSetFor<HeapBlock<CopyWorkListSegment> >() +{ + return m_workListRegionSet; +} + template <typename T> inline BlockAllocator::RegionSet& BlockAllocator::regionSetFor() { diff --git a/Source/JavaScriptCore/heap/CopiedBlock.h b/Source/JavaScriptCore/heap/CopiedBlock.h index 83fdb08da..7f585585c 100644 --- a/Source/JavaScriptCore/heap/CopiedBlock.h +++ b/Source/JavaScriptCore/heap/CopiedBlock.h @@ -27,11 +27,14 @@ #define CopiedBlock_h #include "BlockAllocator.h" +#include "CopyWorkList.h" #include "HeapBlock.h" #include "JSValue.h" #include "JSValueInlines.h" #include "Options.h" #include <wtf/Atomics.h> +#include <wtf/OwnPtr.h> +#include <wtf/PassOwnPtr.h> namespace JSC { @@ -44,12 +47,13 @@ public: static CopiedBlock* create(DeadBlock*); static CopiedBlock* createNoZeroFill(DeadBlock*); + void pin(); bool isPinned(); unsigned liveBytes(); - void reportLiveBytes(unsigned); + void reportLiveBytes(JSCell*, unsigned); void didSurviveGC(); - bool didEvacuateBytes(unsigned); + void didEvacuateBytes(unsigned); bool shouldEvacuate(); bool canBeRecycled(); @@ -74,10 +78,18 @@ public: static const size_t blockSize = 32 * KB; + bool hasWorkList(); + CopyWorkList& workList(); + private: CopiedBlock(Region*); void zeroFillWilderness(); // Can be called at any time to zero-fill to the end of the block. +#if ENABLE(PARALLEL_GC) + SpinLock m_workListLock; +#endif + OwnPtr<CopyWorkList> m_workList; + size_t m_remaining; uintptr_t m_isPinned; unsigned m_liveBytes; @@ -114,45 +126,24 @@ inline CopiedBlock::CopiedBlock(Region* region) , m_isPinned(false) , m_liveBytes(0) { - ASSERT(is8ByteAligned(reinterpret_cast<void*>(m_remaining))); -} - -inline void CopiedBlock::reportLiveBytes(unsigned bytes) -{ #if ENABLE(PARALLEL_GC) - unsigned oldValue = 0; - unsigned newValue = 0; - do { - oldValue = m_liveBytes; - newValue = oldValue + bytes; - } while (!WTF::weakCompareAndSwap(&m_liveBytes, oldValue, newValue)); -#else - m_liveBytes += bytes; + m_workListLock.Init(); #endif + ASSERT(is8ByteAligned(reinterpret_cast<void*>(m_remaining))); } inline void CopiedBlock::didSurviveGC() { m_liveBytes = 0; m_isPinned = false; + if (m_workList) + m_workList.clear(); } -inline bool CopiedBlock::didEvacuateBytes(unsigned bytes) +inline void CopiedBlock::didEvacuateBytes(unsigned bytes) { ASSERT(m_liveBytes >= bytes); -#if ENABLE(PARALLEL_GC) - unsigned oldValue = 0; - unsigned newValue = 0; - do { - oldValue = m_liveBytes; - newValue = oldValue - bytes; - } while (!WTF::weakCompareAndSwap(&m_liveBytes, oldValue, newValue)); - ASSERT(m_liveBytes < oldValue); - return !newValue; -#else m_liveBytes -= bytes; - return !m_liveBytes; -#endif } inline bool CopiedBlock::canBeRecycled() @@ -165,6 +156,13 @@ inline bool CopiedBlock::shouldEvacuate() return static_cast<double>(m_liveBytes) / static_cast<double>(payloadCapacity()) <= Options::minCopiedBlockUtilization(); } +inline void CopiedBlock::pin() +{ + m_isPinned = true; + if (m_workList) + m_workList.clear(); +} + inline bool CopiedBlock::isPinned() { return m_isPinned; @@ -230,6 +228,16 @@ inline size_t CopiedBlock::capacity() return region()->blockSize(); } +inline bool CopiedBlock::hasWorkList() +{ + return !!m_workList; +} + +inline CopyWorkList& CopiedBlock::workList() +{ + return *m_workList; +} + } // namespace JSC #endif diff --git a/Source/JavaScriptCore/heap/CopiedBlockInlines.h b/Source/JavaScriptCore/heap/CopiedBlockInlines.h new file mode 100644 index 000000000..0068abcdd --- /dev/null +++ b/Source/JavaScriptCore/heap/CopiedBlockInlines.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef CopiedBlockInlines_h +#define CopiedBlockInlines_h + +#include "CopiedBlock.h" +#include "Heap.h" + +namespace JSC { + +inline void CopiedBlock::reportLiveBytes(JSCell* owner, unsigned bytes) +{ +#if ENABLE(PARALLEL_GC) + SpinLockHolder locker(&m_workListLock); +#endif + m_liveBytes += bytes; + + if (!shouldEvacuate()) { + pin(); + return; + } + + if (!m_workList) + m_workList = adoptPtr(new CopyWorkList(Heap::heap(owner)->blockAllocator())); + + m_workList->append(owner); +} + +} // namespace JSC + +#endif // CopiedBlockInlines_h diff --git a/Source/JavaScriptCore/heap/CopiedSpace.h b/Source/JavaScriptCore/heap/CopiedSpace.h index 3a698e8dc..e3727100e 100644 --- a/Source/JavaScriptCore/heap/CopiedSpace.h +++ b/Source/JavaScriptCore/heap/CopiedSpace.h @@ -47,6 +47,7 @@ class CopiedBlock; class CopiedSpace { friend class CopyVisitor; + friend class GCThreadSharedData; friend class SlotVisitor; friend class JIT; public: diff --git a/Source/JavaScriptCore/heap/CopiedSpaceInlines.h b/Source/JavaScriptCore/heap/CopiedSpaceInlines.h index 9d222f549..41f94dd74 100644 --- a/Source/JavaScriptCore/heap/CopiedSpaceInlines.h +++ b/Source/JavaScriptCore/heap/CopiedSpaceInlines.h @@ -54,7 +54,7 @@ inline bool CopiedSpace::contains(void* ptr, CopiedBlock*& result) inline void CopiedSpace::pin(CopiedBlock* block) { - block->m_isPinned = true; + block->pin(); } inline void CopiedSpace::pinIfNecessary(void* opaquePointer) diff --git a/Source/JavaScriptCore/heap/CopyVisitor.cpp b/Source/JavaScriptCore/heap/CopyVisitor.cpp index 22ab57882..281d4bd3b 100644 --- a/Source/JavaScriptCore/heap/CopyVisitor.cpp +++ b/Source/JavaScriptCore/heap/CopyVisitor.cpp @@ -27,6 +27,7 @@ #include "CopyVisitor.h" #include "CopyVisitorInlines.h" +#include "CopyWorkList.h" #include "GCThreadSharedData.h" #include "JSCell.h" #include "JSObject.h" @@ -41,17 +42,24 @@ CopyVisitor::CopyVisitor(GCThreadSharedData& shared) void CopyVisitor::copyFromShared() { - GCCopyPhaseFunctor functor(*this); - Vector<MarkedBlock*>& blocksToCopy = m_shared.m_blocksToCopy; - size_t startIndex, endIndex; - - m_shared.getNextBlocksToCopy(startIndex, endIndex); - while (startIndex < endIndex) { - for (size_t i = startIndex; i < endIndex; i++) - blocksToCopy[i]->forEachLiveCell(functor); - m_shared.getNextBlocksToCopy(startIndex, endIndex); + size_t next, end; + m_shared.getNextBlocksToCopy(next, end); + while (next < end) { + for (; next < end; ++next) { + CopiedBlock* block = m_shared.m_blocksToCopy[next]; + if (!block->hasWorkList()) + continue; + + CopyWorkList& workList = block->workList(); + for (CopyWorkList::iterator it = workList.begin(); it != workList.end(); ++it) + visitCell(*it); + + ASSERT(!block->liveBytes()); + m_shared.m_copiedSpace->recycleEvacuatedBlock(block); + } + m_shared.getNextBlocksToCopy(next, end); } - ASSERT(startIndex == endIndex); + ASSERT(next == end); } } // namespace JSC diff --git a/Source/JavaScriptCore/heap/CopyVisitor.h b/Source/JavaScriptCore/heap/CopyVisitor.h index 45a2e0ad9..c5f7272a9 100644 --- a/Source/JavaScriptCore/heap/CopyVisitor.h +++ b/Source/JavaScriptCore/heap/CopyVisitor.h @@ -31,6 +31,7 @@ namespace JSC { class GCThreadSharedData; +class JSCell; class CopyVisitor { public: @@ -50,6 +51,7 @@ public: private: void* allocateNewSpaceSlow(size_t); + void visitCell(JSCell*); GCThreadSharedData& m_shared; CopiedAllocator m_copiedAllocator; diff --git a/Source/JavaScriptCore/heap/CopyVisitorInlines.h b/Source/JavaScriptCore/heap/CopyVisitorInlines.h index bd7879429..1557af93d 100644 --- a/Source/JavaScriptCore/heap/CopyVisitorInlines.h +++ b/Source/JavaScriptCore/heap/CopyVisitorInlines.h @@ -34,25 +34,11 @@ namespace JSC { -class GCCopyPhaseFunctor : public MarkedBlock::VoidFunctor { -public: - GCCopyPhaseFunctor(CopyVisitor& visitor) - : m_visitor(visitor) - { - } - - void operator()(JSCell* cell) - { - Structure* structure = cell->structure(); - if (!structure->outOfLineCapacity() && !hasIndexedProperties(structure->indexingType())) - return; - ASSERT(structure->classInfo()->methodTable.copyBackingStore == JSObject::copyBackingStore); - JSObject::copyBackingStore(cell, m_visitor); - } - -private: - CopyVisitor& m_visitor; -}; +inline void CopyVisitor::visitCell(JSCell* cell) +{ + ASSERT(cell->structure()->classInfo()->methodTable.copyBackingStore == JSObject::copyBackingStore); + JSObject::copyBackingStore(cell, *this); +} inline bool CopyVisitor::checkIfShouldCopy(void* oldPtr, size_t bytes) { @@ -110,8 +96,8 @@ inline void CopyVisitor::didCopy(void* ptr, size_t bytes) CopiedBlock* block = CopiedSpace::blockFor(ptr); ASSERT(!block->isPinned()); - if (block->didEvacuateBytes(bytes)) - m_shared.m_copiedSpace->recycleEvacuatedBlock(block); + block->didEvacuateBytes(bytes); + } } // namespace JSC diff --git a/Source/JavaScriptCore/heap/CopyWorkList.h b/Source/JavaScriptCore/heap/CopyWorkList.h new file mode 100644 index 000000000..164e2ddce --- /dev/null +++ b/Source/JavaScriptCore/heap/CopyWorkList.h @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef CopyWorkList_h +#define CopyWorkList_h + +#include <wtf/Vector.h> + +namespace JSC { + +class JSCell; + +class CopyWorkListSegment : public HeapBlock<CopyWorkListSegment> { +public: + static CopyWorkListSegment* create(DeadBlock* block) + { + return new (NotNull, block) CopyWorkListSegment(block->region()); + } + + size_t size() { return m_size; } + bool isFull() { return reinterpret_cast<char*>(&data()[size()]) >= endOfBlock(); } + JSCell* get(size_t index) { return data()[index]; } + + void append(JSCell* cell) + { + ASSERT(!isFull()); + data()[m_size] = cell; + m_size += 1; + } + + static const size_t blockSize = 512; + +private: + CopyWorkListSegment(Region* region) + : HeapBlock<CopyWorkListSegment>(region) + , m_size(0) + { + } + + JSCell** data() { return reinterpret_cast<JSCell**>(this + 1); } + char* endOfBlock() { return reinterpret_cast<char*>(this) + blockSize; } + + size_t m_size; +}; + +class CopyWorkListIterator { + friend class CopyWorkList; +public: + JSCell* get() { return m_currentSegment->get(m_currentIndex); } + JSCell* operator*() { return get(); } + JSCell* operator->() { return get(); } + + CopyWorkListIterator& operator++() + { + m_currentIndex++; + + if (m_currentIndex >= m_currentSegment->size()) { + m_currentIndex = 0; + m_currentSegment = m_currentSegment->next(); + + ASSERT(!m_currentSegment || m_currentSegment->size()); + } + + return *this; + } + + bool operator==(const CopyWorkListIterator& other) const + { + return m_currentSegment == other.m_currentSegment && m_currentIndex == other.m_currentIndex; + } + + bool operator!=(const CopyWorkListIterator& other) const + { + return !(*this == other); + } + + CopyWorkListIterator() + : m_currentSegment(0) + , m_currentIndex(0) + { + } + +private: + CopyWorkListIterator(CopyWorkListSegment* startSegment, size_t startIndex) + : m_currentSegment(startSegment) + , m_currentIndex(startIndex) + { + } + + CopyWorkListSegment* m_currentSegment; + size_t m_currentIndex; +}; + +class CopyWorkList { +public: + typedef CopyWorkListIterator iterator; + + CopyWorkList(BlockAllocator&); + ~CopyWorkList(); + + void append(JSCell*); + iterator begin(); + iterator end(); + +private: + DoublyLinkedList<CopyWorkListSegment> m_segments; + BlockAllocator& m_blockAllocator; +}; + +inline CopyWorkList::CopyWorkList(BlockAllocator& blockAllocator) + : m_blockAllocator(blockAllocator) +{ +} + +inline CopyWorkList::~CopyWorkList() +{ + while (!m_segments.isEmpty()) + m_blockAllocator.deallocate(CopyWorkListSegment::destroy(m_segments.removeHead())); +} + +inline void CopyWorkList::append(JSCell* cell) +{ + if (m_segments.isEmpty() || m_segments.tail()->isFull()) + m_segments.append(CopyWorkListSegment::create(m_blockAllocator.allocate<CopyWorkListSegment>())); + + ASSERT(!m_segments.tail()->isFull()); + + m_segments.tail()->append(cell); +} + +inline CopyWorkList::iterator CopyWorkList::begin() +{ + return CopyWorkListIterator(m_segments.head(), 0); +} + +inline CopyWorkList::iterator CopyWorkList::end() +{ + return CopyWorkListIterator(); +} + +} // namespace JSC + +#endif // CopyWorkList_h diff --git a/Source/JavaScriptCore/heap/GCThreadSharedData.cpp b/Source/JavaScriptCore/heap/GCThreadSharedData.cpp index f513fafab..5d2e908f1 100644 --- a/Source/JavaScriptCore/heap/GCThreadSharedData.cpp +++ b/Source/JavaScriptCore/heap/GCThreadSharedData.cpp @@ -59,7 +59,6 @@ GCThreadSharedData::GCThreadSharedData(JSGlobalData* globalData) , m_sharedMarkStack(globalData->heap.blockAllocator()) , m_numberOfActiveParallelMarkers(0) , m_parallelMarkersShouldExit(false) - , m_blocksToCopy(globalData->heap.m_blockSnapshot) , m_copyIndex(0) , m_numberOfActiveGCThreads(0) , m_gcThreadsShouldWait(false) @@ -166,7 +165,7 @@ void GCThreadSharedData::didStartCopying() { { SpinLockHolder locker(&m_copyLock); - m_blocksToCopy = m_globalData->heap.m_blockSnapshot; + WTF::copyToVector(m_copiedSpace->m_blockSet, m_blocksToCopy); m_copyIndex = 0; } diff --git a/Source/JavaScriptCore/heap/GCThreadSharedData.h b/Source/JavaScriptCore/heap/GCThreadSharedData.h index b80cc5af2..dbc11b552 100644 --- a/Source/JavaScriptCore/heap/GCThreadSharedData.h +++ b/Source/JavaScriptCore/heap/GCThreadSharedData.h @@ -94,7 +94,7 @@ private: HashSet<void*> m_opaqueRoots; SpinLock m_copyLock; - Vector<MarkedBlock*>& m_blocksToCopy; + Vector<CopiedBlock*> m_blocksToCopy; size_t m_copyIndex; static const size_t s_blockFragmentLength = 32; diff --git a/Source/JavaScriptCore/heap/Heap.h b/Source/JavaScriptCore/heap/Heap.h index 90c9f2ab1..2df365643 100644 --- a/Source/JavaScriptCore/heap/Heap.h +++ b/Source/JavaScriptCore/heap/Heap.h @@ -179,6 +179,7 @@ namespace JSC { private: friend class CodeBlock; + friend class CopiedBlock; friend class GCAwareJITStubRoutine; friend class JITStubRoutine; friend class LLIntOffsetsExtractor; diff --git a/Source/JavaScriptCore/heap/SlotVisitor.h b/Source/JavaScriptCore/heap/SlotVisitor.h index 53c7de64f..7d16dc2ed 100644 --- a/Source/JavaScriptCore/heap/SlotVisitor.h +++ b/Source/JavaScriptCore/heap/SlotVisitor.h @@ -82,7 +82,7 @@ public: void harvestWeakReferences(); void finalizeUnconditionalFinalizers(); - void copyLater(void*, size_t); + void copyLater(JSCell*, void*, size_t); #if ENABLE(SIMPLE_HEAP_PROFILING) VTableSpectrum m_visitedTypeCounts; diff --git a/Source/JavaScriptCore/heap/SlotVisitorInlines.h b/Source/JavaScriptCore/heap/SlotVisitorInlines.h index ea8126f87..d76ac552a 100644 --- a/Source/JavaScriptCore/heap/SlotVisitorInlines.h +++ b/Source/JavaScriptCore/heap/SlotVisitorInlines.h @@ -26,6 +26,7 @@ #ifndef SlotVisitorInlines_h #define SlotVisitorInlines_h +#include "CopiedBlockInlines.h" #include "CopiedSpaceInlines.h" #include "Options.h" #include "SlotVisitor.h" @@ -160,7 +161,7 @@ inline void SlotVisitor::donateAndDrain() drain(); } -inline void SlotVisitor::copyLater(void* ptr, size_t bytes) +inline void SlotVisitor::copyLater(JSCell* owner, void* ptr, size_t bytes) { if (CopiedSpace::isOversize(bytes)) { m_shared.m_copiedSpace->pin(CopiedSpace::oversizeBlockFor(ptr)); @@ -171,10 +172,7 @@ inline void SlotVisitor::copyLater(void* ptr, size_t bytes) if (block->isPinned()) return; - block->reportLiveBytes(bytes); - - if (!block->shouldEvacuate()) - m_shared.m_copiedSpace->pin(block); + block->reportLiveBytes(owner, bytes); } } // namespace JSC diff --git a/Source/JavaScriptCore/jit/JITDisassembler.cpp b/Source/JavaScriptCore/jit/JITDisassembler.cpp index 35b939913..0ec72e205 100644 --- a/Source/JavaScriptCore/jit/JITDisassembler.cpp +++ b/Source/JavaScriptCore/jit/JITDisassembler.cpp @@ -44,11 +44,11 @@ JITDisassembler::~JITDisassembler() { } -void JITDisassembler::dump(LinkBuffer& linkBuffer) +void JITDisassembler::dump(PrintStream& out, LinkBuffer& linkBuffer) { - dataLogF("Baseline JIT code for CodeBlock %p, instruction count = %u:\n", m_codeBlock, m_codeBlock->instructionCount()); - dataLogF(" Code at [%p, %p):\n", linkBuffer.debugAddress(), static_cast<char*>(linkBuffer.debugAddress()) + linkBuffer.debugSize()); - dumpDisassembly(linkBuffer, m_startOfCode, m_labelForBytecodeIndexInMainPath[0]); + out.print("Baseline JIT code for CodeBlock ", RawPointer(m_codeBlock), ", instruction count = ", m_codeBlock->instructionCount(), "\n"); + out.print(" Code at [", RawPointer(linkBuffer.debugAddress()), ", ", RawPointer(static_cast<char*>(linkBuffer.debugAddress()) + linkBuffer.debugSize()), "):\n"); + dumpDisassembly(out, linkBuffer, m_startOfCode, m_labelForBytecodeIndexInMainPath[0]); MacroAssembler::Label firstSlowLabel; for (unsigned i = 0; i < m_labelForBytecodeIndexInSlowPath.size(); ++i) { @@ -57,30 +57,35 @@ void JITDisassembler::dump(LinkBuffer& linkBuffer) break; } } - dumpForInstructions(linkBuffer, " ", m_labelForBytecodeIndexInMainPath, firstSlowLabel.isSet() ? firstSlowLabel : m_endOfSlowPath); - dataLogF(" (End Of Main Path)\n"); - dumpForInstructions(linkBuffer, " (S) ", m_labelForBytecodeIndexInSlowPath, m_endOfSlowPath); - dataLogF(" (End Of Slow Path)\n"); + dumpForInstructions(out, linkBuffer, " ", m_labelForBytecodeIndexInMainPath, firstSlowLabel.isSet() ? firstSlowLabel : m_endOfSlowPath); + out.print(" (End Of Main Path)\n"); + dumpForInstructions(out, linkBuffer, " (S) ", m_labelForBytecodeIndexInSlowPath, m_endOfSlowPath); + out.print(" (End Of Slow Path)\n"); + + dumpDisassembly(out, linkBuffer, m_endOfSlowPath, m_endOfCode); +} - dumpDisassembly(linkBuffer, m_endOfSlowPath, m_endOfCode); +void JITDisassembler::dump(LinkBuffer& linkBuffer) +{ + dump(WTF::dataFile(), linkBuffer); } -void JITDisassembler::dumpForInstructions(LinkBuffer& linkBuffer, const char* prefix, Vector<MacroAssembler::Label>& labels, MacroAssembler::Label endLabel) +void JITDisassembler::dumpForInstructions(PrintStream& out, LinkBuffer& linkBuffer, const char* prefix, Vector<MacroAssembler::Label>& labels, MacroAssembler::Label endLabel) { for (unsigned i = 0 ; i < labels.size();) { if (!labels[i].isSet()) { i++; continue; } - dataLogF("%s", prefix); + out.print(prefix); m_codeBlock->dump(i); for (unsigned nextIndex = i + 1; ; nextIndex++) { if (nextIndex >= labels.size()) { - dumpDisassembly(linkBuffer, labels[i], endLabel); + dumpDisassembly(out, linkBuffer, labels[i], endLabel); return; } if (labels[nextIndex].isSet()) { - dumpDisassembly(linkBuffer, labels[i], labels[nextIndex]); + dumpDisassembly(out, linkBuffer, labels[i], labels[nextIndex]); i = nextIndex; break; } @@ -88,11 +93,11 @@ void JITDisassembler::dumpForInstructions(LinkBuffer& linkBuffer, const char* pr } } -void JITDisassembler::dumpDisassembly(LinkBuffer& linkBuffer, MacroAssembler::Label from, MacroAssembler::Label to) +void JITDisassembler::dumpDisassembly(PrintStream& out, LinkBuffer& linkBuffer, MacroAssembler::Label from, MacroAssembler::Label to) { CodeLocationLabel fromLocation = linkBuffer.locationOf(from); CodeLocationLabel toLocation = linkBuffer.locationOf(to); - disassemble(fromLocation, bitwise_cast<uintptr_t>(toLocation.executableAddress()) - bitwise_cast<uintptr_t>(fromLocation.executableAddress()), " ", WTF::dataFile()); + disassemble(fromLocation, bitwise_cast<uintptr_t>(toLocation.executableAddress()) - bitwise_cast<uintptr_t>(fromLocation.executableAddress()), " ", out); } } // namespace JSC diff --git a/Source/JavaScriptCore/jit/JITDisassembler.h b/Source/JavaScriptCore/jit/JITDisassembler.h index f8e917d98..ca914748c 100644 --- a/Source/JavaScriptCore/jit/JITDisassembler.h +++ b/Source/JavaScriptCore/jit/JITDisassembler.h @@ -57,10 +57,11 @@ public: void setEndOfCode(MacroAssembler::Label label) { m_endOfCode = label; } void dump(LinkBuffer&); + void dump(PrintStream&, LinkBuffer&); private: - void dumpForInstructions(LinkBuffer&, const char* prefix, Vector<MacroAssembler::Label>& labels, MacroAssembler::Label endLabel); - void dumpDisassembly(LinkBuffer&, MacroAssembler::Label from, MacroAssembler::Label to); + void dumpForInstructions(PrintStream&, LinkBuffer&, const char* prefix, Vector<MacroAssembler::Label>& labels, MacroAssembler::Label endLabel); + void dumpDisassembly(PrintStream&, LinkBuffer&, MacroAssembler::Label from, MacroAssembler::Label to); CodeBlock* m_codeBlock; MacroAssembler::Label m_startOfCode; diff --git a/Source/JavaScriptCore/jsc.cpp b/Source/JavaScriptCore/jsc.cpp index 07a05b0c9..9db4eba86 100644 --- a/Source/JavaScriptCore/jsc.cpp +++ b/Source/JavaScriptCore/jsc.cpp @@ -540,7 +540,7 @@ static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scr Vector<char> scriptBuffer; if (dump) - BytecodeGenerator::setDumpsGeneratedCode(true); + JSC::Options::dumpGeneratedBytecodes() = true; JSGlobalData& globalData = globalObject->globalData(); diff --git a/Source/JavaScriptCore/parser/Parser.cpp b/Source/JavaScriptCore/parser/Parser.cpp index 049a51939..cf3cb4e4f 100644 --- a/Source/JavaScriptCore/parser/Parser.cpp +++ b/Source/JavaScriptCore/parser/Parser.cpp @@ -812,6 +812,7 @@ template <FunctionRequirements requirements, bool nameIsInContainingScope, class { AutoPopScopeRef functionScope(this, pushScope()); functionScope->setIsFunction(); + int functionStart = m_token.m_location.startOffset; if (match(IDENT)) { name = m_token.m_data.ident; next(); @@ -865,7 +866,7 @@ template <FunctionRequirements requirements, bool nameIsInContainingScope, class OwnPtr<SourceProviderCacheItem> newInfo; int functionLength = closeBracePos - openBracePos; if (TreeBuilder::CanUseFunctionCache && m_functionCache && functionLength > minimumFunctionLengthToCache) { - newInfo = adoptPtr(new SourceProviderCacheItem(m_token.m_location.line, closeBracePos)); + newInfo = adoptPtr(new SourceProviderCacheItem(functionStart, m_token.m_location.line, closeBracePos)); functionScope->saveFunctionInfo(newInfo.get()); } diff --git a/Source/JavaScriptCore/parser/SourceProviderCacheItem.h b/Source/JavaScriptCore/parser/SourceProviderCacheItem.h index 9ca121e2a..ec3890560 100644 --- a/Source/JavaScriptCore/parser/SourceProviderCacheItem.h +++ b/Source/JavaScriptCore/parser/SourceProviderCacheItem.h @@ -35,8 +35,9 @@ namespace JSC { class SourceProviderCacheItem { WTF_MAKE_FAST_ALLOCATED; public: - SourceProviderCacheItem(int closeBraceLine, int closeBracePos) - : closeBraceLine(closeBraceLine) + SourceProviderCacheItem(unsigned functionStart, unsigned closeBraceLine, unsigned closeBracePos) + : functionStart(functionStart) + , closeBraceLine(closeBraceLine) , closeBracePos(closeBracePos) { } @@ -59,12 +60,16 @@ public: token.m_location.line = closeBraceLine; return token; } + + unsigned functionStart : 31; + bool needsFullActivation : 1; - int closeBraceLine; - int closeBracePos; - bool usesEval; - bool strictMode; - bool needsFullActivation; + unsigned closeBraceLine : 31; + bool usesEval : 1; + + unsigned closeBracePos : 31; + bool strictMode : 1; + Vector<RefPtr<StringImpl> > usedVariables; Vector<RefPtr<StringImpl> > writtenVariables; }; diff --git a/Source/JavaScriptCore/runtime/JSObject.cpp b/Source/JavaScriptCore/runtime/JSObject.cpp index 564093e33..dc73e04b0 100644 --- a/Source/JavaScriptCore/runtime/JSObject.cpp +++ b/Source/JavaScriptCore/runtime/JSObject.cpp @@ -129,13 +129,7 @@ ALWAYS_INLINE void JSObject::copyButterfly(CopyVisitor& visitor, Butterfly* butt size_t count; switch (structure->indexingType()) { - case ALL_UNDECIDED_INDEXING_TYPES: { - currentTarget = 0; - currentSource = 0; - count = 0; - break; - } - + case ALL_UNDECIDED_INDEXING_TYPES: case ALL_CONTIGUOUS_INDEXING_TYPES: case ALL_INT32_INDEXING_TYPES: case ALL_DOUBLE_INDEXING_TYPES: { @@ -190,7 +184,7 @@ ALWAYS_INLINE void JSObject::visitButterfly(SlotVisitor& visitor, Butterfly* but // Mark the properties. visitor.appendValues(butterfly->propertyStorage() - storageSize, storageSize); - visitor.copyLater(butterfly->base(preCapacity, propertyCapacity), capacityInBytes); + visitor.copyLater(this, butterfly->base(preCapacity, propertyCapacity), capacityInBytes); // Mark the array if appropriate. switch (structure->indexingType()) { diff --git a/Source/JavaScriptCore/runtime/JSValue.h b/Source/JavaScriptCore/runtime/JSValue.h index bd9b90466..f6447d0bd 100644 --- a/Source/JavaScriptCore/runtime/JSValue.h +++ b/Source/JavaScriptCore/runtime/JSValue.h @@ -39,458 +39,458 @@ namespace JSC { // values as being missing, so it is useful to have it abbreviated. #define QNaN (std::numeric_limits<double>::quiet_NaN()) - class ExecState; - class JSCell; - class JSGlobalData; - class JSGlobalObject; - class JSObject; - class JSString; - class PropertyName; - class PropertySlot; - class PutPropertySlot; +class ExecState; +class JSCell; +class JSGlobalData; +class JSGlobalObject; +class JSObject; +class JSString; +class PropertyName; +class PropertySlot; +class PutPropertySlot; #if ENABLE(DFG_JIT) - namespace DFG { - class AssemblyHelpers; - class JITCompiler; - class JITCodeGenerator; - class JSValueSource; - class OSRExitCompiler; - class SpeculativeJIT; - } +namespace DFG { +class AssemblyHelpers; +class JITCompiler; +class JITCodeGenerator; +class JSValueSource; +class OSRExitCompiler; +class SpeculativeJIT; +} #endif #if ENABLE(LLINT_C_LOOP) - namespace LLInt { - class CLoop; - } +namespace LLInt { +class CLoop; +} #endif - struct ClassInfo; - struct Instruction; - struct MethodTable; +struct ClassInfo; +struct Instruction; +struct MethodTable; - template <class T> class WriteBarrierBase; +template <class T> class WriteBarrierBase; - enum PreferredPrimitiveType { NoPreference, PreferNumber, PreferString }; +enum PreferredPrimitiveType { NoPreference, PreferNumber, PreferString }; - typedef int64_t EncodedJSValue; +typedef int64_t EncodedJSValue; - union EncodedValueDescriptor { - int64_t asInt64; +union EncodedValueDescriptor { + int64_t asInt64; #if USE(JSVALUE32_64) - double asDouble; + double asDouble; #elif USE(JSVALUE64) - JSCell* ptr; + JSCell* ptr; #endif #if CPU(BIG_ENDIAN) - struct { - int32_t tag; - int32_t payload; - } asBits; + struct { + int32_t tag; + int32_t payload; + } asBits; #else - struct { - int32_t payload; - int32_t tag; - } asBits; + struct { + int32_t payload; + int32_t tag; + } asBits; #endif - }; - - // This implements ToInt32, defined in ECMA-262 9.5. - JS_EXPORT_PRIVATE int32_t toInt32(double); - - // This implements ToUInt32, defined in ECMA-262 9.6. - inline uint32_t toUInt32(double number) - { - // As commented in the spec, the operation of ToInt32 and ToUint32 only differ - // in how the result is interpreted; see NOTEs in sections 9.5 and 9.6. - return toInt32(number); - } - - class JSValue { - friend struct EncodedJSValueHashTraits; - friend class JIT; - friend class JITStubs; - friend class JITStubCall; - friend class JSInterfaceJIT; - friend class SpecializedThunkJIT; +}; + +// This implements ToInt32, defined in ECMA-262 9.5. +JS_EXPORT_PRIVATE int32_t toInt32(double); + +// This implements ToUInt32, defined in ECMA-262 9.6. +inline uint32_t toUInt32(double number) +{ + // As commented in the spec, the operation of ToInt32 and ToUint32 only differ + // in how the result is interpreted; see NOTEs in sections 9.5 and 9.6. + return toInt32(number); +} + +class JSValue { + friend struct EncodedJSValueHashTraits; + friend class JIT; + friend class JITStubs; + friend class JITStubCall; + friend class JSInterfaceJIT; + friend class SpecializedThunkJIT; #if ENABLE(DFG_JIT) - friend class DFG::AssemblyHelpers; - friend class DFG::JITCompiler; - friend class DFG::JITCodeGenerator; - friend class DFG::JSValueSource; - friend class DFG::OSRExitCompiler; - friend class DFG::SpeculativeJIT; + friend class DFG::AssemblyHelpers; + friend class DFG::JITCompiler; + friend class DFG::JITCodeGenerator; + friend class DFG::JSValueSource; + friend class DFG::OSRExitCompiler; + friend class DFG::SpeculativeJIT; #endif #if ENABLE(LLINT_C_LOOP) - friend class LLInt::CLoop; + friend class LLInt::CLoop; #endif - public: +public: #if USE(JSVALUE32_64) - enum { Int32Tag = 0xffffffff }; - enum { BooleanTag = 0xfffffffe }; - enum { NullTag = 0xfffffffd }; - enum { UndefinedTag = 0xfffffffc }; - enum { CellTag = 0xfffffffb }; - enum { EmptyValueTag = 0xfffffffa }; - enum { DeletedValueTag = 0xfffffff9 }; - - enum { LowestTag = DeletedValueTag }; + enum { Int32Tag = 0xffffffff }; + enum { BooleanTag = 0xfffffffe }; + enum { NullTag = 0xfffffffd }; + enum { UndefinedTag = 0xfffffffc }; + enum { CellTag = 0xfffffffb }; + enum { EmptyValueTag = 0xfffffffa }; + enum { DeletedValueTag = 0xfffffff9 }; + + enum { LowestTag = DeletedValueTag }; #endif - static EncodedJSValue encode(JSValue); - static JSValue decode(EncodedJSValue); - - enum JSNullTag { JSNull }; - enum JSUndefinedTag { JSUndefined }; - enum JSTrueTag { JSTrue }; - enum JSFalseTag { JSFalse }; - enum EncodeAsDoubleTag { EncodeAsDouble }; - - JSValue(); - JSValue(JSNullTag); - JSValue(JSUndefinedTag); - JSValue(JSTrueTag); - JSValue(JSFalseTag); - JSValue(JSCell* ptr); - JSValue(const JSCell* ptr); - - // Numbers - JSValue(EncodeAsDoubleTag, double); - explicit JSValue(double); - explicit JSValue(char); - explicit JSValue(unsigned char); - explicit JSValue(short); - explicit JSValue(unsigned short); - explicit JSValue(int); - explicit JSValue(unsigned); - explicit JSValue(long); - explicit JSValue(unsigned long); - explicit JSValue(long long); - explicit JSValue(unsigned long long); - - operator bool() const; - bool operator==(const JSValue& other) const; - bool operator!=(const JSValue& other) const; - - bool isInt32() const; - bool isUInt32() const; - bool isDouble() const; - bool isTrue() const; - bool isFalse() const; - - int32_t asInt32() const; - uint32_t asUInt32() const; - double asDouble() const; - bool asBoolean() const; - double asNumber() const; - - // Querying the type. - bool isEmpty() const; - bool isFunction() const; - bool isUndefined() const; - bool isNull() const; - bool isUndefinedOrNull() const; - bool isBoolean() const; - bool isNumber() const; - bool isString() const; - bool isPrimitive() const; - bool isGetterSetter() const; - bool isObject() const; - bool inherits(const ClassInfo*) const; + static EncodedJSValue encode(JSValue); + static JSValue decode(EncodedJSValue); + + enum JSNullTag { JSNull }; + enum JSUndefinedTag { JSUndefined }; + enum JSTrueTag { JSTrue }; + enum JSFalseTag { JSFalse }; + enum EncodeAsDoubleTag { EncodeAsDouble }; + + JSValue(); + JSValue(JSNullTag); + JSValue(JSUndefinedTag); + JSValue(JSTrueTag); + JSValue(JSFalseTag); + JSValue(JSCell* ptr); + JSValue(const JSCell* ptr); + + // Numbers + JSValue(EncodeAsDoubleTag, double); + explicit JSValue(double); + explicit JSValue(char); + explicit JSValue(unsigned char); + explicit JSValue(short); + explicit JSValue(unsigned short); + explicit JSValue(int); + explicit JSValue(unsigned); + explicit JSValue(long); + explicit JSValue(unsigned long); + explicit JSValue(long long); + explicit JSValue(unsigned long long); + + operator bool() const; + bool operator==(const JSValue& other) const; + bool operator!=(const JSValue& other) const; + + bool isInt32() const; + bool isUInt32() const; + bool isDouble() const; + bool isTrue() const; + bool isFalse() const; + + int32_t asInt32() const; + uint32_t asUInt32() const; + double asDouble() const; + bool asBoolean() const; + double asNumber() const; + + // Querying the type. + bool isEmpty() const; + bool isFunction() const; + bool isUndefined() const; + bool isNull() const; + bool isUndefinedOrNull() const; + bool isBoolean() const; + bool isNumber() const; + bool isString() const; + bool isPrimitive() const; + bool isGetterSetter() const; + bool isObject() const; + bool inherits(const ClassInfo*) const; - // Extracting the value. - bool getString(ExecState*, WTF::String&) const; - WTF::String getString(ExecState*) const; // null string if not a string - JSObject* getObject() const; // 0 if not an object + // Extracting the value. + bool getString(ExecState*, WTF::String&) const; + WTF::String getString(ExecState*) const; // null string if not a string + JSObject* getObject() const; // 0 if not an object - // Extracting integer values. - bool getUInt32(uint32_t&) const; + // Extracting integer values. + bool getUInt32(uint32_t&) const; - // Basic conversions. - JSValue toPrimitive(ExecState*, PreferredPrimitiveType = NoPreference) const; - bool getPrimitiveNumber(ExecState*, double& number, JSValue&); - - bool toBoolean(ExecState*) const; - - // toNumber conversion is expected to be side effect free if an exception has - // been set in the ExecState already. - double toNumber(ExecState*) const; - JSString* toString(ExecState*) const; - WTF::String toWTFString(ExecState*) const; - WTF::String toWTFStringInline(ExecState*) const; - JSObject* toObject(ExecState*) const; - JSObject* toObject(ExecState*, JSGlobalObject*) const; - - // Integer conversions. - JS_EXPORT_PRIVATE double toInteger(ExecState*) const; - double toIntegerPreserveNaN(ExecState*) const; - int32_t toInt32(ExecState*) const; - uint32_t toUInt32(ExecState*) const; - - // Floating point conversions (this is a convenience method for webcore; - // signle precision float is not a representation used in JS or JSC). - float toFloat(ExecState* exec) const { return static_cast<float>(toNumber(exec)); } - - // Object operations, with the toObject operation included. - JSValue get(ExecState*, PropertyName) const; - JSValue get(ExecState*, PropertyName, PropertySlot&) const; - JSValue get(ExecState*, unsigned propertyName) const; - JSValue get(ExecState*, unsigned propertyName, PropertySlot&) const; - void put(ExecState*, PropertyName, JSValue, PutPropertySlot&); - void putToPrimitive(ExecState*, PropertyName, JSValue, PutPropertySlot&); - void putToPrimitiveByIndex(ExecState*, unsigned propertyName, JSValue, bool shouldThrow); - void putByIndex(ExecState*, unsigned propertyName, JSValue, bool shouldThrow); - - JSObject* toThisObject(ExecState*) const; - - static bool equal(ExecState* exec, JSValue v1, JSValue v2); - static bool equalSlowCase(ExecState* exec, JSValue v1, JSValue v2); - static bool equalSlowCaseInline(ExecState* exec, JSValue v1, JSValue v2); - static bool strictEqual(ExecState* exec, JSValue v1, JSValue v2); - static bool strictEqualSlowCase(ExecState* exec, JSValue v1, JSValue v2); - static bool strictEqualSlowCaseInline(ExecState* exec, JSValue v1, JSValue v2); - - bool isCell() const; - JSCell* asCell() const; - JS_EXPORT_PRIVATE bool isValidCallee(); + // Basic conversions. + JSValue toPrimitive(ExecState*, PreferredPrimitiveType = NoPreference) const; + bool getPrimitiveNumber(ExecState*, double& number, JSValue&); + + bool toBoolean(ExecState*) const; + + // toNumber conversion is expected to be side effect free if an exception has + // been set in the ExecState already. + double toNumber(ExecState*) const; + JSString* toString(ExecState*) const; + WTF::String toWTFString(ExecState*) const; + WTF::String toWTFStringInline(ExecState*) const; + JSObject* toObject(ExecState*) const; + JSObject* toObject(ExecState*, JSGlobalObject*) const; + + // Integer conversions. + JS_EXPORT_PRIVATE double toInteger(ExecState*) const; + double toIntegerPreserveNaN(ExecState*) const; + int32_t toInt32(ExecState*) const; + uint32_t toUInt32(ExecState*) const; + + // Floating point conversions (this is a convenience method for webcore; + // signle precision float is not a representation used in JS or JSC). + float toFloat(ExecState* exec) const { return static_cast<float>(toNumber(exec)); } + + // Object operations, with the toObject operation included. + JSValue get(ExecState*, PropertyName) const; + JSValue get(ExecState*, PropertyName, PropertySlot&) const; + JSValue get(ExecState*, unsigned propertyName) const; + JSValue get(ExecState*, unsigned propertyName, PropertySlot&) const; + void put(ExecState*, PropertyName, JSValue, PutPropertySlot&); + void putToPrimitive(ExecState*, PropertyName, JSValue, PutPropertySlot&); + void putToPrimitiveByIndex(ExecState*, unsigned propertyName, JSValue, bool shouldThrow); + void putByIndex(ExecState*, unsigned propertyName, JSValue, bool shouldThrow); + + JSObject* toThisObject(ExecState*) const; + + static bool equal(ExecState* exec, JSValue v1, JSValue v2); + static bool equalSlowCase(ExecState* exec, JSValue v1, JSValue v2); + static bool equalSlowCaseInline(ExecState* exec, JSValue v1, JSValue v2); + static bool strictEqual(ExecState* exec, JSValue v1, JSValue v2); + static bool strictEqualSlowCase(ExecState* exec, JSValue v1, JSValue v2); + static bool strictEqualSlowCaseInline(ExecState* exec, JSValue v1, JSValue v2); + + bool isCell() const; + JSCell* asCell() const; + JS_EXPORT_PRIVATE bool isValidCallee(); - JSValue structureOrUndefined() const; + JSValue structureOrUndefined() const; - JS_EXPORT_PRIVATE char* description() const; + JS_EXPORT_PRIVATE char* description() const; - JS_EXPORT_PRIVATE JSObject* synthesizePrototype(ExecState*) const; + JS_EXPORT_PRIVATE JSObject* synthesizePrototype(ExecState*) const; - private: - template <class T> JSValue(WriteBarrierBase<T>); +private: + template <class T> JSValue(WriteBarrierBase<T>); - enum HashTableDeletedValueTag { HashTableDeletedValue }; - JSValue(HashTableDeletedValueTag); + enum HashTableDeletedValueTag { HashTableDeletedValue }; + JSValue(HashTableDeletedValueTag); - inline const JSValue asValue() const { return *this; } - JS_EXPORT_PRIVATE double toNumberSlowCase(ExecState*) const; - JS_EXPORT_PRIVATE JSString* toStringSlowCase(ExecState*) const; - JS_EXPORT_PRIVATE WTF::String toWTFStringSlowCase(ExecState*) const; - JS_EXPORT_PRIVATE JSObject* toObjectSlowCase(ExecState*, JSGlobalObject*) const; - JS_EXPORT_PRIVATE JSObject* toThisObjectSlowCase(ExecState*) const; + inline const JSValue asValue() const { return *this; } + JS_EXPORT_PRIVATE double toNumberSlowCase(ExecState*) const; + JS_EXPORT_PRIVATE JSString* toStringSlowCase(ExecState*) const; + JS_EXPORT_PRIVATE WTF::String toWTFStringSlowCase(ExecState*) const; + JS_EXPORT_PRIVATE JSObject* toObjectSlowCase(ExecState*, JSGlobalObject*) const; + JS_EXPORT_PRIVATE JSObject* toThisObjectSlowCase(ExecState*) const; #if USE(JSVALUE32_64) - /* - * On 32-bit platforms USE(JSVALUE32_64) should be defined, and we use a NaN-encoded - * form for immediates. - * - * The encoding makes use of unused NaN space in the IEEE754 representation. Any value - * with the top 13 bits set represents a QNaN (with the sign bit set). QNaN values - * can encode a 51-bit payload. Hardware produced and C-library payloads typically - * have a payload of zero. We assume that non-zero payloads are available to encode - * pointer and integer values. Since any 64-bit bit pattern where the top 15 bits are - * all set represents a NaN with a non-zero payload, we can use this space in the NaN - * ranges to encode other values (however there are also other ranges of NaN space that - * could have been selected). - * - * For JSValues that do not contain a double value, the high 32 bits contain the tag - * values listed in the enums below, which all correspond to NaN-space. In the case of - * cell, integer and bool values the lower 32 bits (the 'payload') contain the pointer - * integer or boolean value; in the case of all other tags the payload is 0. - */ - uint32_t tag() const; - int32_t payload() const; + /* + * On 32-bit platforms USE(JSVALUE32_64) should be defined, and we use a NaN-encoded + * form for immediates. + * + * The encoding makes use of unused NaN space in the IEEE754 representation. Any value + * with the top 13 bits set represents a QNaN (with the sign bit set). QNaN values + * can encode a 51-bit payload. Hardware produced and C-library payloads typically + * have a payload of zero. We assume that non-zero payloads are available to encode + * pointer and integer values. Since any 64-bit bit pattern where the top 15 bits are + * all set represents a NaN with a non-zero payload, we can use this space in the NaN + * ranges to encode other values (however there are also other ranges of NaN space that + * could have been selected). + * + * For JSValues that do not contain a double value, the high 32 bits contain the tag + * values listed in the enums below, which all correspond to NaN-space. In the case of + * cell, integer and bool values the lower 32 bits (the 'payload') contain the pointer + * integer or boolean value; in the case of all other tags the payload is 0. + */ + uint32_t tag() const; + int32_t payload() const; #if ENABLE(LLINT_C_LOOP) - // This should only be used by the LLInt C Loop interpreter who needs - // synthesize JSValue from its "register"s holding tag and payload - // values. - explicit JSValue(int32_t tag, int32_t payload); + // This should only be used by the LLInt C Loop interpreter who needs + // synthesize JSValue from its "register"s holding tag and payload + // values. + explicit JSValue(int32_t tag, int32_t payload); #endif #elif USE(JSVALUE64) - /* - * On 64-bit platforms USE(JSVALUE64) should be defined, and we use a NaN-encoded - * form for immediates. - * - * The encoding makes use of unused NaN space in the IEEE754 representation. Any value - * with the top 13 bits set represents a QNaN (with the sign bit set). QNaN values - * can encode a 51-bit payload. Hardware produced and C-library payloads typically - * have a payload of zero. We assume that non-zero payloads are available to encode - * pointer and integer values. Since any 64-bit bit pattern where the top 15 bits are - * all set represents a NaN with a non-zero payload, we can use this space in the NaN - * ranges to encode other values (however there are also other ranges of NaN space that - * could have been selected). - * - * This range of NaN space is represented by 64-bit numbers begining with the 16-bit - * hex patterns 0xFFFE and 0xFFFF - we rely on the fact that no valid double-precision - * numbers will begin fall in these ranges. - * - * The top 16-bits denote the type of the encoded JSValue: - * - * Pointer { 0000:PPPP:PPPP:PPPP - * / 0001:****:****:**** - * Double { ... - * \ FFFE:****:****:**** - * Integer { FFFF:0000:IIII:IIII - * - * The scheme we have implemented encodes double precision values by performing a - * 64-bit integer addition of the value 2^48 to the number. After this manipulation - * no encoded double-precision value will begin with the pattern 0x0000 or 0xFFFF. - * Values must be decoded by reversing this operation before subsequent floating point - * operations my be peformed. - * - * 32-bit signed integers are marked with the 16-bit tag 0xFFFF. - * - * The tag 0x0000 denotes a pointer, or another form of tagged immediate. Boolean, - * null and undefined values are represented by specific, invalid pointer values: - * - * False: 0x06 - * True: 0x07 - * Undefined: 0x0a - * Null: 0x02 - * - * These values have the following properties: - * - Bit 1 (TagBitTypeOther) is set for all four values, allowing real pointers to be - * quickly distinguished from all immediate values, including these invalid pointers. - * - With bit 3 is masked out (TagBitUndefined) Undefined and Null share the - * same value, allowing null & undefined to be quickly detected. - * - * No valid JSValue will have the bit pattern 0x0, this is used to represent array - * holes, and as a C++ 'no value' result (e.g. JSValue() has an internal value of 0). - */ - - // These values are #defines since using static const integers here is a ~1% regression! - - // This value is 2^48, used to encode doubles such that the encoded value will begin - // with a 16-bit pattern within the range 0x0001..0xFFFE. - #define DoubleEncodeOffset 0x1000000000000ll - // If all bits in the mask are set, this indicates an integer number, - // if any but not all are set this value is a double precision number. - #define TagTypeNumber 0xffff000000000000ll - - // All non-numeric (bool, null, undefined) immediates have bit 2 set. - #define TagBitTypeOther 0x2ll - #define TagBitBool 0x4ll - #define TagBitUndefined 0x8ll - // Combined integer value for non-numeric immediates. - #define ValueFalse (TagBitTypeOther | TagBitBool | false) - #define ValueTrue (TagBitTypeOther | TagBitBool | true) - #define ValueUndefined (TagBitTypeOther | TagBitUndefined) - #define ValueNull (TagBitTypeOther) - - // TagMask is used to check for all types of immediate values (either number or 'other'). - #define TagMask (TagTypeNumber | TagBitTypeOther) - - // These special values are never visible to JavaScript code; Empty is used to represent - // Array holes, and for uninitialized JSValues. Deleted is used in hash table code. - // These values would map to cell types in the JSValue encoding, but not valid GC cell - // pointer should have either of these values (Empty is null, deleted is at an invalid - // alignment for a GC cell, and in the zero page). - #define ValueEmpty 0x0ll - #define ValueDeleted 0x4ll + /* + * On 64-bit platforms USE(JSVALUE64) should be defined, and we use a NaN-encoded + * form for immediates. + * + * The encoding makes use of unused NaN space in the IEEE754 representation. Any value + * with the top 13 bits set represents a QNaN (with the sign bit set). QNaN values + * can encode a 51-bit payload. Hardware produced and C-library payloads typically + * have a payload of zero. We assume that non-zero payloads are available to encode + * pointer and integer values. Since any 64-bit bit pattern where the top 15 bits are + * all set represents a NaN with a non-zero payload, we can use this space in the NaN + * ranges to encode other values (however there are also other ranges of NaN space that + * could have been selected). + * + * This range of NaN space is represented by 64-bit numbers begining with the 16-bit + * hex patterns 0xFFFE and 0xFFFF - we rely on the fact that no valid double-precision + * numbers will begin fall in these ranges. + * + * The top 16-bits denote the type of the encoded JSValue: + * + * Pointer { 0000:PPPP:PPPP:PPPP + * / 0001:****:****:**** + * Double { ... + * \ FFFE:****:****:**** + * Integer { FFFF:0000:IIII:IIII + * + * The scheme we have implemented encodes double precision values by performing a + * 64-bit integer addition of the value 2^48 to the number. After this manipulation + * no encoded double-precision value will begin with the pattern 0x0000 or 0xFFFF. + * Values must be decoded by reversing this operation before subsequent floating point + * operations my be peformed. + * + * 32-bit signed integers are marked with the 16-bit tag 0xFFFF. + * + * The tag 0x0000 denotes a pointer, or another form of tagged immediate. Boolean, + * null and undefined values are represented by specific, invalid pointer values: + * + * False: 0x06 + * True: 0x07 + * Undefined: 0x0a + * Null: 0x02 + * + * These values have the following properties: + * - Bit 1 (TagBitTypeOther) is set for all four values, allowing real pointers to be + * quickly distinguished from all immediate values, including these invalid pointers. + * - With bit 3 is masked out (TagBitUndefined) Undefined and Null share the + * same value, allowing null & undefined to be quickly detected. + * + * No valid JSValue will have the bit pattern 0x0, this is used to represent array + * holes, and as a C++ 'no value' result (e.g. JSValue() has an internal value of 0). + */ + + // These values are #defines since using static const integers here is a ~1% regression! + + // This value is 2^48, used to encode doubles such that the encoded value will begin + // with a 16-bit pattern within the range 0x0001..0xFFFE. + #define DoubleEncodeOffset 0x1000000000000ll + // If all bits in the mask are set, this indicates an integer number, + // if any but not all are set this value is a double precision number. + #define TagTypeNumber 0xffff000000000000ll + + // All non-numeric (bool, null, undefined) immediates have bit 2 set. + #define TagBitTypeOther 0x2ll + #define TagBitBool 0x4ll + #define TagBitUndefined 0x8ll + // Combined integer value for non-numeric immediates. + #define ValueFalse (TagBitTypeOther | TagBitBool | false) + #define ValueTrue (TagBitTypeOther | TagBitBool | true) + #define ValueUndefined (TagBitTypeOther | TagBitUndefined) + #define ValueNull (TagBitTypeOther) + + // TagMask is used to check for all types of immediate values (either number or 'other'). + #define TagMask (TagTypeNumber | TagBitTypeOther) + + // These special values are never visible to JavaScript code; Empty is used to represent + // Array holes, and for uninitialized JSValues. Deleted is used in hash table code. + // These values would map to cell types in the JSValue encoding, but not valid GC cell + // pointer should have either of these values (Empty is null, deleted is at an invalid + // alignment for a GC cell, and in the zero page). + #define ValueEmpty 0x0ll + #define ValueDeleted 0x4ll #endif - EncodedValueDescriptor u; - }; + EncodedValueDescriptor u; +}; - typedef IntHash<EncodedJSValue> EncodedJSValueHash; +typedef IntHash<EncodedJSValue> EncodedJSValueHash; #if USE(JSVALUE32_64) - struct EncodedJSValueHashTraits : HashTraits<EncodedJSValue> { - static const bool emptyValueIsZero = false; - static EncodedJSValue emptyValue() { return JSValue::encode(JSValue()); } - static void constructDeletedValue(EncodedJSValue& slot) { slot = JSValue::encode(JSValue(JSValue::HashTableDeletedValue)); } - static bool isDeletedValue(EncodedJSValue value) { return value == JSValue::encode(JSValue(JSValue::HashTableDeletedValue)); } - }; +struct EncodedJSValueHashTraits : HashTraits<EncodedJSValue> { + static const bool emptyValueIsZero = false; + static EncodedJSValue emptyValue() { return JSValue::encode(JSValue()); } + static void constructDeletedValue(EncodedJSValue& slot) { slot = JSValue::encode(JSValue(JSValue::HashTableDeletedValue)); } + static bool isDeletedValue(EncodedJSValue value) { return value == JSValue::encode(JSValue(JSValue::HashTableDeletedValue)); } +}; #else - struct EncodedJSValueHashTraits : HashTraits<EncodedJSValue> { - static void constructDeletedValue(EncodedJSValue& slot) { slot = JSValue::encode(JSValue(JSValue::HashTableDeletedValue)); } - static bool isDeletedValue(EncodedJSValue value) { return value == JSValue::encode(JSValue(JSValue::HashTableDeletedValue)); } - }; +struct EncodedJSValueHashTraits : HashTraits<EncodedJSValue> { + static void constructDeletedValue(EncodedJSValue& slot) { slot = JSValue::encode(JSValue(JSValue::HashTableDeletedValue)); } + static bool isDeletedValue(EncodedJSValue value) { return value == JSValue::encode(JSValue(JSValue::HashTableDeletedValue)); } +}; #endif - typedef HashMap<EncodedJSValue, unsigned, EncodedJSValueHash, EncodedJSValueHashTraits> JSValueMap; - - // Stand-alone helper functions. - inline JSValue jsNull() - { - return JSValue(JSValue::JSNull); - } - - inline JSValue jsUndefined() - { - return JSValue(JSValue::JSUndefined); - } - - inline JSValue jsBoolean(bool b) - { - return b ? JSValue(JSValue::JSTrue) : JSValue(JSValue::JSFalse); - } - - ALWAYS_INLINE JSValue jsDoubleNumber(double d) - { - ASSERT(JSValue(JSValue::EncodeAsDouble, d).isNumber()); - return JSValue(JSValue::EncodeAsDouble, d); - } - - ALWAYS_INLINE JSValue jsNumber(double d) - { - ASSERT(JSValue(d).isNumber()); - return JSValue(d); - } - - ALWAYS_INLINE JSValue jsNumber(char i) - { - return JSValue(i); - } - - ALWAYS_INLINE JSValue jsNumber(unsigned char i) - { - return JSValue(i); - } - - ALWAYS_INLINE JSValue jsNumber(short i) - { - return JSValue(i); - } - - ALWAYS_INLINE JSValue jsNumber(unsigned short i) - { - return JSValue(i); - } - - ALWAYS_INLINE JSValue jsNumber(int i) - { - return JSValue(i); - } - - ALWAYS_INLINE JSValue jsNumber(unsigned i) - { - return JSValue(i); - } - - ALWAYS_INLINE JSValue jsNumber(long i) - { - return JSValue(i); - } - - ALWAYS_INLINE JSValue jsNumber(unsigned long i) - { - return JSValue(i); - } - - ALWAYS_INLINE JSValue jsNumber(long long i) - { - return JSValue(i); - } - - ALWAYS_INLINE JSValue jsNumber(unsigned long long i) - { - return JSValue(i); - } - - inline bool operator==(const JSValue a, const JSCell* b) { return a == JSValue(b); } - inline bool operator==(const JSCell* a, const JSValue b) { return JSValue(a) == b; } - - inline bool operator!=(const JSValue a, const JSCell* b) { return a != JSValue(b); } - inline bool operator!=(const JSCell* a, const JSValue b) { return JSValue(a) != b; } +typedef HashMap<EncodedJSValue, unsigned, EncodedJSValueHash, EncodedJSValueHashTraits> JSValueMap; + +// Stand-alone helper functions. +inline JSValue jsNull() +{ + return JSValue(JSValue::JSNull); +} + +inline JSValue jsUndefined() +{ + return JSValue(JSValue::JSUndefined); +} + +inline JSValue jsBoolean(bool b) +{ + return b ? JSValue(JSValue::JSTrue) : JSValue(JSValue::JSFalse); +} + +ALWAYS_INLINE JSValue jsDoubleNumber(double d) +{ + ASSERT(JSValue(JSValue::EncodeAsDouble, d).isNumber()); + return JSValue(JSValue::EncodeAsDouble, d); +} + +ALWAYS_INLINE JSValue jsNumber(double d) +{ + ASSERT(JSValue(d).isNumber()); + return JSValue(d); +} + +ALWAYS_INLINE JSValue jsNumber(char i) +{ + return JSValue(i); +} + +ALWAYS_INLINE JSValue jsNumber(unsigned char i) +{ + return JSValue(i); +} + +ALWAYS_INLINE JSValue jsNumber(short i) +{ + return JSValue(i); +} + +ALWAYS_INLINE JSValue jsNumber(unsigned short i) +{ + return JSValue(i); +} + +ALWAYS_INLINE JSValue jsNumber(int i) +{ + return JSValue(i); +} + +ALWAYS_INLINE JSValue jsNumber(unsigned i) +{ + return JSValue(i); +} + +ALWAYS_INLINE JSValue jsNumber(long i) +{ + return JSValue(i); +} + +ALWAYS_INLINE JSValue jsNumber(unsigned long i) +{ + return JSValue(i); +} + +ALWAYS_INLINE JSValue jsNumber(long long i) +{ + return JSValue(i); +} + +ALWAYS_INLINE JSValue jsNumber(unsigned long long i) +{ + return JSValue(i); +} + +inline bool operator==(const JSValue a, const JSCell* b) { return a == JSValue(b); } +inline bool operator==(const JSCell* a, const JSValue b) { return JSValue(a) == b; } + +inline bool operator!=(const JSValue a, const JSCell* b) { return a != JSValue(b); } +inline bool operator!=(const JSCell* a, const JSValue b) { return JSValue(a) != b; } } // namespace JSC diff --git a/Source/JavaScriptCore/runtime/Options.h b/Source/JavaScriptCore/runtime/Options.h index 99a5f85a2..5ad30bde3 100644 --- a/Source/JavaScriptCore/runtime/Options.h +++ b/Source/JavaScriptCore/runtime/Options.h @@ -68,9 +68,12 @@ namespace JSC { \ v(bool, forceDFGCodeBlockLiveness, false) \ \ + v(bool, dumpGeneratedBytecodes, false) \ + \ /* showDisassembly implies showDFGDisassembly. */ \ v(bool, showDisassembly, false) \ v(bool, showDFGDisassembly, false) \ + v(bool, showAllDFGNodes, false) \ \ v(unsigned, maximumOptimizationCandidateInstructionCount, 10000) \ \ diff --git a/Source/JavaScriptCore/runtime/StringPrototype.cpp b/Source/JavaScriptCore/runtime/StringPrototype.cpp index 93009d806..25f989776 100644 --- a/Source/JavaScriptCore/runtime/StringPrototype.cpp +++ b/Source/JavaScriptCore/runtime/StringPrototype.cpp @@ -338,24 +338,26 @@ static ALWAYS_INLINE JSValue jsSpliceSubstringsWithSeparators(ExecState* exec, J return jsString(exec, StringImpl::create(source.impl(), std::max(0, position), std::min(sourceSize, length))); } - int totalLength = 0; - bool allSeperators8Bit = true; + Checked<int, RecordOverflow> totalLength = 0; + bool allSeparators8Bit = true; for (int i = 0; i < rangeCount; i++) totalLength += substringRanges[i].length; for (int i = 0; i < separatorCount; i++) { totalLength += separators[i].length(); if (separators[i].length() && !separators[i].is8Bit()) - allSeperators8Bit = false; + allSeparators8Bit = false; } + if (totalLength.hasOverflowed()) + return throwOutOfMemoryError(exec); if (!totalLength) return jsEmptyString(exec); - if (source.is8Bit() && allSeperators8Bit) { + if (source.is8Bit() && allSeparators8Bit) { LChar* buffer; const LChar* sourceData = source.characters8(); - RefPtr<StringImpl> impl = StringImpl::tryCreateUninitialized(totalLength, buffer); + RefPtr<StringImpl> impl = StringImpl::tryCreateUninitialized(totalLength.unsafeGet(), buffer); if (!impl) return throwOutOfMemoryError(exec); @@ -380,7 +382,7 @@ static ALWAYS_INLINE JSValue jsSpliceSubstringsWithSeparators(ExecState* exec, J } UChar* buffer; - RefPtr<StringImpl> impl = StringImpl::tryCreateUninitialized(totalLength, buffer); + RefPtr<StringImpl> impl = StringImpl::tryCreateUninitialized(totalLength.unsafeGet(), buffer); if (!impl) return throwOutOfMemoryError(exec); diff --git a/Source/Platform/ChangeLog b/Source/Platform/ChangeLog index 7e7e10da2..76ba46c00 100644 --- a/Source/Platform/ChangeLog +++ b/Source/Platform/ChangeLog @@ -1,3 +1,72 @@ +2012-11-28 Tommy Widenflycht <tommyw@google.com> + + Add basic implementation for MediaStreamAudioDestinationNode + https://bugs.webkit.org/show_bug.cgi?id=101815 + + Reviewed by Chris Rogers. + + Adds the consumer interface and related functionality to WebMediaStreamSource. + + * chromium/public/WebAudioDestinationConsumer.h: Added. + (WebKit): + (WebAudioDestinationConsumer): + (WebKit::WebAudioDestinationConsumer::~WebAudioDestinationConsumer): + * chromium/public/WebMediaStreamSource.h: + (WebKit): + (WebMediaStreamSource): + +2012-11-27 Eberhard Graether <egraether@google.com> + + [chromium] Add WebLayerTreeViewClient API to request font atlas + https://bugs.webkit.org/show_bug.cgi?id=102958 + + Reviewed by James Robinson. + + This change makes the font atlas creation accessible to the WebLayerTreeView. + + * chromium/public/WebLayerTreeViewClient.h: + (WebKit): + (WebLayerTreeViewClient): + (WebKit::WebLayerTreeViewClient::createFontAtlas): + +2012-11-27 Eberhard Graether <egraether@google.com> + + Plumbing showPaintRects out of InspectorPageAgent to use a different drawing implementation if available. + https://bugs.webkit.org/show_bug.cgi?id=102452 + + Reviewed by Pavel Feldman. + + This change makes the showPaintRects setting in the Web Inspector's settings notify InspectorClient + when changed. And the default paint rects drawing is not used if an alternative is available. + This allows Chromium to draw the paint rects in the compositor's HUDLayer. + + * chromium/public/WebLayerTreeView.h: + (WebLayerTreeView): + (WebKit::WebLayerTreeView::setShowPaintRects): + +2012-11-27 Keishi Hattori <keishi@webkit.org> + + Add WebLocalizedString for validation type badinput + https://bugs.webkit.org/show_bug.cgi?id=103381 + + Reviewed by Kent Tamura. + + Adding WebLocalizedString enums for validation type badinput text. + + * chromium/public/WebLocalizedString.h: + +2012-11-26 James Robinson <jamesr@chromium.org> + + [chromium] Remove deprecated and unused WebGraphicsContext3D compositor binding calls + https://bugs.webkit.org/show_bug.cgi?id=103322 + + Reviewed by Adam Barth. + + These have been uncalled for a while. + + * chromium/public/WebLayerTreeViewClient.h: + (WebLayerTreeViewClient): + 2012-11-23 Sami Kyostila <skyostil@chromium.org> [chromium] Remove WebScreenInfo.{horizontal,vertical}DPI diff --git a/Source/WebCore/platform/PlatformGestureCurveTarget.h b/Source/Platform/chromium/public/WebAudioDestinationConsumer.h index b28b292c1..ec1e57336 100644 --- a/Source/WebCore/platform/PlatformGestureCurveTarget.h +++ b/Source/Platform/chromium/public/WebAudioDestinationConsumer.h @@ -22,22 +22,22 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef PlatformGestureCurveTarget_h -#define PlatformGestureCurveTarget_h +#ifndef WebAudioDestinationConsumer_h +#define WebAudioDestinationConsumer_h -namespace WebCore { +#include "WebVector.h" -class IntPoint; +namespace WebKit { -class PlatformGestureCurveTarget { +class WebAudioDestinationConsumer { public: - virtual void scrollBy(const IntPoint&) = 0; - // FIXME: add interfaces for scroll(), etc. + virtual ~WebAudioDestinationConsumer() { } -protected: - virtual ~PlatformGestureCurveTarget() { } + // The size of the vector is the number of audio channels, and numberOfFrames is the + // number of audio frames in the (possibly multi-channel) buffer in a planar format. + virtual void consumeAudio(const WebVector<const float*>&, size_t numberOfFrames) = 0; }; -} // namespace WebCore +} // namespace WebKit -#endif +#endif // WebAudioDestinationConsumer_h diff --git a/Source/Platform/chromium/public/WebLayerTreeView.h b/Source/Platform/chromium/public/WebLayerTreeView.h index 7c3b11395..38b6449aa 100644 --- a/Source/Platform/chromium/public/WebLayerTreeView.h +++ b/Source/Platform/chromium/public/WebLayerTreeView.h @@ -182,6 +182,9 @@ public: // Toggles the FPS counter in the HUD layer virtual void setShowFPSCounter(bool) { } + // Toggles the paint rects in the HUD layer + virtual void setShowPaintRects(bool) { } + // Provides a font atlas to use for debug visualizations. The atlas must be a bitmap containing glyph data, a table of // ASCII character values to a subrectangle of the atlas representing the corresponding glyph, and the glyph height. virtual void setFontAtlas(WebRect asciiToRectTable[128], const SkBitmap&, int fontHeight) { } diff --git a/Source/Platform/chromium/public/WebLayerTreeViewClient.h b/Source/Platform/chromium/public/WebLayerTreeViewClient.h index 5b9929f0e..2ca6b0a51 100644 --- a/Source/Platform/chromium/public/WebLayerTreeViewClient.h +++ b/Source/Platform/chromium/public/WebLayerTreeViewClient.h @@ -26,11 +26,13 @@ #ifndef WebLayerTreeViewClient_h #define WebLayerTreeViewClient_h +class SkBitmap; + namespace WebKit { class WebCompositorOutputSurface; -class WebGraphicsContext3D; class WebInputHandler; class WebThread; +struct WebRect; struct WebSize; class WebLayerTreeViewClient { @@ -57,15 +59,6 @@ public: // compositor thread through the WebCompositor interface. virtual void applyScrollAndScale(const WebSize& scrollDelta, float scaleFactor) = 0; - // DEPRECATED: Creates a 3D context suitable for the compositing. This may be called - // more than once if the context gets lost. This will be removed once - // downstream dependencies have been removed. - virtual WebGraphicsContext3D* createContext3D() { return 0; } - - // DEPRECATED: Signals a successful rebinding of the 3D context (e.g. after a lost - // context event). - virtual void didRebindGraphicsContext(bool) { return; } - // Creates the output surface. This may be called more than once // if the context gets lost. virtual WebCompositorOutputSurface* createOutputSurface() { return 0; } @@ -100,6 +93,11 @@ public: // internally schedule a compositing pass when needed. virtual void scheduleComposite() = 0; + // Creates a font atlas to use for debug visualizations. The atlas is a bitmap + // containing glyph data, a table of ASCII character values to a subrectangle + // of the atlas representing the corresponding glyph, and the glyph height. + virtual void createFontAtlas(SkBitmap&, WebRect asciiToRectTable[128], int& fontHeight) { } + protected: virtual ~WebLayerTreeViewClient() { } }; diff --git a/Source/Platform/chromium/public/WebLocalizedString.h b/Source/Platform/chromium/public/WebLocalizedString.h index 0717cd448..854e71f4e 100644 --- a/Source/Platform/chromium/public/WebLocalizedString.h +++ b/Source/Platform/chromium/public/WebLocalizedString.h @@ -86,6 +86,8 @@ struct WebLocalizedString { SubmitButtonDefaultLabel, ThisMonthButtonLabel, ThisWeekButtonLabel, + ValidationBadInputForNumber, + ValidationBadInputForDateTime, ValidationPatternMismatch, ValidationRangeOverflow, ValidationRangeUnderflow, diff --git a/Source/Platform/chromium/public/WebMediaStreamSource.h b/Source/Platform/chromium/public/WebMediaStreamSource.h index 3a972f1d8..cff9fce20 100644 --- a/Source/Platform/chromium/public/WebMediaStreamSource.h +++ b/Source/Platform/chromium/public/WebMediaStreamSource.h @@ -34,13 +34,14 @@ #include "WebCommon.h" #include "WebNonCopyable.h" #include "WebPrivatePtr.h" +#include "WebVector.h" namespace WebCore { class MediaStreamSource; } namespace WebKit { - +class WebAudioDestinationConsumer; class WebString; class WebMediaStreamSource { @@ -91,6 +92,13 @@ public: WEBKIT_EXPORT ExtraData* extraData() const; WEBKIT_EXPORT void setExtraData(ExtraData*); + // Only used if if this is a WebAudio source. + // The WebAudioDestinationConsumer is not owned, and has to be disposed of separately + // after calling removeAudioConsumer. + WEBKIT_EXPORT bool requiresAudioConsumer() const; + WEBKIT_EXPORT void addAudioConsumer(WebAudioDestinationConsumer*); + WEBKIT_EXPORT bool removeAudioConsumer(WebAudioDestinationConsumer*); + #if WEBKIT_IMPLEMENTATION WebMediaStreamSource(const WTF::PassRefPtr<WebCore::MediaStreamSource>&); WebMediaStreamSource& operator=(WebCore::MediaStreamSource*); diff --git a/Source/WTF/ChangeLog b/Source/WTF/ChangeLog index 5dd0e9b82..380ee628b 100644 --- a/Source/WTF/ChangeLog +++ b/Source/WTF/ChangeLog @@ -1,3 +1,181 @@ +2012-11-28 Filip Pizlo <fpizlo@apple.com> + + SpeculatedType dumping should not use the static char buffer[thingy] idiom + https://bugs.webkit.org/show_bug.cgi?id=103584 + + Reviewed by Michael Saboff. + + Added a StringPrintStream, and made it easy to create dumpers for typedefs to primitives. + + * GNUmakefile.list.am: + * WTF.gypi: + * WTF.pro: + * WTF.vcproj/WTF.vcproj: + * WTF.xcodeproj/project.pbxproj: + * wtf/CMakeLists.txt: + * wtf/PrintStream.cpp: + (WTF::dumpCharacter): + * wtf/PrintStream.h: + (WTF::printInternal): + * wtf/StringPrintStream.cpp: Added. + (WTF::StringPrintStream::StringPrintStream): + (WTF::StringPrintStream::~StringPrintStream): + (WTF::StringPrintStream::vprintf): + (WTF::StringPrintStream::toCString): + (WTF::StringPrintStream::increaseSize): + * wtf/StringPrintStream.h: Added. + (StringPrintStream): + (WTF::toCString): + +2012-11-28 Michael Saboff <msaboff@apple.com> + + Update String Stats for recent dataLog changes and add summary + https://bugs.webkit.org/show_bug.cgi?id=103583 + + Reviewed by Filip Pizlo. + + Updated calls to dataLog() to dataLogF() as a results of r135469. + Added total savings from 8 bit strings in bytes and as a percentage. + + * wtf/text/StringImpl.cpp: + (WTF::StringStats::printStats): + +2012-11-28 Roger Fong <roger_fong@apple.com> + + Make DataLog work/compile properly on Windows. + https://bugs.webkit.org/show_bug.cgi?id=103544 + + Reviewed by Filip Pizlo. + + * wtf/DataLog.cpp: + (WTF::initializeLogFileOnce): + +2012-11-28 Filip Pizlo <fpizlo@apple.com> + + It should be possible to say dataLog("count = ", count, "\n") instead of dataLogF("count = %d\n", count) + https://bugs.webkit.org/show_bug.cgi?id=103009 + + Reviewed by Michael Saboff. + + Added the ability to use out.print(...) and dataLog(...) variadically and with + WTF::printInternal(PrintStream&, const T&) overloads for any type T that you want + to be able to pass as an argument to out.print() or dataLog(). Also added one + example class for doing this: RawPointer, which can be used to force a pointer + to be printed as "%p" rather than matching any overloads that you might want to + introduce. + + * GNUmakefile.list.am: + * WTF.gypi: + * WTF.pro: + * WTF.vcproj/WTF.vcproj: + * WTF.xcodeproj/project.pbxproj: + * wtf/CMakeLists.txt: + * wtf/DataLog.h: + (WTF): + (WTF::dataLog): + * wtf/PrintStream.cpp: + (WTF::printInternal): + (WTF): + * wtf/PrintStream.h: + (PrintStream): + (WTF::PrintStream::print): + (WTF): + * wtf/RawPointer.h: Added. + (WTF): + (RawPointer): + (WTF::RawPointer::RawPointer): + (WTF::RawPointer::value): + +2012-11-27 Filip Pizlo <fpizlo@apple.com> + + Convert some remaining uses of FILE* to PrintStream&. + + Rubber stamped by Mark Hahnenberg. + + * wtf/BitVector.cpp: + (WTF::BitVector::dump): + * wtf/BitVector.h: + (BitVector): + +2012-11-27 Pratik Solanki <psolanki@apple.com> + + objc/objc-runtime.h does not exist on all PLATFORM(MAC) + https://bugs.webkit.org/show_bug.cgi?id=101780 + + Reviewed by Brent Fulgham. + + Clean up header includes so we don't include objc/objc-runtime.h. + + * wtf/Functional.h: + * wtf/ObjcRuntimeExtras.h: Include objc/message.h here so we don't rely on proper ordering + of includes in files that include this header. + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135828. + http://trac.webkit.org/changeset/135828 + https://bugs.webkit.org/show_bug.cgi?id=103405 + + [Chromium] Multiple ASAN errors after a WebKit roll due to + mismatched malloc/delete (not free) resulting from + StringImpl::deref() (Requested by apavlov on #webkit). + + * wtf/FastAllocBase.h: + * wtf/Platform.h: + +2012-11-26 Adam Barth <abarth@webkit.org> + + [Chromium] fastMalloc has an extra branch on Windows + https://bugs.webkit.org/show_bug.cgi?id=103027 + + Reviewed by Eric Seidel. + + There's no need to override the new/delete operators on non-Mac + platform because: + + 1) We use the system malloc anyway. + 2) We've modified the system malloc to crash in out-of-memory conditions. + + This patch removes a branch (and a call) from malloc, which will + hopefully improve performance. I haven't measured the performance + characteristics of this patch, but I will look at the graphs closely + when landing. + + * wtf/FastAllocBase.h: + * wtf/Platform.h: + +2012-11-26 Filip Pizlo <fpizlo@apple.com> + + DataLog to a file should work if there are multiple processes using WTF + https://bugs.webkit.org/show_bug.cgi?id=103323 + + Reviewed by Mark Hahnenberg. + + Whereas before DataLog would open a file with the name you specified, now it'll open a file with the + name plus the PID appended to it. So if you are dealing with multiple processes running with DataLog + to a file enabled, you'll get multiple separate log files. + + * wtf/DataLog.cpp: + (WTF::initializeLogFileOnce): + +2012-11-26 Zeno Albisser <zeno@webkit.org> + + [Qt] Fix the LLInt build on Mac + https://bugs.webkit.org/show_bug.cgi?id=97587 + + Reviewed by Simon Hausmann. + + * wtf/InlineASM.h: + Use OS(DARWIN) instead of PLATFORM(MAC), + in order to allow Qt to use the same code. + * wtf/Platform.h: + +2012-11-26 Patrick Gansterer <paroga@webkit.org> + + Build fix for WinCE after r135640. + + * wtf/DataLog.cpp: + 2012-11-24 Adam Barth <abarth@webkit.org> Chromium should use TCMalloc on Mac to go fast diff --git a/Source/WTF/GNUmakefile.list.am b/Source/WTF/GNUmakefile.list.am index a9337b789..88cce1398 100644 --- a/Source/WTF/GNUmakefile.list.am +++ b/Source/WTF/GNUmakefile.list.am @@ -135,6 +135,7 @@ wtf_sources += \ Source/WTF/wtf/RandomNumber.cpp \ Source/WTF/wtf/RandomNumber.h \ Source/WTF/wtf/RandomNumberSeed.h \ + Source/WTF/wtf/RawPointer.h\ Source/WTF/wtf/RedBlackTree.h \ Source/WTF/wtf/RefCounted.h \ Source/WTF/wtf/RefCountedArray.h \ @@ -158,6 +159,8 @@ wtf_sources += \ Source/WTF/wtf/StdLibExtras.h \ Source/WTF/wtf/StreamBuffer.h \ Source/WTF/wtf/StringExtras.h \ + Source/WTF/wtf/StringPrintStream.cpp \ + Source/WTF/wtf/StringPrintStream.h \ Source/WTF/wtf/StringHasher.h \ Source/WTF/wtf/TCPackedCache.h \ Source/WTF/wtf/TCPageMap.h \ diff --git a/Source/WTF/WTF.gypi b/Source/WTF/WTF.gypi index 34b7f4b85..df80c063c 100644 --- a/Source/WTF/WTF.gypi +++ b/Source/WTF/WTF.gypi @@ -85,6 +85,7 @@ 'wtf/PossiblyNull.h', 'wtf/PrintStream.h', 'wtf/RandomNumber.h', + 'wtf/RawPointer.h', 'wtf/RefCounted.h', 'wtf/RefCountedLeakCounter.h', 'wtf/RefPtr.h', @@ -98,6 +99,7 @@ 'wtf/StdLibExtras.h', 'wtf/StringExtras.h', 'wtf/StringHasher.h', + 'wtf/StringPrintStream.h', 'wtf/TemporaryChange.h', 'wtf/ThreadRestrictionVerifier.h', 'wtf/ThreadSafeRefCounted.h', @@ -199,6 +201,7 @@ 'wtf/SizeLimits.cpp', 'wtf/StackBounds.cpp', 'wtf/StringExtras.cpp', + 'wtf/StringPrintStream.cpp', 'wtf/TCPackedCache.h', 'wtf/TCPageMap.h', 'wtf/TCSpinLock.h', diff --git a/Source/WTF/WTF.pro b/Source/WTF/WTF.pro index 90286c20b..366194bbd 100644 --- a/Source/WTF/WTF.pro +++ b/Source/WTF/WTF.pro @@ -131,6 +131,7 @@ HEADERS += \ PrintStream.h \ RandomNumber.h \ RandomNumberSeed.h \ + RawPointer.h \ RedBlackTree.h \ RefCounted.h \ RefCountedLeakCounter.h \ @@ -145,6 +146,7 @@ HEADERS += \ StdLibExtras.h \ StringExtras.h \ StringHasher.h \ + StringPrintStream.h \ TCPackedCache.h \ TCSpinLock.h \ TCSystemAlloc.h \ @@ -234,6 +236,7 @@ SOURCES += \ RefCountedLeakCounter.cpp \ SHA1.cpp \ StackBounds.cpp \ + StringPrintStream.cpp \ TCSystemAlloc.cpp \ Threading.cpp \ TypeTraits.cpp \ diff --git a/Source/WTF/WTF.vcproj/WTF.vcproj b/Source/WTF/WTF.vcproj/WTF.vcproj index 73024bd15..3ba017d0d 100644 --- a/Source/WTF/WTF.vcproj/WTF.vcproj +++ b/Source/WTF/WTF.vcproj/WTF.vcproj @@ -1125,6 +1125,10 @@ >
</File>
<File
+ RelativePath="..\wtf\RawPointer.h"
+ >
+ </File>
+ <File
RelativePath="..\wtf\RedBlackTree.h"
>
</File>
@@ -1209,6 +1213,14 @@ >
</File>
<File
+ RelativePath="..\wtf\StringPrintStream.cpp"
+ >
+ </File>
+ <File
+ RelativePath="..\wtf\StringPrintStream.h"
+ >
+ </File>
+ <File
RelativePath="..\wtf\TCPackedCache.h"
>
</File>
diff --git a/Source/WTF/WTF.xcodeproj/project.pbxproj b/Source/WTF/WTF.xcodeproj/project.pbxproj index 58cda1645..c210b5c6d 100644 --- a/Source/WTF/WTF.xcodeproj/project.pbxproj +++ b/Source/WTF/WTF.xcodeproj/project.pbxproj @@ -21,11 +21,14 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ + 0F87105A16643F190090B0AD /* RawPointer.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F87105916643F190090B0AD /* RawPointer.h */; }; 0F9D3360165DBA73005AD387 /* FilePrintStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0F9D335B165DBA73005AD387 /* FilePrintStream.cpp */; }; 0F9D3361165DBA73005AD387 /* FilePrintStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F9D335C165DBA73005AD387 /* FilePrintStream.h */; }; 0F9D3362165DBA73005AD387 /* PrintStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0F9D335D165DBA73005AD387 /* PrintStream.cpp */; }; 0F9D3363165DBA73005AD387 /* PrintStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F9D335E165DBA73005AD387 /* PrintStream.h */; }; 0FD81AC5154FB22E00983E72 /* FastBitVector.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FD81AC4154FB22E00983E72 /* FastBitVector.h */; settings = {ATTRIBUTES = (); }; }; + 0FDDBFA71666DFA300C55FEF /* StringPrintStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0FDDBFA51666DFA300C55FEF /* StringPrintStream.cpp */; }; + 0FDDBFA81666DFA300C55FEF /* StringPrintStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FDDBFA61666DFA300C55FEF /* StringPrintStream.h */; }; 143F611F1565F0F900DB514A /* RAMSize.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 143F611D1565F0F900DB514A /* RAMSize.cpp */; }; 143F61201565F0F900DB514A /* RAMSize.h in Headers */ = {isa = PBXBuildFile; fileRef = 143F611E1565F0F900DB514A /* RAMSize.h */; settings = {ATTRIBUTES = (); }; }; 14F3B0F715E45E4600210069 /* SaturatedArithmetic.h in Headers */ = {isa = PBXBuildFile; fileRef = 14F3B0F615E45E4600210069 /* SaturatedArithmetic.h */; settings = {ATTRIBUTES = (); }; }; @@ -318,11 +321,14 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 0F87105916643F190090B0AD /* RawPointer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RawPointer.h; sourceTree = "<group>"; }; 0F9D335B165DBA73005AD387 /* FilePrintStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FilePrintStream.cpp; sourceTree = "<group>"; }; 0F9D335C165DBA73005AD387 /* FilePrintStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FilePrintStream.h; sourceTree = "<group>"; }; 0F9D335D165DBA73005AD387 /* PrintStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PrintStream.cpp; sourceTree = "<group>"; }; 0F9D335E165DBA73005AD387 /* PrintStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrintStream.h; sourceTree = "<group>"; }; 0FD81AC4154FB22E00983E72 /* FastBitVector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FastBitVector.h; sourceTree = "<group>"; }; + 0FDDBFA51666DFA300C55FEF /* StringPrintStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StringPrintStream.cpp; sourceTree = "<group>"; }; + 0FDDBFA61666DFA300C55FEF /* StringPrintStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StringPrintStream.h; sourceTree = "<group>"; }; 143F611D1565F0F900DB514A /* RAMSize.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RAMSize.cpp; sourceTree = "<group>"; }; 143F611E1565F0F900DB514A /* RAMSize.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RAMSize.h; sourceTree = "<group>"; }; 14F3B0F615E45E4600210069 /* SaturatedArithmetic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SaturatedArithmetic.h; sourceTree = "<group>"; }; @@ -807,6 +813,7 @@ A8A472FB151A825B004123FF /* RandomNumber.cpp */, A8A472FC151A825B004123FF /* RandomNumber.h */, A8A472FD151A825B004123FF /* RandomNumberSeed.h */, + 0F87105916643F190090B0AD /* RawPointer.h */, A8A472FE151A825B004123FF /* RedBlackTree.h */, A8A472FF151A825B004123FF /* RefCounted.h */, A8A47300151A825B004123FF /* RefCountedArray.h */, @@ -834,6 +841,8 @@ A8A47312151A825B004123FF /* StringExtras.cpp */, A8A47313151A825B004123FF /* StringExtras.h */, A8A47314151A825B004123FF /* StringHasher.h */, + 0FDDBFA51666DFA300C55FEF /* StringPrintStream.cpp */, + 0FDDBFA61666DFA300C55FEF /* StringPrintStream.h */, A8A47315151A825B004123FF /* TCPackedCache.h */, A8A47316151A825B004123FF /* TCPageMap.h */, A8A47317151A825B004123FF /* TCSpinLock.h */, @@ -1237,6 +1246,8 @@ A8A47487151A825B004123FF /* WTFThreadData.h in Headers */, 0F9D3361165DBA73005AD387 /* FilePrintStream.h in Headers */, 0F9D3363165DBA73005AD387 /* PrintStream.h in Headers */, + 0F87105A16643F190090B0AD /* RawPointer.h in Headers */, + 0FDDBFA81666DFA300C55FEF /* StringPrintStream.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1407,6 +1418,7 @@ A8A47486151A825B004123FF /* WTFThreadData.cpp in Sources */, 0F9D3360165DBA73005AD387 /* FilePrintStream.cpp in Sources */, 0F9D3362165DBA73005AD387 /* PrintStream.cpp in Sources */, + 0FDDBFA71666DFA300C55FEF /* StringPrintStream.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Source/WTF/wtf/BitVector.cpp b/Source/WTF/wtf/BitVector.cpp index d1a8de790..6327e0aa1 100644 --- a/Source/WTF/wtf/BitVector.cpp +++ b/Source/WTF/wtf/BitVector.cpp @@ -106,13 +106,13 @@ void BitVector::resizeOutOfLine(size_t numBits) m_bitsOrPointer = bitwise_cast<uintptr_t>(newOutOfLineBits) >> 1; } -void BitVector::dump(FILE* out) +void BitVector::dump(PrintStream& out) { for (size_t i = 0; i < size(); ++i) { if (get(i)) - fprintf(out, "1"); + out.printf("1"); else - fprintf(out, "-"); + out.printf("-"); } } diff --git a/Source/WTF/wtf/BitVector.h b/Source/WTF/wtf/BitVector.h index 2c3284c7e..1673ac58b 100644 --- a/Source/WTF/wtf/BitVector.h +++ b/Source/WTF/wtf/BitVector.h @@ -28,6 +28,7 @@ #include <stdio.h> #include <wtf/Assertions.h> +#include <wtf/PrintStream.h> #include <wtf/StdLibExtras.h> namespace WTF { @@ -168,7 +169,7 @@ public: clear(bit); } - void dump(FILE* out); + void dump(PrintStream& out); private: static unsigned bitsInPointer() diff --git a/Source/WTF/wtf/CMakeLists.txt b/Source/WTF/wtf/CMakeLists.txt index 4f822a548..9ba49504b 100644 --- a/Source/WTF/wtf/CMakeLists.txt +++ b/Source/WTF/wtf/CMakeLists.txt @@ -90,6 +90,7 @@ SET(WTF_HEADERS PrintStream.h RandomNumber.h RandomNumberSeed.h + RawPointer.h RedBlackTree.h RefCounted.h RefCountedLeakCounter.h @@ -104,6 +105,7 @@ SET(WTF_HEADERS StdLibExtras.h StringExtras.h StringHasher.h + StringPrintStream.h TCPackedCache.h TCPageMap.h TCSpinLock.h @@ -183,6 +185,7 @@ SET(WTF_SOURCES SHA1.cpp StackBounds.cpp StringExtras.cpp + StringPrintStream.cpp Threading.cpp TypeTraits.cpp WTFThreadData.cpp diff --git a/Source/WTF/wtf/DataLog.cpp b/Source/WTF/wtf/DataLog.cpp index 97e0e972e..d9d0e5fb9 100644 --- a/Source/WTF/wtf/DataLog.cpp +++ b/Source/WTF/wtf/DataLog.cpp @@ -27,12 +27,26 @@ #include "DataLog.h" #include <stdarg.h> #include <wtf/FilePrintStream.h> +#include <wtf/WTFThreadData.h> #include <wtf/Threading.h> +#if OS(UNIX) +#include <unistd.h> +#endif + +#if OS(WINCE) +#ifndef _IONBF +#define _IONBF 0x0004 +#endif +#endif + #define DATA_LOG_TO_FILE 0 -// Uncomment to force logging to the given file regardless of what the environment variable says. -// #define DATA_LOG_FILENAME "/tmp/WTFLog.txt" +// Uncomment to force logging to the given file regardless of what the environment variable says. Note that +// we will append ".<pid>.txt" where <pid> is the PID. + +// This path won't work on Windows, make sure to change to something like C:\\Users\\<more path>\\log.txt. +#define DATA_LOG_FILENAME "/tmp/WTFLog" namespace WTF { @@ -50,12 +64,20 @@ static void initializeLogFileOnce() #else const char* filename = getenv("WTF_DATA_LOG_FILENAME"); #endif + char actualFilename[1024]; + +#if PLATFORM(WIN) + _snprintf(actualFilename, sizeof(actualFilename), "%s.%d.txt", filename, GetCurrentProcessId()); +#else + snprintf(actualFilename, sizeof(actualFilename), "%s.%d.txt", filename, getpid()); +#endif + if (filename) { - FILE* rawFile = fopen(filename, "w"); + FILE* rawFile = fopen(actualFilename, "w"); if (rawFile) file = new FilePrintStream(rawFile); else - fprintf(stderr, "Warning: Could not open log file %s for writing.\n", filename); + fprintf(stderr, "Warning: Could not open log file %s for writing.\n", actualFilename); } #endif // DATA_LOG_TO_FILE if (!file) diff --git a/Source/WTF/wtf/DataLog.h b/Source/WTF/wtf/DataLog.h index ebb7cbeab..f434b71d3 100644 --- a/Source/WTF/wtf/DataLog.h +++ b/Source/WTF/wtf/DataLog.h @@ -40,8 +40,69 @@ WTF_EXPORT_PRIVATE void dataLogFV(const char* format, va_list) WTF_ATTRIBUTE_PRI WTF_EXPORT_PRIVATE void dataLogF(const char* format, ...) WTF_ATTRIBUTE_PRINTF(1, 2); WTF_EXPORT_PRIVATE void dataLogFString(const char*); +template<typename T> +void dataLog(const T& value) +{ + dataFile().print(value); +} + +template<typename T1, typename T2> +void dataLog(const T1& value1, const T2& value2) +{ + dataFile().print(value1, value2); +} + +template<typename T1, typename T2, typename T3> +void dataLog(const T1& value1, const T2& value2, const T3& value3) +{ + dataFile().print(value1, value2, value3); +} + +template<typename T1, typename T2, typename T3, typename T4> +void dataLog(const T1& value1, const T2& value2, const T3& value3, const T4& value4) +{ + dataFile().print(value1, value2, value3, value4); +} + +template<typename T1, typename T2, typename T3, typename T4, typename T5> +void dataLog(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5) +{ + dataFile().print(value1, value2, value3, value4, value5); +} + +template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> +void dataLog(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6) +{ + dataFile().print(value1, value2, value3, value4, value5, value6); +} + +template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> +void dataLog(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6, const T7& value7) +{ + dataFile().print(value1, value2, value3, value4, value5, value6, value7); +} + +template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> +void dataLog(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6, const T7& value7, const T8& value8) +{ + dataFile().print(value1, value2, value3, value4, value5, value6, value7, value8); +} + +template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> +void dataLog(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6, const T7& value7, const T8& value8, const T9& value9) +{ + dataFile().print(value1, value2, value3, value4, value5, value6, value7, value8, value9); +} + +template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> +void dataLog(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6, const T7& value7, const T8& value8, const T9& value9, const T10& value10) +{ + dataFile().print(value1, value2, value3, value4, value5, value6, value7, value8, value9, value10); +} + } // namespace WTF +using WTF::dataLog; using WTF::dataLogF; using WTF::dataLogFString; diff --git a/Source/WTF/wtf/Functional.h b/Source/WTF/wtf/Functional.h index f507e0cb1..828ac2f91 100644 --- a/Source/WTF/wtf/Functional.h +++ b/Source/WTF/wtf/Functional.h @@ -33,7 +33,6 @@ #if PLATFORM(MAC) && COMPILER_SUPPORTS(BLOCKS) #include <Block.h> -#include <objc/objc-runtime.h> #include <wtf/ObjcRuntimeExtras.h> #endif diff --git a/Source/WTF/wtf/InlineASM.h b/Source/WTF/wtf/InlineASM.h index 37069a7e7..0a2fe78b7 100644 --- a/Source/WTF/wtf/InlineASM.h +++ b/Source/WTF/wtf/InlineASM.h @@ -77,7 +77,7 @@ // FIXME: figure out how this works on all the platforms. I know that // on ELF, the preferred form is ".Lstuff" as opposed to "Lstuff". // Don't know about any of the others. -#if PLATFORM(MAC) +#if OS(DARWIN) #define LOCAL_LABEL_STRING(name) "L" #name #elif OS(LINUX) \ || OS(FREEBSD) \ diff --git a/Source/WTF/wtf/ObjcRuntimeExtras.h b/Source/WTF/wtf/ObjcRuntimeExtras.h index 3788d4a89..5420f2757 100644 --- a/Source/WTF/wtf/ObjcRuntimeExtras.h +++ b/Source/WTF/wtf/ObjcRuntimeExtras.h @@ -25,6 +25,8 @@ #ifndef WTF_ObjcRuntimeExtras_h #define WTF_ObjcRuntimeExtras_h +#include <objc/message.h> + template<typename RetType> RetType wtfObjcMsgSend(id target, SEL selector) { diff --git a/Source/WTF/wtf/Platform.h b/Source/WTF/wtf/Platform.h index 12ffbf207..16030199a 100644 --- a/Source/WTF/wtf/Platform.h +++ b/Source/WTF/wtf/Platform.h @@ -926,7 +926,7 @@ #if !defined(ENABLE_LLINT) \ && ENABLE(JIT) \ && (OS(DARWIN) || OS(LINUX)) \ - && (PLATFORM(MAC) || PLATFORM(IOS) || PLATFORM(GTK) || (PLATFORM(QT) && OS(LINUX))) \ + && (PLATFORM(MAC) || PLATFORM(IOS) || PLATFORM(GTK) || PLATFORM(QT)) \ && (CPU(X86) || CPU(X86_64) || CPU(ARM_THUMB2)) #define ENABLE_LLINT 1 #endif diff --git a/Source/WTF/wtf/PrintStream.cpp b/Source/WTF/wtf/PrintStream.cpp index 5d77a83c6..c6123e171 100644 --- a/Source/WTF/wtf/PrintStream.cpp +++ b/Source/WTF/wtf/PrintStream.cpp @@ -47,5 +47,78 @@ void PrintStream::flush() { } +void printInternal(PrintStream& out, const char* string) +{ + out.printf("%s", string); +} + +void printInternal(PrintStream& out, const CString& string) +{ + out.print(string.data()); +} + +void printInternal(PrintStream& out, const String& string) +{ + out.print(string.utf8()); +} + +void printInternal(PrintStream& out, bool value) +{ + if (value) + out.print("true"); + else + out.print("false"); +} + +void printInternal(PrintStream& out, int value) +{ + out.printf("%d", value); +} + +void printInternal(PrintStream& out, unsigned value) +{ + out.printf("%u", value); +} + +void printInternal(PrintStream& out, long value) +{ + out.printf("%ld", value); +} + +void printInternal(PrintStream& out, unsigned long value) +{ + out.printf("%lu", value); +} + +void printInternal(PrintStream& out, long long value) +{ + out.printf("%lld", value); +} + +void printInternal(PrintStream& out, unsigned long long value) +{ + out.printf("%llu", value); +} + +void printInternal(PrintStream& out, float value) +{ + out.print(static_cast<double>(value)); +} + +void printInternal(PrintStream& out, double value) +{ + out.printf("%lf", value); +} + +void printInternal(PrintStream& out, RawPointer value) +{ + out.printf("%p", value.value()); +} + +void dumpCharacter(PrintStream& out, char value) +{ + out.printf("%c", value); +} + } // namespace WTF diff --git a/Source/WTF/wtf/PrintStream.h b/Source/WTF/wtf/PrintStream.h index 3158488a5..88329fd97 100644 --- a/Source/WTF/wtf/PrintStream.h +++ b/Source/WTF/wtf/PrintStream.h @@ -30,6 +30,7 @@ #include <wtf/FastAllocBase.h> #include <wtf/Noncopyable.h> #include <wtf/Platform.h> +#include <wtf/RawPointer.h> #include <wtf/StdLibExtras.h> namespace WTF { @@ -49,10 +50,175 @@ public: // Typically a no-op for many subclasses of PrintStream, this is a hint that // the implementation should flush its buffers if it had not done so already. virtual void flush(); + + template<typename T> + void print(const T& value) + { + printInternal(*this, value); + } + + template<typename T1, typename T2> + void print(const T1& value1, const T2& value2) + { + print(value1); + print(value2); + } + + template<typename T1, typename T2, typename T3> + void print(const T1& value1, const T2& value2, const T3& value3) + { + print(value1); + print(value2); + print(value3); + } + + template<typename T1, typename T2, typename T3, typename T4> + void print(const T1& value1, const T2& value2, const T3& value3, const T4& value4) + { + print(value1); + print(value2); + print(value3); + print(value4); + } + + template<typename T1, typename T2, typename T3, typename T4, typename T5> + void print(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5) + { + print(value1); + print(value2); + print(value3); + print(value4); + print(value5); + } + + template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> + void print(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6) + { + print(value1); + print(value2); + print(value3); + print(value4); + print(value5); + print(value6); + } + + template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> + void print(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6, const T7& value7) + { + print(value1); + print(value2); + print(value3); + print(value4); + print(value5); + print(value6); + print(value7); + } + + template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> + void print(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6, const T7& value7, const T8& value8) + { + print(value1); + print(value2); + print(value3); + print(value4); + print(value5); + print(value6); + print(value7); + print(value8); + } + + template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> + void print(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6, const T7& value7, const T8& value8, const T9& value9) + { + print(value1); + print(value2); + print(value3); + print(value4); + print(value5); + print(value6); + print(value7); + print(value8); + print(value9); + } + + template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> + void print(const T1& value1, const T2& value2, const T3& value3, const T4& value4, const T5& value5, const T6& value6, const T7& value7, const T8& value8, const T9& value9, const T10& value10) + { + print(value1); + print(value2); + print(value3); + print(value4); + print(value5); + print(value6); + print(value7); + print(value8); + print(value9); + print(value10); + } }; +void printInternal(PrintStream&, const char*); +void printInternal(PrintStream&, const CString&); +void printInternal(PrintStream&, const String&); +inline void printInternal(PrintStream& out, char* value) { printInternal(out, static_cast<const char*>(value)); } +inline void printInternal(PrintStream& out, CString& value) { printInternal(out, static_cast<const CString&>(value)); } +inline void printInternal(PrintStream& out, String& value) { printInternal(out, static_cast<const String&>(value)); } +void printInternal(PrintStream&, bool); +void printInternal(PrintStream&, int); +void printInternal(PrintStream&, unsigned); +void printInternal(PrintStream&, long); +void printInternal(PrintStream&, unsigned long); +void printInternal(PrintStream&, long long); +void printInternal(PrintStream&, unsigned long long); +void printInternal(PrintStream&, float); +void printInternal(PrintStream&, double); +void printInternal(PrintStream&, RawPointer); + +template<typename T> +void printInternal(PrintStream& out, const T& value) +{ + value.dump(out); +} + +#define MAKE_PRINT_ADAPTOR(Name, Type, function) \ + class Name { \ + public: \ + Name(const Type& value) \ + : m_value(value) \ + { \ + } \ + void dump(PrintStream& out) const \ + { \ + function(out, m_value); \ + } \ + private: \ + Type m_value; \ + } + +#define MAKE_PRINT_METHOD_ADAPTOR(Name, Type, method) \ + class Name { \ + public: \ + Name(const Type& value) \ + : m_value(value) \ + { \ + } \ + void dump(PrintStream& out) const \ + { \ + m_value.method(out); \ + } \ + private: \ + Type m_value; \ + } + +// Use an adaptor-based dumper for characters to avoid situations where +// you've "compressed" an integer to a character and it ends up printing +// as ASCII when you wanted it to print as a number. +void dumpCharacter(PrintStream&, char); +MAKE_PRINT_ADAPTOR(CharacterDump, char, dumpCharacter); + } // namespace WTF +using WTF::CharacterDump; using WTF::PrintStream; #endif // PrintStream_h diff --git a/Source/WTF/wtf/RawPointer.h b/Source/WTF/wtf/RawPointer.h new file mode 100644 index 000000000..24ca074ef --- /dev/null +++ b/Source/WTF/wtf/RawPointer.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RawPointer_h +#define RawPointer_h + +namespace WTF { + +class RawPointer { +public: + RawPointer() + : m_value(0) + { + } + + explicit RawPointer(void* value) + : m_value(value) + { + } + + void* value() const { return m_value; } + +private: + void* m_value; +}; + +} // namespace WTF + +using WTF::RawPointer; + +#endif // RawPointer_h diff --git a/Source/WTF/wtf/StringPrintStream.cpp b/Source/WTF/wtf/StringPrintStream.cpp new file mode 100644 index 000000000..41e1f83fe --- /dev/null +++ b/Source/WTF/wtf/StringPrintStream.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "StringPrintStream.h" + +#include <stdarg.h> +#include <stdio.h> +#include <wtf/FastMalloc.h> + +namespace WTF { + +StringPrintStream::StringPrintStream() + : m_buffer(m_inlineBuffer) + , m_next(0) + , m_size(sizeof(m_inlineBuffer)) +{ + m_buffer[0] = 0; // Make sure that we always have a null terminator. +} + +StringPrintStream::~StringPrintStream() +{ + if (m_buffer == m_inlineBuffer) + return; + fastFree(m_buffer); +} + +void StringPrintStream::vprintf(const char* format, va_list argList) +{ + ASSERT(m_next < m_size); + ASSERT(!m_buffer[m_next]); + + va_list firstPassArgList; +#if OS(WINDOWS) + firstPassArgList = argList; +#else + va_copy(firstPassArgList, argList); +#endif + + int numberOfBytesNotIncludingTerminatorThatWouldHaveBeenWritten = + vsnprintf(m_buffer + m_next, m_size - m_next, format, firstPassArgList); + + int numberOfBytesThatWouldHaveBeenWritten = + numberOfBytesNotIncludingTerminatorThatWouldHaveBeenWritten + 1; + + if (m_next + numberOfBytesThatWouldHaveBeenWritten <= m_size) { + m_next += numberOfBytesNotIncludingTerminatorThatWouldHaveBeenWritten; + return; // This means that vsnprintf() succeeded. + } + + increaseSize(m_next + numberOfBytesThatWouldHaveBeenWritten); + + int numberOfBytesNotIncludingTerminatorThatWereWritten = + vsnprintf(m_buffer + m_next, m_size - m_next, format, argList); + + int numberOfBytesThatWereWritten = numberOfBytesNotIncludingTerminatorThatWereWritten + 1; + + ASSERT_UNUSED(numberOfBytesThatWereWritten, m_next + numberOfBytesThatWereWritten <= m_size); + + m_next += numberOfBytesNotIncludingTerminatorThatWereWritten; + + ASSERT(m_next < m_size); + ASSERT(!m_buffer[m_next]); +} + +CString StringPrintStream::toCString() +{ + ASSERT(m_next == strlen(m_buffer)); + return CString(m_buffer, m_next); +} + +void StringPrintStream::increaseSize(size_t newSize) +{ + ASSERT(newSize > m_size); + ASSERT(newSize > sizeof(m_inlineBuffer)); + + // Use exponential resizing to reduce thrashing. + m_size = newSize << 1; + + // Use fastMalloc instead of fastRealloc because we know that for the sizes we're using, + // fastRealloc will just do malloc+free anyway. Also, this simplifies the code since + // we can't realloc the inline buffer. + char* newBuffer = static_cast<char*>(fastMalloc(m_size)); + memcpy(newBuffer, m_buffer, m_next + 1); + if (m_buffer != m_inlineBuffer) + fastFree(m_buffer); + m_buffer = newBuffer; +} + +} // namespace WTF + diff --git a/Source/WTF/wtf/StringPrintStream.h b/Source/WTF/wtf/StringPrintStream.h new file mode 100644 index 000000000..9290f0867 --- /dev/null +++ b/Source/WTF/wtf/StringPrintStream.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef StringPrintStream_h +#define StringPrintStream_h + +#include <wtf/PrintStream.h> +#include <wtf/text/CString.h> + +namespace WTF { + +class StringPrintStream : public PrintStream { +public: + StringPrintStream(); + ~StringPrintStream(); + + virtual void vprintf(const char* format, va_list) WTF_ATTRIBUTE_PRINTF(2, 0); + + CString toCString(); + +private: + void increaseSize(size_t); + + char* m_buffer; + size_t m_next; + size_t m_size; + char m_inlineBuffer[128]; +}; + +// Stringify any type T that has a WTF::printInternal(PrintStream&, const T&) +template<typename T> +CString toCString(const T& value) +{ + StringPrintStream stream; + stream.print(value); + return stream.toCString(); +} + +} // namespace WTF + +using WTF::StringPrintStream; +using WTF::toCString; + +#endif // StringPrintStream_h + diff --git a/Source/WTF/wtf/text/StringImpl.cpp b/Source/WTF/wtf/text/StringImpl.cpp index 84799adbb..f995c6414 100644 --- a/Source/WTF/wtf/text/StringImpl.cpp +++ b/Source/WTF/wtf/text/StringImpl.cpp @@ -33,6 +33,7 @@ #include <wtf/unicode/CharacterNames.h> #ifdef STRING_STATS +#include <unistd.h> #include <wtf/DataLog.h> #endif @@ -80,23 +81,27 @@ void StringStats::removeString(StringImpl* string) void StringStats::printStats() { - dataLog("String stats for process id %d:\n", getpid()); + dataLogF("String stats for process id %d:\n", getpid()); unsigned long long totalNumberCharacters = m_total8BitData + m_total16BitData; double percent8Bit = m_totalNumberStrings ? ((double)m_number8BitStrings * 100) / (double)m_totalNumberStrings : 0.0; double average8bitLength = m_number8BitStrings ? (double)m_total8BitData / (double)m_number8BitStrings : 0.0; - dataLog("%8u (%5.2f%%) 8 bit %12llu chars %12llu bytes avg length %6.1f\n", m_number8BitStrings, percent8Bit, m_total8BitData, m_total8BitData, average8bitLength); + dataLogF("%8u (%5.2f%%) 8 bit %12llu chars %12llu bytes avg length %6.1f\n", m_number8BitStrings, percent8Bit, m_total8BitData, m_total8BitData, average8bitLength); double percent16Bit = m_totalNumberStrings ? ((double)m_number16BitStrings * 100) / (double)m_totalNumberStrings : 0.0; double average16bitLength = m_number16BitStrings ? (double)m_total16BitData / (double)m_number16BitStrings : 0.0; - dataLog("%8u (%5.2f%%) 16 bit %12llu chars %12llu bytes avg length %6.1f\n", m_number16BitStrings, percent16Bit, m_total16BitData, m_total16BitData * 2, average16bitLength); + dataLogF("%8u (%5.2f%%) 16 bit %12llu chars %12llu bytes avg length %6.1f\n", m_number16BitStrings, percent16Bit, m_total16BitData, m_total16BitData * 2, average16bitLength); double percentUpconverted = m_totalNumberStrings ? ((double)m_numberUpconvertedStrings * 100) / (double)m_number8BitStrings : 0.0; double averageUpconvertedLength = m_numberUpconvertedStrings ? (double)m_totalUpconvertedData / (double)m_numberUpconvertedStrings : 0.0; - dataLog("%8u (%5.2f%%) upconverted %12llu chars %12llu bytes avg length %6.1f\n", m_numberUpconvertedStrings, percentUpconverted, m_totalUpconvertedData, m_totalUpconvertedData * 2, averageUpconvertedLength); + dataLogF("%8u (%5.2f%%) upconverted %12llu chars %12llu bytes avg length %6.1f\n", m_numberUpconvertedStrings, percentUpconverted, m_totalUpconvertedData, m_totalUpconvertedData * 2, averageUpconvertedLength); double averageLength = m_totalNumberStrings ? (double)totalNumberCharacters / (double)m_totalNumberStrings : 0.0; - dataLog("%8u Total %12llu chars %12llu bytes avg length %6.1f\n", m_totalNumberStrings, totalNumberCharacters, m_total8BitData + (m_total16BitData + m_totalUpconvertedData) * 2, averageLength); + unsigned long long totalDataBytes = m_total8BitData + (m_total16BitData + m_totalUpconvertedData) * 2; + dataLogF("%8u Total %12llu chars %12llu bytes avg length %6.1f\n", m_totalNumberStrings, totalNumberCharacters, totalDataBytes, averageLength); + unsigned long long totalSavedBytes = m_total8BitData - m_totalUpconvertedData; + double percentSavings = totalSavedBytes ? ((double)totalSavedBytes * 100) / (double)(totalDataBytes + totalSavedBytes) : 0.0; + dataLogF(" Total savings %12llu bytes (%5.2f%%)\n", totalSavedBytes, percentSavings); } #endif diff --git a/Source/WebCore/CMakeLists.txt b/Source/WebCore/CMakeLists.txt index 6a99fa26b..b40b4ad5f 100644 --- a/Source/WebCore/CMakeLists.txt +++ b/Source/WebCore/CMakeLists.txt @@ -332,6 +332,7 @@ SET(WebCore_IDL_FILES css/WebKitCSSKeyframeRule.idl css/WebKitCSSKeyframesRule.idl css/WebKitCSSMatrix.idl + css/WebKitCSSMixFunctionValue.idl css/WebKitCSSRegionRule.idl css/WebKitCSSTransformValue.idl css/WebKitCSSViewportRule.idl @@ -1632,6 +1633,7 @@ SET(WebCore_SOURCES loader/FTPDirectoryParser.cpp loader/FormState.cpp loader/FormSubmission.cpp + loader/FrameLoadRequest.cpp loader/FrameLoader.cpp loader/FrameLoaderStateMachine.cpp loader/HistoryController.cpp @@ -2549,9 +2551,7 @@ ENDIF() IF (ENABLE_SMOOTH_SCROLLING) LIST(APPEND WebCore_SOURCES - platform/ActivePlatformGestureAnimation.cpp platform/ScrollAnimatorNone.cpp - platform/TouchFlingPlatformGestureCurve.cpp ) ENDIF () diff --git a/Source/WebCore/ChangeLog b/Source/WebCore/ChangeLog index 45f8cf911..c8b1b688b 100644 --- a/Source/WebCore/ChangeLog +++ b/Source/WebCore/ChangeLog @@ -1,3 +1,4677 @@ +2012-11-29 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r136111. + http://trac.webkit.org/changeset/136111 + https://bugs.webkit.org/show_bug.cgi?id=103620 + + Broke compilation on Mac (unused private field m_matchMode) + (Requested by apavlov on #webkit). + + * CMakeLists.txt: + * GNUmakefile.list.am: + * Target.pri: + * WebCore.gypi: + * WebCore.vcproj/WebCore.vcproj: + * WebCore.xcodeproj/project.pbxproj: + * html/HTMLSelectElement.cpp: + (WebCore): + (WebCore::HTMLSelectElement::HTMLSelectElement): + (WebCore::stripLeadingWhiteSpace): + (WebCore::HTMLSelectElement::typeAheadFind): + * html/HTMLSelectElement.h: + (HTMLSelectElement): + * html/TypeAhead.cpp: Removed. + * html/TypeAhead.h: Removed. + * html/shadow/DateTimeSymbolicFieldElement.cpp: + (WebCore::DateTimeSymbolicFieldElement::DateTimeSymbolicFieldElement): + (WebCore::DateTimeSymbolicFieldElement::handleKeyboardEvent): + * html/shadow/DateTimeSymbolicFieldElement.h: + (DateTimeSymbolicFieldElement): + +2012-11-29 Keishi Hattori <keishi@webkit.org> + + Better type ahead for DateTimeSymbolicFieldElement + https://bugs.webkit.org/show_bug.cgi?id=103031 + + Reviewed by Kent Tamura. + + This cuts out the type ahead code that will be used by HTMLSelectElement + and DateTimeSymbolicFieldElement into a TypeAhead class. This will + improve DateTimeSymbolicFieldElement type ahead which was first + character match only, by adding cycling, prefix match and index number + match. + + Added tests to month-multiple-fields-keyboard-events.html. + + * GNUmakefile.list.am: Added TypeAhead.{h,cpp} + * Target.pri: Ditto. + * WebCore.gypi: Ditto. + * WebCore.vcproj/WebCore.vcproj: Ditto. + * WebCore.xcodeproj/project.pbxproj: Ditto. + * CMakeLists.txt: Ditto. + * html/HTMLSelectElement.cpp: + (WebCore): + (WebCore::HTMLSelectElement::HTMLSelectElement): + (WebCore::HTMLSelectElement::indexOfSelectedOption): Returns index of current selection. + (WebCore::HTMLSelectElement::optionCount): Returns total number of options. + (WebCore::HTMLSelectElement::optionAtIndex): Returns option at index. + (WebCore::HTMLSelectElement::typeAheadFind): Use TypeAhead. + * html/HTMLSelectElement.h: + (HTMLSelectElement): + * html/TypeAhead.cpp: Added. + (WebCore): + (WebCore::TypeAhead::TypeAhead): + (WebCore::stripLeadingWhiteSpace): Moved from HTMLSelectElement.cpp. + (WebCore::TypeAhead::handleEvent): Returns index for match. + * html/TypeAhead.h: Added. + (WebCore): + (TypeAheadDataSource): Provide the data about the options that TypeAhead should match against. + (TypeAhead): + * html/shadow/DateTimeSymbolicFieldElement.cpp: + (WebCore::DateTimeSymbolicFieldElement::DateTimeSymbolicFieldElement): + (WebCore::DateTimeSymbolicFieldElement::handleKeyboardEvent): + (WebCore::DateTimeSymbolicFieldElement::indexOfSelectedOption): + (WebCore): + (WebCore::DateTimeSymbolicFieldElement::optionCount): + (WebCore::DateTimeSymbolicFieldElement::optionAtIndex): + * html/shadow/DateTimeSymbolicFieldElement.h: + (DateTimeSymbolicFieldElement): + +2012-11-29 Andrei Bucur <abucur@adobe.com> + + [CSS Regions] Fix content node renderers ordering inside the named flow thread + https://bugs.webkit.org/show_bug.cgi?id=103501 + + Reviewed by David Hyatt. + + This patch fixes two issues with how content nodes renderers are added to a named flow thread. + The first issue was about determining the insertion position of a renderer inside the children list of a named flow thread. Before this patch, the + insertion point was based on both the DOM ordering of the elements and insertion order of previous renderers. + The patch fixes this and makes the renderer position just a function of the DOM ordering of elements. + The second issue appeared when next/previousRenderer methods were skipping nodes because they had the flow-into property as a side effect + of copying the style of the parent element (e.g. Text nodes). The patch ensures the skipped nodes are also elements. + + Tests: fast/regions/named-flow-content-order-1.html + fast/regions/named-flow-content-order-2.html + fast/regions/named-flow-content-order-3.html + + * dom/NodeRenderingContext.cpp: + (WebCore::NodeRenderingContext::nextRenderer): Skip only elements. + (WebCore::NodeRenderingContext::previousRenderer): Skip only elements. + * rendering/RenderNamedFlowThread.cpp: + (WebCore::RenderNamedFlowThread::addFlowChild): Insert the renderer in the list based on the DOM position of the owner element. + * rendering/RenderNamedFlowThread.h: + (RenderNamedFlowThread): + * rendering/RenderObject.cpp: + (WebCore::RenderObject::renderNamedFlowThreadWrapper): Rename to eliminate the confusion with enclosingRenderFlowThread. + (WebCore::RenderObject::insertedIntoTree): + (WebCore::RenderObject::willBeRemovedFromTree): + * rendering/RenderObject.h: + (RenderObject): + +2012-11-28 Mike West <mkwst@chromium.org> + + Add a test to ensure that 'seamless' iframes do not inherit contenteditable. + https://bugs.webkit.org/show_bug.cgi?id=95890 + + Reviewed by Ojan Vafai. + + We don't currently support inheriting contenteditable into a seamless + frame. http://html5.org/tools/web-apps-tracker?from=7318&to=7319 + brought the spec in line with WebKit's behavior (ha!). This patch + defends the behavior by adding a test, and removes a FIXME comment + now that the question is settled. + + It also exposes a brand new bug: https://bugs.webkit.org/show_bug.cgi?id=103539 + How exciting. + + Test: fast/frames/seamless/seamless-contenteditable-not-inherited.html + + * css/StyleResolver.cpp: + (WebCore::StyleResolver::styleForDocument): + No functional change, just dropping a FIXME comment. + +2012-11-28 Mike West <mkwst@chromium.org> + + Web Inspector: Console message's anchor element should be trimmed for readability. + https://bugs.webkit.org/show_bug.cgi?id=100095 + + Reviewed by Pavel Feldman. + + We're currently trimming URLs that go through + 'WebInspector.linkifyURLAsNode' down to 150 characters total. Not all + URLs go that path, however. We were missing a few cases that dropped + back to the default Linkifier (which especially showed up for "Live" + anchor elements). + + This patch ensures that anything using WebInspector.Linkifier is also + trimmed by default. It adds a new constant to do so in order to avoid + magic numbers in the code. + + Test: http/tests/inspector/network/script-as-text-loading-long-url.html + + * inspector/front-end/Linkifier.js: + (WebInspector.Linkifier): + Pass the max length into the default formatter that's created and + stored when creating a 'WebInspector.Linkifier' object. + * inspector/front-end/ResourceUtils.js: + (WebInspector.linkifyURLAsNode): + Use the new maxlength constant rather than hard-coding 150. + +2012-11-28 Kentaro Hara <haraken@chromium.org> + + Unreviewed. Rebaselined run-bindings-tests. + + * bindings/scripts/test/V8/V8TestNode.h: + (WebCore::toV8Fast): + +2012-11-28 Shinya Kawanaka <shinyak@chromium.org> + + [Shadow] ShadowRoot should cache InsertionPointList. + https://bugs.webkit.org/show_bug.cgi?id=103212 + + Reviewed by Hajime Morita. + + When distributing or invalidating distribution, we used to traverse all descendent nodes in Shadow DOM. + If ShadowRoot has a InsertionPoint list, we can just traverse the list. + + No new tests, should be covered by existing tests. + + * dom/ShadowRoot.cpp: + (WebCore::ShadowRoot::insertionPointList): + (WebCore): + * dom/ShadowRoot.h: + (ShadowRoot): + * html/shadow/ContentDistributor.cpp: + (WebCore::ShadowRootContentDistributionData::ShadowRootContentDistributionData): + (WebCore::ShadowRootContentDistributionData::invalidateInsertionPointList): + (WebCore): + (WebCore::ShadowRootContentDistributionData::ensureInsertionPointList): Creates InsertionPoint list + if it's not created and return it. + (WebCore::ContentDistributor::distribute): Traverse InsertionPointList instead of all descendent nodes in Shadow DOM. + (WebCore::ContentDistributor::invalidate): ditto. + * html/shadow/ContentDistributor.h: + (WebCore::ShadowRootContentDistributionData::incrementNumberOfShadowElementChildren): Invalidate InsertionPointList cache. + (WebCore::ShadowRootContentDistributionData::decrementNumberOfShadowElementChildren): ditto. + (WebCore::ShadowRootContentDistributionData::incrementNumberOfContentElementChildren): ditto. + (WebCore::ShadowRootContentDistributionData::decrementNumberOfContentElementChildren): ditto. + (ShadowRootContentDistributionData): + +2012-11-28 Michael Pruett <michael@68k.org> + + IndexedDB: Remove duplicate toWireString() and createFromWire() methods in JSC SerializedScriptValue + https://bugs.webkit.org/show_bug.cgi?id=103554 + + Reviewed by Kentaro Hara. + + In r135022, duplicate createFromWire() and toWireString() methods + were added to the JSC version of SerializedScriptValue. In + order to allow the JSC SerializedScriptValue to compile when + ENABLE(INDEXED_DATABASE) is turned on, these new methods have + been removed and the old methods have been moved outside the + ENABLE(INDEXED_DATABASE) guard. + + No new tests. No change in functionality. + + * WebCore.exp.in: + * bindings/js/SerializedScriptValue.cpp: + (WebCore::SerializedScriptValue::toWireString): + (WebCore): + (WebCore::SerializedScriptValue::createFromWire): + * bindings/js/SerializedScriptValue.h: + +2012-11-28 Hajime Morrita <morrita@google.com> + + [Shadow DOM] Element.createShadowRoot() should be prefixed. + https://bugs.webkit.org/show_bug.cgi?id=103595 + + Reviewed by Kentaro Hara. + + No new tests, updated shadow-aware-create-shadow-root.html to follow the change. + + * dom/Element.idl: + +2012-11-28 Hayato Ito <hayato@chromium.org> + + Node::compareDocumentPosition returns wrong value for a node in the different shadow tree. + https://bugs.webkit.org/show_bug.cgi?id=103502 + + Reviewed by Dimitri Glazkov. + + Make Node::compareDocumentPosition() return the correct value when two nodes are in the different shadow trees. + + Test: fast/dom/shadow/compare-document-position.html + + * dom/Node.cpp: + (WebCore::Node::compareDocumentPosition): + +2012-11-28 Joshua Bell <jsbell@chromium.org> + + [Chromium] IndexedDB: Assert/crash in indexing layout tests in content_shell + https://bugs.webkit.org/show_bug.cgi?id=103562 + + Reviewed by Tony Chang. + + In multi-process ports, an commit request or setIndexesReady request may arrive from the + front-end after the back-end has already aborted. Don't freak out if those occur. + + Tests: storage/indexeddb/index-population.html + storage/indexeddb/lazy-index-population.html + storage/indexeddb/transaction-error.html + + * Modules/indexeddb/IDBObjectStoreBackendImpl.cpp: + (WebCore::IDBObjectStoreBackendImpl::setIndexKeys): Ensure transaction hasn't finished before continuing. + (WebCore::IDBObjectStoreBackendImpl::setIndexesReady): Ditto. + * Modules/indexeddb/IDBTransactionBackendImpl.cpp: + (WebCore::IDBTransactionBackendImpl::commit): Ignore a commit request if already aborted. + +2012-11-28 Shinya Kawanaka <shinyak@chromium.org> + + [Shadow] Move Distribution requirements from ShadowRoot + https://bugs.webkit.org/show_bug.cgi?id=103481 + + Reviewed by Hajime Morita. + + We would like to shrink the ShadowRoot memory size in this patch. ShadowRoot had several distribution related members, + however they were used only if ShadowRoot has <content>, <shadow>, or nested ShadowRoot. + Since <input> or <textarea> do not have such requirements, the members consume a few amount of memory. + + We remove them from ShadowRoot and introduce some RareData-like data structure for ShadowRoot. + This will reduce memory footprint in most cases. + + No new tests, refactoring. + + * WebCore.exp.in: + * dom/ShadowRoot.cpp: + (SameSizeAsShadowRoot): Reduced 3 * sizeof(unsigned) bytes from ShadowRoot. + (WebCore::ShadowRoot::ShadowRoot): DistributionData is created only when necessary. <input> or <textarea> won't + create such data. + (WebCore::ShadowRoot::assignedTo): + (WebCore): + (WebCore::ShadowRoot::setAssignedTo): + (WebCore::ShadowRoot::ensureDistributionData): + (WebCore::ShadowRoot::registerShadowElement): + (WebCore::ShadowRoot::unregisterShadowElement): + (WebCore::ShadowRoot::hasShadowInsertionPoint): + (WebCore::ShadowRoot::registerContentElement): + (WebCore::ShadowRoot::unregisterContentElement): + (WebCore::ShadowRoot::hasContentElement): + (WebCore::ShadowRoot::registerElementShadow): + (WebCore::ShadowRoot::unregisterElementShadow): + (WebCore::ShadowRoot::hasElementShadow): + (WebCore::ShadowRoot::countElementShadow): + (WebCore::ShadowRoot::reportMemoryUsage): + * dom/ShadowRoot.h: + (WebCore): + (ShadowRoot): + (WebCore::ShadowRoot::distributionData): + * html/shadow/ContentDistributor.cpp: + (WebCore::ShadowRootContentDistributionData::ShadowRootContentDistributionData): + (WebCore): + * html/shadow/ContentDistributor.h: + (ShadowRootContentDistributionData): Distribution related fields in ShadowRoot are moved to here. + (WebCore::ShadowRootContentDistributionData::insertionPointAssignedTo): + (WebCore::ShadowRootContentDistributionData::setInsertionPointAssignedTo): + (WebCore::ShadowRootContentDistributionData::incrementNumberOfShadowElementChildren): + (WebCore::ShadowRootContentDistributionData::decrementNumberOfShadowElementChildren): + (WebCore::ShadowRootContentDistributionData::numberOfShadowElementChildren): + (WebCore::ShadowRootContentDistributionData::incrementNumberOfContentElementChildren): + (WebCore::ShadowRootContentDistributionData::decrementNumberOfContentElementChildren): + (WebCore::ShadowRootContentDistributionData::numberOfContentElementChildren): + (WebCore::ShadowRootContentDistributionData::incrementNumberOfElementShadowChildren): + (WebCore::ShadowRootContentDistributionData::decrementNumberOfElementShadowChildren): + (WebCore::ShadowRootContentDistributionData::numberOfElementShadowChildren): + (WebCore): + +2012-11-23 Dirk Schulze <krit@webkit.org> + + Remove -webkit-mask-attachment + https://bugs.webkit.org/show_bug.cgi?id=67137 + + Reviewed by David Hyatt. + + Remove CSS property '-webkit-attachment'. The CSS WG agreed that this should not be + part of the CSS Masking specification. WebKit never implemented the behavior of + attached masks either. The property was just exposed in CSSOM. + + Test: Added negative tests to fast/masking/parsing-mask.html. + + * css/CSSComputedStyleDeclaration.cpp: + (WebCore): + (WebCore::CSSComputedStyleDeclaration::getPropertyCSSValue): + * css/CSSParser.cpp: + (WebCore::CSSParser::parseValue): + (WebCore::CSSParser::parseFillProperty): + * css/CSSProperty.cpp: + (WebCore::CSSProperty::isInheritedProperty): + * css/CSSPropertyNames.in: + * css/StyleBuilder.cpp: + (WebCore::StyleBuilder::StyleBuilder): + * css/StylePropertySet.cpp: + (WebCore::StylePropertySet::asText): + * css/StylePropertyShorthand.cpp: + (WebCore::webkitMaskShorthand): + * css/StyleResolver.cpp: + (WebCore::StyleResolver::applyProperty): + * rendering/style/RenderStyle.h: + +2012-11-28 Michael Pruett <michael@68k.org> + + IndexedDB: Add forward declaration of SecurityOrigin to IDBBackingStore.h + https://bugs.webkit.org/show_bug.cgi?id=103578 + + Reviewed by Kentaro Hara. + + Add forward declaration of SecurityOrigin to IDBBackingStore.h + in order to enable compilation of IndexedDB for JSC. + + Tests: storage/indexeddb/* + + * Modules/indexeddb/IDBBackingStore.h: + (WebCore): + +2012-11-28 Hajime Morrita <morrita@google.com> + + checkAcceptChild() needs fewer virtual calls + https://bugs.webkit.org/show_bug.cgi?id=103372 + + Reviewed by Ojan Vafai. + + This change reorganizes checkAcceptChild family for speed. + + - Made Node::checkAddChild and Node::checkReplaceChild() static inline functions + in ContainerNode.cpp. checkAcceptChild() was also moved to the same file. This allows us + more aggressive inlining. + + - Added a fast path in checkAcceptChild(), where we can assume that the parent is element + and the new child is element or text. Under this assumption, we need no extra type checks + and just needs a cycle prevention through Node::contains(). This is faster than current generic version. + + - Moved extra checks from checkAddChild() and checkReplaceChild() to + checkAcceptChild(). This allows the fast path skips even these extra checks. + + - Node::canReplaceChild() is devirtualized. Since the only override is on + Document, we can check isDocumentNode() to call it directly. + + - The default implemenation of Node::canReplaceChild() just calls isChildTypeAllowed(). + That is what an extra check for checkAddChild() did. So we can share these code path in checkAcceptChild(). + + This gains 2-3% win on Dromaeo dom-modify.html. + + No new tests, covered by existing tests. + + * dom/ContainerNode.cpp: + (WebCore::isChildTypeAllowed): Moved from Node.cpp + (WebCore::checkAcceptChild): Moved from Node.cpp, Added a fast path. + (WebCore::checkAddChild): Moved from Node.cpp + (WebCore::checkReplaceChild): Moved from Node.cpp + (WebCore::ContainerNode::insertBefore): Followed the signature change. + (WebCore::ContainerNode::replaceChild): Followed the signature change, moved null check from checkReplaceChild to here. + (WebCore::ContainerNode::appendChild): Followed the signature change. + * dom/Document.h: + (Document): + * dom/Node.cpp: + * dom/Node.h: + (WebCore::Node::isDocumentTypeNode): Added for better readability of call sites. + +2012-11-28 Kenichi Ishibashi <bashi@chromium.org> + + StyleResolver should not set NaN to font size + https://bugs.webkit.org/show_bug.cgi?id=99506 + + Reviewed by Abhishek Arya. + + fixedScaleFactor could be NaN since settings->defaultFixedFontSize() + and settings->defaultFontSize() are zero in some case. This turns + out setting NaN to font size. Add a zero checks so that + fixedScaleFactor won't be NaN. + + Test: fast/css/font-size-nan.html + + * css/StyleResolver.cpp: + (WebCore::StyleResolver::checkForGenericFamilyChange): + +2012-11-28 Tim Horton <timothy_horton@apple.com> + + [mac] WebHTMLConverter should maintain font size even when there is no related NSFont + https://bugs.webkit.org/show_bug.cgi?id=103568 + + Reviewed by Alexey Proskuryakov. + + WebHTMLConverter should use the default font at the correct size when it + encounters a font that cannot be backed by an NSFont (e.g. a WebFont). + + * platform/mac/HTMLConverter.mm: + (+[WebHTMLConverter editingAttributedStringFromRange:]): + +2012-11-23 Dirk Schulze <krit@webkit.org> + + CSS parser does not support -webkit-mask-size for -webkit-mask shorthand + https://bugs.webkit.org/show_bug.cgi?id=103020 + + Reviewed by David Hyatt. + + Harmonize the syntax of '-webkit-mask' property with 'background' according to the + CSS Masking specification[1]. This should make it easier to maintain both shorthand + properties in the long term. + It is very unlikely that a lot of content (if any) is affected by this change. The + computed style still is not implemented and this change should rather make it easier + for developers. + + With the harmonization, the '-webkit-mask-size' property is part of the shorthand as + well now. + + parsing-mask.html covers all the changes. Added new tests for the changed syntax and + '-webkit-mask-size' + + [1] http://dvcs.w3.org/hg/FXTF/raw-file/tip/masking/index.html#mask-property + + * css/CSSParser.cpp: + (WebCore::CSSParser::parseValue): + (WebCore::CSSParser::parseFillShorthand): + * css/StylePropertySet.cpp: + (WebCore::StylePropertySet::getLayeredShorthandValue): + * css/StylePropertyShorthand.cpp: + (WebCore::webkitMaskShorthand): + +2012-11-28 Alec Flett <alecflett@chromium.org> + + IndexedDB: Change frontend to call IDBDatabaseBackendInterface::createTransaction() + https://bugs.webkit.org/show_bug.cgi?id=102732 + + Reviewed by Tony Chang. + + Use the new createTransaction, now that it has been stubbed + out. This is part 2 of 3 of a refactor. See + https://bugs.webkit.org/show_bug.cgi?id=102733 for part 3. + + No new tests as this refactor simply keeps and propagates a + counter that is currently unused. + + * Modules/indexeddb/IDBDatabase.cpp: + (WebCore::IDBDatabase::nextTransactionId): + (WebCore): + (WebCore::IDBDatabase::transaction): + * Modules/indexeddb/IDBDatabase.h: + (IDBDatabase): + * Modules/indexeddb/IDBOpenDBRequest.cpp: + (WebCore::IDBOpenDBRequest::onUpgradeNeeded): + * Modules/indexeddb/IDBRequest.cpp: + (WebCore::IDBRequest::onSuccess): + * Modules/indexeddb/IDBTransaction.cpp: + (WebCore::IDBTransaction::create): + (WebCore::IDBTransaction::IDBTransaction): + * Modules/indexeddb/IDBTransaction.h: + (IDBTransaction): + +2012-11-28 Michael Saboff <msaboff@apple.com> + + HTMLFontElement font size parsing should directly handle 8 bit strings + https://bugs.webkit.org/show_bug.cgi?id=103315 + + Reviewed by Oliver Hunt. + + Split parseFontSize() into a templated function based on character type and a wrapper that determines + a string's bitness before calling the template. + + No new tests. No change in functionality. + + * html/HTMLFontElement.cpp: + (WebCore::parseFontSize): + +2012-11-28 Robert Kroeger <rjkroege@chromium.org> + + remove unused PlatformGestureCurve code + https://bugs.webkit.org/show_bug.cgi?id=103296 + + Reviewed by Adam Barth. + + Previous CLs have made the Chromium embedder provide gesture fling + curve implementation to WebKit. Consequently no platform uses the + gestural fling code currently found in WebKit. This CL removes this code. + + Code removal only: covered by existing tests. + + * CMakeLists.txt: + * GNUmakefile.list.am: + * WebCore.gypi: + * platform/ActivePlatformGestureAnimation.cpp: Removed. + * platform/ActivePlatformGestureAnimation.h: Removed. + * platform/PlatformGestureCurve.h: Removed. + * platform/PlatformGestureCurveTarget.h: Removed. + * platform/ScrollAnimatorNone.cpp: References to removed code removed. + * platform/ScrollAnimatorNone.h: + * platform/TouchFlingPlatformGestureCurve.cpp: Removed. + * platform/TouchFlingPlatformGestureCurve.h: Removed. + * platform/WheelFlingPlatformGestureCurve.cpp: Removed. + * platform/WheelFlingPlatformGestureCurve.h: Removed. + * platform/chromium/support/PlatformGestureCurveFactory.cpp: Removed. + * platform/chromium/support/PlatformGestureCurveFactory.h: Removed. + * platform/chromium/support/WebFlingAnimatorToGestureCurveAdapter.h: Removed. + +2012-11-28 Abhishek Arya <inferno@chromium.org> + + Heap-use-after-free in WebCore::EventHandler::handleMousePressEvent + https://bugs.webkit.org/show_bug.cgi?id=101098 + + Reviewed by Adam Barth. + + |subframe| can be blown away inside passMousePressEventToSubframe + call. Use RefPtr to protect it in handleMousePressEvent function. + We use similar approach in handleMouseMoveEvent function. + + No new tests. Test is extremely time dependent and needs to trigger + interaction gesture. Reproduced on ClusterFuzz. + + * page/EventHandler.cpp: + (WebCore::EventHandler::handleMousePressEvent): + +2012-11-28 Tom Sepez <tsepez@chromium.org> + + XSSAuditor bypass with script src=data: URL ending in <!-- + https://bugs.webkit.org/show_bug.cgi?id=103548 + + Reviewed by Adam Barth. + + This fixes an additional case where characters from the page itself are + included with the snippet to match against the reflected vector, and the + JS remains legitimate because of a <!--- comment. Truncate the snippet at + such a comment. + + Test: http/tests/security/xssAuditor/script-tag-with-source-data-url3.html + + * html/parser/XSSAuditor.cpp: + (WebCore::XSSAuditor::decodedSnippetForAttribute): + +2012-11-28 Abhishek Arya <inferno@chromium.org> + + Heap-use-after-free in WebCore::RenderLayerModelObject::hasSelfPaintingL +ayer + https://bugs.webkit.org/show_bug.cgi?id=101970 + + Reviewed by David Hyatt. + + RenderInline::splitFlow and RenderBlock::splitFlow re-use |pre| + block in some cases. In those cases, |pre| might hold floating objects + and those floating descendants might get moved to |post| block. If + the |pre| block does not get a layout later, then the floating + descendant will never get removed since it is now part of |post| + ancestor chain. We don't want failing-to-layout bugs turned into + security bugs and hence clear floating objects list since we expect + it to be rebuilt in subsequent layout. + + Test: fast/block/float/float-not-removed-from-pre-block.html + + * rendering/RenderBlock.cpp: + (WebCore::RenderBlock::splitFlow): Call removeFloatingObjects on |pre| block. + (WebCore::RenderBlock::removeFloatingObjects): Clear all floating objects from our list. + (WebCore): + * rendering/RenderBlock.h: + (RenderBlock): + * rendering/RenderInline.cpp: + (WebCore::RenderInline::splitFlow): Call removeFloatingObjects on |pre| block. + +2012-11-28 Mark Pilgrim <pilgrim@chromium.org> + + [Chromium] Remove pluginsScriptableObject from PlatformSupport + https://bugs.webkit.org/show_bug.cgi?id=103542 + + Reviewed by Adam Barth. + + Part of a refactoring series. See tracking bug 82948. + + * bindings/v8/ScriptController.cpp: + (WebCore::ScriptController::createScriptInstanceForWidget): + * platform/chromium/PlatformSupport.h: + (PlatformSupport): + * plugins/PluginViewBase.h: + (PluginViewBase): + (WebCore::PluginViewBase::scriptableObject): + +2012-11-28 Otto Derek Cheung <otcheung@rim.com> + + [BlackBerry] CookieJarBlackBerry will use document settings for cookiesEnabled + https://bugs.webkit.org/show_bug.cgi?id=103560 + + Reviewed by Rob Buis. + + PR 253490 + + CookieJarBlackBerry will now use page settings to check whether + cookie is enabled. + + Tested setting/reading cookies on different client cookie settings using + javascript and HTTP. Cookie behaviour is now back to spec. + + * loader/blackberry/CookieJarBlackBerry.cpp: + (WebCore::cookies): + (WebCore::cookieRequestHeaderFieldValue): + +2012-11-28 Mark Pilgrim <pilgrim@chromium.org> + + [Chromium][Win] Remove ensureFontLoaded from PlatformSupport + https://bugs.webkit.org/show_bug.cgi?id=97696 + + Reviewed by Adam Barth. + + Move ensureFontLoaded() from PlatformSupport to + FontPlatformDataChromiumWin. Part of a refactoring series; see + tracking bug 82948. + + * platform/chromium/PlatformSupport.h: + (PlatformSupport): + * platform/graphics/chromium/FontCacheChromiumWin.cpp: + (WebCore::fontContainsCharacter): + * platform/graphics/chromium/FontChromiumWin.cpp: + (WebCore::drawGlyphsWin): + * platform/graphics/chromium/FontPlatformDataChromiumWin.cpp: + (WebCore::FontPlatformData::scriptFontProperties): + (WebCore): + (WebCore::FontPlatformData::ensureFontLoaded): + * platform/graphics/chromium/FontPlatformDataChromiumWin.h: + (FontPlatformData): + * platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp: + (WebCore::getGlyphIndices): + (WebCore::fillBMPGlyphs): + * platform/graphics/chromium/SimpleFontDataChromiumWin.cpp: + (WebCore::SimpleFontData::platformInit): + (WebCore::SimpleFontData::determinePitch): + (WebCore::SimpleFontData::platformBoundsForGlyph): + (WebCore::SimpleFontData::platformWidthForGlyph): + * platform/graphics/chromium/UniscribeHelperTextRun.cpp: + (WebCore::UniscribeHelperTextRun::tryToPreloadFont): + * platform/graphics/skia/SkiaFontWin.cpp: + (WebCore::paintSkiaText): + +2012-11-28 peavo@outlook.com <peavo@outlook.com> + + [WinCairo] Crash when requesting favicon. + https://bugs.webkit.org/show_bug.cgi?id=102689 + + Reviewed by Brent Fulgham. + + * platform/graphics/BitmapImage.h: Made frameCount() method virtual, subclasses made for testing can then override it. + * platform/graphics/win/ImageCairoWin.cpp: + (WebCore::BitmapImage::getHBITMAPOfSize): Added NULL pointer check. + (WebCore::BitmapImage::drawFrameMatchingSourceSize): Added NULL pointer check. + +2012-11-28 Tony Chang <tony@chromium.org> + + Move internals.settings.setPageScaleFactor to internals.setPageScaleFactor + https://bugs.webkit.org/show_bug.cgi?id=103559 + + Reviewed by Jochen Eisinger. + + This method doesn't alter the Settings object, so move it to internals. + + No new tests, this is a refactor. + + * testing/InternalSettings.cpp: Remove. + * testing/InternalSettings.h: Remove. + * testing/InternalSettings.idl: Remove. + * testing/Internals.cpp: + (WebCore::Internals::resetToConsistentState): Add reset code. + (WebCore::Internals::setPageScaleFactor): Add method. + * testing/Internals.h: Add method. + * testing/Internals.idl: Add method. + +2012-11-28 Alexandru Chiculita <achicu@adobe.com> + + [CSS Regions] Elements using transforms are not repainted correctly when rendered in a region + https://bugs.webkit.org/show_bug.cgi?id=102826 + + Reviewed by Dave Hyatt. + + Follow up update of a comment after the patch was landed by the commit queue in r135921. + + * rendering/RenderObject.cpp: + (WebCore::RenderObject::containerForRepaint): + +2012-11-28 Christophe Dumez <christophe.dumez@intel.com> + + CSS3 Multicolumn: column-span should accept value 'none' (instead of '1') + https://bugs.webkit.org/show_bug.cgi?id=101462 + + Reviewed by David Hyatt. + + According to the latest CSS3 Multi-column specification: + http://www.w3.org/TR/2011/CR-css3-multicol-20110412/#column-span + + column-span should accept values [ none | all ], instead of + [ 1 | all ]. This patch updates WebKit implementation to reflect + this change in the specification. The value 1 is still supported + for compatibility reasons and is mapped to none. + + No new tests, already covered by existing tests. + + * css/CSSComputedStyleDeclaration.cpp: + (WebCore::CSSComputedStyleDeclaration::getPropertyCSSValue): + * css/CSSParser.cpp: + (WebCore::CSSParser::parseValue): + * css/CSSPrimitiveValueMappings.h: + (WebCore::CSSPrimitiveValue::CSSPrimitiveValue): + (WebCore::CSSPrimitiveValue::operator ColumnSpan): + * rendering/style/RenderStyle.h: + * rendering/style/RenderStyleConstants.h: + +2012-11-28 Anton Vayvod <avayvod@chromium.org> + + Text Autosizing: Clusters should use width of LCA of their text nodes + https://bugs.webkit.org/show_bug.cgi?id=102562 + + Reviewed by Kenneth Rohde Christiansen. + + Many pages set a max-width on their content. So especially for the + RenderView, instead of just taking the width of |cluster| we find + the lowest common ancestor of the first and last descendant text node of + the cluster (i.e. the deepest wrapper block that contains all the text), + and use its width instead. + + Tests: fast/text-autosizing/cluster-with-narrow-lca-and-cluster.html + fast/text-autosizing/cluster-with-narrow-lca.html + fast/text-autosizing/cluster-with-wide-lca.html + fast/text-autosizing/list-item-out-of-flow.html + fast/text-autosizing/wide-in-narrow-overflow-scroll.html + + * rendering/TextAutosizer.cpp: + (WebCore::TextAutosizer::processCluster): use text nodes LCA instead of cluster for width calculation + (WebCore::TextAutosizer::isAutosizingContainer): list items that are out of parent list element's flow are valid containers (that therefore become clusters in isAutosizingCluster) + (WebCore::TextAutosizer::findDeepestBlockContainingAllText): searches for LCA of text nodes ignoring descendant clusters + (WebCore::TextAutosizer::findFirstTextLeafNotInCluster): searches for the first or the last (depending on specified direction) text leaf node in-order ignoring any descendant clusters + * rendering/TextAutosizer.h: new private methods declarations and an enum for tree traversal direction. + +2012-11-28 Sadrul Habib Chowdhury <sadrul@chromium.org> + + cleanup: Change some code to be cleaner, more readable and style conforming + https://bugs.webkit.org/show_bug.cgi?id=103543 + + Reviewed by Antonio Gomes. + + Use more appropriate function name and more meaningful variable names to make the code cleaner. + This is covered by existing tests. This does not make any behavioural changes, so no new tests. + + * page/EventHandler.cpp: + (WebCore::closestScrollableNodeInDocumentIfPossible): + (WebCore::EventHandler::handleWheelEvent): + +2012-11-28 Alexandru Chiculita <achicu@adobe.com> + + [CSS Regions] Crash when using hover and first-letter inside a flow-thread + https://bugs.webkit.org/show_bug.cgi?id=102957 + + Reviewed by David Hyatt. + + Some RenderObjects use a different path when they are destroyed. That's because they are dynamically + added just before layout happens and their parent is usually not their actual owner. In those cases the parent + will remove the object from the tree, but it's actually the owner that will destroy the object and all its + children. + + RenderFlowThread maintains a RenderBoxRegionInfo object for each RenderObject that is rendered inside the + flow-thread. When the RenderObject is removed from the RenderFlowThread, the associated RenderBoxRegionInfo object + also needs to be removed. + + In these special cases (list-marker, first-letter), the object itself was removed from the RenderFlowThread, + but its children were still left in the flow-thread. When the these special objects were later destroyed, + they will remove their own children. Removing their children means it will try to remove them from the + associated RenderFlowThread. However, in this cases there would be no link back to the parent flow-thread, + as the tree is now detached from the enclosing RenderFlowThread. + + Added code that recursively removes the whole children tree from the RenderFlowThread when the root is removed. + + Tests: fast/regions/firstletter-inside-flowthread.html + fast/regions/listmarker-inside-flowthread.html + + * rendering/RenderObject.cpp: + (WebCore::RenderObject::willBeRemovedFromTree): + (WebCore::RenderObject::removeFromRenderFlowThread): + (WebCore): + (WebCore::RenderObject::removeFromRenderFlowThreadRecursive): + * rendering/RenderObject.h: + (RenderObject): + +2012-11-28 Alexandru Chiculita <achicu@adobe.com> + + [CSS Regions] Auto-height regions will not calculate the height correctly when the content changes dynamically + https://bugs.webkit.org/show_bug.cgi?id=102954 + + Reviewed by David Hyatt. + + Whenever the flow changes, we need to reset the region computed auto-heights. + However, when we reset the region heights to "auto" or "un-computed", we also need to make + sure that all the region breaks are counted again, so that we split regions correctly during the new layout. + I've reused the m_regionsInvalidated property to force the flow do a complete layout. + + Test: fast/regions/autoheight-dynamic-update.html + + * rendering/RenderFlowThread.cpp: + (WebCore::RenderFlowThread::resetRegionsOverrideLogicalContentHeight): + +2012-11-28 Alexandru Chiculita <achicu@adobe.com> + + [CSS Regions] InRenderFlowThread returns false in the first setStyle + https://bugs.webkit.org/show_bug.cgi?id=102839 + + Reviewed by Dave Hyatt. + + Some render objects use the "inRenderFlowThread" during the first styleWillChange/styleDidChange. + The first call to these methods comes from NodeRendererFactory::createRenderer. That happens before the RenderObject is + attached to the parent renderer, meaning that inRenderFlowThread is false. That means a RenderLayerBacking will be + created for renderers inside the RenderFlowThread, but composited layers inside the RenderFlowThread are not supported yet. + https://bugs.webkit.org/show_bug.cgi?id=84900 + + Test: fast/repaint/region-painting-composited-element.html + + * dom/NodeRenderingContext.cpp: + (WebCore::NodeRendererFactory::createRenderer): + Added code to propagate the inRenderFlowThread flag from the parent node before the style is set for the first time. + +2012-11-28 Dan Bernstein <mitz@apple.com> + + <rdar://problem/12645085> REGRESSION (r130851): With kerning enabled, a white-space: pre-wrap inline starting with tab+space has the wrong width + https://bugs.webkit.org/show_bug.cgi?id=103541 + + Reviewed by Anders Carlsson. + + Test: fast/text/tab-with-kerning.html + + When kerning is enabled, words are measured with their trailing space, then the width of a + space is subtracted. The logic to do this was incorrectly being invoked even when the + trailing whitespace character was a tab or a newline. + + * rendering/RenderBlockLineLayout.cpp: + (WebCore::RenderBlock::LineBreaker::nextLineBreak): Changed to check only for the space + character, not other space-like characters. + +2012-11-28 Nate Chapin <japhet@chromium.org> + + Move empty loading to DocumentLoader, simplify FrameLoader::init() + https://bugs.webkit.org/show_bug.cgi?id=101512 + + Reviewed by Adam Barth. + + No new tests, though several outputs changed because we no longer send resource + load callbacks for empty loads. + + * loader/DocumentLoader.cpp: + (WebCore::DocumentLoader::DocumentLoader): + (WebCore::DocumentLoader::~DocumentLoader): + (WebCore::DocumentLoader::finishedLoading): + (WebCore::DocumentLoader::commitData): + (WebCore::DocumentLoader::clearMainResourceLoader): + (WebCore::DocumentLoader::isLoadingInAPISense): + (WebCore::DocumentLoader::documentURL): + (WebCore::DocumentLoader::isLoadingMainResource): + (WebCore::DocumentLoader::maybeLoadEmpty): + (WebCore): + (WebCore::DocumentLoader::startLoadingMainResource): Handle empty main resource + loads directly here. + * loader/DocumentLoader.h: + (WebCore::DocumentLoader::serverRedirectSourceForHistory): + (DocumentLoader): + * loader/FrameLoader.cpp: + (WebCore::FrameLoader::FrameLoader): Initialize some variables whose values + were previously being reset in init(). Given that the FrameLoader is in + an inconsistent state before init() is called anyway, there doesn't seem + to be a disadvantage to just initializing them to their post-init() values. + (WebCore::FrameLoader::init): Just call startLoadingMainResource(), instead of + doing a bunch of direct calls to functions FrameLoader shouldn't know about. + * loader/FrameLoaderStateMachine.cpp: + (WebCore::FrameLoaderStateMachine::FrameLoaderStateMachine): + * loader/FrameLoaderStateMachine.h: + * loader/MainResourceLoader.cpp: Throughout, remove the concept of an empty load. + (WebCore::MainResourceLoader::loadNow): This only returned true when an empty + load got deferred, which won't happen now. Return void and always treat + as returning false. + * loader/MainResourceLoader.h: + (MainResourceLoader): + +2012-11-28 Antoine Quint <graouts@apple.com> + + Calling .removeCue() for a cue that was never added should raise a NOT_FOUND_ERR + https://bugs.webkit.org/show_bug.cgi?id=103412 + + Reviewed by Eric Carlson. + + Updating the .removeCue() implementation to match the latest spec. This means we now + raise a NOT_FOUND_ERR exception when trying to remove a cue that wasn't present in the + cue list instead of a INVALID_STATE_ERR exception like the spec used to mandate. + + * html/track/TextTrack.cpp: + (WebCore::TextTrack::removeCue): + +2012-11-28 Zeno Albisser <zeno@webkit.org> + + [Qt][Win] Enable usage of QTWEBKIT_PLUGIN_PATH. + https://bugs.webkit.org/show_bug.cgi?id=103529 + + This patch enables the same behavior for Windows + as it is currently implemented for all other operating + systems supported by Qt. + Directories listed in the environment variable + QTWEBKIT_PLUGIN_PATH are being searched for additional + plugins. + The only difference is that directories on Windows + need to be separated by a semicolon instead of a colon. + + Reviewed by Kenneth Rohde Christiansen. + + * plugins/win/PluginDatabaseWin.cpp: + (WebCore): + (WebCore::addQtWebKitPluginPath): + (WebCore::PluginDatabase::defaultPluginDirectories): + +2012-11-28 Adam Barth <abarth@webkit.org> + + [v8] 4% regression in dom_traverse tests + https://bugs.webkit.org/show_bug.cgi?id=102858 + + Unreviewed. + + This patch is a manual rollout of + http://trac.webkit.org/changeset/134729. We can't do a mechanical + rollout because V8DOMWrapper::getCachedWrapper no longer exists. + + * bindings/scripts/CodeGeneratorV8.pm: + (GenerateHeader): + +2012-11-28 Denis Nomiyama <d.nomiyama@samsung.com> + + Removed extra definition of GLXContext. + https://bugs.webkit.org/show_bug.cgi?id=103500 + + Reviewed by Martin Robinson. + + A minor cleanup to remove a spare definition of GLXContext in GLContextGLX.h. + + No new tests. This doesn't change any behavior. + + * platform/graphics/glx/GLContextGLX.h: + +2012-11-28 Sadrul Habib Chowdhury <sadrul@chromium.org> + + Fix gesture scrolling when the target-element of scroll-begin is removed + https://bugs.webkit.org/show_bug.cgi?id=103355 + + Reviewed by Antonio Gomes. + + When a touch-scroll starts, the node under the touch-point gets latched, and + subsequent scroll-update events are dispatched to that node. But if the node is + removed while the gesture event is in progress (e.g. in a dynamically updated + list), then the scrolling stops, although there are enough elements to still + enable scrolling. So instead of latching on to the node immediately under the + touch point, latch on to the scrollable node under the touch point. + + Test: fast/events/touch/gesture/touch-gesture-scroll-remove-node.html + + * page/EventHandler.cpp: + (WebCore::getClosestScrollableNodeInDocumentIfPossible): + (WebCore): + (WebCore::EventHandler::handleWheelEvent): + +2012-11-28 Anton Obzhirov <a.obzhirov@samsung.com> + + Fix .libs/libwebkitgtk-3.0.so: undefined reference to `WebCore::validationMessageBadInputForNumberText(). + https://bugs.webkit.org/show_bug.cgi?id=103509 + + Reviewed by Philippe Normand. + + GTK build fix after r136001. + + * platform/gtk/LocalizedStringsGtk.cpp: + (WebCore::validationMessageBadInputForNumberText): + (WebCore): + +2012-11-28 Byungwoo Lee <bw80.lee@samsung.com> + + [EFL] Use mutex locker in wakeUp() to ensure thread-safety. + https://bugs.webkit.org/show_bug.cgi?id=101132 + + Reviewed by Gyuyoung Kim. + + Add mutex locker for the ecore pipe to ensure thread-safety of + RunLoop::wakeUp(). + + RunLoop::wakeUp() can be called by multiple thread. It uses + ecore_pipe_write() function but the function is not thread-safe. + + * platform/RunLoop.h: + (RunLoop): + * platform/efl/RunLoopEfl.cpp: + (WebCore::RunLoop::wakeUp): + +2012-11-28 Ryuan Choi <ryuan.choi@gmail.com> + + [EFL] Refactor theme to choose whether to support foreground color of selection + https://bugs.webkit.org/show_bug.cgi?id=102037 + + Reviewed by Kenneth Rohde Christiansen. + + If foreground selection color is supported, selected text is painted to + SelectionForegroundColor instead of text color. If not, text can be painted + to text color. + + However, EFL port does not have a way to disable support of foreground + selection color. So this patch refactors color classes of theme from + active and inactive to foreground and background in order to disable support + of foreground selection color when foreground color class is not specified. + + * platform/efl/RenderThemeEfl.cpp: + (WebCore::fillColorsFromEdjeClass): + Returned false without error message when colorClass is not specified. + (WebCore::RenderThemeEfl::setColorFromThemeClass): + (WebCore::RenderThemeEfl::loadTheme): + (WebCore::RenderThemeEfl::RenderThemeEfl): + (WebCore::RenderThemeEfl::supportsSelectionForegroundColors): + (WebCore): + * platform/efl/RenderThemeEfl.h: + (RenderThemeEfl): + +2012-11-28 Allan Sandfeld Jensen <allan.jensen@digia.com> + + Move childrenAffectedBy bits from RenderStyle to Element + https://bugs.webkit.org/show_bug.cgi?id=101448 + + Unreviewed buildfix. + + To use renderStyle() on some Macs we need to include NodeRenderStyle.h. + + * dom/ContainerNode.cpp: + +2012-11-28 Allan Sandfeld Jensen <allan.jensen@digia.com> + + Move childrenAffectedBy bits from RenderStyle to Element + https://bugs.webkit.org/show_bug.cgi?id=101448 + https://bugs.webkit.org/show_bug.cgi?id=98021 + + Reviewed by Antti Koivisto. + + Moves facts observed about restyling dependencies out of RenderStyle and + into RareData for Node and Element. This also enables further cleanup + in related code that tried to deal with problems caused with the placement + of the data. + + Test: fast/css/nth-child-not-in-rightmost.html + + * css/SelectorChecker.cpp: + (WebCore::SelectorChecker::checkSelector): + (WebCore::SelectorChecker::checkOneSelector): + * css/SiblingTraversalStrategies.h: + (WebCore::DOMSiblingTraversalStrategy::countElementsBefore): + * css/StyleResolver.cpp: + (WebCore::StyleResolver::sortAndTransferMatchedRules): + (WebCore::StyleResolver::canShareStyleWithElement): + (WebCore::parentElementPreventsSharing): + (WebCore::StyleResolver::locateSharedStyle): + * dom/ContainerNode.cpp: + (WebCore::ContainerNode::setActive): + (WebCore::ContainerNode::setHovered): + * dom/Element.cpp: + (WebCore::Element::detach): + (WebCore::Element::recalcStyle): + (WebCore::checkForEmptyStyleChange): + (WebCore::checkForSiblingStyleChanges): + (WebCore::Element::setChildrenAffectedByHover): + (WebCore::Element::setChildrenAffectedByActive): + (WebCore::Element::setChildrenAffectedByDrag): + (WebCore::Element::setChildrenAffectedByFirstChildRules): + (WebCore::Element::setChildrenAffectedByLastChildRules): + (WebCore::Element::setChildrenAffectedByDirectAdjacentRules): + (WebCore::Element::setChildrenAffectedByForwardPositionalRules): + (WebCore::Element::setChildrenAffectedByBackwardPositionalRules): + (WebCore::Element::setChildIndex): + (WebCore::Element::rareDataStyleAffectedByEmpty): + (WebCore::Element::rareDataChildrenAffectedByHover): + (WebCore::Element::rareDataChildrenAffectedByActive): + (WebCore::Element::rareDataChildrenAffectedByDrag): + (WebCore::Element::rareDataChildrenAffectedByFirstChildRules): + (WebCore::Element::rareDataChildrenAffectedByLastChildRules): + (WebCore::Element::rareDataChildrenAffectedByDirectAdjacentRules): + (WebCore::Element::rareDataChildrenAffectedByForwardPositionalRules): + (WebCore::Element::rareDataChildrenAffectedByBackwardPositionalRules): + (WebCore::Element::rareDataChildIndex): + * dom/Element.h: + (Element): + (WebCore::Element::styleAffectedByEmpty): + (WebCore::Element::childrenAffectedByHover): + (WebCore::Element::childrenAffectedByActive): + (WebCore::Element::childrenAffectedByDrag): + (WebCore::Element::childrenAffectedByPositionalRules): + (WebCore::Element::childrenAffectedByFirstChildRules): + (WebCore::Element::childrenAffectedByLastChildRules): + (WebCore::Element::childrenAffectedByDirectAdjacentRules): + (WebCore::Element::childrenAffectedByForwardPositionalRules): + (WebCore::Element::childrenAffectedByBackwardPositionalRules): + (WebCore::Element::childIndex): + * dom/ElementRareData.h: + (ElementRareData): + (WebCore::ElementRareData::resetComputedStyle): + (WebCore::ElementRareData::resetDynamicRestyleObservations): + * dom/Node.cpp: + (WebCore::Node::diff): + * dom/NodeRareData.h: + (WebCore::NodeRareData::NodeRareData): + (WebCore::NodeRareData::childrenAffectedByHover): + (WebCore::NodeRareData::setChildrenAffectedByHover): + (WebCore::NodeRareData::childrenAffectedByActive): + (WebCore::NodeRareData::setChildrenAffectedByActive): + (WebCore::NodeRareData::childrenAffectedByDrag): + (WebCore::NodeRareData::setChildrenAffectedByDrag): + (NodeRareData): + (WebCore::NodeRareData::childrenAffectedByFirstChildRules): + (WebCore::NodeRareData::setChildrenAffectedByFirstChildRules): + (WebCore::NodeRareData::childrenAffectedByLastChildRules): + (WebCore::NodeRareData::setChildrenAffectedByLastChildRules): + (WebCore::NodeRareData::childrenAffectedByDirectAdjacentRules): + (WebCore::NodeRareData::setChildrenAffectedByDirectAdjacentRules): + (WebCore::NodeRareData::childrenAffectedByForwardPositionalRules): + (WebCore::NodeRareData::setChildrenAffectedByForwardPositionalRules): + (WebCore::NodeRareData::childrenAffectedByBackwardPositionalRules): + (WebCore::NodeRareData::setChildrenAffectedByBackwardPositionalRules): + (WebCore::NodeRareData::childIndex): + (WebCore::NodeRareData::setChildIndex): + * dom/NodeRenderingContext.cpp: + (WebCore::NodeRenderingContext::createRendererForElementIfNeeded): + * page/TouchAdjustment.cpp: + (WebCore::TouchAdjustment::nodeRespondsToTapGesture): + * rendering/RenderObject.cpp: + (WebCore::RenderObject::updateDragState): + * rendering/style/RenderStyle.cpp: + (WebCore::RenderStyle::copyNonInheritedFrom): + * rendering/style/RenderStyle.h: + +2012-11-28 Zeno Albisser <zeno@webkit.org> + + GraphicsSurface: Implement usage of GraphicsSurface for WebGL in WK1. + https://bugs.webkit.org/show_bug.cgi?id=103497 + + Unreviewed buildfix. + + Any usage of GraphicsSurface needs to be wrapped with USE(GRAPHICS_SURFACE). + + * platform/graphics/qt/GraphicsContext3DQt.cpp: + (WebCore::GraphicsContext3DPrivate::paintToTextureMapper): + +2012-11-28 Zeno Albisser <zeno@webkit.org> + + GraphicsSurface: Implement usage of GraphicsSurface for WebGL in WK1. + https://bugs.webkit.org/show_bug.cgi?id=103497 + + This is a temporary workaround for an issue with GraphicsSurfaceMac. + GraphicsSurfaceMac is currently implemented using CGL only. + CGL does not allow us to properly restore the NSView a context was made current with. + Therefore we have to go through QOpenGLContext to ensure the context + is being restored correctly. + As soon as we are updating GraphicsSurfaceMac to use NSOpenGL, + we should revert this patch. + + Reviewed by Simon Hausmann. + + * platform/graphics/qt/GraphicsContext3DQt.cpp: + (WebCore::GraphicsContext3DPrivate::paintToTextureMapper): + +2012-11-28 Zeno Albisser <zeno@webkit.org> + + GraphicsSurface: Implement usage of GraphicsSurface for WebGL in WK1. + https://bugs.webkit.org/show_bug.cgi?id=103497 + + Using GraphicsSurface for WebGL in WK1 allows us to share + the code with the WK2 implementation. + + Reviewed by Simon Hausmann. + + * platform/graphics/qt/GraphicsContext3DQt.cpp: + (WebCore::GraphicsContext3DPrivate::GraphicsContext3DPrivate): + Remove obsolete code. + (WebCore::GraphicsContext3DPrivate::paintToTextureMapper): + After blitting the multisample framebuffer, + we can copy the contents onto the GraphicsSurface. + Right after that we can use the GraphicsSurface + as a texture origin to paint to the TextureMapper. + Flags related to flipping and blending are being resolved + by GraphicsSurface, and do not need to be handled here anymore. + (WebCore::GraphicsContext3DPrivate::copyToGraphicsSurface): + Remove a redundant makeCurrentIfNeeded call. + The original context is being restored by + blitMultisampleFramebufferAndRestoreContext anyway. + Instead of explicitly calling swapBuffers here, + we call swapBuffers on the GraphicsSurface implicitly + after in GraphicsSurfacePrivate::copyFromTexture(). + * platform/graphics/surfaces/mac/GraphicsSurfaceMac.cpp: + Add members to hold the reading end texture IDs. + The texture on the reading side are in a different + context than the texture on the writing side. + By using GraphicsSurface in WK1 we have to distinguish + between these textures, as a single instance serves + for reading and writing. + (WebCore::GraphicsSurfacePrivate::GraphicsSurfacePrivate): + (WebCore::GraphicsSurfacePrivate::~GraphicsSurfacePrivate): + (WebCore::GraphicsSurfacePrivate::swapBuffers): + (WebCore::GraphicsSurfacePrivate::copyFromTexture): + Add an implicit call to swapBuffers(). + (WebCore::GraphicsSurfacePrivate::frontBufferTextureID): + (GraphicsSurfacePrivate): + * platform/graphics/surfaces/qt/GraphicsSurfaceGLX.cpp: + (WebCore::GraphicsSurfacePrivate::GraphicsSurfacePrivate): + Add a flag to distinguish between sending and receiving/reading + side of the surface. This flag is being initialized in the constructor + which is the only place where we know if an instance will be used for + writing or reading. + The purpose of this flag is to avoid erroneously swapping the buffers + on the reading side. We can no longer rely on m_xPixmap for this purpose. + (WebCore::GraphicsSurfacePrivate::swapBuffers): + (WebCore::GraphicsSurfacePrivate::copyFromTexture): + (WebCore::GraphicsSurfacePrivate::glxPixmap): + Lazily create the GLX pixmap on demand. + (GraphicsSurfacePrivate): + (WebCore::GraphicsSurface::platformImport): + +2012-11-28 Roger Fong <roger_fong@apple.com> + + Unreviewed. Fix extra spaces in SimpleFontData::initGDIFont(). + + * platform/graphics/win/SimpleFontDataWin.cpp: + (WebCore::SimpleFontData::initGDIFont): + +2012-11-28 Dan Carney <dcarney@google.com> + + [V8] Crash wrapping media element when MediaPlayer isn't available + https://bugs.webkit.org/show_bug.cgi?id=103431 + + Reviewed by Kentaro Hara. + + Call HTMLElement::createWrapper directly when dispatching a + disabled MediaElement wrap. + + No new tests. Testing this must apparently be manual. + + * bindings/scripts/CodeGeneratorV8.pm: + (GenerateHeader): + * dom/make_names.pl: + (printWrapperFunctions): + (printWrapperFactoryHeaderFile): + +2012-11-28 Roger Fong <roger_fong@apple.com> + + Initialize identity matrix in SimpleFontData::initGDIFont() properly. + https://bugs.webkit.org/show_bug.cgi?id=103499 + <rdar://problem/12400700> + + Reviewed by Timothy Horton. + + We are incorrectly initializing the matrix passed into GetGlyphOutline. + This patch fixes MAT2 initialization to match the way we initialize the + identity matrix in SimpleFontData::boundsForGDIGlyph and SimpleFontData::widthForGDIGlyph. + + * platform/graphics/win/SimpleFontDataWin.cpp: + (WebCore::SimpleFontData::initGDIFont): + +2012-11-28 Huang Dongsung <luxtella@company100.net> + + [Texmap] REGRESSION(r135620) QtTestBrowser crashes on Google-gravity. + https://bugs.webkit.org/show_bug.cgi?id=103410 + + Reviewed by Noam Rosenthal. + + GraphicsLayerTextureMapper::updateBackingStore() should return early + before TextureMapper is set. + + GraphicsLayer::FlushCompositingState() can be called by RenderLayerBacking. It + means this method can be called before creating TextureMapper. So + TextureMapperLayer::flushCompositingState() checks and returns early if + TextureMapper was not created. + + However, GraphicsLayerTextureMapper::updateBackingStore() expects that TextureMapper + always exists. updateBackingStore should also return early when TextureMapper + was not created. + + No new tests. Covered by existing tests. + + * platform/graphics/texmap/GraphicsLayerTextureMapper.cpp: + (WebCore::GraphicsLayerTextureMapper::setNeedsDisplay): + (WebCore::GraphicsLayerTextureMapper::setNeedsDisplayInRect): + (WebCore::GraphicsLayerTextureMapper::didFlushCompositingState): + (WebCore::GraphicsLayerTextureMapper::prepareBackingStore): + +2012-11-28 Tommy Widenflycht <tommyw@google.com> + + Add basic implementation for MediaStreamAudioDestinationNode + https://bugs.webkit.org/show_bug.cgi?id=101815 + + Reviewed by Chris Rogers. + + Implements an audio destination node which has a MediaStream. + This can be added to a PeerConnection with peerConnection.addStream(). + Please see use case (3): + https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/webrtc-integration.html + + Test: webaudio/mediastreamaudiodestinationnode.html + + * Modules/webaudio/AudioContext.cpp: + (WebCore): + (WebCore::AudioContext::createMediaStreamDestination): + * Modules/webaudio/AudioContext.h: + (WebCore): + (AudioContext): + * Modules/webaudio/AudioContext.idl: + * Modules/webaudio/AudioNode.h: + * Modules/webaudio/MediaStreamAudioDestinationNode.cpp: Added. + (WebCore): + (WebCore::MediaStreamAudioDestinationNode::create): + (WebCore::MediaStreamAudioDestinationNode::MediaStreamAudioDestinationNode): + (WebCore::MediaStreamAudioDestinationNode::mediaStreamSource): + (WebCore::MediaStreamAudioDestinationNode::~MediaStreamAudioDestinationNode): + (WebCore::MediaStreamAudioDestinationNode::process): + (WebCore::MediaStreamAudioDestinationNode::reset): + * Modules/webaudio/MediaStreamAudioDestinationNode.h: Added. + (WebCore): + (MediaStreamAudioDestinationNode): + (WebCore::MediaStreamAudioDestinationNode::stream): + * Modules/webaudio/MediaStreamAudioDestinationNode.idl: Added. + * WebCore.gypi: + * platform/audio/AudioDestinationConsumer.h: Copied from Source/WebCore/platform/mediastream/MediaStreamSource.cpp. + (WebCore): + (AudioDestinationConsumer): + (WebCore::AudioDestinationConsumer::~AudioDestinationConsumer): + * platform/chromium/support/WebMediaStreamSource.cpp: + (WebKit::WebMediaStreamSource::extraData): + (WebKit::WebMediaStreamSource::setExtraData): + (WebKit::WebMediaStreamSource::requiresAudioConsumer): + (WebKit): + (ConsumerWrapper): + (WebKit::ConsumerWrapper::create): + (WebKit::ConsumerWrapper::consumer): + (WebKit::ConsumerWrapper::ConsumerWrapper): + (WebKit::ConsumerWrapper::consumeAudio): + (WebKit::WebMediaStreamSource::addAudioConsumer): + (WebKit::WebMediaStreamSource::removeAudioConsumer): + * platform/mediastream/MediaStreamSource.cpp: + (WebCore::MediaStreamSource::create): + (WebCore::MediaStreamSource::MediaStreamSource): + (WebCore::MediaStreamSource::addAudioConsumer): + (WebCore): + (WebCore::MediaStreamSource::removeAudioConsumer): + (WebCore::MediaStreamSource::consumeAudio): + * platform/mediastream/MediaStreamSource.h: + (WebCore): + (MediaStreamSource): + (WebCore::MediaStreamSource::requiresAudioConsumer): + (WebCore::MediaStreamSource::audioConsumers): + +2012-11-27 Mike West <mkwst@chromium.org> + + Improve WebSocketChannel connection failure console messages. + https://bugs.webkit.org/show_bug.cgi?id=103448 + + Reviewed by Adam Barth. + + When a WebSocket connection fails, the current implementation of + WebSocketChannel::fail binds the generated console message to the + document's URL, but doesn't give much indication as to the connection + itself. This patch adjusts the console message to explicitly show the + URL of the failed connection to give developers a better chance of + debugging and resolving errors. + + * Modules/websockets/WebSocketChannel.cpp: + (WebCore::WebSocketChannel::fail): + Drop the URL parameter from addConsoleMessage, in favour of adding + the WebSocketHandshake's URL to the message text. + +2012-11-27 Zan Dobersek <zandobersek@gmail.com> + + Unreviewed functionality fix, return the height in ImageFrame::height() + on non-Skia platforms. + + * platform/image-decoders/ImageDecoder.h: + (WebCore::ImageFrame::height): + +2012-11-27 Viatcheslav Ostapenko <v.ostapenko@samsung.com> + + Optimization in image decoding + https://bugs.webkit.org/show_bug.cgi?id=88424 + + Reviewed by Brent Fulgham. + + Optimization in image decoding. + Reduce branching and multiplications in GIF image decoding loops and functions. + Rebase and update of original patch by Misha Tyutyunik <michael.tyuytunik@nokia.com> + + Covered by existing tests. + + * platform/image-decoders/gif/GIFImageDecoder.cpp: + (WebCore::GIFImageDecoder::haveDecodedRow): + +2012-11-27 Michael Saboff <msaboff@apple.com> + + TextIterator unnecessarily converts 8 bit strings to 16 bits + https://bugs.webkit.org/show_bug.cgi?id=103295 + + Reviewed by Brent Fulgham. + + Changed TextIterator to use the contained string instead of calling characters() on that string. + Other sources of text, like emitCharacter() still use the contained UChar* buffer. + Added appendTextToStringBuilder() to append the text contents of the current iterator to a string builder + irrespective of the source of the text. + + No new tests as functionality covered by existing tests. + + * WebCore.exp.in: Updated plainText export and eliminated plainTextToMallocAllocatedBuffer export + * accessibility/AccessibilityObject.cpp: + (WebCore::AccessibilityObject::stringForVisiblePositionRange): Updated to use TextIterator::appendTextToStringBuilder() + * editing/TextIterator.cpp: + (WebCore::TextIterator::characterAt): New function to return the indexed character of the current TextIterator + (WebCore::TextIterator::appendTextToStringBuilder): Added method to append whatever the current text to a StringBuilder + (WebCore::TextIterator::emitText): Eliminated accessing the character data via characters(). + (WebCore::TextIterator::rangeFromLocationAndLength): Changed to use characterAt(). + (WebCore::plainText): Combined with plainTextToMallocAllocatedBuffer(). + * editing/TextIterator.h: + (WebCore::TextIterator::startOffset): New getter. + (WebCore::TextIterator::string): New getter. + (WebCore::TextIterator::characters): Updated to use correct test source. + * page/ContextMenuController.cpp: + (WebCore::selectionContainsPossibleWord): Changed to use characterAt(). + +2012-11-27 Noel Gordon <noel.gordon@gmail.com> + + Inline ImageFrame width() and height() + https://bugs.webkit.org/show_bug.cgi?id=103401 + + Reviewed by Brent Fulgham. + + Inline ImageFrame width() and height() to improve the performance of ImageFrame + function getAddr(x,y) per https://bugs.webkit.org/show_bug.cgi?id=88424#c38 + + No new tests. Covered by many existing tests. + + * platform/image-decoders/ImageDecoder.cpp: Remove width() and height() routines + since they now inlined in the ImageFrame class definition in ImageDecoder.h. + * platform/image-decoders/ImageDecoder.h: Add inline definitions of width() and + height() for all ports. + * platform/image-decoders/skia/ImageDecoderSkia.cpp: + (WebCore::ImageFrame::width): Remove. + (WebCore::ImageFrame::height): Remove. + +2012-11-27 Michael Pruett <michael@68k.org> + + Remove ASSERT_NOT_REACHED() from IDBCursorBackendImpl::postSuccessHandlerCallback() + https://bugs.webkit.org/show_bug.cgi?id=103461 + + Reviewed by Kentaro Hara. + + The assertion is applicable only to the Chromium port. + + Tests: storage/indexeddb/* + + * Modules/indexeddb/IDBCursorBackendImpl.h: + (WebCore::IDBCursorBackendImpl::postSuccessHandlerCallback): + +2012-11-27 Shinya Kawanaka <shinyak@chromium.org> + + [Refactoring] HasSelectorForClassStyleFunctor in Element.cpp seems verbose + https://bugs.webkit.org/show_bug.cgi?id=103474 + + Reviewed by Hajime Morita. + + The code introduced in r135174 looks verbose. We would like to make it simpler. + We have removed several inline functions and unnecessary structs. + + No new tests, simple refactoring. + + * dom/Element.cpp: + (WebCore): + (WebCore::checkSelectorForClassChange): + (WebCore::Element::classAttributeChanged): + (WebCore::Element::shouldInvalidateDistributionWhenAttributeChanged): + +2012-11-27 Julien Chaffraix <jchaffraix@webkit.org> + + Support proper <percent> / calc() resolution for grid items + https://bugs.webkit.org/show_bug.cgi?id=102968 + + Reviewed by Ojan Vafai. + + This change introduces a mechanism similar to logical height / width override + but for containing block. This is required as we don't have a renderer for the + grid area but any <percent> or calc() size should be resolved against the grid + area size (which is sized after the grid tracks). + + Tests: fast/css-grid-layout/calc-resolution-grid-item.html + fast/css-grid-layout/percent-resolution-grid-item.html + fast/css-grid-layout/percent-grid-item-in-percent-grid-track.html + fast/css-grid-layout/percent-grid-item-in-percent-grid-track-in-percent-grid.html + + * rendering/RenderBox.cpp: + (WebCore::RenderBox::willBeDestroyed): + Remove any containing block size override. + + (WebCore::RenderBox::overrideContainingBlockContentLogicalWidth): + (WebCore::RenderBox::overrideContainingBlockContentLogicalHeight): + (WebCore::RenderBox::hasOverrideContainingBlockLogicalWidth): + (WebCore::RenderBox::hasOverrideContainingBlockLogicalHeight): + (WebCore::RenderBox::setOverrideContainingBlockContentLogicalWidth): + (WebCore::RenderBox::setOverrideContainingBlockContentLogicalHeight): + (WebCore::RenderBox::clearContainingBlockOverrideSize): + Containing block override size functions. + + (WebCore::RenderBox::containingBlockLogicalWidthForContent): + Updated the function to check for any override logical width. + + (WebCore::RenderBox::containingBlockLogicalHeightForContent): + New function, similar to RenderBox::containingBlockLogicalWidthForContent. + + (WebCore::RenderBox::perpendicularContainingBlockLogicalHeight): + (WebCore::RenderBox::computePercentageLogicalHeight): + Updated these function to return overrideContainingBlockContentLogicalHeight as needed. + + (WebCore::RenderBox::computeReplacedLogicalHeightUsing): + (WebCore::RenderBox::availableLogicalHeightUsing): + Updated these functions to use the new containingBlockLogicalHeightForContent instead + of availableLogicalHeight. + + * rendering/RenderBox.h: + Added the previous new functions. + + * rendering/RenderGrid.cpp: + (WebCore::RenderGrid::layoutGridItems): + Updated to override the containing block size so that we properly size our grid items. + +2012-11-27 Kent Tamura <tkent@chromium.org> + + Fix build errors by r135955. + + * dom/ShadowRoot.cpp: Use struct instead of class. + * dom/TreeScope.cpp: Ditto. + +2012-11-27 Eugene Klyuchnikov <eustas@chromium.com> + + Web Inspector: [Timeline] "Show CPU activity on the ruler" settings checkbox does not take effect until Inspector restart + https://bugs.webkit.org/show_bug.cgi?id=102210 + + Reviewed by Pavel Feldman. + + The checkbox changes should take effect in the real time. + + * inspector/front-end/SettingsScreen.js: + (WebInspector.GenericSettingsTab): + Do not show checkpox if browser is not capable. + * inspector/front-end/TimelinePanel.js: + Added setting change listener. + +2012-11-27 Andreas Kling <akling@apple.com> + + Compile time size assertions for TreeScope, ShadowRoot and ElementAttributeData. + + Rubber-stamped by Anders Carlsson. + + * dom/ShadowRoot.cpp: + (SameSizeAsShadowRoot): + * dom/TreeScope.cpp: + (SameSizeAsTreeScope): + * dom/ElementAttributeData.cpp: Derp. + +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + There's a FIXME that we have too many FrameLoader::load*() functions. This patch consolidates 3 into 1. + There are still a few more load functions that will be consolidated later. Using FrameLoadRequest as + the interface into FrameLoader will also provide a place to pass in the initiator. Finally, this matches + the refactoring done with CachedResourceRequest and CachedResourceLoader. + + No new tests. No change in functionality. + + * WebCore.exp.in: + * loader/FrameLoadRequest.h: + (WebCore::FrameLoadRequest::FrameLoadRequest): + (WebCore::FrameLoadRequest::setLockHistory): These are former arguments to load(). + (WebCore::FrameLoadRequest::lockHistory): Ditto. + (FrameLoadRequest): + (WebCore::FrameLoadRequest::setShouldCheckNewWindowPolicy): Ditto. + (WebCore::FrameLoadRequest::shouldCheckNewWindowPolicy): Ditto. + (WebCore::FrameLoadRequest::substituteData): Ditto. + (WebCore::FrameLoadRequest::setSubstituteData): Ditto. + (WebCore::FrameLoadRequest::hasSubstituteData): Ditto. + * loader/FrameLoader.cpp: + (WebCore::FrameLoader::load): No change in behavior, just merged it all into one function. + * loader/FrameLoader.h: + (FrameLoader): + * page/DragController.cpp: + (WebCore::DragController::performDrag): + +2012-11-27 Jer Noble <jer.noble@apple.com> + + Unreviewed build fix; NSSize is not a CGSize in 32-bit. + + * platform/mac/WebCoreFullScreenWarningView.mm: + +2012-11-27 Dean Jackson <dino@apple.com> + + Attempted build fix for my last commit. The private member variable + is only used on MAC (at the moment) so guard it with #if PLATFORM. + I did this rather than having another constructor, because I expect + other platforms will follow the MAC code soon. + + * html/shadow/MediaControlElements.cpp: + (WebCore::MediaControlToggleClosedCaptionsButtonElement::MediaControlToggleClosedCaptionsButtonElement): + * html/shadow/MediaControlElements.h: + +2012-11-14 Jer Noble <jer.noble@apple.com> + + Add a new shared class WebCoreFullScreenPlaceholderView, for use in WebKit and WebKit2. + https://bugs.webkit.org/show_bug.cgi?id=102300 + + Reviewed by Anders Carlsson. + + Add a new shared class WebCoreFullScreenPlaceholderView, which presents the contents of the + WebView prior to full screen with a message informing the user how to exit from full screen mode. + + * platform/mac/WebCoreFullScreenPlaceholderView.mm: + (-[WebCoreFullScreenPlaceholderView initWithFrame:]): Create the warning view and set up the placeholder layer. + (-[WebCoreFullScreenPlaceholderView setContents:]): Pass along to content view layer. + (-[WebCoreFullScreenPlaceholderView contents]): Ditto. + (-[WebCoreFullScreenPlaceholderView setExitWarningVisible:]): Show or hide the exit warning. + (-[WebCoreFullScreenPlaceholderView mouseDown:]): Call the target with action. + + Add a localized string entry for the "click to exit" text: + * English.lproj/Localizable.strings: + * platform/LocalizedStrings.cpp: + (WebCore::clickToExitFullScreenText): + * platform/LocalizedStrings.h: + * English.lproj/Localizable.strings: + + Add the new files to the project and exports list: + * WebCore.exp.in: + * WebCore.xcodeproj/project.pbxproj: + +2012-11-27 Andreas Kling <akling@apple.com> + + Shrink ShadowRoot and TreeScope. + <http://webkit.org/b/103459> + + Reviewed by Antti Koivisto. + + We're creating ~1500 ShadowRoots on Apple's PLT3 content (from <input> and <textarea> elements) + and a lot of this is wasted space. + + Shrink ShadowRoot and TreeScope a bit by making TreeScope's DocumentOrderedMaps heap-allocated + and packing the counters on ShadowRoot harder together with the bits. + + 202kB progression on Membuster3. + + * dom/ShadowRoot.cpp: + (WebCore::ShadowRoot::ShadowRoot): + * dom/ShadowRoot.h: + (WebCore::ShadowRoot::countElementShadow): + (ShadowRoot): + * dom/TreeScope.cpp: + (WebCore::TreeScope::TreeScope): + (WebCore::TreeScope::getElementById): + (WebCore::TreeScope::addElementById): + (WebCore::TreeScope::removeElementById): + (WebCore::TreeScope::addImageMap): + (WebCore::TreeScope::removeImageMap): + (WebCore::TreeScope::getImageMap): + (WebCore::TreeScope::addLabel): + (WebCore::TreeScope::removeLabel): + (WebCore::TreeScope::labelElementForId): + * dom/TreeScope.h: + (WebCore::TreeScope::shouldCacheLabelsByForAttribute): + (TreeScope): + (WebCore::TreeScope::hasElementWithId): + (WebCore::TreeScope::containsMultipleElementsWithId): + +2012-11-14 Jer Noble <jer.noble@apple.com> + + Add a new shared class WebCoreFullScreenWarningView which presents a styled warning message. + https://bugs.webkit.org/show_bug.cgi?id=102299 + + Reviewed by Alexey Proskuryakov. + + Add a shared implementation of a warning view for use in WebKit and WebKit2. + + * platform/mac/WebCoreFullScreenWarningView.h: Added. + * platform/mac/WebCoreFullScreenWarningView.mm: Added. + (-[WebCoreFullScreenWarningView initWithTitle:]): Create the view. + + Add the new files to the project and exports list: + * WebCore.exp.in: + * WebCore.xcodeproj/project.pbxproj: + +2012-11-27 Dean Jackson <dino@apple.com> + + Make track list control active + https://bugs.webkit.org/show_bug.cgi?id=101670 + + Reviewed by Eric Carlson. + + Hook up the event handler for the captions menu so that it enables or + disables tracks in the associated HTMLMediaElement. + + Test: media/video-controls-captions-trackmenu.html + + * html/HTMLMediaElement.cpp: + (WebCore::HTMLMediaElement::toggleTrackAtIndex): New method to toggle the state of a track, by index. + * html/HTMLMediaElement.h: + (HTMLMediaElement): Ditto. + (WebCore::HTMLMediaElement::textTracksOffIndex): Static method to return the "Off" value. + * html/shadow/MediaControlElements.cpp: + (WebCore::trackListIndexForElement): Helper function to take a track list <li> element and return the value of the custom attribute. + (WebCore::MediaControlToggleClosedCaptionsButtonElement::updateDisplayType): Toggle the state of the button based on captions visibility. + (WebCore::MediaControlToggleClosedCaptionsButtonElement::defaultEventHandler): On Mac platforms show the captions menu. On other platforms, toggle captions. + (WebCore::MediaControlClosedCaptionsTrackListElement::MediaControlClosedCaptionsTrackListElement): Now has a reference to the controls. + (WebCore::MediaControlClosedCaptionsTrackListElement::create): + (WebCore::MediaControlClosedCaptionsTrackListElement::defaultEventHandler): When the user clicks on a track list item, look + for the custom attribute that identifies the associated track, and then toggle that track. + (WebCore::MediaControlClosedCaptionsTrackListElement::updateDisplay): Set a class on the track list elements so they can be + styled by the injected CSS (with tick marks to represent visibility). + (WebCore::MediaControlClosedCaptionsTrackListElement::resetTrackListMenu): When building the list of track menu items, add + a custom HTML attribute to the element so that the corresponding track can be found in the event handler. + * html/shadow/MediaControlElements.h: + (MediaControlClosedCaptionsTrackListElement): Add a list of elements representing the track list. + * html/shadow/MediaControlsApple.cpp: + (WebCore::MediaControlsApple::createControls): + (WebCore::MediaControlsApple::changedClosedCaptionsVisibility): Make sure to update the track menu. + (WebCore::MediaControlsApple::reset): + * html/shadow/MediaControlsApple.h: + (MediaControlsApple): + +2012-11-27 Joshua Bell <jsbell@chromium.org> + + IndexedDB: Simplify transaction timers and event tracking + https://bugs.webkit.org/show_bug.cgi?id=102984 + + Reviewed by Tony Chang. + + Now that the transaction "commit" decision is made on the front-end, the back end no-longer + needs to be aware of when individual IDBRequests have dispatched to script or track pending + events (except for preemptive ones like createIndex). This also lets two timers be collapsed + into one which significantly simplifies the code flow in IDBTransactionBackendImpl. + + No new tests - just simplification. Exercised by storage/indexeddb/transaction-*.html etc. + + * Modules/indexeddb/IDBCursorBackendImpl.cpp: + (WebCore::IDBCursorBackendImpl::prefetchContinueInternal): No more tracking. + (WebCore::IDBCursorBackendImpl::prefetchReset): No more tracking. + * Modules/indexeddb/IDBDatabaseBackendImpl.cpp: + (WebCore::IDBDatabaseBackendImpl::createObjectStoreInternal): No more tracking. + (WebCore::IDBDatabaseBackendImpl::deleteObjectStoreInternal): No more tracking. + * Modules/indexeddb/IDBObjectStoreBackendImpl.cpp: + (WebCore::IDBObjectStoreBackendImpl::setIndexesReadyInternal): No more tracking. + (WebCore::IDBObjectStoreBackendImpl::createIndexInternal): No more tracking. + (WebCore::IDBObjectStoreBackendImpl::deleteIndexInternal): No more tracking. + * Modules/indexeddb/IDBRequest.cpp: + (WebCore::IDBRequest::dispatchEvent): Order must be: + 1. request is unregistered from transaction (so request list may be empty) + 2. abort transaction if event being dispatched was an error + 3. deactivate transaction (which may commit if #1 left it empty and #2 didn't abort) + * Modules/indexeddb/IDBTransactionBackendImpl.cpp: + (WebCore::IDBTransactionBackendImpl::IDBTransactionBackendImpl): Need to track if commit + was requested; previously the front end would have triggered an event timer which, on + completion, would be the signal that the front end was finished. + (WebCore::IDBTransactionBackendImpl::scheduleTask): Schedule a timer to service the new + task, if necessary. + (WebCore::IDBTransactionBackendImpl::abort): + (WebCore::IDBTransactionBackendImpl::hasPendingTasks): + (WebCore::IDBTransactionBackendImpl::commit): + (WebCore::IDBTransactionBackendImpl::taskTimerFired): Picks up "commit" responsibilities + from the now deleted taskEventTimerFired, if everything is truly complete done. + * Modules/indexeddb/IDBTransactionBackendImpl.h: + (IDBTransactionBackendImpl): + * Modules/indexeddb/IDBTransactionBackendInterface.h: + (WebCore::IDBTransactionBackendInterface::didCompleteTaskEvents): Removed from interface. + +2012-11-27 Kentaro Hara <haraken@chromium.org> + + [V8] Replace toWebCoreString()/toWebCoreAtomicString() in CodeGeneratorV8.pm with V8StringResource + https://bugs.webkit.org/show_bug.cgi?id=103391 + + Reviewed by Adam Barth. + + This is an incremental effort for fixing bug 103331. + I confirmed that this patch causes no performance regression + for the micro benchmarks (https://bugs.webkit.org/attachment.cgi?id=176178). + + No tests. No change in behavior. + + * bindings/scripts/CodeGeneratorV8.pm: + (GenerateNormalAttrSetter): + (GenerateEventListenerCallback): + * bindings/scripts/test/V8/V8TestEventTarget.cpp: + (WebCore::TestEventTargetV8Internal::addEventListenerCallback): + (WebCore::TestEventTargetV8Internal::removeEventListenerCallback): + * bindings/scripts/test/V8/V8TestObj.cpp: + (WebCore::TestObjV8Internal::addEventListenerCallback): + (WebCore::TestObjV8Internal::removeEventListenerCallback): + +2012-11-27 Alexandru Chiculita <achicu@adobe.com> + + [CSS Regions] Elements using transforms are not repainted correctly when rendered in a region + https://bugs.webkit.org/show_bug.cgi?id=102826 + + Reviewed by David Hyatt. + + When the page is composited, all the elements will have a composited repaint container. In that case we will + never catch the repaints in the RenderFlowThread, but they will go directly to the RenderView. + There's a single case when the parent composited layer of an element inside the RenderFlowThread will get + its own repaints. That case only happens when the parent composited layer is also part of the same flow thread. + Right now compositing is disabled for elements inside the RenderFlowThread, so that case doesn't even happen yet. + That will be fixed in https://bugs.webkit.org/show_bug.cgi?id=84900. + + Test: fast/repaint/region-painting-in-composited-view.html + + * rendering/RenderObject.cpp: + (WebCore::RenderObject::containerForRepaint): + +2012-11-27 Tony Chang <tony@chromium.org> + + Unreviewed, win compile fix take 2. + + Try again to force this file to recompile. + + * rendering/RenderingAllInOne.cpp: + +2012-11-27 Tony Chang <tony@chromium.org> + + Unreviewed, win compile fix. + + Touch RenderingAllInOne.cpp to force it to rebuild. + + * rendering/RenderingAllInOne.cpp: + +2012-11-27 Tim Horton <timothy_horton@apple.com> + + PDFPlugin: Scroll bars do not grow on hover + https://bugs.webkit.org/show_bug.cgi?id=103382 + <rdar://problem/12555262> + + Reviewed by Beth Dakin. + + Export a few WebCore::Scrollbar methods to WebKit(2). + + * WebCore.exp.in: + +2012-11-27 Tom Sepez <tsepez@chromium.org> + + Regression(r129406): Fix the scope of the WidgetHierarchyUpdateSuspensionScope in Element::Attach(). + https://bugs.webkit.org/show_bug.cgi?id=100803 + + Reviewed by Abhishek Arya. + + Ensures that the suspension scope has gone out of scope before calling into + resumePostAttachCallbacks(). + + Test: fast/dom/adopt-node-crash-2.html + + * dom/Element.cpp: + (WebCore::Element::attach): + +2012-11-27 Tony Chang <tony@chromium.org> + + Remove hidden limiter div in the input slider shadow DOM + https://bugs.webkit.org/show_bug.cgi?id=102993 + + Reviewed by Ojan Vafai. + + The shadow DOM for input sliders would have a hidden div (the TrackLimiterElement) + the size of the thumb which would limit the position of thumb since the width of + the thumb takes up space in the track. This patch simplifies the shadow DOM by + removing this hidden div and computing the position of the thumb taking the size of + the thumb into account. + + No new tests, covered by existing tests in fast/forms. + + * css/mediaControlsChromium.css: + (input[type="range"]::-webkit-media-slider-container > div): We were depending on the behavior of the limiter having negative margins, causing the slider div + to overflow. Moving the negative margin to the slider produces the same effect. + * css/mediaControlsChromiumAndroid.css: + (input[type="range"]::-webkit-media-slider-container > div): Ditto. + * html/RangeInputType.cpp: + (WebCore::RangeInputType::createShadowSubtree): Remove limiter div. + * html/shadow/SliderThumbElement.cpp: + (WebCore::RenderSliderContainer::layout): Adjust the available space for the thumb and correctly position in the vertical case. + (WebCore::SliderThumbElement::setPositionFromPoint): Adjust the usable track size and simplify RTL code (no need to account for the limiter). + (WebCore): Delete limiter code. + * html/shadow/SliderThumbElement.h: + (WebCore): Delete limiter code. + * rendering/RenderSlider.cpp: + (WebCore::RenderSlider::layout): Delete limiter code. + * rendering/RenderTheme.cpp: + (WebCore::RenderTheme::paintSliderTicks): Simplify code for painting tick marks. + +2012-11-27 Alpha Lam <hclam@chromium.org> + + [chromium] Implement full-featured image cache + https://bugs.webkit.org/show_bug.cgi?id=99784 + + Reviewed by Stephen White. + + Implement a thread-safe image cache to be used with deferred image + decoding. Image cache can now be accessed on any thread. + + The patch implements the following logic: + 1. Mutex to protect all cache operations. + 2. Cache indexing using key (ImageFrameGenerator*, SkISize scaledSize) + 3. Cache lookup. + 4. Cache insertion. + 5. Generation of cache entry by scaling full size image. + 6. Generation of cache entries by decoding and scaling. + + Classes involved: + + ImageDecodingStore + + Responsible for owning cache entries and indexing. Pruning and memory + management will be added later. + + ImageFrameGenerator + + Responsible for generating new cache enties and insert them into + ImageDecodingStore. + + LazyDecodingPixelRef + + Responsible for cache lookup and lazy generation of cache entries + using ImageFrameGenerator. There is a mutex to protect concurrent + lock operations. + + These items are not implemented in this patch: + 1. Cache pruning. + 2. Setting cache memory limit. + 3. Cache deletion. + 4. Caching incomplete images and ImageDecoder. + + Unit tests added in ImageFrameGeneratorTest.cpp. + Layout tests are under platform/chromium/virtual/fast/images. + + * platform/graphics/chromium/DeferredImageDecoder.cpp: + (WebCore::DeferredImageDecoder::~DeferredImageDecoder): + (WebCore::DeferredImageDecoder::createResizedLazyDecodingBitmap): + (WebCore::DeferredImageDecoder::setEnabled): + (WebCore): + (WebCore::DeferredImageDecoder::frameBufferAtIndex): + (WebCore::DeferredImageDecoder::createLazyDecodingBitmap): + * platform/graphics/chromium/DeferredImageDecoder.h: + (DeferredImageDecoder): + * platform/graphics/chromium/ImageDecodingStore.cpp: + (WebCore::ImageDecodingStore::instance): + (WebCore::ImageDecodingStore::initializeOnce): + (WebCore::ImageDecodingStore::shutdown): + (WebCore::ImageDecodingStore::lockCompleteCache): + Lookup complete cache entry using hash key, increment use count. + (WebCore::ImageDecodingStore::lockIncompleteCache): TODO. + (WebCore::ImageDecodingStore::unlockCache): + Lookup cache entry using hash key, decrement use count. + (WebCore): + (WebCore::ImageDecodingStore::insertAndLockCache): + Insert new cache entry and increment use count. + (WebCore::ImageDecodingStore::prune): TODO. + * platform/graphics/chromium/ImageDecodingStore.h: + (WebCore): + (ImageDecodingStore): + (WebCore::ImageDecodingStore::CacheEntry::create): + (WebCore::ImageDecodingStore::CacheEntry::createAndUse): + (CacheEntry): + (WebCore::ImageDecodingStore::CacheEntry::CacheEntry): + (WebCore::ImageDecodingStore::CacheEntry::~CacheEntry): + * platform/graphics/chromium/ImageFrameGenerator.cpp: + (WebCore::ImageFrameGenerator::ImageFrameGenerator): + (WebCore::ImageFrameGenerator::setData): + (WebCore::ImageFrameGenerator::decodeAndScale): + Method for creating new cache entries. This is protected by a mutex + to prevent concurrent operations. Which means only one thread can + generate new cache entries for a set of encoded data. + (WebCore): + (WebCore::ImageFrameGenerator::tryToLockCache): + Tries to lookup a cache entry. + (WebCore::ImageFrameGenerator::tryToScale): + Tries to lookup a full size cache entry and generate a scaled version. + (WebCore::ImageFrameGenerator::tryToDecodeAndScale): + Tries to decode and scale. + * platform/graphics/chromium/ImageFrameGenerator.h: + (WebCore): + (ImageDecoderFactory): + (WebCore::ImageFrameGenerator::create): + (ImageFrameGenerator): + (WebCore::ImageFrameGenerator::setImageDecoderFactoryForTesting): + * platform/graphics/chromium/LazyDecodingPixelRef.cpp: + (WebCore::LazyDecodingPixelRef::LazyDecodingPixelRef): + (WebCore::LazyDecodingPixelRef::onLockPixels): + (WebCore::LazyDecodingPixelRef::onUnlockPixels): + * platform/graphics/chromium/LazyDecodingPixelRef.h: + (WebCore): + (LazyDecodingPixelRef): + * platform/graphics/chromium/ScaledImageFragment.cpp: + (WebCore::ScaledImageFragment::ScaledImageFragment): + * platform/graphics/chromium/ScaledImageFragment.h: + (WebCore): + (WebCore::ScaledImageFragment::create): + (ScaledImageFragment): + (WebCore::ScaledImageFragment::scaledSize): + * platform/graphics/chromium/SkSizeHash.h: Added. + (WTF): + +2012-11-27 Mike West <mkwst@chromium.org> + + Expanding variable names in ConsoleMessage. + https://bugs.webkit.org/show_bug.cgi?id=103436 + + Reviewed by Adam Barth. + + Variable names like 'm' should be replaced with full words, like + 'myOhMyThisIsAnAwesomeVariable' (or something more descriptive). + + * inspector/ConsoleMessage.cpp: + (WebCore::ConsoleMessage::ConsoleMessage): + * inspector/ConsoleMessage.h: + (ConsoleMessage): + +2012-11-27 Aaron Colwell <acolwell@chromium.org> + + Use-after-free in media player handling + https://bugs.webkit.org/show_bug.cgi?id=103426 + + Reviewed by Eric Carlson. + + Fixed use-after-free bugs caused by the MediaSource not being closed before the HTMLMediaElement or the MediaPlayer + is destroyed. Closing the MediaSource causes it to clear its reference to the MediaPlayer which prevents + the use-after-free problems from happening. + + Test: http/tests/media/media-source/video-media-source-closed-on-htmlmediaelement-destruction.html + + * html/HTMLMediaElement.cpp: + (WebCore::HTMLMediaElement::~HTMLMediaElement): + (WebCore::HTMLMediaElement::clearMediaPlayer): + +2012-11-27 David Grogan <dgrogan@chromium.org> + + IndexedDB: Remove IDBDatabase.setVersion API + https://bugs.webkit.org/show_bug.cgi?id=94972 + + Reviewed by Tony Chang. + + This has been out of the spec for over a year. No other browser has + implemented it for close to a year. + + Tests - removed.html + + * Modules/indexeddb/IDBCallbacks.h: + (IDBCallbacks): + * Modules/indexeddb/IDBDatabase.cpp: + (WebCore::IDBDatabase::IDBDatabase): + * Modules/indexeddb/IDBDatabase.h: + (IDBDatabase): + * Modules/indexeddb/IDBDatabase.idl: + * Modules/indexeddb/IDBDatabaseBackendImpl.cpp: + (WebCore::IDBDatabaseBackendImpl::processPendingCalls): + * Modules/indexeddb/IDBDatabaseBackendImpl.h: + (IDBDatabaseBackendImpl): + * Modules/indexeddb/IDBDatabaseBackendInterface.h: + (IDBDatabaseBackendInterface): + * Modules/indexeddb/IDBRequest.cpp: + * Modules/indexeddb/IDBRequest.h: + +2012-11-27 Mike West <mkwst@chromium.org> + + Log to console when autofocus is blocked by sandbox attribute. + https://bugs.webkit.org/show_bug.cgi?id=103255 + + Reviewed by Ojan Vafai. + + Adding a short log message when autofocus is blocked by a document's + sandbox flags, as it's currently a black box. + + Test: fast/forms/autofocus-in-sandbox-without-allow-scripts.html + + * html/HTMLFormControlElement.cpp: + (WebCore::shouldAutofocus): + +2012-11-27 Dean Jackson <dino@apple.com> + + Attempted build fix after http://trac.webkit.org/changeset/135888. + + * WebCore.exp.in: + * WebCore.order: + +2012-11-27 Ryosuke Niwa <rniwa@webkit.org> + + Build fix after r135890. #else, not #elif. + + * platform/graphics/ca/PlatformCALayer.h: + (PlatformCALayer): + +2012-11-27 Ryosuke Niwa <rniwa@webkit.org> + + HTMLCollection on Document should be stored on NodeListsNodeData like other HTMLCollections and LiveNodeLists + https://bugs.webkit.org/show_bug.cgi?id=103364 + + Reviewed by Anders Carlsson. + + Replaced the HTMLCollection storage in Document by NodeListsNodeData used by other HTMLCollection's + and LiveNodeList's. Now NodeListsNodeData is the only storage for HTMLCollection and LiveNodeList. + + * dom/Document.cpp: + (WebCore::Document::Document): Removed code for m_collection since it has been removed. + (WebCore::Document::~Document): Ditto. + (WebCore::Document::registerNodeList): Renamed. + (WebCore::Document::unregisterNodeList): Ditto. + (WebCore::Document::ensureCachedCollection): Renamed from cachedCollection to match the convetion + used elsewhere. Also use NodeListNodeData::addCacheWithAtomicName now that m_collection is gone. + (WebCore::Document::images): + (WebCore::Document::applets): + (WebCore::Document::embeds): + (WebCore::Document::plugins): + (WebCore::Document::scripts): + (WebCore::Document::links): + (WebCore::Document::forms): + (WebCore::Document::anchors): + (WebCore::Document::all): + (WebCore::Document::windowNamedItems): Use addCacheWithAtomicName. + (WebCore::Document::documentNamedItems): Ditto. + (WebCore::Document::reportMemoryUsage): Removed code for m_collection since it has been removed. + * dom/Document.h: + (WebCore::Document): Removed m_collections, m_documentNamedItemCollections, and + m_windowNamedItemCollections. + * dom/Element.cpp: + (WebCore::Element::ensureCachedHTMLCollection): Merged ElementRareData::ensureCachedHTMLCollection. + (WebCore::Element::cachedHTMLCollection): Merged ElementRareData::cachedHTMLCollection. + * Source/WebCore/dom/ElementRareData.h: Removed ensureCachedHTMLCollection, cachedHTMLCollection, + and removeCachedHTMLCollection since they're no longer used. + * dom/LiveNodeList.h: + (WebCore::LiveNodeListBase::LiveNodeListBase): Call registerNodeList now that LiveNodeList + and HTMLCollection share the same storage in all nodes. + (WebCore::LiveNodeListBase::~LiveNodeListBase): Ditto about unregisterNodeList. + (WebCore::LiveNodeList): Removed the calls to registerNodeList and unregisterNodeList since they + are now called in the base class. + * dom/NameNodeList.h: + (WebCore::NameNodeList::create): + * dom/NodeRareData.h: + (WebCore::NodeListsNodeData::addCacheWithAtomicName): Pass in CollectionType as the second argument + to T::create. This is used in HTMLNameCollection::create. Sevearl LiveNodeList constructors and + create functions have been modified to support this. + (WebCore::NodeListsNodeData::adoptTreeScope): + (WebCore::NodeListsNodeData::namedNodeListKey): CollectionType is no longer restricted in its range. + * dom/TagNodeList.h: + (WebCore::TagNodeList::create): + (WebCore::HTMLTagNodeList::create): + * html/CollectionType.h: Deleted a bunch of unused inline functions and constants, and cleanup enum. + * html/HTMLCollection.cpp: + (WebCore::HTMLCollection::HTMLCollection): Removed the call to registerNodeListCache since it's called + in LiveNodeListBase now. + (WebCore::HTMLCollection::~HTMLCollection): Ditto. Also replaced calls to removeCachedHTMLCollection + of Element and Document by a call to NodeListsNodeData::removeCacheWithAtomicName. + * html/HTMLFormControlsCollection.cpp: + (WebCore::HTMLFormControlsCollection::HTMLFormControlsCollection): + (WebCore::HTMLFormControlsCollection::create): + * html/HTMLFormControlsCollection.h: + (HTMLFormControlsCollection): + * html/HTMLNameCollection.cpp: + (WebCore::HTMLNameCollection::HTMLNameCollection): + (WebCore::HTMLNameCollection::~HTMLNameCollection): + * html/HTMLNameCollection.h: + (WebCore::HTMLNameCollection::create): + (HTMLNameCollection): + * html/HTMLOptionsCollection.cpp: + (WebCore::HTMLOptionsCollection::HTMLOptionsCollection): + (WebCore::HTMLOptionsCollection::create): + * html/HTMLOptionsCollection.h: + (HTMLOptionsCollection): + * html/HTMLTableRowsCollection.cpp: + (WebCore::HTMLTableRowsCollection::HTMLTableRowsCollection): + (WebCore::HTMLTableRowsCollection::create): + * html/HTMLTableRowsCollection.h: + (HTMLTableRowsCollection): + * html/LabelsNodeList.h: + (WebCore::LabelsNodeList::create): + * html/RadioNodeList.h: + (WebCore::RadioNodeList::create): + +2012-11-27 Pravin D <pravind.2k4@gmail.com> + + max-height property not respected in case of tables + https://bugs.webkit.org/show_bug.cgi?id=98633 + + Reviewed by Julien Chaffraix. + + The max-height property determines the maximum computed height an element can have. In case of tables + the computed height was not being limited by the max-height property. The current patch fixes the same. + + Test: fast/table/css-table-max-height.html + + * rendering/RenderTable.cpp: + (WebCore::RenderTable::convertStyleLogicalHeightToComputedHeight): + Helper function to compute height from the given style height. + This function handles style height of type fixed, percent and viewport percent. + As height of type 'calculated' gets internally resolved to either fixed or percent + there is no special handling required for the same. + + (WebCore): + (WebCore::RenderTable::layout): + Logic to compute the logical height of an element such that it does not exceed the max-height value given that + min-width < Content height < max-height, when min-height < max-height. + However max-height value is not respected if either min-height > max-height or Content height > max-height. + + * rendering/RenderTable.h: + (RenderTable): + Function definition for the newly add function convertStyleLogicalHeightToComputedHeight(). + +2012-11-27 Roger Fong <roger_fong@apple.com> + + Windows specific implementation of usesTileCacheLayer needed after r133056. + https://bugs.webkit.org/show_bug.cgi?id=103321 + + Reviewed by Simon Fraser. + + After r133056 it no longer suffices to use the existing usesTileCacheLayer method on Windows. + The change resulted in 3 crashing tests: + compositing/rotated-tiled-clamped + compositing/rotated-tiled-preserve3d-clamped + fast/events/tabindex-focus-blur-all + + * platform/graphics/ca/PlatformCALayer.h: + (WebCore::PlatformCALayer::usesTileCacheLayer): + (PlatformCALayer): + Adding in platform specific method for Windows that returns false for this method. + +2012-11-27 Christophe Dumez <christophe.dumez@intel.com> + + Canvas does not draw any text if the font is not fully loaded yet + https://bugs.webkit.org/show_bug.cgi?id=103392 + + Reviewed by Kenneth Rohde Christiansen. + + Update CanvasRenderingContext2D::drawTextInternal() so that the + text is being drawn, even if custom fonts are still being loaded. + Without this, WebKit was not drawing any text on the canvas if + the needed font is custom and is not fully loaded yet. This seems + broken. + + The new behavior is according to specification: + http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html + + The specification says: "If a font is used before it is fully + loaded, or if the font style source object does not have that + font in scope at the time the font is to be used, then it must be + treated as if it was an unknown font, falling back to another as + described by the relevant CSS specifications." + + Test: http/tests/canvas/canvas-slow-font-loading.html + + * html/canvas/CanvasRenderingContext2D.cpp: + (WebCore::CanvasRenderingContext2D::drawTextInternal): + * platform/graphics/Font.cpp: + (WebCore::Font::drawText): Add argument to specify the behavior + when custom fonts are not ready. By default, it will not draw + anything (same behavior as before). However, the Canvas code + can now request that a fallback font is used if the custom + font is not fully loaded yet. + * platform/graphics/Font.h: #undef Complex if defined to avoid + conflicting with Complex value in CodePath enum. X11/X.h is + defining Complex to 0. + * platform/graphics/GraphicsContext.cpp: + (WebCore::GraphicsContext::drawBidiText): + * platform/graphics/GraphicsContext.h: + (WebCore): + (GraphicsContext): + +2012-11-27 Dean Jackson <dino@apple.com> + + No need for ExceptionCode in HTMLMediaElement::load + https://bugs.webkit.org/show_bug.cgi?id=103438 + + Reviewed by Eric Carlson. + + After https://bugs.webkit.org/show_bug.cgi?id=103318, there is no + need for the ExceptionCode parameter in load(). The HTML5 spec says + that all errors in loading are communicated via state. + http://dev.w3.org/html5/spec/media-elements.html#dom-media-load + + Of the 29 tests exercising load(), none of them were exercising + exceptions (obviously). + + * html/HTMLMediaElement.cpp: + (WebCore::HTMLMediaElement::load): + (WebCore::HTMLMediaElement::resume): + * html/HTMLMediaElement.h: + * html/HTMLMediaElement.idl: + +2012-11-27 Robert Hogan <robert@webkit.org> + + REGRESSION (r125578): word-wrapping in absolute position with nbsp, word-spacing and custom font + https://bugs.webkit.org/show_bug.cgi?id=101443 + + Reviewed by David Hyatt. + + Leading non-breaking space in a text run should always get word-spacing applied. When RenderText + calculates the preferred with of a run of text it breaks it up into word segments that contain + no breaking spaces and calculates the width of each. So when calculating the width of ' b' + it needs to add word-spacing to the leading non-breaking space as it does not get collapsed away. + + Test: fast/text/word-space-nbsp.html + + * platform/graphics/WidthIterator.cpp: + (WebCore::WidthIterator::advanceInternal): + +2012-11-27 Yong Li <yoli@rim.com> + + [BlackBerry] EventLoop should end when WebKit thread is exiting + https://bugs.webkit.org/show_bug.cgi?id=103301 + + Reviewed by Rob Buis. + RIM PR# 194379. + Internally reviewed by Joe Mason. + + Break the nested event loop when WebKit thread has been asked to quit. + + * platform/blackberry/EventLoopBlackBerry.cpp: + (WebCore::EventLoop::cycle): + +2012-11-27 Pratik Solanki <psolanki@apple.com> + + objc/objc-runtime.h does not exist on all PLATFORM(MAC) + https://bugs.webkit.org/show_bug.cgi?id=101780 + + Reviewed by Brent Fulgham. + + Clean up header includes so we don't include objc/objc-runtime.h. + + No new tests because no functional changes. + + * bridge/objc/objc_header.h: + * page/mac/EventHandlerMac.mm: + * platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm: + * platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm: + * platform/graphics/ca/mac/PlatformCALayerMac.mm: + * platform/graphics/mac/MediaPlayerPrivateQTKit.mm: + * platform/graphics/mac/WebLayer.mm: + * platform/mac/WebCoreObjCExtras.mm: + * platform/mac/WebVideoFullscreenController.mm: + +2012-11-27 Eberhard Graether <egraether@google.com> + + Plumbing showPaintRects out of InspectorPageAgent to use a different drawing implementation if available. + https://bugs.webkit.org/show_bug.cgi?id=102452 + + Reviewed by Pavel Feldman. + + This change makes the showPaintRects setting in the Web Inspector's settings notify InspectorClient + when changed. And the default paint rects drawing is not used if an alternative is available. + This allows Chromium to draw the paint rects in the compositor's HUDLayer. + + No new tests. + + * inspector/InspectorClient.h: + (WebCore::InspectorClient::overridesShowPaintRects): + (WebCore::InspectorClient::setShowPaintRects): + (InspectorClient): + * inspector/InspectorPageAgent.cpp: + (PageAgentState): + (WebCore::InspectorPageAgent::restore): + (WebCore::InspectorPageAgent::disable): + (WebCore::InspectorPageAgent::setShowPaintRects): + (WebCore::InspectorPageAgent::didPaint): + +2012-11-27 Allan Sandfeld Jensen <allan.jensen@digia.com> + + Unreviewed cleanup. + + Remove leftover file that was replaced by PlatformScreenQt.cpp 4 years ago. + + * platform/qt/ScreenQt.cpp: Removed. + +2012-11-27 Istiaque Ahmed <lazyboy@chromium.org> + + freeV8NPObject: Skip trying to remove object from per context data's ObjectMap if the object does not exist in the map. + https://bugs.webkit.org/show_bug.cgi?id=103356 + + Reviewed by Adam Barth. + + Before introducing per context data, it used to be the case that we would ignore removing v8 object + from context data's map if we couldn't find it. With perContextData change, this turned into an ASSERT + instead and we had crash reports. + Related crbug.com/154462. + + Test: platform/chromium/plugins/release-frame-content-window.html + + * bindings/v8/NPV8Object.cpp: + (WebCore::freeV8NPObject): + +2012-11-27 Marja Hölttä <marja@chromium.org> + + Add callbacks to the FrameLoaderClient when a resource is requested + https://bugs.webkit.org/show_bug.cgi?id=92761 + + Reviewed by Adam Barth. + + In Chromium, when an extension script cancels a network + request (which happens out of process), we'd like to + notify content scripts running on the current page about + which elements failed to load because the requests were + cancelled (as opposed to e.g. the network request just + didn't work). Since the resource request itself does not + carry any information what DOM element is was made for, + currently a content script has to search the DOM tree and + guess which requests will be cancelled by its counter + part. By adding these callbacks, the embedder can make + this connection explictly. + + Test: platform/chromium/fast/loader/resource-request-callbacks.html + + * loader/FrameLoaderClient.h: + (WebCore): + (WebCore::FrameLoaderClient::dispatchWillRequestResource): + (FrameLoaderClient): + * loader/cache/CachedResourceLoader.cpp: + (WebCore::CachedResourceLoader::requestResource): + +2012-11-27 Dean Jackson <dino@apple.com> + + Unreviewed build fix for r135866. + + * html/HTMLMediaElement.cpp: + (WebCore::HTMLMediaElement::load): + +2012-11-27 Leo Yang <leoyang@rim.com> + + [BlackBerry] Adapt to the change of BlackBerry::Platform::FilterStream::notifyHeadersReceived + https://bugs.webkit.org/show_bug.cgi?id=103425 + + Reviewed by Yong Li. + + A const has been added for HeaderList parameter of BlackBerry::Platform::FilterStream::notifyHeadersReceived. + The patch is adapting to this change. + + No functionalities changed no new tests. + + * platform/network/blackberry/NetworkJob.cpp: + (WebCore::NetworkJob::notifyHeadersReceived): + * platform/network/blackberry/NetworkJob.h: + (NetworkJob): + * platform/network/blackberry/rss/RSSFilterStream.cpp: + (WebCore::RSSFilterStream::notifyHeadersReceived): + * platform/network/blackberry/rss/RSSFilterStream.h: + +2012-11-27 Min Qin <qinmin@chromium.org> + + Don't throw an exception if user gesture is required for load + https://bugs.webkit.org/show_bug.cgi?id=103318 + + Reviewed by Eric Carlson. + + There is no need to throw an exception if media load requires user gesture. + Since chrome does not render the poster and media control after an exception is thrown, throwing an exception may break a lot of sites on android. + Change a current test to match the new behavior: media/video-load-require-user-gesture.html + + * html/HTMLMediaElement.cpp: + (WebCore::HTMLMediaElement::load): + +2012-11-27 VÃctor Manuel Jáquez Leal <vjaquez@igalia.com> + + [GStreamer] Verify if GStreamer was previously initialized + https://bugs.webkit.org/show_bug.cgi?id=103151 + + Reviewed by Philippe Normand. + + This patch calls gst_is_initialized() before calling gst_init_check() + in order to verify if GStreamer has not been initialized before. + + This is useful particularly for WebKit1 so the applications could + initialize GStreamer before. + + As the API call was added in GStreamer v0.10.31, the patch fences the + call only in that version of GStreamer or above. + + No new tests, existing media tests cover this change. + + * platform/graphics/gstreamer/GStreamerUtilities.cpp: + (WebCore::initializeGStreamer): + +2012-11-27 Kentaro Hara <haraken@chromium.org> + + [V8] Remove V8StringResource::m_string + https://bugs.webkit.org/show_bug.cgi?id=103367 + + Reviewed by Adam Barth. + + This patch cleans up V8StringResource and removes V8StringResource::m_string. + This patch won't change performance. (This patch just adds one redundant IsString() + check and one IsInt32() check.) I confirmed no performance regression in micro benchmarks + (https://bugs.webkit.org/attachment.cgi?id=176178). + + No tests. No change in behavior. + + * bindings/v8/V8Binding.cpp: + (WebCore::v8NonStringValueToWebCoreString): + * bindings/v8/V8StringResource.cpp: + (WebCore::int32ToWebCoreStringFast): + (WebCore::String): + (WebCore::AtomicString): + (WebCore): + * bindings/v8/V8StringResource.h: + (WebCore::V8StringResource::V8StringResource): + (WebCore::V8StringResource::prepareBase): + (WebCore::V8StringResource::toString): + (V8StringResource): + (WebCore::::prepare): + +2012-11-27 Alec Flett <alecflett@chromium.org> + + IndexedDB: stub out IDBDatabaseBackendInterface::createTransaction + https://bugs.webkit.org/show_bug.cgi?id=102730 + + Reviewed by Darin Fisher. + + Stub out and support passing a 64-bit transaction id + so the frontend can refer to transactions by id rather than + a proxy object or a direct pointer reference. This will ultimately + loosen ownership and lifetime of transactions from the frontend + and backend. + + No new tests, this is just part of a refactor. + + * Modules/indexeddb/IDBDatabase.cpp: + * Modules/indexeddb/IDBDatabaseBackendImpl.cpp: + (WebCore): + (WebCore::IDBDatabaseBackendImpl::transaction): + (WebCore::IDBDatabaseBackendImpl::createTransaction): + * Modules/indexeddb/IDBDatabaseBackendImpl.h: + (IDBDatabaseBackendImpl): + * Modules/indexeddb/IDBDatabaseBackendInterface.h: + (IDBDatabaseBackendInterface): + * Modules/indexeddb/IDBTransactionBackendImpl.cpp: + (WebCore::IDBTransactionBackendImpl::create): + (WebCore::IDBTransactionBackendImpl::IDBTransactionBackendImpl): + * Modules/indexeddb/IDBTransactionBackendImpl.h: + (IDBTransactionBackendImpl): + (WebCore::IDBTransactionBackendImpl::id): + +2012-11-27 Andrei Bucur <abucur@adobe.com> + + [CSS Regions] Crash when dispatching regionlayoutupdate + https://bugs.webkit.org/show_bug.cgi?id=102944 + + Reviewed by Andreas Kling. + + The event dispatch function was incorrectly assuming the RenderNamedFlowThread is valid. Because the event is asynchronous it's + possible for the flow to be in the "NULL" state (the renderer is 0) while the regionlayoutupdate event is dispatched. + + Test: fast/regions/webkit-named-flow-event-crash.html + + * dom/WebKitNamedFlow.cpp: + (WebCore::WebKitNamedFlow::dispatchRegionLayoutUpdateEvent): Remove the ASSERT and don't dispatch the event if the flow is + in the "NULL" state. + +2012-11-27 Mihnea Ovidenie <mihnea@adobe.com> + + [CSS Regions] Absolutely positioned regions do not expand to fill their container + https://bugs.webkit.org/show_bug.cgi?id=102385 + + Reviewed by Julien Chaffraix. + + In the case of an absolutely positioned region with height auto, height computation should follow + the path of block elements instead of replaced elements. + + Tests: fast/regions/autosize-abspos-anchoredregion-vertlr.html + fast/regions/autosize-abspos-anchoredregion.html + + * rendering/RenderBox.cpp: + (WebCore::RenderBox::computePositionedLogicalHeight): Skip replaced element height computation when a region has height auto. + * rendering/RenderRegion.h: + (WebCore::RenderRegion::shouldHaveAutoLogicalHeight): Make it private since it is not accessed from outside. + +2012-11-27 Alexander Pavlov <apavlov@chromium.org> + + Incorrect value of CSSStyleDeclaration#length when a shorthand property is inherit or initial + https://bugs.webkit.org/show_bug.cgi?id=73002 + + Reviewed by Alexis Menard. + + Before the patch, "inherit" and "initial" shorthands would get added to the StylePropertySet as-is, their longhands unspecified. + This patch tackles two aspects of the problem: + - When parsing "initial" and "inherit" shorthands, their longhands are added to the property set with the corresponding values. + - When querying "initial" and "inherit" shorthands, their values are reconstructed from the longhands as usual, but if all of the longhands + are found to have the same explicit "initial" or "inherit" value, the respective single value is returned as the shorthand value. + + When reconstructing shorthands, a "common value" is tracked. If all longhands involved have the same explicit value, it becomes the + "common value", otherwise it is a String(). The "inherit" or "initial" common value ultimately becomes the shorthand value + (except for the "background-position" shorthand, which is a special case). + + * css/CSSParser.cpp: + (WebCore::parseKeywordValue): Parse shorthands' "initial" and "inherit" values using the CSSParser. + (WebCore::CSSParser::addExpandedPropertyForValue): Add simple property or all sharthand's longhands with given value and priority. + (WebCore::CSSParser::parseValue): For "initial" and "inherit" shorthands, add their longhands with the respective value, not the shorthands proper. + * css/CSSParser.h: Add addExpandedPropertyForValue(). + * css/StylePropertySet.cpp: + (WebCore::isInitialOrInherit): Check if the value is "initial" or "inherit". + (WebCore): + (WebCore::StylePropertySet::appendFontLonghandValueIfExplicit): Modified to track the common value for the "font" shorthand. + (WebCore::StylePropertySet::fontValue): Ditto. + (WebCore::StylePropertySet::get4Values): Return "inherit" or "initial" if all 4 values are explicitly "inherit" or "initial". + (WebCore::StylePropertySet::getLayeredShorthandValue): Use the common value approach for layered shorthands. + (WebCore::StylePropertySet::getShorthandValue): Ditto for ordinary shorthands. + (WebCore::StylePropertySet::borderPropertyValue): Ditto for the "border" shorthand. + * css/StylePropertySet.h: Modify the appendFontLonghandValueIfExplicit() signature. + * html/canvas/CanvasRenderingContext2D.cpp: + (WebCore::CanvasRenderingContext2D::setFont): Now that "inherit" and "initial" shorthands are represented by their longhands, + we need to check the string value of the "font" shorthand for being "inherit" or "initial" instead: getPropertyCSSValue() no longer works, + since the shorthand itself is no longer added to the StylePropertySet. + +2012-11-27 Kentaro Hara <haraken@chromium.org> + + Unreviewed. Renamed TRYCATCH => V8TRYCATCH. + (I forgot to apply reviewer's comment in bug 103352 when landing r135817.) + + * bindings/scripts/CodeGeneratorV8.pm: + (GenerateParametersCheck): + (GenerateEventConstructorCallback): + (ConvertToV8StringResource): + * bindings/scripts/test/V8/V8Float64Array.cpp: + (WebCore::Float64ArrayV8Internal::fooCallback): + * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: + (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): + (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): + * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: + (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): + * bindings/scripts/test/V8/V8TestEventConstructor.cpp: + (WebCore::V8TestEventConstructor::constructorCallback): + * bindings/scripts/test/V8/V8TestEventTarget.cpp: + (WebCore::TestEventTargetV8Internal::itemCallback): + (WebCore::TestEventTargetV8Internal::dispatchEventCallback): + * bindings/scripts/test/V8/V8TestInterface.cpp: + (WebCore::TestInterfaceV8Internal::supplementalStaticAttrAttrSetter): + (WebCore::TestInterfaceV8Internal::supplementalStr2AttrSetter): + (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): + (WebCore::V8TestInterface::constructorCallback): + * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: + (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): + * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: + (WebCore::V8TestNamedConstructorConstructorCallback): + * bindings/scripts/test/V8/V8TestObj.cpp: + (WebCore::TestObjV8Internal::staticStringAttrAttrSetter): + (WebCore::TestObjV8Internal::stringAttrAttrSetter): + (WebCore::TestObjV8Internal::reflectedStringAttrAttrSetter): + (WebCore::TestObjV8Internal::reflectedURLAttrAttrSetter): + (WebCore::TestObjV8Internal::reflectedCustomURLAttrAttrSetter): + (WebCore::TestObjV8Internal::stringAttrWithGetterExceptionAttrSetter): + (WebCore::TestObjV8Internal::stringAttrWithSetterExceptionAttrSetter): + (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): + (WebCore::TestObjV8Internal::longMethodWithArgsCallback): + (WebCore::TestObjV8Internal::objMethodWithArgsCallback): + (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): + (WebCore::TestObjV8Internal::methodReturningSequenceCallback): + (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): + (WebCore::TestObjV8Internal::idbKeyCallback): + (WebCore::TestObjV8Internal::optionsObjectCallback): + (WebCore::TestObjV8Internal::methodWithOptionalArgCallback): + (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): + (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): + (WebCore::TestObjV8Internal::methodWithOptionalStringCallback): + (WebCore::TestObjV8Internal::methodWithOptionalStringIsUndefinedCallback): + (WebCore::TestObjV8Internal::methodWithOptionalStringIsNullStringCallback): + (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): + (WebCore::TestObjV8Internal::overloadedMethod1Callback): + (WebCore::TestObjV8Internal::overloadedMethod2Callback): + (WebCore::TestObjV8Internal::overloadedMethod3Callback): + (WebCore::TestObjV8Internal::overloadedMethod4Callback): + (WebCore::TestObjV8Internal::overloadedMethod6Callback): + (WebCore::TestObjV8Internal::overloadedMethod7Callback): + (WebCore::TestObjV8Internal::overloadedMethod8Callback): + (WebCore::TestObjV8Internal::overloadedMethod9Callback): + (WebCore::TestObjV8Internal::overloadedMethod10Callback): + (WebCore::TestObjV8Internal::overloadedMethod11Callback): + (WebCore::TestObjV8Internal::classMethodWithOptionalCallback): + (WebCore::TestObjV8Internal::overloadedMethod12Callback): + (WebCore::TestObjV8Internal::classMethodWithClampCallback): + (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): + (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): + (WebCore::TestObjV8Internal::enabledPerContextMethod1Callback): + (WebCore::TestObjV8Internal::enabledPerContextMethod2Callback): + (WebCore::TestObjV8Internal::stringArrayFunctionCallback): + (WebCore::TestObjV8Internal::convert1Callback): + (WebCore::TestObjV8Internal::convert2Callback): + (WebCore::TestObjV8Internal::convert4Callback): + (WebCore::TestObjV8Internal::convert5Callback): + (WebCore::TestObjV8Internal::strictFunctionCallback): + (WebCore::TestObjV8Internal::variadicStringMethodCallback): + (WebCore::TestObjV8Internal::variadicDoubleMethodCallback): + (WebCore::TestObjV8Internal::variadicNodeMethodCallback): + * bindings/scripts/test/V8/V8TestOverloadedConstructors.cpp: + (WebCore::V8TestOverloadedConstructors::constructor1Callback): + (WebCore::V8TestOverloadedConstructors::constructor2Callback): + (WebCore::V8TestOverloadedConstructors::constructor3Callback): + (WebCore::V8TestOverloadedConstructors::constructor4Callback): + * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: + (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): + * bindings/v8/V8Binding.h: + (WebCore::toV8Sequence): + * bindings/v8/V8BindingMacros.h: + * bindings/v8/custom/V8BlobCustom.cpp: + (WebCore::V8Blob::constructorCallbackCustom): + * bindings/v8/custom/V8ConsoleCustom.cpp: + (WebCore::V8Console::profileCallback): + (WebCore::V8Console::profileEndCallback): + * bindings/v8/custom/V8DOMWindowCustom.cpp: + (WebCore::handlePostMessageCallback): + * bindings/v8/custom/V8DataViewCustom.cpp: + (WebCore::V8DataView::getInt8Callback): + (WebCore::V8DataView::getUint8Callback): + (WebCore::V8DataView::setInt8Callback): + (WebCore::V8DataView::setUint8Callback): + * bindings/v8/custom/V8DeviceMotionEventCustom.cpp: + (WebCore::V8DeviceMotionEvent::initDeviceMotionEventCallback): + * bindings/v8/custom/V8DeviceOrientationEventCustom.cpp: + (WebCore::V8DeviceOrientationEvent::initDeviceOrientationEventCallback): + * bindings/v8/custom/V8DocumentCustom.cpp: + (WebCore::V8Document::evaluateCallback): + * bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp: + (WebCore::V8HTMLOptionsCollection::addCallback): + * bindings/v8/custom/V8HistoryCustom.cpp: + (WebCore::V8History::pushStateCallback): + (WebCore::V8History::replaceStateCallback): + * bindings/v8/custom/V8IntentCustom.cpp: + (WebCore::V8Intent::constructorCallbackCustom): + * bindings/v8/custom/V8SQLTransactionCustom.cpp: + (WebCore::V8SQLTransaction::executeSqlCallback): + * bindings/v8/custom/V8SQLTransactionSyncCustom.cpp: + (WebCore::V8SQLTransactionSync::executeSqlCallback): + * bindings/v8/custom/V8SVGLengthCustom.cpp: + (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): + * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: + (WebCore::V8WebGLRenderingContext::getExtensionCallback): + * bindings/v8/custom/V8WorkerContextCustom.cpp: + (WebCore::V8WorkerContext::importScriptsCallback): + +2012-11-27 Dan Carney <dcarney@google.com> + + [V8] add contextForWorld helper function to ScriptController + https://bugs.webkit.org/show_bug.cgi?id=103376 + + Reviewed by Kentaro Hara. + + Reducing some commonly occuring code with an inline function. + + No new tests. No change in functionality. + + * bindings/v8/ScriptController.cpp: + (WebCore::ScriptController::contextForWorld): + (WebCore): + (WebCore::ScriptController::currentWorldContext): + (WebCore::ScriptController::mainWorldContext): + * bindings/v8/ScriptController.h: + (ScriptController): + +2012-11-26 Allan Sandfeld Jensen <allan.jensen@digia.com> + + [Qt] Implement the mimetype icon methods + https://bugs.webkit.org/show_bug.cgi?id=103260 + + Reviewed by Simon Hausmann. + + * platform/graphics/Icon.h: + (Icon): + * platform/graphics/qt/IconQt.cpp: + (WebCore::Icon::createIconForFiles): + (WebCore::Icon::paint): + +2012-09-17 Allan Sandfeld Jensen <allan.jensen@nokia.com> + + Incorrect rect-based hit-test result when hit-test region includes culled inlines + https://bugs.webkit.org/show_bug.cgi?id=88376 + + Reviewed by Dave Hyatt. + + Move the handling of culled inlines from HitTestResult::addNodeToRectBasedTestResult to + InlineFlowBox::nodeAtPoint. This makes it possible to fix a number of bugs with how + culled inlines were handled. They are now checked after all their children, and may + terminate area-based hit-testing if they contain the whole area. + + Tests: fast/dom/nodesFromRect/nodesFromRect-culled-inlines.html + fast/dom/nodesFromRect/nodesFromRect-culled-inline-with-linebreak.html + + * rendering/HitTestResult.cpp: + (WebCore::HitTestLocation::HitTestLocation): + (WebCore::HitTestResult::addNodeToRectBasedTestResult): + * rendering/HitTestResult.h: + (HitTestLocation): + * rendering/InlineFlowBox.cpp: + (WebCore::InlineFlowBox::nodeAtPoint): + * rendering/RenderInline.cpp: + (WebCore::RenderInline::hitTestCulledInline): + * rendering/RenderInline.h: + (RenderInline): + +2012-11-27 Kenneth Rohde Christiansen <kenneth@webkit.org> + + REGRESSION(134887) [Qt][EFL][WK2] Repaint counter not working + https://bugs.webkit.org/show_bug.cgi?id=103261 + + Reviewed by Noam Rosenthal. + + Fixed regression introduced in 134887, which introduced the + updateContentsNoSwizzle method and called it directly from + the repaint counter. + + This method obviously needs to bind the texture. + + * platform/graphics/texmap/TextureMapperGL.cpp: + (WebCore::BitmapTextureGL::updateContentsNoSwizzle): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * CMakeLists.txt: + * GNUmakefile.list.am: + * Target.pri: + * WebCore.exp.in: + * WebCore.gypi: + * WebCore.vcproj/WebCore.vcproj: + * WebCore.xcodeproj/project.pbxproj: + * loader/FrameLoadRequest.cpp: Removed. + * loader/FrameLoadRequest.h: + (WebCore::FrameLoadRequest::FrameLoadRequest): + (FrameLoadRequest): + * loader/FrameLoader.cpp: + (WebCore::FrameLoader::load): + * loader/FrameLoader.h: + (FrameLoader): + * page/DragController.cpp: + (WebCore::DragController::performDrag): + * plugins/PluginView.cpp: + (WebCore::PluginView::performRequest): + +2012-11-27 Kent Tamura <tkent@chromium.org> + + Implement ValidityState::badInput + https://bugs.webkit.org/show_bug.cgi?id=102861 + + Reviewed by Hajime Morita. + + Add ValidityState::badInput, add hasBadInput, which always returns + false, to FormAssociatedElement, HTMLInputElement, and InputType. + + For NumberInputType, we had hasUnacceptableValue, which was a hack to + make an input element match to :invalid if the element had non-number + strings. We don't need the hack any more because badInput affects :invalid + style. hasUnacceptableValue is re-used for hasBadInput implementation. + We cleared invalid numbers when elements lost focus to tell users that + the element had invalid numbers. We don't need this behavior because the + interactive validation tells it. + + For date/time input types, we should make an input badInput when the + input has empty value but its sub-fields have values. It covers both of + partial input cases such as 12/--/2012 and invalid dates such as + 02/31/2012. + + For other types, ValidityState::badInput always returns false. + + This patch doesn't contain tests for badInput validation messages. They + will be added later. + + Tests: fast/forms/date-multiple-fields/date-multiple-fields-validity-badinput.html + fast/forms/datetime-multiple-fields/datetime-multiple-fields-validity-badinput.html + fast/forms/datetimelocal-multiple-fields/datetimelocal-multiple-fields-validity-badinput.html + fast/forms/month-multiple-fields/month-multiple-fields-validity-badinput.html + fast/forms/number/number-validity-badinput.html + fast/forms/time-multiple-fields/time-multiple-fields-validity-badinput.html + fast/forms/week-multiple-fields/week-multiple-fields-validity-badinput.html + + * html/ValidityState.idl: Add badInput IDL attribute. + * html/ValidityState.h: + (ValidityState): Add badInput. + * html/ValidityState.cpp: + (WebCore::ValidityState::badInput): + Added. Calls FormAssociatedElement::hasBadInput. + + * html/FormAssociatedElement.h: + (FormAssociatedElement): Add hasBadInput. + * html/FormAssociatedElement.cpp: + (WebCore::FormAssociatedElement::hasBadInput): + Added. It always returns false. + (WebCore::FormAssociatedElement::valid): Takes account of hasBadInput(). + + * html/HTMLInputElement.h: + (HTMLInputElement): + Remove hasUnacceptableValue, and add hasBadInput override. + * html/HTMLInputElement.cpp: + (WebCore::HTMLInputElement::hasBadInput): + Added. Delegate to InputType::hasBadInput. + (WebCore): Remove hasUnacceptableValue. + + * html/InputType.h: + (InputType): Add hasBadInput and badInputText, and remove + hasUnacceptableValue. + * html/InputType.cpp: + (WebCore::InputType::hasBadInput): Added. Returns false. + (WebCore::InputType::badInputText): + Added. This function should not be called because hasBadInput always + returns false. + (WebCore::InputType::validationMessage): + Supports badInput. This returns badInputText if hasBadInput is true. + + * html/NumberInputType.h: + (NumberInputType): Add hasBadInput and badInputTest. Remove + handleBlurEvent and hasUnacceptableValue. + * html/NumberInputType.cpp: + Remove handleBlurEvent, which cleared invalid number strings. + (WebCore::NumberInputType::hasBadInput): + Added. We don't need to check existence of a renderer. The standard form + validation feature doesn't care of it. + (WebCore::NumberInputType::badInputText): Returns + validationMessageBadInputForNumberText defined in LocalizedStrings.h. + * css/SelectorChecker.cpp: + (WebCore::SelectorChecker::checkOneSelector): + Remove a hack for hasUnacceptableValue. isValidFormControlElement takes + account of badInput. + * dom/Element.h: Remove hasUnacceptableValue. + + * html/BaseMultipleFieldsDateAndTimeInputType.h: + (BaseMultipleFieldsDateAndTimeInputType): Add hasBadInput and badInputText. + * html/BaseMultipleFieldsDateAndTimeInputType.cpp: + (WebCore::BaseMultipleFieldsDateAndTimeInputType::badInputText): + Returns validationMessageBadInputForDateTimeText defined in LocalizedStrings.h. + (WebCore::BaseMultipleFieldsDateAndTimeInputType::hasBadInput): + Added. + (WebCore::BaseMultipleFieldsDateAndTimeInputType::setValue): + Add setNeedsValidityCheck call. It is needed because + updateInnerTextValue can modify subfields empty state. + + * html/TextFieldInputType.cpp: + (WebCore::TextFieldInputType::subtreeHasChanged): Update a comment. + * platform/LocalizedStrings.h: + (WebCore): Add validationMessageBadInputForNumberText and + validationMessageBadInputForDateTimeText. + * platform/LocalizedStrings.cpp: + (WebCore::validationMessageBadInputForNumberText): + Added a placeholder implementation. This should be fixed later. + * platform/blackberry/LocalizedStringsBlackBerry.cpp: + (WebCore::validationMessageBadInputForNumberText): Ditto. + * platform/efl/LocalizedStringsEfl.cpp: + (WebCore::validationMessageBadInputForNumberText): Ditto. + * platform/qt/LocalizedStringsQt.cpp: + (WebCore::validationMessageBadInputForNumberText): Ditto. + +2012-11-27 Hajime Morrita <morrita@google.com> + + [Refactoring] NodeFlags::IsShadowRootFlag should be Node::IsDocumentFragmentFlag + https://bugs.webkit.org/show_bug.cgi?id=103370 + + Reviewed by Kentaro Hara. + + This chagne introduces Node::IsDocumentFragmentFlag so that we can + have fast Node::isDocumentFragment(). + + Note that Node::isShadowRoot() can become slightly slower when it + returns true, but that is minor in terms of the number of calls at runtime. + + No new tests. No behavior change. + + * dom/DocumentFragment.cpp: + (WebCore::DocumentFragment::create): + * dom/DocumentFragment.h: + * dom/Node.cpp: + (WebCore::Node::documentFragmentIsShadowRoot): + (WebCore): + * dom/Node.h: + (Node): + (WebCore::Node::isDocumentFragment): + (WebCore::Node::isShadowRoot): + (WebCore::Node::parentNode): + (WebCore::Node::parentNodeGuaranteedHostFree): + * dom/ShadowRoot.h: + +2012-11-26 Kent Tamura <tkent@chromium.org> + + :read-only selector should match to date/time input types + https://bugs.webkit.org/show_bug.cgi?id=103350 + + Reviewed by Kentaro Hara. + + We supported :read-only and :read-write only for text form controls; + i.e. <textarea> and text-field <input>. According to [1], we should + support them for date/time types. So, this patch removes + isTextFormControl check in SelectorChecker, and just relies on + shouldMatchRead{Only,Write}Selector virtual functions. + + Tests: Update fast/forms/*/*-appearance-pseudo-classes.html. + + [1] http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary + + * css/SelectorChecker.cpp: + (WebCore::SelectorChecker::checkOneSelector): + Remove isFormControlElement check and isTextFormControl check. + + * html/HTMLFormControlElement.cpp: + Remove shouldMatchRead{Only,Write}Selector functions. We don't need + common implementations any more. + * html/HTMLFormControlElement.h: Ditto. + + * html/HTMLTextAreaElement.h: + (HTMLTextAreaElement): Add shouldMatchRead{Only,Write}Selector overrides. + * html/HTMLTextAreaElement.cpp: + (WebCore::HTMLTextAreaElement::shouldMatchReadOnlySelector): Added. + (WebCore::HTMLTextAreaElement::shouldMatchReadWriteSelector): Added. + + * html/HTMLInputElement.h: + (HTMLInputElement): Add shouldMatchRead{Only,Write}Selector overrides. + * html/HTMLInputElement.cpp: + (WebCore::HTMLInputElement::shouldMatchReadOnlySelector): + Added. This checks InputType::supportsReadOnly and readOnly. + (WebCore::HTMLInputElement::shouldMatchReadWriteSelector): Ditto. + + * html/InputType.h: + (InputType): Add supportsReadOnly. + * html/InputType.cpp: + (WebCore::InputType::supportsReadOnly): Added. Returns false by default. + + * html/BaseDateAndTimeInputType.h: + (BaseDateAndTimeInputType): Add supportsReadOnly. + * html/BaseDateAndTimeInputType.cpp: + (WebCore::BaseDateAndTimeInputType::supportsReadOnly): Added. Returns true. + * html/TextFieldInputType.h: + (TextFieldInputType): Add supportsReadOnly. + * html/TextFieldInputType.cpp: + (WebCore::TextFieldInputType::supportsReadOnly): Added. Returns true. + +2012-11-26 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135822. + http://trac.webkit.org/changeset/135822 + https://bugs.webkit.org/show_bug.cgi?id=103369 + + Undo the revert of r135818, since that change does not affect + code used by Chromium (Requested by apavlov on #webkit). + + * platform/graphics/texmap/GraphicsLayerTextureMapper.cpp: + (WebCore::GraphicsLayerTextureMapper::setMaskLayer): + (WebCore::GraphicsLayerTextureMapper::setContentsVisible): + +2012-11-26 Michael Pruett <michael@68k.org> + + [GTK] Fix build error on GTK due to r135749 + https://bugs.webkit.org/show_bug.cgi?id=103365 + + Reviewed by Dean Jackson. + + In r135749, many files which were already included + in webcore_built_sources were erroneously added to + webcore_svg_built_sources in GNUmakefile.list.am. + + * GNUmakefile.list.am: + +2012-11-26 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135818. + http://trac.webkit.org/changeset/135818 + https://bugs.webkit.org/show_bug.cgi?id=103368 + + platform/chromium/virtual/threaded/compositing/visibility + /visibility-simple-webgl-layer.html crash on Mountain Lion + (Requested by apavlov on #webkit). + + * platform/graphics/texmap/GraphicsLayerTextureMapper.cpp: + (WebCore::GraphicsLayerTextureMapper::setMaskLayer): + (WebCore::GraphicsLayerTextureMapper::setContentsVisible): + +2012-11-26 Huang Dongsung <luxtella@company100.net> + + Coordinated Graphics: Set visibility to a mask layer in GraphicsLayer::setContentsVisible(). + https://bugs.webkit.org/show_bug.cgi?id=103297 + + Reviewed by Noam Rosenthal. + + GraphicsLayerTextureMapper and CoordinatedGraphicsLayer set the visibility of a + mask layer in setContentsVisible() and setMaskLayer() like setting a size. + This patch is needed because RenderLayerBacking does not set the visibility to a + mask layer like the size. + + This patch does not change user experience because an invisible layer is not + rendered although the mask layer is rendered. In that sense, it is an + optimization patch. + + No new tests. It is an optimization patch. + + * platform/graphics/texmap/GraphicsLayerTextureMapper.cpp: + (WebCore::GraphicsLayerTextureMapper::setMaskLayer): + (WebCore::GraphicsLayerTextureMapper::setContentsVisible): + +2012-11-26 Kentaro Hara <haraken@chromium.org> + + [V8] Rename EXCEPTION_BLOCK() macros + https://bugs.webkit.org/show_bug.cgi?id=103352 + + Reviewed by Adam Barth. + + Since V8Parameter was renamed to V8StringResource, + we rename macros that use V8Parameter. + + EXCEPTION_BLOCK() => V8TRYCATCH() + STRING_TO_V8PARAMETER_EXCEPTION_BLOCK() => V8TRYCATCH_FOR_V8STRINGRESOURCE() + STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID() => V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID() + + No tests. No change in behavior. + + * bindings/scripts/CodeGeneratorV8.pm: + (GenerateParametersCheck): + (GenerateEventConstructorCallback): + (ConvertToV8StringResource): + * bindings/scripts/test/V8/V8Float64Array.cpp: + (WebCore::Float64ArrayV8Internal::fooCallback): + * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: + (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): + (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): + * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: + (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): + * bindings/scripts/test/V8/V8TestEventConstructor.cpp: + (WebCore::V8TestEventConstructor::constructorCallback): + * bindings/scripts/test/V8/V8TestEventTarget.cpp: + (WebCore::TestEventTargetV8Internal::itemCallback): + (WebCore::TestEventTargetV8Internal::dispatchEventCallback): + * bindings/scripts/test/V8/V8TestInterface.cpp: + (WebCore::TestInterfaceV8Internal::supplementalStaticAttrAttrSetter): + (WebCore::TestInterfaceV8Internal::supplementalStr2AttrSetter): + (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): + (WebCore::V8TestInterface::constructorCallback): + * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: + (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): + * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: + (WebCore::V8TestNamedConstructorConstructorCallback): + * bindings/scripts/test/V8/V8TestObj.cpp: + (WebCore::TestObjV8Internal::staticStringAttrAttrSetter): + (WebCore::TestObjV8Internal::stringAttrAttrSetter): + (WebCore::TestObjV8Internal::reflectedStringAttrAttrSetter): + (WebCore::TestObjV8Internal::reflectedURLAttrAttrSetter): + (WebCore::TestObjV8Internal::reflectedCustomURLAttrAttrSetter): + (WebCore::TestObjV8Internal::stringAttrWithGetterExceptionAttrSetter): + (WebCore::TestObjV8Internal::stringAttrWithSetterExceptionAttrSetter): + (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): + (WebCore::TestObjV8Internal::longMethodWithArgsCallback): + (WebCore::TestObjV8Internal::objMethodWithArgsCallback): + (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): + (WebCore::TestObjV8Internal::methodReturningSequenceCallback): + (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): + (WebCore::TestObjV8Internal::idbKeyCallback): + (WebCore::TestObjV8Internal::optionsObjectCallback): + (WebCore::TestObjV8Internal::methodWithOptionalArgCallback): + (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): + (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): + (WebCore::TestObjV8Internal::methodWithOptionalStringCallback): + (WebCore::TestObjV8Internal::methodWithOptionalStringIsUndefinedCallback): + (WebCore::TestObjV8Internal::methodWithOptionalStringIsNullStringCallback): + (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): + (WebCore::TestObjV8Internal::overloadedMethod1Callback): + (WebCore::TestObjV8Internal::overloadedMethod2Callback): + (WebCore::TestObjV8Internal::overloadedMethod3Callback): + (WebCore::TestObjV8Internal::overloadedMethod4Callback): + (WebCore::TestObjV8Internal::overloadedMethod6Callback): + (WebCore::TestObjV8Internal::overloadedMethod7Callback): + (WebCore::TestObjV8Internal::overloadedMethod8Callback): + (WebCore::TestObjV8Internal::overloadedMethod9Callback): + (WebCore::TestObjV8Internal::overloadedMethod10Callback): + (WebCore::TestObjV8Internal::overloadedMethod11Callback): + (WebCore::TestObjV8Internal::classMethodWithOptionalCallback): + (WebCore::TestObjV8Internal::overloadedMethod12Callback): + (WebCore::TestObjV8Internal::classMethodWithClampCallback): + (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): + (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): + (WebCore::TestObjV8Internal::enabledPerContextMethod1Callback): + (WebCore::TestObjV8Internal::enabledPerContextMethod2Callback): + (WebCore::TestObjV8Internal::stringArrayFunctionCallback): + (WebCore::TestObjV8Internal::convert1Callback): + (WebCore::TestObjV8Internal::convert2Callback): + (WebCore::TestObjV8Internal::convert4Callback): + (WebCore::TestObjV8Internal::convert5Callback): + (WebCore::TestObjV8Internal::strictFunctionCallback): + (WebCore::TestObjV8Internal::variadicStringMethodCallback): + (WebCore::TestObjV8Internal::variadicDoubleMethodCallback): + (WebCore::TestObjV8Internal::variadicNodeMethodCallback): + * bindings/scripts/test/V8/V8TestOverloadedConstructors.cpp: + (WebCore::V8TestOverloadedConstructors::constructor1Callback): + (WebCore::V8TestOverloadedConstructors::constructor2Callback): + (WebCore::V8TestOverloadedConstructors::constructor3Callback): + (WebCore::V8TestOverloadedConstructors::constructor4Callback): + * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: + (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): + * bindings/v8/V8Binding.h: + (WebCore::toV8Sequence): + * bindings/v8/V8BindingMacros.h: + * bindings/v8/custom/V8BlobCustom.cpp: + (WebCore::V8Blob::constructorCallbackCustom): + * bindings/v8/custom/V8ConsoleCustom.cpp: + (WebCore::V8Console::profileCallback): + (WebCore::V8Console::profileEndCallback): + * bindings/v8/custom/V8DOMWindowCustom.cpp: + (WebCore::handlePostMessageCallback): + * bindings/v8/custom/V8DataViewCustom.cpp: + (WebCore::V8DataView::getInt8Callback): + (WebCore::V8DataView::getUint8Callback): + (WebCore::V8DataView::setInt8Callback): + (WebCore::V8DataView::setUint8Callback): + * bindings/v8/custom/V8DeviceMotionEventCustom.cpp: + (WebCore::V8DeviceMotionEvent::initDeviceMotionEventCallback): + * bindings/v8/custom/V8DeviceOrientationEventCustom.cpp: + (WebCore::V8DeviceOrientationEvent::initDeviceOrientationEventCallback): + * bindings/v8/custom/V8DocumentCustom.cpp: + (WebCore::V8Document::evaluateCallback): + * bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp: + (WebCore::V8HTMLOptionsCollection::addCallback): + * bindings/v8/custom/V8HistoryCustom.cpp: + (WebCore::V8History::pushStateCallback): + (WebCore::V8History::replaceStateCallback): + * bindings/v8/custom/V8IntentCustom.cpp: + (WebCore::V8Intent::constructorCallbackCustom): + * bindings/v8/custom/V8SQLTransactionCustom.cpp: + (WebCore::V8SQLTransaction::executeSqlCallback): + * bindings/v8/custom/V8SQLTransactionSyncCustom.cpp: + (WebCore::V8SQLTransactionSync::executeSqlCallback): + * bindings/v8/custom/V8SVGLengthCustom.cpp: + (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): + * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: + (WebCore::V8WebGLRenderingContext::getExtensionCallback): + * bindings/v8/custom/V8WorkerContextCustom.cpp: + (WebCore::V8WorkerContext::importScriptsCallback): + +2012-11-26 Andreas Kling <akling@apple.com> + + Node: Move AreSVGAttributesValidFlag to ElementAttributeData. + <http://webkit.org/b/103349> + + Reviewed by Anders Carlsson. + + Moved AreSVGAttributesValidFlag to ElementAttributeData and change it to use "dirty" semantics. + This frees up a bit on Node, and we will always have ElementAttributeData if the animated + attributes are dirty anyway. + + * dom/Element.cpp: + (WebCore::Element::getAttribute): + * dom/Element.h: + (WebCore::Element::updateInvalidAttributes): + * dom/ElementAttributeData.cpp: + (WebCore::ElementAttributeData::ElementAttributeData): + * dom/ElementAttributeData.h: + (WebCore::ElementAttributeData::ElementAttributeData): + (ElementAttributeData): + * dom/Node.h: + (Node): + * svg/SVGElement.cpp: + (WebCore::SVGElement::updateAnimatedSVGAttribute): + * svg/SVGElement.h: + (WebCore::SVGElement::invalidateSVGAttributes): + +2012-11-26 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135798. + http://trac.webkit.org/changeset/135798 + https://bugs.webkit.org/show_bug.cgi?id=103354 + + Broke the chrome mac build (Requested by noel_ on #webkit). + + * platform/graphics/chromium/DeferredImageDecoder.cpp: + (WebCore::DeferredImageDecoder::~DeferredImageDecoder): + (WebCore::DeferredImageDecoder::createResizedLazyDecodingBitmap): + (WebCore::DeferredImageDecoder::frameBufferAtIndex): + (WebCore::DeferredImageDecoder::createLazyDecodingBitmap): + * platform/graphics/chromium/DeferredImageDecoder.h: + (DeferredImageDecoder): + * platform/graphics/chromium/ImageDecodingStore.cpp: + (WebCore::ImageDecodingStore::instanceOnMainThread): + (WebCore::ImageDecodingStore::initializeOnMainThread): + (WebCore::ImageDecodingStore::shutdown): + (WebCore::ImageDecodingStore::calledOnValidThread): + (WebCore::ImageDecodingStore::lookupFrameCache): + (WebCore::ImageDecodingStore::deleteFrameCache): + * platform/graphics/chromium/ImageDecodingStore.h: + (WebCore): + (ImageDecodingStore): + * platform/graphics/chromium/ImageFrameGenerator.cpp: + (WebCore::ImageFrameGenerator::ImageFrameGenerator): + (WebCore::ImageFrameGenerator::~ImageFrameGenerator): + (WebCore::ImageFrameGenerator::setData): + (WebCore::ImageFrameGenerator::decodeAndScale): + * platform/graphics/chromium/ImageFrameGenerator.h: + (WebCore): + (WebCore::ImageFrameGenerator::create): + (ImageFrameGenerator): + * platform/graphics/chromium/LazyDecodingPixelRef.cpp: + (WebCore::LazyDecodingPixelRef::LazyDecodingPixelRef): + (WebCore::LazyDecodingPixelRef::onLockPixels): + (WebCore::LazyDecodingPixelRef::onUnlockPixels): + * platform/graphics/chromium/LazyDecodingPixelRef.h: + (WebCore): + (LazyDecodingPixelRef): + * platform/graphics/chromium/ScaledImageFragment.cpp: + (WebCore::ScaledImageFragment::ScaledImageFragment): + (WebCore::ScaledImageFragment::isEqual): + (WebCore): + * platform/graphics/chromium/ScaledImageFragment.h: + (WebCore): + (WebCore::ScaledImageFragment::create): + (ScaledImageFragment): + * platform/graphics/chromium/SkSizeHash.h: Removed. + +2012-11-26 Huang Dongsung <luxtella@company100.net> + + [TexMap] GraphicsLayerTextureMapper::setSize() sets the size of a mask layer. + https://bugs.webkit.org/show_bug.cgi?id=103297 + + Reviewed by Noam Rosenthal. + + Currently, CoordinatedGraphicsLayer sets the size of a mask layer in setSize() + and setMaksLayer(). GraphicsLayerTextureMapper follows the behavior. If so we + don't have to check the size of the mask layer in TextureMapperLayer::flushCompositingState(). + + No new tests. Covered by existing tests. + + * platform/graphics/texmap/GraphicsLayerTextureMapper.cpp: + (WebCore::GraphicsLayerTextureMapper::setMaskLayer): + (WebCore::GraphicsLayerTextureMapper::setSize): + * platform/graphics/texmap/TextureMapperLayer.cpp: + (WebCore::TextureMapperLayer::flushCompositingState): + +2012-11-26 Kentaro Hara <haraken@chromium.org> + + [V8] Remove V8Parameter::object() + https://bugs.webkit.org/show_bug.cgi?id=103340 + + Reviewed by Adam Barth. + + V8Parameter can use m_v8Object directly. + + No tests. No change in behavior. + + * bindings/v8/V8StringResource.h: + (WebCore::::prepare): + +2012-11-26 Kentaro Hara <haraken@chromium.org> + + [V8] Rename V8Parameter to V8StringResource + https://bugs.webkit.org/show_bug.cgi?id=103341 + + Reviewed by Adam Barth. + + We can rename V8Parameter to V8StringResource. In a follow-up patch, + I will rename macros around V8Parameter. + + No tests. No change in behavior. + + * bindings/scripts/CodeGeneratorV8.pm: + (GenerateNormalAttrGetter): + (GenerateNormalAttrSetter): + (GenerateParametersCheck): + (GenerateEventConstructorCallback): + (GetNativeTypeFromSignature): + (GetNativeType): + (ConvertToV8StringResource): + * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: + (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): + * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: + (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): + * bindings/scripts/test/V8/V8TestEventConstructor.cpp: + (WebCore::V8TestEventConstructor::constructorCallback): + * bindings/scripts/test/V8/V8TestInterface.cpp: + (WebCore::TestInterfaceV8Internal::supplementalStaticAttrAttrSetter): + (WebCore::TestInterfaceV8Internal::supplementalStr2AttrSetter): + (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): + (WebCore::V8TestInterface::constructorCallback): + * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: + (WebCore::V8TestNamedConstructorConstructorCallback): + * bindings/scripts/test/V8/V8TestObj.cpp: + (WebCore::TestObjV8Internal::staticStringAttrAttrSetter): + (WebCore::TestObjV8Internal::stringAttrAttrSetter): + (WebCore::TestObjV8Internal::reflectedStringAttrAttrSetter): + (WebCore::TestObjV8Internal::reflectedURLAttrAttrSetter): + (WebCore::TestObjV8Internal::reflectedCustomURLAttrAttrSetter): + (WebCore::TestObjV8Internal::stringAttrWithGetterExceptionAttrSetter): + (WebCore::TestObjV8Internal::stringAttrWithSetterExceptionAttrSetter): + (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): + (WebCore::TestObjV8Internal::longMethodWithArgsCallback): + (WebCore::TestObjV8Internal::objMethodWithArgsCallback): + (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): + (WebCore::TestObjV8Internal::methodWithOptionalStringCallback): + (WebCore::TestObjV8Internal::methodWithOptionalStringIsUndefinedCallback): + (WebCore::TestObjV8Internal::methodWithOptionalStringIsNullStringCallback): + (WebCore::TestObjV8Internal::overloadedMethod1Callback): + (WebCore::TestObjV8Internal::overloadedMethod3Callback): + (WebCore::TestObjV8Internal::overloadedMethod11Callback): + (WebCore::TestObjV8Internal::overloadedMethod12Callback): + (WebCore::TestObjV8Internal::strictFunctionCallback): + (WebCore::TestObjV8Internal::variadicStringMethodCallback): + * bindings/scripts/test/V8/V8TestOverloadedConstructors.cpp: + (WebCore::V8TestOverloadedConstructors::constructor4Callback): + * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: + (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): + * bindings/v8/V8StringResource.h: + (WebCore::V8StringResource::V8StringResource): + (WebCore::::prepare): + * bindings/v8/custom/V8ConsoleCustom.cpp: + (WebCore::V8Console::profileCallback): + (WebCore::V8Console::profileEndCallback): + * bindings/v8/custom/V8DOMWindowCustom.cpp: + (WebCore::handlePostMessageCallback): + * bindings/v8/custom/V8DeviceMotionEventCustom.cpp: + (WebCore::V8DeviceMotionEvent::initDeviceMotionEventCallback): + * bindings/v8/custom/V8DeviceOrientationEventCustom.cpp: + (WebCore::V8DeviceOrientationEvent::initDeviceOrientationEventCallback): + * bindings/v8/custom/V8HistoryCustom.cpp: + (WebCore::V8History::pushStateCallback): + (WebCore::V8History::replaceStateCallback): + * bindings/v8/custom/V8IntentCustom.cpp: + (WebCore::V8Intent::constructorCallbackCustom): + * bindings/v8/custom/V8SQLTransactionCustom.cpp: + (WebCore::V8SQLTransaction::executeSqlCallback): + * bindings/v8/custom/V8SQLTransactionSyncCustom.cpp: + (WebCore::V8SQLTransactionSync::executeSqlCallback): + * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: + (WebCore::V8WebGLRenderingContext::getExtensionCallback): + +2012-11-26 Andreas Kling <akling@apple.com> + + HTMLOptionElement: Remove two unused members. + <http://webkit.org/b/103337> + + Reviewed by Kent Tamura. + + Remove two unused members from HTMLOptionElement, m_value and m_label. + 40kB progression on Membuster3. + + * html/HTMLOptionElement.h: + (HTMLOptionElement): + +2012-11-26 Stephen White <senorblanco@chromium.org> + + [Chromium] Shared graphics context should only pushGroupMarker() once + https://bugs.webkit.org/show_bug.cgi?id=103082 + + Reviewed by James Robinson. + + GraphicsContext3D's pushGroupMarkerEXT() is being called every time + an ImageBuffer is created, leading to unlimited memory growth, since + they share a common GraphicsContext3D. It should be called only once, + on context creation. + + Tested by manually checking the memory usage in Chrome's TaskManager. + (Sorry, I can't think of a way to test this automatically.) + + * platform/graphics/gpu/SharedGraphicsContext3D.cpp: + (WebCore::SharedGraphicsContext3DImpl::getOrCreateContext): + * platform/graphics/skia/ImageBufferSkia.cpp: + (WebCore::createAcceleratedCanvas): + +2012-11-26 Kentaro Hara <haraken@chromium.org> + + [V8] Remove WorkerContextExecutionProxy.{h,cpp} + https://bugs.webkit.org/show_bug.cgi?id=103325 + + Reviewed by Adam Barth. + + Now WorkerContextExecutionProxy.{h,cpp} are empty. + + No tests. No change in behavior. + + * UseV8.cmake: + * WebCore.gypi: + * bindings/v8/ScheduledAction.cpp: + * bindings/v8/V8AbstractEventListener.cpp: + * bindings/v8/V8DOMWrapper.cpp: + * bindings/v8/V8WorkerContextEventListener.h: + (WebCore): + * bindings/v8/WorkerContextExecutionProxy.cpp: Removed. + * bindings/v8/WorkerContextExecutionProxy.h: Removed. + * bindings/v8/WorkerScriptController.cpp: + * bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp: + * bindings/v8/custom/V8MessageChannelCustom.cpp: + * bindings/v8/custom/V8MessagePortCustom.cpp: + * bindings/v8/custom/V8WorkerCustom.cpp: + * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: + +2012-11-26 Michael Saboff <msaboff@apple.com> + + Grapheme cluster functions can be simplified for 8 bit Strings + https://bugs.webkit.org/show_bug.cgi?id=102996 + + Reviewed by Alexey Proskuryakov. + + For 8 bit strings, check for the uncommon CR-LF by looking for any CR. If there aren't any CR characters, + the number of Extended Grapheme Clusters is equal to the string length. If we need to handle Tailored + Graheme Clusters, then this will need to change. + + No new tests. No change in functionality. + + * platform/text/TextBreakIterator.cpp: + (WebCore::numGraphemeClusters): + (WebCore::numCharactersInGraphemeClusters): + +2012-11-26 Istiaque Ahmed <lazyboy@chromium.org> + + Check for empty perContextData while creating NP V8 Object. + https://bugs.webkit.org/show_bug.cgi?id=98448 + + Reviewed by Adam Barth. + + Fixes crash in npCreateV8ScriptObject(), if NP Invoke is called from a document + that is no longer displayed in frame (isCurrentlyDisplayedInFrame() == + false), we have empty perContextData and this results in invalid memory access. + + Test: platform/chromium/plugins/empty-per-context-data.html + + * bindings/v8/NPV8Object.cpp: + (WebCore::npCreateV8ScriptObject): + +2012-11-26 Michael Saboff <msaboff@apple.com> + + HTML/XML parser helper unconsumeCharacters() can push back 8 bit text as 16 bit text + https://bugs.webkit.org/show_bug.cgi?id=103317 + + Reviewed by Oliver Hunt. + + Changed to use the String directly from the StringBuilder instead of creating our own. + Used toStringPreserveCapacity() in case the caller may want to add to the StringBuilder + even though current callers don't. + + No new tests. No change in functionality. + + * xml/parser/CharacterReferenceParserInlines.h: + (WebCore::unconsumeCharacters): + +2012-11-26 Noel Gordon <noel.gordon@gmail.com> + + PNG decode performance: avoid using frame buffer.setRGBA(x,y) + https://bugs.webkit.org/show_bug.cgi?id=103216 + + Reviewed by Brent Fulgham. + + Writing decoded row pixels to the frame buffer with buffer.setRGBA(x,y) is slow compared + to writing direct to the frame buffer address. Use buffer.getAddr() to obtain the output + pixel row address, write the decoded row pixels to that address. + + No new tests. Covered by many existing tests. + + * platform/image-decoders/ImageDecoder.h: + (WebCore::ImageFrame::setRGBA): Make routine setRGBA(PixelData* dest, ...) public. Test + m_premultiplyAlpha once to minimize code branching in this routine. + * platform/image-decoders/png/PNGImageDecoder.cpp: + (WebCore::PNGImageDecoder::rowAvailable): Write decoded row pixels to the frame buffer + using the pixel address form: buffer.setRGBA(address++, ...). + +2012-11-26 Alpha Lam <hclam@chromium.org> + + [chromium] Implement full-featured image cache + https://bugs.webkit.org/show_bug.cgi?id=99784 + + Reviewed by James Robinson. + + Implement a thread-safe image cache to be used with deferred image + decoding. Image cache can now be accessed on any thread. + + The patch implements the following logic: + 1. Mutex to protect all cache operations. + 2. Cache indexing using key (ImageFrameGenerator*, SkISize scaledSize) + 3. Cache lookup. + 4. Cache insertion. + 5. Generation of cache entry by scaling full size image. + 6. Generation of cache entries by decoding and scaling. + + Classes involved: + + ImageDecodingStore + + Responsible for owning cache entries and indexing. Pruning and memory + management will be added later. + + ImageFrameGenerator + + Responsible for generating new cache enties and insert them into + ImageDecodingStore. + + LazyDecodingPixelRef + + Responsible for cache lookup and lazy generation of cache entries + using ImageFrameGenerator. There is a mutex to protect concurrent + lock operations. + + These items are not implemented in this patch: + 1. Cache pruning. + 2. Setting cache memory limit. + 3. Cache deletion. + 4. Caching incomplete images and ImageDecoder. + + Unit tests added in ImageFrameGeneratorTest.cpp. + Layout tests are under platform/chromium/virtual/fast/images. + + * platform/graphics/chromium/DeferredImageDecoder.cpp: + (WebCore::DeferredImageDecoder::~DeferredImageDecoder): + (WebCore::DeferredImageDecoder::createResizedLazyDecodingBitmap): + (WebCore::DeferredImageDecoder::setEnabled): + (WebCore): + (WebCore::DeferredImageDecoder::frameBufferAtIndex): + (WebCore::DeferredImageDecoder::createLazyDecodingBitmap): + * platform/graphics/chromium/DeferredImageDecoder.h: + (DeferredImageDecoder): + * platform/graphics/chromium/ImageDecodingStore.cpp: + (WebCore::ImageDecodingStore::instance): + (WebCore::ImageDecodingStore::initializeOnce): + (WebCore::ImageDecodingStore::shutdown): + (WebCore::ImageDecodingStore::lockCompleteCache): + Lookup complete cache entry using hash key, increment use count. + (WebCore::ImageDecodingStore::lockIncompleteCache): TODO. + (WebCore::ImageDecodingStore::unlockCache): + Lookup cache entry using hash key, decrement use count. + (WebCore): + (WebCore::ImageDecodingStore::insertAndLockCache): + Insert new cache entry and increment use count. + (WebCore::ImageDecodingStore::prune): TODO. + * platform/graphics/chromium/ImageDecodingStore.h: + (WebCore): + (ImageDecodingStore): + (WebCore::ImageDecodingStore::CacheEntry::create): + (WebCore::ImageDecodingStore::CacheEntry::createAndUse): + (CacheEntry): + (WebCore::ImageDecodingStore::CacheEntry::CacheEntry): + (WebCore::ImageDecodingStore::CacheEntry::~CacheEntry): + * platform/graphics/chromium/ImageFrameGenerator.cpp: + (WebCore::ImageFrameGenerator::ImageFrameGenerator): + (WebCore::ImageFrameGenerator::setData): + (WebCore::ImageFrameGenerator::decodeAndScale): + Method for creating new cache entries. This is protected by a mutex + to prevent concurrent operations. Which means only one thread can + generate new cache entries for a set of encoded data. + (WebCore): + (WebCore::ImageFrameGenerator::tryToLockCache): + Tries to lookup a cache entry. + (WebCore::ImageFrameGenerator::tryToScale): + Tries to lookup a full size cache entry and generate a scaled version. + (WebCore::ImageFrameGenerator::tryToDecodeAndScale): + Tries to decode and scale. + * platform/graphics/chromium/ImageFrameGenerator.h: + (WebCore): + (ImageDecoderFactory): + (WebCore::ImageFrameGenerator::create): + (ImageFrameGenerator): + (WebCore::ImageFrameGenerator::setImageDecoderFactoryForTesting): + * platform/graphics/chromium/LazyDecodingPixelRef.cpp: + (WebCore::LazyDecodingPixelRef::LazyDecodingPixelRef): + (WebCore::LazyDecodingPixelRef::onLockPixels): + (WebCore::LazyDecodingPixelRef::onUnlockPixels): + * platform/graphics/chromium/LazyDecodingPixelRef.h: + (WebCore): + (LazyDecodingPixelRef): + * platform/graphics/chromium/ScaledImageFragment.cpp: + (WebCore::ScaledImageFragment::ScaledImageFragment): + * platform/graphics/chromium/ScaledImageFragment.h: + (WebCore): + (WebCore::ScaledImageFragment::create): + (ScaledImageFragment): + (WebCore::ScaledImageFragment::scaledSize): + * platform/graphics/chromium/SkSizeHash.h: Added. + (WTF): + +2012-11-26 Andreas Kling <akling@apple.com> + + Node: Remove IsSynchronizingSVGAttributesFlag. + <http://webkit.org/b/103328> + + Reviewed by Antti Koivisto. + + Animated SVG attributes used to be synchronized by using DOM API which could use unwanted re-entrancy + via callbacks below Element::attributeChanged(). The "is synchronizing SVG attributes" flag was used + to protect against such re-entrancy. + + These days, lazy attributes are synchronized using Element::setSynchronizedLazyAttribute() to avoid + issues like this. The flag does nothing, so we can just remove it. + + * dom/Node.h: + (WebCore): + * svg/SVGElement.cpp: + (WebCore::SVGElement::attributeChanged): + (WebCore::SVGElement::updateAnimatedSVGAttribute): + +2012-11-26 Kentaro Hara <haraken@chromium.org> + + [V8] Refactor WorkerScriptController + https://bugs.webkit.org/show_bug.cgi?id=103330 + + Reviewed by Adam Barth. + + r135703 just moved methods from WorkerContextExecutionProxy + to WorkerScriptController. We should refactor the methods as a follow-up. + + No tests. No change in behavior. + + * bindings/v8/WorkerScriptController.cpp: + (WebCore::WorkerScriptController::~WorkerScriptController): + (WebCore::WorkerScriptController::disposeContext): + (WebCore::WorkerScriptController::initializeContextIfNeeded): + (WebCore::WorkerScriptController::evaluate): + (WebCore::WorkerScriptController::disableEval): + * bindings/v8/WorkerScriptController.h: + (WorkerScriptController): + +2012-11-26 Varun Jain <varunjain@chromium.org> + + LongPress and LongTap gestures should start drag/drop and open context menu respectively. + https://bugs.webkit.org/show_bug.cgi?id=101545 + + Reviewed by Antonio Gomes. + + For LongPress, we simulate drag by sending a mouse down and mouse drag + events. If a drag is not started (because maybe there is no draggable + element), then we show context menu instead (which is the current + behavior for LongPress). For LongTap, we use the existing functions that + LongPress uses to summon the context menu. LongPress initiated drag and + drop can be enabled/disabled by the platform using the Setting + touchDragDropEnabled which is disabled by default. + + Tests: fast/events/touch/gesture/context-menu-on-long-tap.html + fast/events/touch/gesture/long-press-on-draggable-element-triggers-drag.html + + * page/EventHandler.cpp: + (WebCore::EventHandler::EventHandler): + (WebCore::EventHandler::clear): + (WebCore::EventHandler::handleMouseDraggedEvent): + (WebCore::EventHandler::handleGestureEvent): + (WebCore::EventHandler::handleGestureLongPress): + (WebCore::EventHandler::handleGestureLongTap): + (WebCore): + (WebCore::EventHandler::handleGestureForTextSelectionOrContextMenu): + (WebCore::EventHandler::adjustGesturePosition): + (WebCore::EventHandler::handleDrag): + * page/EventHandler.h: + (EventHandler): + * page/Settings.in: + +2012-11-26 Andreas Kling <akling@apple.com> + + RenderStyle: Move 'list-style-image' to rare inherited data. + <http://webkit.org/b/103300> + + Reviewed by Antti Koivisto. + + list-style-image is not nearly common enough to merit a spot in StyleInheritedData. + Move it to StyleRareInheritedData. + + 134kB progression on Membuster3. + + * rendering/style/RenderStyle.cpp: + (WebCore::RenderStyle::diff): + (WebCore::RenderStyle::listStyleImage): + (WebCore::RenderStyle::setListStyleImage): + * rendering/style/StyleInheritedData.cpp: + (WebCore::StyleInheritedData::StyleInheritedData): + (WebCore::StyleInheritedData::operator==): + * rendering/style/StyleInheritedData.h: + (StyleInheritedData): + * rendering/style/StyleRareInheritedData.h: + * rendering/style/StyleRareInheritedData.cpp: + (SameSizeAsStyleRareInheritedData): + (WebCore::StyleRareInheritedData::StyleRareInheritedData): + (WebCore::StyleRareInheritedData::operator==): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + There's a FIXME that we have too many FrameLoader::load*() functions. This patch consolidates 3 into 1. + There are still a few more load functions that will be consolidated later. Using FrameLoadRequest as + the interface into FrameLoader will also provide a place to pass in the initiator. Finally, this matches + the refactoring done with CachedResourceRequest and CachedResourceLoader. + + No new tests. No change in functionality. + + * WebCore.exp.in: + * loader/FrameLoadRequest.h: + (WebCore::FrameLoadRequest::FrameLoadRequest): + (WebCore::FrameLoadRequest::setLockHistory): These are former arguments to load(). + (WebCore::FrameLoadRequest::lockHistory): Ditto. + (FrameLoadRequest): + (WebCore::FrameLoadRequest::setShouldCheckNewWindowPolicy): Ditto. + (WebCore::FrameLoadRequest::shouldCheckNewWindowPolicy): Ditto. + (WebCore::FrameLoadRequest::substituteData): Ditto. + (WebCore::FrameLoadRequest::setSubstituteData): Ditto. + (WebCore::FrameLoadRequest::hasSubstituteData): Ditto. + * loader/FrameLoader.cpp: + (WebCore::FrameLoader::load): No change in behavior, just merged it all into one function. + * loader/FrameLoader.h: + (FrameLoader): + * page/DragController.cpp: + (WebCore::DragController::performDrag): + +2012-11-24 Genevieve Mak <gmak@rim.com> + + [BlackBerry] Stop sending touch events to plugins. + https://bugs.webkit.org/show_bug.cgi?id=103188 + + Reviewed by Rob Buis. + + Reviewed internally by Jeff Rogers and Mike Lattanzio. + No tests required. + PR #248605 + + * plugins/blackberry/PluginViewBlackBerry.cpp: + (WebCore::PluginView::handleTouchEvent): + (WebCore::PluginView::handleMouseEvent): + +2012-11-26 Adenilson Cavalcanti <cavalcantii@gmail.com> + + Removing unnecessary friend classes in RenderObject: LayoutRepainter, RenderSVGContainer + https://bugs.webkit.org/show_bug.cgi?id=103164 + + Reviewed by Simon Fraser. + + Removing some of classes marked as friend of RenderObject. This patch solves this issue + for 2 classes: RenderSVGContainer (that is derived from RenderObject) and LayoutRepainter + (that accesses one const member function in RenderObject that is now made public). + + No new tests, no changes in functionality. + + * rendering/RenderObject.h: + (RenderObject): + (WebCore::RenderObject::outlineBoundsForRepaint): + +2012-11-26 Jon Lee <jonlee@apple.com> + + Pass clicks through to the restarted plugin + https://bugs.webkit.org/show_bug.cgi?id=102150 + <rdar://problem/12695575> + + Reviewed by Simon Fraser. + + Add a new state to the machine for plugin snapshotting, called PlayingWithPendingMouseClick. + This represents the state where the plugin is playing, but before the pending mouse click + has been fired. Once the click is sent, the plugin state transitions to Playing. For + situations where the plugin just runs normally without a simulated click, the plugin state + jumps from DisplayingSnapshot straight to Playing, as before. + + * html/HTMLPlugInElement.h: Add new display state to represent when the plugin is running, + but a pending mouse click is about to be sent to the plugin. + (WebCore::HTMLPlugInElement::dispatchPendingMouseClick): Called by the plugin when it is + ok for the element to send the pending mouse click. + * html/HTMLPlugInElement.cpp: + (WebCore::HTMLPlugInElement::defaultEventHandler): Update the handler to pass the event + to the renderer to handle if the state is before PlayingWithPendingMouseClick. + + * html/HTMLPlugInImageElement.h: + * html/HTMLPlugInImageElement.cpp: Add a click timer to delay the mouse click so that the + plugin has some time to initialize. + (WebCore::HTMLPlugInImageElement::HTMLPlugInImageElement): Initialize the mouse timer. + (WebCore::HTMLPlugInImageElement::setPendingClickEvent): Keep track of the click event + the user made to restart the plugin. + (WebCore::HTMLPlugInImageElement::dispatchPendingMouseClick): Start the timer. + (WebCore::HTMLPlugInImageElement::simulatedMouseClickTimerFired): When the timer fires, + dispatch the simulated click, with mouse over, mouse down, and mouse up events. Transition + to the Playing state, and we no longer need the click event. + + * rendering/RenderSnapshottedPlugIn.cpp: Change the threshold state to PlayingWithPendingMouseClick + instead of Playing, since that is the earliest state where the plugin is playing. + (WebCore::RenderSnapshottedPlugIn::paint): + (WebCore::RenderSnapshottedPlugIn::paintReplaced): + (WebCore::RenderSnapshottedPlugIn::getCursor): + (WebCore::RenderSnapshottedPlugIn::handleEvent): If the user clicked on the button, jump to + Playing, and don't send a simulated click. Otherwise, transition to PlayingWithPendingMouseClick, + and keep track of that mouse event. + + * WebCore.exp.in: Export MouseRelatedEvent::offsetX() and offsetY(). + +2012-11-26 Dan Carney <dcarney@google.com> + + Refactor V8 bindings to allow content scripts to access subframes + https://bugs.webkit.org/show_bug.cgi?id=93646 + + Reviewed by Adam Barth. + + Isolated window shells are now initialized on the fly + as needed. + + No new tests. Existing test modified. + + * bindings/v8/DOMWrapperWorld.cpp: + (WebCore::DOMWrapperWorld::ensureIsolatedWorld): + * bindings/v8/DOMWrapperWorld.h: + (WebCore::DOMWrapperWorld::createdFromUnitializedWorld): + (DOMWrapperWorld): + * bindings/v8/ScriptController.cpp: + (WebCore::ScriptController::currentWorldContext): + +2012-11-26 Alex Christensen <alex.christensen@flexsim.com> + + clipboardwin compile error for win64 + https://bugs.webkit.org/show_bug.cgi?id=94124 + + Reviewed by Brent Fulgham. + + The clipboard utilities code uses std::min with one unsigned int parameter and one size_t parameter. + This causes a problem when compiling for 64-bit Windows because the two types are not the same size. + To resolve this issue, we specify the template type as the type the return value is being cast into + + Fixed a few compile errors for Windows x64 by specifying template parameters. + + * platform/win/ClipboardUtilitiesWin.cpp: + (WebCore::setFileDescriptorData): Specify the types for the std::min macro to avoid compiler errors + under 64-bit builds. + +2012-11-26 Arnaud Renevier <a.renevier@sisa.samsung.com> + + [GTK] GtkSocket is leaked until webview is destroyed. + https://bugs.webkit.org/show_bug.cgi?id=102564 + + Reviewed by Martin Robinson. + + Remove GtkSocket from its parent when pluginview is destroyed. Then, + the GtkSocket and it's possible child widgets are realeased when it is + no more needed. + + No new tests, already covered by existing tests. + + * plugins/gtk/PluginViewGtk.cpp: + (WebCore::PluginView::platformDestroy): + +2012-11-26 Luke Macpherson <macpherson@chromium.org> + + Make StyleResolver::applyProperty use isInherit in CSSPropertyWebkitMarquee instead of calculating equivalent in-place. + https://bugs.webkit.org/show_bug.cgi?id=102446 + + Reviewed by Tony Chang. + + !m_parentNode || !value->isInheritedValue() is equivalent to !isInherit (by De Morgan's law). + + No new tests / code is provably equivalent. + + * css/StyleResolver.cpp: + (WebCore::StyleResolver::applyProperty): + +2012-11-26 Pratik Solanki <psolanki@apple.com> + + Add ResourceBuffer::append(CFDataRef) to get code to compile with USE(NETWORK_CFDATA_ARRAY_CALLBACK) + https://bugs.webkit.org/show_bug.cgi?id=102706 + + Reviewed by Brent Fulgham. + + No new tests because the flag isn't enabled. Also the functionality should be covered by + existing tests. + + * loader/ResourceBuffer.cpp: + (WebCore): + (WebCore::ResourceBuffer::append): + * loader/ResourceBuffer.h: + (ResourceBuffer): + * loader/mac/ResourceLoaderMac.mm: + +2012-11-26 Tony Chang <tony@chromium.org> + + Move more functions from internals.settings to internals + https://bugs.webkit.org/show_bug.cgi?id=102976 + + Reviewed by Adam Barth. + + Move functions that don't have to do with Settings off of internals.settings. + setPagination and configurationForViewport were defined on internals, so we + can inline the functions (no test change). + + setEnableMockPagePopup is moved to Internals. + + No new tests, this is a refactor. + + * testing/InternalSettings.cpp: + (WebCore::InternalSettings::reset): Move reset code into Internals. + * testing/InternalSettings.h: + (InternalSettings): Remove code for setPagination, configurationForViewport and setEnableMockPagePopup. + * testing/InternalSettings.idl: Remove setPagination and setEnableMockPagePopup. + * testing/Internals.cpp: + (WebCore): Use a static to keep track of the MockPagePopupDriver. + (WebCore::Internals::resetToConsistentState): Code from InternalSettings::reset + (WebCore::Internals::setEnableMockPagePopup): Code copied from InternalSettings. + (WebCore::Internals::pagePopupController): Code copied from InternalSettings. + (WebCore::Internals::setPagination): Code copied from InternalSettings. + (WebCore::Internals::configurationForViewport): Code copied from InternalSettings. + * testing/Internals.h: + (Internals): Add setEnableMockPagePopup. + * testing/Internals.idl: Add setEnableMockPagePopup. + +2012-11-26 Andrei Bucur <abucur@adobe.com> + + [CSS Regions] Add Region info for RootLineBoxes and pack the pagination data + https://bugs.webkit.org/show_bug.cgi?id=101332 + + Reviewed by David Hyatt. + + Currently the pagination information for lines is spread between the RootInlineBox and InlineFlowBox classes, consuming memory even though + the boxes were not the result of an pagination layout. To overcome this, a new struct (LineFragmentationData) is created that wraps all the data, + including two new members, the containing Region for the line and a boolean that states if the line was laid out in a Region or not. + The flag is necessary because the sanitize function on LineFragmentationData resets the containing Region to 0 if the Region was removed from + chain (so a value of 0 for the containing Region means two things). The sanitize function should prevent access to an invalid address. + The containing Region is used to detect if a line changed the Region where it resides. This will be helpful especially when implementing region + styling for layout properties (e.g. the font-size property https://bugs.webkit.org/show_bug.cgi?id=95559 ). + A line can change the region when it is shifted inside the containing block or if the entire block moves. This means it's better to delegate + the task of updating the containing Region to the block. + + Tests: fast/regions/line-containing-region-crash.html + + * rendering/InlineFlowBox.cpp: + (SameSizeAsInlineFlowBox): + * rendering/InlineFlowBox.h: + (WebCore::InlineFlowBox::InlineFlowBox): + (InlineFlowBox): + * rendering/RenderBlock.cpp: + (WebCore::RenderBlock::lineWidthForPaginatedLineChanged): + * rendering/RenderBlockLineLayout.cpp: + (WebCore::RenderBlock::layoutRunsAndFloatsInRange): + (WebCore::RenderBlock::linkToEndLineIfNeeded): + (WebCore::RenderBlock::determineStartPosition): + * rendering/RootInlineBox.cpp: + (WebCore::RootInlineBox::RootInlineBox): + (WebCore::RootInlineBox::setContainingRegion): + (WebCore): + (WebCore::RootInlineBox::LineFragmentationData::sanitize): This is an O(1) function that checks if the containig Region is still valid pointer. + * rendering/RootInlineBox.h: + (WebCore): + (WebCore::RootInlineBox::paginationStrut): + (WebCore::RootInlineBox::setPaginationStrut): + (WebCore::RootInlineBox::isFirstAfterPageBreak): + (WebCore::RootInlineBox::setIsFirstAfterPageBreak): + (WebCore::RootInlineBox::paginatedLineWidth): + (WebCore::RootInlineBox::setPaginatedLineWidth): + (RootInlineBox): + (WebCore::RootInlineBox::containingRegion): + (WebCore::RootInlineBox::hasContainingRegion): Use this to determine if the line has a region or not. + (WebCore::RootInlineBox::ensureLineFragmentationData): + (LineFragmentationData): + (WebCore::RootInlineBox::LineFragmentationData::LineFragmentationData): + + +2012-11-26 Michelangelo De Simone <michelangelo@webkit.org> + + [CSS Shaders] Add IDL file and bindings for mix function + https://bugs.webkit.org/show_bug.cgi?id=93011 + + Reviewed by Dean Jackson. + + JavaScript bindings have been added for the Custom Filter mix() + function (WebKitCSSMixFunctionValue). As of now, this is only a + placeholder that extends CSSValueList without adding any new + property. + + Test: css3/filters/custom/custom-filter-mix-bindings.html + + * CMakeLists.txt: mix() IDL has been added to the Generator; + DerivedSources have been included. + * DerivedSources.cpp: Ditto. + * DerivedSources.make: Ditto. + * DerivedSources.pri: Ditto. + * GNUmakefile.list.am: Ditto. + * WebCore.gypi: Ditto. + * WebCore.vcproj/WebCore.vcproj: Ditto. + * WebCore.xcodeproj/project.pbxproj: Ditto. + * bindings/js/JSCSSValueCustom.cpp: + (WebCore::toJS): return a JSC DOM wrapper for WebKitCSSMixFunctionValue. + * bindings/v8/custom/V8CSSValueCustom.cpp: + (WebCore::V8CSSValue::dispatchWrapCustom): Ditto, for V8. + * css/WebKitCSSMixFunctionValue.idl: Added. + +2012-11-26 Simon Fraser <simon.fraser@apple.com> + + Optimize layer updates after scrolling + https://bugs.webkit.org/show_bug.cgi?id=102635 + + Reviewed by Sam Weinig. + + updateLayerPositionsAfterScroll() previously unconditionally cleared clip + rects, and recomputed repaint rects too often. Recomputing both of these + can be very expensive, as they involve tree walks up to the root. + + We can optimize layer updates after document scrolling by only clearing clip + rects, and recomputing repaint rects, if we encounter a fixed- or sticky-position + element. For overflow scroll, we have to clear clip rects and recompute repaint rects. + + * page/FrameView.cpp: + (WebCore::FrameView::repaintFixedElementsAfterScrolling): Call updateLayerPositionsAfterDocumentScroll(). + * rendering/RenderLayer.cpp: + (WebCore::RenderLayer::updateLayerPositions): Call clearClipRects() because + updateLayerPosition() no longer does. + (WebCore::RenderLayer::updateLayerPositionsAfterDocumentScroll): Version of updateLayerPositionsAfterScroll() + that is for document scrolls. It has no need to push layers to the geometry map. + (WebCore::RenderLayer::updateLayerPositionsAfterOverflowScroll): Pushes layers to the geometry map, + and calls updateLayerPositionsAfterScroll() with the IsOverflowScroll flag. + (WebCore::RenderLayer::updateLayerPositionsAfterScroll): Set the HasChangedAncestor flag + if our location changed, and use that as a hint to clear cached rects. Be more conservative + than before about when to clear cached clip rects. + (WebCore::RenderLayer::updateLayerPosition): Move responsibility for calling + clearClipRects() ouf of this function and into callers. + (The one caller outside RenderLayer will be removed via bug 102624). + Return a bool indicating whether our position changed. + (WebCore::RenderLayer::scrollTo): Call updateLayerPositionsAfterOverflowScroll(). + (WebCore::RenderLayer::updateClipRects): Added some #ifdeffed out code that is useful + to verify that cached clips are correct; it's too slow to leave enabled in debug builds. + * rendering/RenderLayer.h: + (WebCore::RenderLayer::setLocation): Change to take a LayoutPoint, rather than separate + x and y. + +2012-11-26 Rafael Brandao <rafael.lobo@openbossa.org> + + [Cairo] Surface should not be destroyed before its usage + https://bugs.webkit.org/show_bug.cgi?id=103273 + + Reviewed by Brent Fulgham. + + * platform/graphics/texmap/TextureMapperGL.cpp: + (WebCore::TextureMapperGL::drawRepaintCounter): There's some calls to get + the bits and stride from surface right after its destructions. It should + be postponed to avoid annoying bugs. + +2012-11-26 Julien Chaffraix <jchaffraix@webkit.org> + + RenderBox::computePercentageLogicalHeight should use containingBlockLogicalWidthForContent + https://bugs.webkit.org/show_bug.cgi?id=103075 + + Reviewed by Ojan Vafai. + + Using the containing block's content logical block was working for most renderers but 2 renderers + were special and were broken in orthogonal writing modes: + - captions as they override containingBlockLogicalWidthForContent to return the table's logical width. + - multi-column renderers as they override availableLogicalWidth to constrain the child to the column logical width. + + By switching to containingBlockLogicalWidthForContent, we got those 2 cases covered. + + Tests: fast/multicol/fixed-column-percent-logical-height-orthogonal-writing-mode.html + fast/table/caption-orthogonal-writing-mode-sizing.html + + * rendering/RenderBox.cpp: + (WebCore::RenderBox::computePercentageLogicalHeight): + Updated the function to track which renderer's containing block we use and call + containingBlockLogicalWidthForContent on it. + +2012-11-26 Abhishek Arya <inferno@chromium.org> + + Crash in Frame::dispatchVisibilityStateChangeEvent. + https://bugs.webkit.org/show_bug.cgi?id=102053 + + Reviewed by Adam Barth. + + Child frame can go away inside webkitvisibilitychange + event handler. Store it in a ref counted vector. + + Test: fast/frames/page-visibility-crash.html + + * page/Frame.cpp: + (WebCore::Frame::dispatchVisibilityStateChangeEvent): + +2012-11-26 Hurnjoo Lee <hurnjoo.lee@samsung.com> + + [Cairo] fillRectWithColor with Color::transparent doesn't perform anything + https://bugs.webkit.org/show_bug.cgi?id=101911 + + Reviewed by Kenneth Rohde Christiansen. + + fillRectWithColor with Color::transparent doesn't perform anything + because fillRectWithColor does early-return if the alpha value of + color is zero. But we expect that fill the rect with transparent color + in case the cairo_operator is CAIRO_OPERATOR_SOURCE. + + Covered by existing tests. + + * platform/graphics/cairo/GraphicsContextCairo.cpp: + (WebCore::fillRectWithColor):Add condition to prevent early-return if + cairo_operator is not CAIRO_OPERATOR_OVER + +2012-11-26 Jae Hyun Park <jae.park@company100.net> + + Remove redundant assignment in TextureMapperLayer::flushCompositingStateSelf + https://bugs.webkit.org/show_bug.cgi?id=103233 + + Reviewed by Noam Rosenthal. + + This patch removes redundant assignment in TextureMapperLayer::flushCompositingStateSelf. + + No new tests, because no change in bahavior. + + * platform/graphics/texmap/TextureMapperLayer.cpp: + (WebCore::TextureMapperLayer::flushCompositingStateSelf): + +2012-11-26 Tamas Czene <tczene@inf.u-szeged.hu> + + OpenCL version of SourceAlpha, SourceGraphics and FETurbulence filter effects + https://bugs.webkit.org/show_bug.cgi?id=99829 + + Reviewed by Zoltan Herczeg. + + This patch contains the OpenCL implementation of SourceAlpha, SourceGraphic, FETurbulence and a simple OpenCL environment. + At the moment only the Qt build system is supported + ~3x speed-up (depending on hardware configuration) + + * Target.pri: + * WebCore.pri: + * platform/graphics/filters/FETurbulence.h: Added platformApplyOpenCL() virtual function. + (FETurbulence): + * platform/graphics/filters/FilterEffect.cpp: Added platform specific apply. + (WebCore::FilterEffect::apply): + (WebCore): + (WebCore::FilterEffect::platformApplyOpenCL): A function to use software computing if a filter is not implemented on OpenCL. It will be deleted after all of the filters are implemented. + (WebCore::FilterEffect::clearResult): + (WebCore::FilterEffect::asImageBuffer): + (WebCore::FilterEffect::openCLImageToImageBuffer): Gets the result of the filter from the OpenCL device and converts it to ImageBuffer type. + (WebCore::FilterEffect::createOpenCLImageResult): Allocates memory on OpenCL device and if it gets an image as a parameter, it uploads the image to the OpenCL device. + (WebCore::FilterEffect::transformResultColorSpace): + * platform/graphics/filters/FilterEffect.h: + (FilterEffect): + (WebCore::FilterEffect::openCLImage): + (WebCore::FilterEffect::setOpenCLImage): + (WebCore::FilterEffect::hasResult): + * platform/graphics/filters/SourceAlpha.h: + (SourceAlpha): + * platform/graphics/filters/SourceGraphic.h: + (SourceGraphic): + * platform/graphics/gpu/opencl/FilterContextOpenCL.cpp: Added. + (WebCore): + (WebCore::FilterContextOpenCL::context): Configures the OpenCL environment. + (WebCore::FilterContextOpenCL::createOpenCLImage): Allocates memory on OpenCL device. + (WebCore::FilterContextOpenCL::openCLTransformColorSpace): OpenCL implementation of transformColorSpace. + (WebCore::FilterContextOpenCL::compileProgram): + * platform/graphics/gpu/opencl/FilterContextOpenCL.h: Added. + (WebCore): + (FilterContextOpenCL): + (WebCore::FilterContextOpenCL::deviceId): + (WebCore::FilterContextOpenCL::deviceContext): + (WebCore::FilterContextOpenCL::commandQueue): + (RunKernel): + (WebCore::FilterContextOpenCL::RunKernel::RunKernel): + (WebCore::FilterContextOpenCL::RunKernel::addArgument): + (WebCore::FilterContextOpenCL::RunKernel::run): + (WebCore::FilterContextOpenCL::kernelByName): Returns the reference of a function in the OpenCL program. + * platform/graphics/gpu/opencl/OpenCLFESourceAlpha.cpp: Added. + (WebCore): + (WebCore::SourceAlpha::platformApplyOpenCL): + * platform/graphics/gpu/opencl/OpenCLFESourceGraphic.cpp: Added. + (WebCore): + (WebCore::SourceGraphic::platformApplyOpenCL): + * platform/graphics/gpu/opencl/OpenCLFETurbulence.cpp: Added. + (WebCore): + (WebCore::FilterContextOpenCL::compileFETurbulence): + (WebCore::FilterContextOpenCL::applyFETurbulence): + (WebCore::FETurbulence::platformApplyOpenCL): + * platform/graphics/gpu/opencl/OpenCLHandle.h: Added. + (WebCore): + (OpenCLHandle): + (WebCore::OpenCLHandle::OpenCLHandle): + (WebCore::OpenCLHandle::operator cl_mem): + (WebCore::OpenCLHandle::operator=): + (WebCore::OpenCLHandle::operator UnspecifiedBoolType): + (WebCore::OpenCLHandle::handleAddress): + (WebCore::OpenCLHandle::clear): + +2012-11-26 'Pavel Feldman' <pfeldman@chromium.org> + + Not reviewed: follow up for r135720, fixing node highlight. + + * inspector/InspectorOverlayPage.html: + +2012-11-26 Viatcheslav Ostapenko <v.ostapenko@samsung.com> + + [EFL] Crashes in compositing layout tests with AC on. + https://bugs.webkit.org/show_bug.cgi?id=103144 + + Reviewed by Noam Rosenthal. + + Application could leave texture packing parameters in non-zero state before + texture mapper drawing/texture uploading. To avoid crash texture upload should + specify packing parameters before each texture upload if packing is supported. + + Covered by existing tests. + + * platform/graphics/texmap/TextureMapperGL.cpp: + (WebCore::BitmapTextureGL::updateContentsNoSwizzle): + +2012-11-26 George Staikos <staikos@webkit.org> + + [BlackBerry] Remove a lot of unnecessary and incorrect code causing crashes + https://bugs.webkit.org/show_bug.cgi?id=103199 + + Reviewed by Yong Li. + + This is the first big step to unforking this code. It's very close to + where it needs to be now, but the first step is to get rid of the + crashes by deleting code that isn't needed and makes bad assumptions + about object lifetime. Crashes were found by automation without + test case or reproduction steps. + + * loader/blackberry/CookieJarBlackBerry.cpp: + (WebCore::cookies): delete most code + (WebCore::setCookies): delete most code + +2012-11-26 Thiago Marcos P. Santos <thiago.santos@intel.com> + + Viewport CSS rules should not clamp values like Viewport META + https://bugs.webkit.org/show_bug.cgi?id=103068 + + Reviewed by Kenneth Rohde Christiansen. + + CSS Device Adaption does not clamp the length and zoom values the + same way as the Viewport META. In fact, they are not clamped at all, + but instead, we just make sure that length values are at least 1px. + + Tests: css3/device-adapt/opera/constrain-018.xhtml + css3/device-adapt/opera/constrain-019.xhtml + css3/device-adapt/opera/constrain-023.xhtml + css3/device-adapt/opera/constrain-024.xhtml + + * dom/ViewportArguments.cpp: + (WebCore::ViewportArguments::resolve): + +2012-11-26 Mike West <mkwst@chromium.org> + + Web Inspector: URLs containing '^' are improperly linked in console messages. + https://bugs.webkit.org/show_bug.cgi?id=103248 + + Reviewed by Yury Semikhatsky. + + This patch adds '^' to WebInspector's regex of acceptable characters for + URLs that it knows how to display. + + Test: http/tests/inspector/network/script-as-text-loading-with-caret.html + + * inspector/front-end/ResourceUtils.js: + (WebInspector.linkifyStringAsFragmentWithCustomLinkifier): + +2012-11-26 Yury Semikhatsky <yurys@chromium.org> + + Unreviewed. Fix Qt minimal compilation after r135713. + + * inspector/InspectorController.h: hid file content behind ENABLE(INSPECTOR) + +2012-11-26 Pavel Feldman <pfeldman@chromium.org> + + Web Inspector: object preview does not render node id, className; logs too many functions for jQuery. + https://bugs.webkit.org/show_bug.cgi?id=103222 + + Reviewed by Yury Semikhatsky. + + - Added node class name and id into the preview + - Now keeps track of properties separately from array indexes. + + * inspector/InjectedScriptSource.js: + (.): + * inspector/InspectorOverlayPage.html: + * inspector/front-end/ConsoleMessage.js: + (WebInspector.ConsoleMessageImpl.prototype._appendObjectPreview): + (WebInspector.ConsoleMessageImpl.prototype._appendPropertyPreview): + +2012-11-26 Florin Malita <fmalita@chromium.org> + + RenderSVGResourceContainer does not clear cached data on removal + https://bugs.webkit.org/show_bug.cgi?id=102620 + + Reviewed by Dirk Schulze. + + RenderSVGResourceContainer::removeClient needs to also remove the client from specialized + caches, otherwise we can end up with stale references. + + Test: svg/custom/stale-resource-data-crash.svg + + * rendering/svg/RenderSVGResourceContainer.cpp: + (WebCore::RenderSVGResourceContainer::removeClient): + +2012-11-26 'Pavel Feldman' <pfeldman@chromium.org> + + Not reviewed: rolling out r135714 and r135712 for breaking debug tests. + + * inspector/InjectedScriptSource.js: + (.): + * inspector/InspectorOverlayPage.html: + * inspector/front-end/ConsoleMessage.js: + (WebInspector.ConsoleMessageImpl.prototype._appendObjectPreview): + +2012-11-26 Zeno Albisser <zeno@webkit.org> + + [Qt][Win] buildfix after r135706. + https://bugs.webkit.org/show_bug.cgi?id=103249 + + The Windows implementation of GraphicsSurface cannot use + m_size anymore, as this member has been removed. + Further it needs to implement a platformSize() function. + + Reviewed by Kenneth Rohde Christiansen. + + * platform/graphics/surfaces/win/GraphicsSurfaceWin.cpp: + (WebCore::GraphicsSurfacePrivate::size): + (WebCore::GraphicsSurface::platformPaintToTextureMapper): + (WebCore::GraphicsSurface::platformSize): + (WebCore): + +2012-11-26 Yury Semikhatsky <yurys@chromium.org> + + Web Inspector: unify agents handling in Page and Worker inspector controllers + https://bugs.webkit.org/show_bug.cgi?id=103238 + + Reviewed by Alexander Pavlov. + + Introduced a class that represents a collection of inspector agents and allows + to call methods declared on InspectorAgentBaseInterface for all registered agents. + InspectorController and WorkerInspectorController switched to this class. + + * inspector/InspectorBaseAgent.cpp: + (WebCore::InspectorAgentRegistry::append): + (WebCore): + (WebCore::InspectorAgentRegistry::setFrontend): + (WebCore::InspectorAgentRegistry::clearFrontend): + (WebCore::InspectorAgentRegistry::restore): + (WebCore::InspectorAgentRegistry::registerInDispatcher): + (WebCore::InspectorAgentRegistry::discardAgents): + * inspector/InspectorBaseAgent.h: + (InspectorAgentRegistry): + (WebCore): + * inspector/InspectorController.cpp: + (WebCore::InspectorController::~InspectorController): + (WebCore::InspectorController::connectFrontend): + (WebCore::InspectorController::disconnectFrontend): + (WebCore::InspectorController::reconnectFrontend): + * inspector/InspectorController.h: + (InspectorController): + +2012-11-26 Pavel Feldman <pfeldman@chromium.org> + + Web Inspector: object preview does not render node id, className; logs too many functions for jQuery. + https://bugs.webkit.org/show_bug.cgi?id=103222 + + Reviewed by Yury Semikhatsky. + + - Added node class name and id into the preview + - Now keeps track of properties separately from array indexes. + + * inspector/InjectedScriptSource.js: + (.): + * inspector/InspectorOverlayPage.html: + * inspector/front-end/ConsoleMessage.js: + (WebInspector.ConsoleMessageImpl.prototype._appendObjectPreview): + (WebInspector.ConsoleMessageImpl.prototype._appendPropertyPreview): + +2012-11-26 Andrey Adaikin <aandrey@chromium.org> + + Web Inspector: [WebGL] Save WebGL extensions and restore on replay + https://bugs.webkit.org/show_bug.cgi?id=103141 + + Reviewed by Yury Semikhatsky. + + Save WebGL extensions that were enabled by the application, and restore it before the replay. + Drive-by: remove redundant if- checks in WebGL custom function wrappers (similar to 2D canvas). + + * inspector/InjectedScriptCanvasModuleSource.js: + (.): + +2012-11-26 Allan Sandfeld Jensen <allan.jensen@digia.com> + + HitTestResult should not be a HitTestLocation + https://bugs.webkit.org/show_bug.cgi?id=101590 + + Reviewed by Sam Weinig. + + Change HitTestResult from being a HitTestLocation to having a HitTestLocation. + A result of a test should not be a special case of the location of the test. + + No change in functionality. No new tests. + + * rendering/HitTestResult.cpp: + (WebCore::HitTestResult::HitTestResult): + (WebCore::HitTestResult::operator=): + (WebCore::HitTestResult::isSelected): + (WebCore::HitTestResult::spellingToolTip): + (WebCore::HitTestResult::replacedString): + * rendering/HitTestResult.h: + (WebCore::HitTestResult::isRectBasedTest): + (WebCore::HitTestResult::pointInInnerNodeFrame): + (WebCore::HitTestResult::hitTestLocation): + (HitTestResult): + +2012-11-26 Marja Hölttä <marja@chromium.org> + + Circular reference between Document and MediaQueryMatcher. + https://bugs.webkit.org/show_bug.cgi?id=103242 + + Reviewed by Kenneth Rohde Christiansen. + + It's not enough to clean up listeners in MediaQueryMatcher in ~Document, + since MediaQueryListListener keeps the Document alive. This caused + www.crbug.com/113983. + + No new tests: No visible change in behavior (except that it doesn't leak memory). + + * dom/Document.cpp: + (WebCore::Document::~Document): + (WebCore::Document::detach): + +2012-11-26 Eugene Klyuchnikov <eustas@chromium.org> + + Web Inspector: HeapProfiler: remove snapshotView reference from data-grids. + https://bugs.webkit.org/show_bug.cgi?id=103240 + + Reviewed by Yury Semikhatsky. + + Cleanup: remove redundant dependency. + + * inspector/front-end/HeapSnapshotDataGrids.js: Do not store view ref. + * inspector/front-end/HeapSnapshotGridNodes.js: + Removed unused assignments. + * inspector/front-end/HeapSnapshotView.js: + Do not pass self to data-grids. + +2012-11-26 Zeno Albisser <zeno@webkit.org> + + GraphicsSurface should only store its size in a single place. + https://bugs.webkit.org/show_bug.cgi?id=103143 + + Reviewed by Kenneth Rohde Christiansen. + + * platform/graphics/qt/GraphicsContext3DQt.cpp: + (WebCore::GraphicsContext3DPrivate::GraphicsContext3DPrivate): + Cosmetics only. + * platform/graphics/surfaces/GraphicsSurface.cpp: + (WebCore::GraphicsSurface::size): + Return the size as received from the platform abstraction. + (WebCore): + (WebCore::GraphicsSurface::GraphicsSurface): + * platform/graphics/surfaces/GraphicsSurface.h: + (GraphicsSurface): + Remove data member m_size. + * platform/graphics/surfaces/mac/GraphicsSurfaceMac.cpp: + (WebCore::GraphicsSurfacePrivate::GraphicsSurfacePrivate): + Always take the size of the GraphicsSurface as an argument. + (WebCore::GraphicsSurfacePrivate::size): + (GraphicsSurfacePrivate): + (WebCore::GraphicsSurface::platformPaintToTextureMapper): + Retrieve the size from GraphicsSurfacePrivate where necessary. + (WebCore::GraphicsSurface::platformSize): + (WebCore): + (WebCore::GraphicsSurface::platformImport): + * platform/graphics/surfaces/qt/GraphicsSurfaceGLX.cpp: + (WebCore::GraphicsSurfacePrivate::GraphicsSurfacePrivate): + Add a constructor that takes a window id as an argument + for the receiving side of the GraphcisSurface. + The GraphicsSurface can then determine its dimensions + from the provided XWindow. + (WebCore::GraphicsSurfacePrivate::createPixmap): + (WebCore::GraphicsSurfacePrivate::size): + Query the size of the GraphicsSurface backing from X. + (WebCore::GraphicsSurface::platformPaintToTextureMapper): + Retrieve the size from GraphicsSurfacePrivate where necessary. + (WebCore::GraphicsSurface::platformSize): + (WebCore): + (WebCore::GraphicsSurface::platformImport): + +2012-11-26 Thiago Santos <thiago.sousa.santos@collabora.com> + + [GStreamer] Floating reference handling fix + https://bugs.webkit.org/show_bug.cgi?id=101349 + + Reviewed by Philippe Normand. + + GStreamer 0.10 and 1.0 differ when creating GstGhostPad from pad + templates, the 1.0 doesn't take ownership on the passed + GstPadTemplate, while 0.10 does. So this patch adds a + GStreamerVersioning function to handle this different approach + transparently in Webkit gstreamer elements. + + Existing media tests cover this change. + + * platform/audio/gstreamer/WebKitWebAudioSourceGStreamer.cpp: + (webkit_web_audio_src_init): + * platform/graphics/gstreamer/GStreamerVersioning.cpp: + (webkitGstGhostPadFromStaticTemplate): + * platform/graphics/gstreamer/GStreamerVersioning.h: + * platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp: + (webkit_web_src_init): + +2012-11-26 Kentaro Hara <haraken@chromium.org> + + [V8] Remove WorkerContextExecutionProxy + https://bugs.webkit.org/show_bug.cgi?id=103210 + + Reviewed by Adam Barth. + + This patch moves all methods in WorkerContextExecutionProxy + to WorkerScriptController. + + Due to the dependency between WorkerContextExecutionProxy's methods, + it is a bit difficult to split this patch into pieces. + This patch simply moves methods without changing their logic. + Also this patch doesn't remove empty WorkerContextExecutionProxy.{h,cpp} + to keep the diff sane. I will address these issues in a follow-up patch. + + Tests: fast/worker/* + + * bindings/v8/ScriptState.cpp: + (WebCore::scriptStateFromWorkerContext): + * bindings/v8/V8Binding.cpp: + (WebCore::toV8Context): + * bindings/v8/V8WorkerContextEventListener.cpp: + (WebCore::V8WorkerContextEventListener::handleEvent): + * bindings/v8/WorkerContextExecutionProxy.cpp: + * bindings/v8/WorkerContextExecutionProxy.h: + * bindings/v8/WorkerScriptController.cpp: + (WebCore::WorkerScriptController::WorkerScriptController): + (WebCore::WorkerScriptController::~WorkerScriptController): + (WebCore::WorkerScriptController::dispose): + (WebCore): + (WebCore::WorkerScriptController::initializeIfNeeded): + (WebCore::WorkerScriptController::evaluate): + (WebCore::WorkerScriptController::setEvalAllowed): + (WebCore::WorkerScriptController::disableEval): + * bindings/v8/WorkerScriptController.h: + (WebCore): + (WebCore::WorkerContextExecutionState::WorkerContextExecutionState): + (WorkerContextExecutionState): + (WorkerScriptController): + (WebCore::WorkerScriptController::context): + * bindings/v8/WorkerScriptDebugServer.cpp: + (WebCore::WorkerScriptDebugServer::addListener): + * bindings/v8/custom/V8WorkerContextCustom.cpp: + (WebCore::SetTimeoutOrInterval): + (WebCore::toV8): + 2012-11-26 Hajime Morrita <morrita@google.com> [Refactoring] Some Node::isDescendant calls can be replaced with Node::contains() @@ -5378,7 +10052,7 @@ Unreviewed. Fix Chromium Win compilation after r135255. https://bugs.webkit.org/show_bug.cgi?id=97803 - * WebCore.gypi: removed reference to platform/wince/DragDataWince.cpp which + * WebCore.gypi: removed reference to platform/wince/DragDataWince.cpp which was deleted in the aforementioned change. 2012-11-19 Kentaro Hara <haraken@chromium.org> diff --git a/Source/WebCore/DerivedSources.cpp b/Source/WebCore/DerivedSources.cpp index af2b59dcd..ab8113958 100644 --- a/Source/WebCore/DerivedSources.cpp +++ b/Source/WebCore/DerivedSources.cpp @@ -487,6 +487,9 @@ #include "JSWebKitCSSKeyframesRule.cpp" #include "JSWebKitCSSTransformValue.cpp" #include "JSWebKitCSSMatrix.cpp" +#if ENABLE(CSS_SHADERS) +#include "JSWebKitCSSMixFunctionValue.cpp" +#endif #include "JSWebKitCSSRegionRule.cpp" #include "JSWebKitNamedFlow.cpp" #include "JSWebKitPoint.cpp" diff --git a/Source/WebCore/DerivedSources.make b/Source/WebCore/DerivedSources.make index 05896f18e..e536fd13a 100644 --- a/Source/WebCore/DerivedSources.make +++ b/Source/WebCore/DerivedSources.make @@ -194,6 +194,7 @@ BINDING_IDLS = \ $(WebCore)/css/WebKitCSSKeyframeRule.idl \ $(WebCore)/css/WebKitCSSKeyframesRule.idl \ $(WebCore)/css/WebKitCSSMatrix.idl \ + $(WebCore)/css/WebKitCSSMixFunctionValue.idl \ $(WebCore)/css/WebKitCSSRegionRule.idl \ $(WebCore)/css/WebKitCSSTransformValue.idl \ $(WebCore)/css/WebKitCSSViewportRule.idl \ diff --git a/Source/WebCore/DerivedSources.pri b/Source/WebCore/DerivedSources.pri index 3686cc47b..7e2245fd8 100644 --- a/Source/WebCore/DerivedSources.pri +++ b/Source/WebCore/DerivedSources.pri @@ -211,6 +211,7 @@ IDL_BINDINGS += \ $$PWD/css/WebKitCSSKeyframeRule.idl \ $$PWD/css/WebKitCSSKeyframesRule.idl \ $$PWD/css/WebKitCSSMatrix.idl \ + $$PWD/css/WebKitCSSMixFunctionValue.idl \ $$PWD/css/WebKitCSSRegionRule.idl \ $$PWD/css/WebKitCSSTransformValue.idl \ $$PWD/css/WebKitCSSViewportRule.idl \ diff --git a/Source/WebCore/English.lproj/Localizable.strings b/Source/WebCore/English.lproj/Localizable.strings Binary files differindex a0a876617..8c655d619 100644 --- a/Source/WebCore/English.lproj/Localizable.strings +++ b/Source/WebCore/English.lproj/Localizable.strings diff --git a/Source/WebCore/GNUmakefile.list.am b/Source/WebCore/GNUmakefile.list.am index 70e108730..8fb637870 100644 --- a/Source/WebCore/GNUmakefile.list.am +++ b/Source/WebCore/GNUmakefile.list.am @@ -805,6 +805,8 @@ webcore_built_sources += \ DerivedSources/WebCore/JSWebKitCSSKeyframesRule.h \ DerivedSources/WebCore/JSWebKitCSSMatrix.cpp \ DerivedSources/WebCore/JSWebKitCSSMatrix.h \ + DerivedSources/WebCore/JSWebKitCSSMixFunctionValue.cpp \ + DerivedSources/WebCore/JSWebKitCSSMixFunctionValue.h \ DerivedSources/WebCore/JSWebKitCSSRegionRule.cpp \ DerivedSources/WebCore/JSWebKitCSSRegionRule.h \ DerivedSources/WebCore/JSWebKitCSSTransformValue.cpp \ @@ -1336,6 +1338,7 @@ dom_binding_idls += \ $(WebCore)/css/WebKitCSSKeyframeRule.idl \ $(WebCore)/css/WebKitCSSKeyframesRule.idl \ $(WebCore)/css/WebKitCSSMatrix.idl \ + $(WebCore)/css/WebKitCSSMixFunctionValue.idl \ $(WebCore)/css/WebKitCSSRegionRule.idl \ $(WebCore)/css/WebKitCSSTransformValue.idl \ $(WebCore)/css/WebKitCSSViewportRule.idl \ @@ -3871,13 +3874,14 @@ webcore_sources += \ Source/WebCore/loader/FormState.h \ Source/WebCore/loader/FormSubmission.cpp \ Source/WebCore/loader/FormSubmission.h \ + Source/WebCore/loader/FrameLoadRequest.cpp \ + Source/WebCore/loader/FrameLoadRequest.h \ Source/WebCore/loader/FrameLoaderClient.h \ Source/WebCore/loader/FrameLoader.cpp \ Source/WebCore/loader/FrameLoader.h \ Source/WebCore/loader/FrameLoaderStateMachine.cpp \ Source/WebCore/loader/FrameLoaderStateMachine.h \ Source/WebCore/loader/FrameLoaderTypes.h \ - Source/WebCore/loader/FrameLoadRequest.h \ Source/WebCore/loader/FrameNetworkingContext.h \ Source/WebCore/loader/FTPDirectoryParser.cpp \ Source/WebCore/loader/FTPDirectoryParser.h \ @@ -5227,10 +5231,6 @@ webcore_platform_sources += \ Source/WebCore/platform/audio/VectorMath.h \ Source/WebCore/platform/audio/ZeroPole.cpp \ Source/WebCore/platform/audio/ZeroPole.h \ - Source/WebCore/platform/ActivePlatformGestureAnimation.cpp \ - Source/WebCore/platform/ActivePlatformGestureAnimation.h \ - Source/WebCore/platform/PlatformGestureCurve.h \ - Source/WebCore/platform/PlatformGestureCurveTarget.h \ Source/WebCore/platform/Arena.cpp \ Source/WebCore/platform/Arena.h \ Source/WebCore/platform/AsyncFileSystem.cpp \ @@ -5758,8 +5758,6 @@ webcore_platform_sources += \ Source/WebCore/platform/PlatformEvent.cpp \ Source/WebCore/platform/PlatformEvent.h \ Source/WebCore/platform/PlatformExportMacros.h \ - Source/WebCore/platform/PlatformGestureCurve.h \ - Source/WebCore/platform/PlatformGestureEvent.h \ Source/WebCore/platform/PlatformKeyboardEvent.h \ Source/WebCore/platform/PlatformMemoryInstrumentation.cpp \ Source/WebCore/platform/PlatformMemoryInstrumentation.h \ @@ -5890,8 +5888,6 @@ webcore_platform_sources += \ Source/WebCore/platform/text/UnicodeRange.cpp \ Source/WebCore/platform/text/UnicodeRange.h \ Source/WebCore/platform/text/WritingMode.h \ - Source/WebCore/platform/TouchFlingPlatformGestureCurve.cpp \ - Source/WebCore/platform/TouchFlingPlatformGestureCurve.h \ Source/WebCore/platform/ThemeTypes.h \ Source/WebCore/platform/ThreadCheck.h \ Source/WebCore/platform/ThreadGlobalData.cpp \ diff --git a/Source/WebCore/Modules/indexeddb/IDBBackingStore.h b/Source/WebCore/Modules/indexeddb/IDBBackingStore.h index b0a59887a..f4becb976 100644 --- a/Source/WebCore/Modules/indexeddb/IDBBackingStore.h +++ b/Source/WebCore/Modules/indexeddb/IDBBackingStore.h @@ -42,6 +42,7 @@ class LevelDBTransaction; class IDBFactoryBackendImpl; class IDBKey; class IDBKeyRange; +class SecurityOrigin; class IDBBackingStore : public RefCounted<IDBBackingStore> { public: diff --git a/Source/WebCore/Modules/indexeddb/IDBCallbacks.h b/Source/WebCore/Modules/indexeddb/IDBCallbacks.h index d1511454d..b88b0cde3 100644 --- a/Source/WebCore/Modules/indexeddb/IDBCallbacks.h +++ b/Source/WebCore/Modules/indexeddb/IDBCallbacks.h @@ -56,8 +56,6 @@ public: virtual void onSuccess(PassRefPtr<IDBCursorBackendInterface>, PassRefPtr<IDBKey>, PassRefPtr<IDBKey> primaryKey, PassRefPtr<SerializedScriptValue>) = 0; // From IDBObjectStore.add()/put(), IDBIndex.getKey() virtual void onSuccess(PassRefPtr<IDBKey>) = 0; - // From IDBDatabase.setVersion() - virtual void onSuccess(PassRefPtr<IDBTransactionBackendInterface>) = 0; // From IDBObjectStore/IDBIndex.get()/count(), and various methods that yield null/undefined. virtual void onSuccess(PassRefPtr<SerializedScriptValue>) = 0; // From IDBObjectStore/IDBIndex.get() (with key injection) @@ -72,7 +70,7 @@ public: virtual void onSuccess(PassRefPtr<IDBKey>, PassRefPtr<IDBKey> primaryKey, PassRefPtr<SerializedScriptValue>) = 0; // From IDBCursor.advance()/continue() virtual void onSuccessWithPrefetch(const Vector<RefPtr<IDBKey> >& keys, const Vector<RefPtr<IDBKey> >& primaryKeys, const Vector<RefPtr<SerializedScriptValue> >& values) = 0; - // From IDBFactory.open()/deleteDatabase(), IDBDatabase.setVersion() + // From IDBFactory.open()/deleteDatabase() virtual void onBlocked() { ASSERT_NOT_REACHED(); } virtual void onBlocked(int64_t existingVersion) { ASSERT_NOT_REACHED(); } // From IDBFactory.open() diff --git a/Source/WebCore/Modules/indexeddb/IDBCursorBackendImpl.cpp b/Source/WebCore/Modules/indexeddb/IDBCursorBackendImpl.cpp index b4944ca89..22357f8d4 100644 --- a/Source/WebCore/Modules/indexeddb/IDBCursorBackendImpl.cpp +++ b/Source/WebCore/Modules/indexeddb/IDBCursorBackendImpl.cpp @@ -173,14 +173,12 @@ void IDBCursorBackendImpl::prefetchContinueInternal(ScriptExecutionContext*, Pas return; } - cursor->m_transaction->addPendingEvents(foundKeys.size() - 1); callbacks->onSuccessWithPrefetch(foundKeys, foundPrimaryKeys, foundValues); } void IDBCursorBackendImpl::prefetchReset(int usedPrefetches, int unusedPrefetches) { IDB_TRACE("IDBCursorBackendImpl::prefetchReset"); - m_transaction->addPendingEvents(-unusedPrefetches); m_cursor = m_savedCursor; m_savedCursor = 0; diff --git a/Source/WebCore/Modules/indexeddb/IDBCursorBackendImpl.h b/Source/WebCore/Modules/indexeddb/IDBCursorBackendImpl.h index 1f74c3391..b8b77ec16 100644 --- a/Source/WebCore/Modules/indexeddb/IDBCursorBackendImpl.h +++ b/Source/WebCore/Modules/indexeddb/IDBCursorBackendImpl.h @@ -63,7 +63,7 @@ public: virtual void deleteFunction(PassRefPtr<IDBCallbacks>, ExceptionCode&); virtual void prefetchContinue(int numberToFetch, PassRefPtr<IDBCallbacks>, ExceptionCode&); virtual void prefetchReset(int usedPrefetches, int unusedPrefetches); - virtual void postSuccessHandlerCallback() { ASSERT_NOT_REACHED(); } + virtual void postSuccessHandlerCallback() { } PassRefPtr<IDBKey> key() const { return m_cursor->key(); } PassRefPtr<IDBKey> primaryKey() const { return m_cursor->primaryKey(); } diff --git a/Source/WebCore/Modules/indexeddb/IDBDatabase.cpp b/Source/WebCore/Modules/indexeddb/IDBDatabase.cpp index e5ea41e0a..e799c0db2 100644 --- a/Source/WebCore/Modules/indexeddb/IDBDatabase.cpp +++ b/Source/WebCore/Modules/indexeddb/IDBDatabase.cpp @@ -36,7 +36,6 @@ #include "IDBDatabaseError.h" #include "IDBDatabaseException.h" #include "IDBEventDispatcher.h" -#include "IDBFactoryBackendInterface.h" #include "IDBIndex.h" #include "IDBKeyPath.h" #include "IDBObjectStore.h" @@ -48,6 +47,8 @@ #include "ScriptCallStack.h" #include "ScriptExecutionContext.h" #include <limits> +#include <wtf/Atomics.h> +#include <wtf/Threading.h> namespace WebCore { @@ -64,7 +65,6 @@ IDBDatabase::IDBDatabase(ScriptExecutionContext* context, PassRefPtr<IDBDatabase , m_closePending(false) , m_contextStopped(false) , m_databaseCallbacks(callbacks) - , m_didSpamConsole(false) { // We pass a reference of this object before it can be adopted. relaxAdoptionRequirement(); @@ -76,6 +76,14 @@ IDBDatabase::~IDBDatabase() close(); } +int64_t IDBDatabase::nextTransactionId() +{ + // Only keep a 32-bit counter to allow ports to use the other 32 + // bits of the id. + AtomicallyInitializedStatic(int, currentTransactionId = 0); + return atomicIncrement(¤tTransactionId); +} + void IDBDatabase::transactionCreated(IDBTransaction* transaction) { ASSERT(transaction); @@ -202,30 +210,6 @@ void IDBDatabase::deleteObjectStore(const String& name, ExceptionCode& ec) } } -PassRefPtr<IDBVersionChangeRequest> IDBDatabase::setVersion(ScriptExecutionContext* context, const String& version, ExceptionCode& ec) -{ - if (!m_didSpamConsole) { - String consoleMessage = ASCIILiteral("The setVersion() method is non-standard and will be removed. Use the \"upgradeneeded\" event instead."); - context->addConsoleMessage(JSMessageSource, LogMessageType, WarningMessageLevel, consoleMessage); - m_didSpamConsole = true; - } - - if (version.isNull()) { - ec = TypeError; - return 0; - } - - if (m_versionChangeTransaction) { - ec = IDBDatabaseException::IDB_INVALID_STATE_ERR; - return 0; - } - - RefPtr<IDBVersionChangeRequest> request = IDBVersionChangeRequest::create(context, IDBAny::create(this), version); - ASSERT(m_backend); - m_backend->setVersion(version, request, m_databaseCallbacks, ec); - return request; -} - PassRefPtr<IDBTransaction> IDBDatabase::transaction(ScriptExecutionContext* context, const Vector<String>& scope, const String& modeString, ExceptionCode& ec) { if (!scope.size()) { @@ -256,12 +240,14 @@ PassRefPtr<IDBTransaction> IDBDatabase::transaction(ScriptExecutionContext* cont // can be queued against the transaction at any point. They will start executing as soon as the // appropriate locks have been acquired. // Also note that each backend object corresponds to exactly one IDBTransaction object. - RefPtr<IDBTransactionBackendInterface> transactionBackend = m_backend->transaction(objectStoreIds, mode); + int64_t transactionId = nextTransactionId(); + RefPtr<IDBTransactionBackendInterface> transactionBackend = m_backend->createTransaction(transactionId, objectStoreIds, mode); if (!transactionBackend) { ASSERT(ec); return 0; } - RefPtr<IDBTransaction> transaction = IDBTransaction::create(context, transactionBackend, scope, mode, this); + + RefPtr<IDBTransaction> transaction = IDBTransaction::create(context, transactionId, transactionBackend, scope, mode, this); transactionBackend->setCallbacks(transaction.get()); return transaction.release(); } diff --git a/Source/WebCore/Modules/indexeddb/IDBDatabase.h b/Source/WebCore/Modules/indexeddb/IDBDatabase.h index ee2d23234..a8ab94d94 100644 --- a/Source/WebCore/Modules/indexeddb/IDBDatabase.h +++ b/Source/WebCore/Modules/indexeddb/IDBDatabase.h @@ -68,7 +68,6 @@ public: PassRefPtr<IDBTransaction> transaction(ScriptExecutionContext*, const Vector<String>&, const String& mode, ExceptionCode&); PassRefPtr<IDBTransaction> transaction(ScriptExecutionContext*, const String&, const String& mode, ExceptionCode&); void deleteObjectStore(const String& name, ExceptionCode&); - PassRefPtr<IDBVersionChangeRequest> setVersion(ScriptExecutionContext*, const String& version, ExceptionCode&); void close(); DEFINE_ATTRIBUTE_EVENT_LISTENER(abort); @@ -99,6 +98,8 @@ public: return findObjectStoreId(name) != IDBObjectStoreMetadata::InvalidId; } + static int64_t nextTransactionId(); + using RefCounted<IDBDatabase>::ref; using RefCounted<IDBDatabase>::deref; @@ -129,8 +130,6 @@ private: Vector<RefPtr<Event> > m_enqueuedEvents; RefPtr<IDBDatabaseCallbacks> m_databaseCallbacks; - - bool m_didSpamConsole; }; } // namespace WebCore diff --git a/Source/WebCore/Modules/indexeddb/IDBDatabase.idl b/Source/WebCore/Modules/indexeddb/IDBDatabase.idl index f6b0be450..0bed24f1b 100644 --- a/Source/WebCore/Modules/indexeddb/IDBDatabase.idl +++ b/Source/WebCore/Modules/indexeddb/IDBDatabase.idl @@ -42,8 +42,6 @@ raises (DOMException); void deleteObjectStore(in DOMString name) raises (DOMException); - [CallWith=ScriptExecutionContext] IDBVersionChangeRequest setVersion(in DOMString version) - raises (DOMException); [CallWith=ScriptExecutionContext] IDBTransaction transaction(in DOMStringList storeNames, in [Optional=DefaultIsNullString] DOMString mode) raises (DOMException); [CallWith=ScriptExecutionContext] IDBTransaction transaction(in sequence<String> storeNames, in [Optional=DefaultIsNullString] DOMString mode) diff --git a/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendImpl.cpp b/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendImpl.cpp index 0dc802109..2cbf9b3c8 100644 --- a/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendImpl.cpp +++ b/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendImpl.cpp @@ -96,28 +96,6 @@ private: RefPtr<IDBCallbacks> m_callbacks; }; -class IDBDatabaseBackendImpl::PendingSetVersionCall { -public: - static PassOwnPtr<PendingSetVersionCall> create(const String& version, PassRefPtr<IDBCallbacks> callbacks, PassRefPtr<IDBDatabaseCallbacks> databaseCallbacks) - { - return adoptPtr(new PendingSetVersionCall(version, callbacks, databaseCallbacks)); - } - String version() { return m_version; } - PassRefPtr<IDBCallbacks> callbacks() { return m_callbacks; } - PassRefPtr<IDBDatabaseCallbacks> databaseCallbacks() { return m_databaseCallbacks; } - -private: - PendingSetVersionCall(const String& version, PassRefPtr<IDBCallbacks> callbacks, PassRefPtr<IDBDatabaseCallbacks> databaseCallbacks) - : m_version(version) - , m_callbacks(callbacks) - , m_databaseCallbacks(databaseCallbacks) - { - } - String m_version; - RefPtr<IDBCallbacks> m_callbacks; - RefPtr<IDBDatabaseCallbacks> m_databaseCallbacks; -}; - PassRefPtr<IDBDatabaseBackendImpl> IDBDatabaseBackendImpl::create(const String& name, IDBBackingStore* database, IDBFactoryBackendImpl* factory, const String& uniqueIdentifier) { RefPtr<IDBDatabaseBackendImpl> backend = adoptRef(new IDBDatabaseBackendImpl(name, database, factory, uniqueIdentifier)); @@ -202,8 +180,6 @@ void IDBDatabaseBackendImpl::createObjectStoreInternal(ScriptExecutionContext*, transaction->abort(); return; } - - transaction->didCompleteTaskEvents(); } PassRefPtr<IDBObjectStoreBackendImpl> IDBDatabaseBackendImpl::objectStore(int64_t id) @@ -232,65 +208,6 @@ void IDBDatabaseBackendImpl::deleteObjectStore(int64_t id, IDBTransactionBackend void IDBDatabaseBackendImpl::deleteObjectStoreInternal(ScriptExecutionContext*, PassRefPtr<IDBDatabaseBackendImpl> database, PassRefPtr<IDBObjectStoreBackendImpl> objectStore, PassRefPtr<IDBTransactionBackendImpl> transaction) { database->m_backingStore->deleteObjectStore(transaction->backingStoreTransaction(), database->id(), objectStore->id()); - transaction->didCompleteTaskEvents(); -} - -void IDBDatabaseBackendImpl::setVersion(const String& version, PassRefPtr<IDBCallbacks> prpCallbacks, PassRefPtr<IDBDatabaseCallbacks> prpDatabaseCallbacks, ExceptionCode& ec) -{ - RefPtr<IDBCallbacks> callbacks = prpCallbacks; - RefPtr<IDBDatabaseCallbacks> databaseCallbacks = prpDatabaseCallbacks; - if (!m_databaseCallbacksSet.contains(databaseCallbacks)) { - callbacks->onError(IDBDatabaseError::create(IDBDatabaseException::IDB_ABORT_ERR, "Connection was closed before set version transaction was created")); - return; - } - for (DatabaseCallbacksSet::const_iterator it = m_databaseCallbacksSet.begin(); it != m_databaseCallbacksSet.end(); ++it) { - // Front end ensures the event is not fired at connections that have closePending set. - if (*it != databaseCallbacks) - (*it)->onVersionChange(version); - } - // FIXME: Only fire onBlocked if there are open connections after the - // VersionChangeEvents are received, not just set up to fire. - // https://bugs.webkit.org/show_bug.cgi?id=71130 - if (connectionCount() > 1) { - callbacks->onBlocked(); - OwnPtr<PendingSetVersionCall> pendingSetVersionCall = PendingSetVersionCall::create(version, callbacks, databaseCallbacks); - m_pendingSetVersionCalls.append(pendingSetVersionCall.release()); - return; - } - if (m_runningVersionChangeTransaction) { - OwnPtr<PendingSetVersionCall> pendingSetVersionCall = PendingSetVersionCall::create(version, callbacks, databaseCallbacks); - m_pendingSetVersionCalls.append(pendingSetVersionCall.release()); - return; - } - - Vector<int64_t> objectStoreIds; - RefPtr<IDBTransactionBackendInterface> transactionInterface = this->transaction(objectStoreIds, IDBTransaction::VERSION_CHANGE); - RefPtr<IDBTransactionBackendImpl> transaction = IDBTransactionBackendImpl::from(transactionInterface.get()); - ASSERT(!ec); - - RefPtr<IDBDatabaseBackendImpl> database = this; - if (!transaction->scheduleTask( - createCallbackTask(&IDBDatabaseBackendImpl::setVersionInternal, database, version, callbacks, transaction), - createCallbackTask(&IDBDatabaseBackendImpl::resetVersion, database, m_metadata.version, m_metadata.intVersion))) { - // FIXME: Remove one of the following lines. - ASSERT_NOT_REACHED(); - ec = IDBDatabaseException::TRANSACTION_INACTIVE_ERR; - } -} - -void IDBDatabaseBackendImpl::setVersionInternal(ScriptExecutionContext*, PassRefPtr<IDBDatabaseBackendImpl> database, const String& version, PassRefPtr<IDBCallbacks> callbacks, PassRefPtr<IDBTransactionBackendImpl> prpTransaction) -{ - RefPtr<IDBTransactionBackendImpl> transaction = prpTransaction; - int64_t databaseId = database->id(); - database->m_metadata.version = version; - database->m_metadata.intVersion = IDBDatabaseMetadata::NoIntVersion; - if (!database->m_backingStore->updateIDBDatabaseMetaData(transaction->backingStoreTransaction(), databaseId, database->m_metadata.version) || !database->m_backingStore->updateIDBDatabaseIntVersion(transaction->backingStoreTransaction(), databaseId, database->m_metadata.intVersion)) { - RefPtr<IDBDatabaseError> error = IDBDatabaseError::create(IDBDatabaseException::UNKNOWN_ERR, "Error writing data to stable storage."); - callbacks->onError(error); - transaction->abort(error); - return; - } - callbacks->onSuccess(PassRefPtr<IDBTransactionBackendInterface>(transaction)); } void IDBDatabaseBackendImpl::setIntVersionInternal(ScriptExecutionContext*, PassRefPtr<IDBDatabaseBackendImpl> database, int64_t version, PassRefPtr<IDBCallbacks> prpCallbacks, PassRefPtr<IDBDatabaseCallbacks> databaseCallbacks, PassRefPtr<IDBTransactionBackendImpl> transaction) @@ -369,28 +286,10 @@ void IDBDatabaseBackendImpl::processPendingCalls() // Fall through when complete, as pending deletes may be (partially) unblocked. } - // Pending calls may be requeued or aborted - Deque<OwnPtr<PendingSetVersionCall> > pendingSetVersionCalls; - m_pendingSetVersionCalls.swap(pendingSetVersionCalls); - while (!pendingSetVersionCalls.isEmpty()) { - ExceptionCode ec = 0; - OwnPtr<PendingSetVersionCall> pendingSetVersionCall = pendingSetVersionCalls.takeFirst(); - setVersion(pendingSetVersionCall->version(), pendingSetVersionCall->callbacks(), pendingSetVersionCall->databaseCallbacks(), ec); - ASSERT(!ec); - } - - // If there were any pending set version calls, we better have started one. - ASSERT(m_pendingSetVersionCalls.isEmpty() || m_runningVersionChangeTransaction); - - // m_pendingSetVersionCalls is non-empty in two cases: - // 1) When two versionchange transactions are requested while another - // version change transaction is running. - // 2) When three versionchange transactions are requested in a row, before - // any of their event handlers are run. // Note that this check is only an optimization to reduce queue-churn and // not necessary for correctness; deleteDatabase and openConnection will // requeue their calls if this condition is true. - if (m_runningVersionChangeTransaction || !m_pendingSetVersionCalls.isEmpty()) + if (m_runningVersionChangeTransaction) return; // Pending calls may be requeued. @@ -402,7 +301,7 @@ void IDBDatabaseBackendImpl::processPendingCalls() } // This check is also not really needed, openConnection would just requeue its calls. - if (m_runningVersionChangeTransaction || !m_pendingSetVersionCalls.isEmpty() || !m_pendingDeleteCalls.isEmpty()) + if (m_runningVersionChangeTransaction || !m_pendingDeleteCalls.isEmpty()) return; Deque<OwnPtr<PendingOpenWithVersionCall> > pendingOpenWithVersionCalls; @@ -422,9 +321,15 @@ void IDBDatabaseBackendImpl::processPendingCalls() } } +// FIXME: Remove this as part of https://bugs.webkit.org/show_bug.cgi?id=102733. PassRefPtr<IDBTransactionBackendInterface> IDBDatabaseBackendImpl::transaction(const Vector<int64_t>& objectStoreIds, unsigned short mode) { - RefPtr<IDBTransactionBackendImpl> transaction = IDBTransactionBackendImpl::create(objectStoreIds, mode, this); + return createTransaction(0, objectStoreIds, mode); +} + +PassRefPtr<IDBTransactionBackendInterface> IDBDatabaseBackendImpl::createTransaction(int64_t transactionId, const Vector<int64_t>& objectStoreIds, unsigned short mode) +{ + RefPtr<IDBTransactionBackendImpl> transaction = IDBTransactionBackendImpl::create(transactionId, objectStoreIds, mode, this); m_transactions.add(transaction.get()); return transaction.release(); } @@ -432,7 +337,7 @@ PassRefPtr<IDBTransactionBackendInterface> IDBDatabaseBackendImpl::transaction(c void IDBDatabaseBackendImpl::openConnection(PassRefPtr<IDBCallbacks> callbacks, PassRefPtr<IDBDatabaseCallbacks> databaseCallbacks) { ASSERT(m_backingStore.get()); - if (!m_pendingDeleteCalls.isEmpty() || m_runningVersionChangeTransaction || !m_pendingSetVersionCalls.isEmpty()) { + if (!m_pendingDeleteCalls.isEmpty() || m_runningVersionChangeTransaction) { m_pendingOpenCalls.append(PendingOpenCall::create(callbacks, databaseCallbacks)); return; } @@ -494,7 +399,7 @@ void IDBDatabaseBackendImpl::openConnectionWithVersion(PassRefPtr<IDBCallbacks> { RefPtr<IDBCallbacks> callbacks = prpCallbacks; RefPtr<IDBDatabaseCallbacks> databaseCallbacks = prpDatabaseCallbacks; - if (!m_pendingDeleteCalls.isEmpty() || m_runningVersionChangeTransaction || !m_pendingSetVersionCalls.isEmpty()) { + if (!m_pendingDeleteCalls.isEmpty() || m_runningVersionChangeTransaction) { m_pendingOpenWithVersionCalls.append(PendingOpenWithVersionCall::create(callbacks, databaseCallbacks, version)); return; } @@ -521,7 +426,7 @@ void IDBDatabaseBackendImpl::openConnectionWithVersion(PassRefPtr<IDBCallbacks> void IDBDatabaseBackendImpl::deleteDatabase(PassRefPtr<IDBCallbacks> prpCallbacks) { - if (m_runningVersionChangeTransaction || !m_pendingSetVersionCalls.isEmpty()) { + if (m_runningVersionChangeTransaction) { m_pendingDeleteCalls.append(PendingDeleteCall::create(prpCallbacks)); return; } diff --git a/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendImpl.h b/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendImpl.h index f0f4938d1..a33967cfd 100644 --- a/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendImpl.h +++ b/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendImpl.h @@ -63,8 +63,9 @@ public: virtual IDBDatabaseMetadata metadata() const; virtual PassRefPtr<IDBObjectStoreBackendInterface> createObjectStore(int64_t id, const String& name, const IDBKeyPath&, bool autoIncrement, IDBTransactionBackendInterface*, ExceptionCode&); virtual void deleteObjectStore(int64_t, IDBTransactionBackendInterface*, ExceptionCode&); - virtual void setVersion(const String& version, PassRefPtr<IDBCallbacks>, PassRefPtr<IDBDatabaseCallbacks>, ExceptionCode&); + // FIXME: Remove this as part of https://bugs.webkit.org/show_bug.cgi?id=102733. virtual PassRefPtr<IDBTransactionBackendInterface> transaction(const Vector<int64_t>&, unsigned short); + virtual PassRefPtr<IDBTransactionBackendInterface> createTransaction(int64_t transactionId, const Vector<int64_t>& objectStoreIds, unsigned short mode); virtual void close(PassRefPtr<IDBDatabaseCallbacks>); PassRefPtr<IDBObjectStoreBackendImpl> objectStore(int64_t id); @@ -85,7 +86,6 @@ private: static void createObjectStoreInternal(ScriptExecutionContext*, PassRefPtr<IDBDatabaseBackendImpl>, PassRefPtr<IDBObjectStoreBackendImpl>, PassRefPtr<IDBTransactionBackendImpl>); static void deleteObjectStoreInternal(ScriptExecutionContext*, PassRefPtr<IDBDatabaseBackendImpl>, PassRefPtr<IDBObjectStoreBackendImpl>, PassRefPtr<IDBTransactionBackendImpl>); - static void setVersionInternal(ScriptExecutionContext*, PassRefPtr<IDBDatabaseBackendImpl>, const String& version, PassRefPtr<IDBCallbacks>, PassRefPtr<IDBTransactionBackendImpl>); static void setIntVersionInternal(ScriptExecutionContext*, PassRefPtr<IDBDatabaseBackendImpl>, int64_t version, PassRefPtr<IDBCallbacks>, PassRefPtr<IDBDatabaseCallbacks>, PassRefPtr<IDBTransactionBackendImpl>); // These are used as setVersion transaction abort tasks. @@ -109,9 +109,6 @@ private: typedef HashSet<IDBTransactionBackendImpl*> TransactionSet; TransactionSet m_transactions; - class PendingSetVersionCall; - Deque<OwnPtr<PendingSetVersionCall> > m_pendingSetVersionCalls; - class PendingOpenCall; Deque<OwnPtr<PendingOpenCall> > m_pendingOpenCalls; diff --git a/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendInterface.h b/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendInterface.h index 9aab5644b..0ae36da37 100644 --- a/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendInterface.h +++ b/Source/WebCore/Modules/indexeddb/IDBDatabaseBackendInterface.h @@ -55,8 +55,9 @@ public: virtual PassRefPtr<IDBObjectStoreBackendInterface> createObjectStore(int64_t, const String& name, const IDBKeyPath&, bool autoIncrement, IDBTransactionBackendInterface*, ExceptionCode&) = 0; virtual void deleteObjectStore(int64_t, IDBTransactionBackendInterface*, ExceptionCode&) = 0; - virtual void setVersion(const String& version, PassRefPtr<IDBCallbacks>, PassRefPtr<IDBDatabaseCallbacks>, ExceptionCode&) = 0; + // FIXME: Remove this as part of https://bugs.webkit.org/show_bug.cgi?id=102733. virtual PassRefPtr<IDBTransactionBackendInterface> transaction(const Vector<int64_t>& objectStoreIds, unsigned short mode) = 0; + virtual PassRefPtr<IDBTransactionBackendInterface> createTransaction(int64_t transactionId, const Vector<int64_t>& objectStoreIds, unsigned short mode) = 0; virtual void close(PassRefPtr<IDBDatabaseCallbacks>) = 0; }; diff --git a/Source/WebCore/Modules/indexeddb/IDBObjectStoreBackendImpl.cpp b/Source/WebCore/Modules/indexeddb/IDBObjectStoreBackendImpl.cpp index 7471cac47..c90dac224 100644 --- a/Source/WebCore/Modules/indexeddb/IDBObjectStoreBackendImpl.cpp +++ b/Source/WebCore/Modules/indexeddb/IDBObjectStoreBackendImpl.cpp @@ -226,6 +226,8 @@ void IDBObjectStoreBackendImpl::setIndexKeys(PassRefPtr<IDBKey> prpPrimaryKey, c IDB_TRACE("IDBObjectStoreBackendImpl::setIndexKeys"); RefPtr<IDBKey> primaryKey = prpPrimaryKey; RefPtr<IDBTransactionBackendImpl> transaction = IDBTransactionBackendImpl::from(transactionPtr); + if (transaction->isFinished()) + return; // FIXME: This method could be asynchronous, but we need to evaluate if it's worth the extra complexity. IDBBackingStore::RecordIdentifier recordIdentifier; @@ -255,6 +257,8 @@ void IDBObjectStoreBackendImpl::setIndexesReady(const Vector<int64_t>& indexIds, OwnPtr<Vector<int64_t> > newIndexIds = adoptPtr(new Vector<int64_t>(indexIds)); RefPtr<IDBTransactionBackendImpl> transaction = IDBTransactionBackendImpl::from(transactionInterface); + if (transaction->isFinished()) + return; if (!transaction->scheduleTask( IDBTransactionBackendInterface::PreemptiveTask, @@ -268,7 +272,6 @@ void IDBObjectStoreBackendImpl::setIndexesReadyInternal(ScriptExecutionContext*, OwnPtr<Vector<int64_t> > indexIds = popIndexIds; for (size_t i = 0; i < indexIds->size(); ++i) transaction->didCompletePreemptiveEvent(); - transaction->didCompleteTaskEvents(); } void IDBObjectStoreBackendImpl::putInternal(ScriptExecutionContext*, PassRefPtr<IDBObjectStoreBackendImpl> objectStore, PassRefPtr<SerializedScriptValue> prpValue, PassRefPtr<IDBKey> prpKey, PutMode putMode, PassRefPtr<IDBCallbacks> callbacks, PassRefPtr<IDBTransactionBackendImpl> prpTransaction, PassOwnPtr<Vector<int64_t> > popIndexIds, PassOwnPtr<Vector<IndexKeys> > popIndexKeys) @@ -407,8 +410,6 @@ void IDBObjectStoreBackendImpl::createIndexInternal(ScriptExecutionContext*, Pas transaction->abort(); return; } - - transaction->didCompleteTaskEvents(); } PassRefPtr<IDBIndexBackendInterface> IDBObjectStoreBackendImpl::index(int64_t indexId) @@ -439,7 +440,6 @@ void IDBObjectStoreBackendImpl::deleteIndex(int64_t indexId, IDBTransactionBacke void IDBObjectStoreBackendImpl::deleteIndexInternal(ScriptExecutionContext*, PassRefPtr<IDBObjectStoreBackendImpl> objectStore, PassRefPtr<IDBIndexBackendImpl> index, PassRefPtr<IDBTransactionBackendImpl> transaction) { objectStore->backingStore()->deleteIndex(transaction->backingStoreTransaction(), objectStore->databaseId(), objectStore->id(), index->id()); - transaction->didCompleteTaskEvents(); } void IDBObjectStoreBackendImpl::openCursor(PassRefPtr<IDBKeyRange> prpRange, IDBCursor::Direction direction, PassRefPtr<IDBCallbacks> prpCallbacks, IDBTransactionBackendInterface::TaskType taskType, IDBTransactionBackendInterface* transactionPtr, ExceptionCode&) diff --git a/Source/WebCore/Modules/indexeddb/IDBOpenDBRequest.cpp b/Source/WebCore/Modules/indexeddb/IDBOpenDBRequest.cpp index b23901619..551d0dd09 100644 --- a/Source/WebCore/Modules/indexeddb/IDBOpenDBRequest.cpp +++ b/Source/WebCore/Modules/indexeddb/IDBOpenDBRequest.cpp @@ -89,7 +89,8 @@ void IDBOpenDBRequest::onUpgradeNeeded(int64_t oldVersion, PassRefPtr<IDBTransac m_databaseCallbacks->connect(idbDatabase.get()); m_databaseCallbacks = 0; - RefPtr<IDBTransaction> frontend = IDBTransaction::create(scriptExecutionContext(), transactionBackend, Vector<String>(), IDBTransaction::VERSION_CHANGE, idbDatabase.get(), this); + int64_t transactionId = IDBDatabase::nextTransactionId(); + RefPtr<IDBTransaction> frontend = IDBTransaction::create(scriptExecutionContext(), transactionId, transactionBackend, Vector<String>(), IDBTransaction::VERSION_CHANGE, idbDatabase.get(), this); transactionBackend->setCallbacks(frontend.get()); m_transaction = frontend; m_result = IDBAny::create(idbDatabase.release()); diff --git a/Source/WebCore/Modules/indexeddb/IDBRequest.cpp b/Source/WebCore/Modules/indexeddb/IDBRequest.cpp index e4d167ffa..03a11b944 100644 --- a/Source/WebCore/Modules/indexeddb/IDBRequest.cpp +++ b/Source/WebCore/Modules/indexeddb/IDBRequest.cpp @@ -78,9 +78,10 @@ IDBRequest::IDBRequest(ScriptExecutionContext* context, PassRefPtr<IDBAny> sourc , m_preventPropagation(false) , m_requestState(context) { - if (m_transaction) { + // Requests associated with IDBFactory (open/deleteDatabase/getDatabaseNames) are not + // associated with transactions. + if (m_transaction) m_transaction->registerRequest(this); - } } IDBRequest::~IDBRequest() @@ -311,31 +312,6 @@ void IDBRequest::onSuccess(PassRefPtr<IDBKey> idbKey) enqueueEvent(createSuccessEvent()); } -void IDBRequest::onSuccess(PassRefPtr<IDBTransactionBackendInterface> prpBackend) -{ - IDB_TRACE("IDBRequest::onSuccess(IDBTransaction)"); - RefPtr<IDBTransactionBackendInterface> backend = prpBackend; - - if (m_contextStopped || !scriptExecutionContext()) { - // Should only be null in tests. - if (backend.get()) - backend->abort(); - return; - } - if (!shouldEnqueueEvent()) - return; - - RefPtr<IDBTransaction> frontend = IDBTransaction::create(scriptExecutionContext(), backend, Vector<String>(), IDBTransaction::VERSION_CHANGE, m_source->idbDatabase().get()); - backend->setCallbacks(frontend.get()); - m_transaction = frontend; - - ASSERT(m_source->type() == IDBAny::IDBDatabaseType); - ASSERT(m_transaction->isVersionChange()); - - m_result = IDBAny::create(frontend.release()); - enqueueEvent(createSuccessEvent()); -} - void IDBRequest::onSuccess(PassRefPtr<SerializedScriptValue> serializedScriptValue) { IDB_TRACE("IDBRequest::onSuccess(SerializedScriptValue)"); @@ -501,30 +477,29 @@ bool IDBRequest::dispatchEvent(PassRefPtr<Event> event) bool dontPreventDefault = IDBEventDispatcher::dispatch(event.get(), targets); - if (m_transaction && m_readyState == DONE) - m_transaction->unregisterRequest(this); - - // If this was the last request in the transaction's list, it may commit here. - if (setTransactionActive) - m_transaction->setActive(false); - - if (cursorToNotify) - cursorToNotify->postSuccessHandlerCallback(); - - if (m_readyState == DONE && (!cursorToNotify || m_cursorFinished) && event->type() != eventNames().upgradeneededEvent) - m_hasPendingActivity = false; - if (m_transaction) { + if (m_readyState == DONE) + m_transaction->unregisterRequest(this); + + // Possibly abort the transaction. This must occur after unregistering (so this request + // doesn't receive a second error) and before deactivating (which might trigger commit). if (event->type() == eventNames().errorEvent && dontPreventDefault && !m_requestAborted) { m_transaction->setError(m_error); ExceptionCode unused; m_transaction->abort(unused); } - if (event->type() != eventNames().blockedEvent) - m_transaction->backend()->didCompleteTaskEvents(); + // If this was the last request in the transaction's list, it may commit here. + if (setTransactionActive) + m_transaction->setActive(false); } + if (cursorToNotify) + cursorToNotify->postSuccessHandlerCallback(); + + if (m_readyState == DONE && (!cursorToNotify || m_cursorFinished) && event->type() != eventNames().upgradeneededEvent) + m_hasPendingActivity = false; + return dontPreventDefault; } diff --git a/Source/WebCore/Modules/indexeddb/IDBRequest.h b/Source/WebCore/Modules/indexeddb/IDBRequest.h index 2dc2de9cd..edaa7ba16 100644 --- a/Source/WebCore/Modules/indexeddb/IDBRequest.h +++ b/Source/WebCore/Modules/indexeddb/IDBRequest.h @@ -91,7 +91,6 @@ public: virtual void onSuccess(PassRefPtr<DOMStringList>); virtual void onSuccess(PassRefPtr<IDBCursorBackendInterface>, PassRefPtr<IDBKey>, PassRefPtr<IDBKey> primaryKey, PassRefPtr<SerializedScriptValue>); virtual void onSuccess(PassRefPtr<IDBKey>); - virtual void onSuccess(PassRefPtr<IDBTransactionBackendInterface>); virtual void onSuccess(PassRefPtr<SerializedScriptValue>); virtual void onSuccess(PassRefPtr<SerializedScriptValue>, PassRefPtr<IDBKey>, const IDBKeyPath&); virtual void onSuccess(int64_t); diff --git a/Source/WebCore/Modules/indexeddb/IDBTransaction.cpp b/Source/WebCore/Modules/indexeddb/IDBTransaction.cpp index 7ab38e9c3..837d546a7 100644 --- a/Source/WebCore/Modules/indexeddb/IDBTransaction.cpp +++ b/Source/WebCore/Modules/indexeddb/IDBTransaction.cpp @@ -44,15 +44,15 @@ namespace WebCore { -PassRefPtr<IDBTransaction> IDBTransaction::create(ScriptExecutionContext* context, PassRefPtr<IDBTransactionBackendInterface> backend, const Vector<String>& objectStoreNames, IDBTransaction::Mode mode, IDBDatabase* db) +PassRefPtr<IDBTransaction> IDBTransaction::create(ScriptExecutionContext* context, int64_t id, PassRefPtr<IDBTransactionBackendInterface> backend, const Vector<String>& objectStoreNames, IDBTransaction::Mode mode, IDBDatabase* db) { IDBOpenDBRequest* openDBRequest = 0; - return create(context, backend, objectStoreNames, mode, db, openDBRequest); + return create(context, id, backend, objectStoreNames, mode, db, openDBRequest); } -PassRefPtr<IDBTransaction> IDBTransaction::create(ScriptExecutionContext* context, PassRefPtr<IDBTransactionBackendInterface> backend, const Vector<String>& objectStoreNames, IDBTransaction::Mode mode, IDBDatabase* db, IDBOpenDBRequest* openDBRequest) +PassRefPtr<IDBTransaction> IDBTransaction::create(ScriptExecutionContext* context, int64_t id, PassRefPtr<IDBTransactionBackendInterface> backend, const Vector<String>& objectStoreNames, IDBTransaction::Mode mode, IDBDatabase* db, IDBOpenDBRequest* openDBRequest) { - RefPtr<IDBTransaction> transaction(adoptRef(new IDBTransaction(context, backend, objectStoreNames, mode, db, openDBRequest))); + RefPtr<IDBTransaction> transaction(adoptRef(new IDBTransaction(context, id, backend, objectStoreNames, mode, db, openDBRequest))); transaction->suspendIfNeeded(); return transaction.release(); } @@ -88,9 +88,10 @@ const AtomicString& IDBTransaction::modeReadWriteLegacy() } -IDBTransaction::IDBTransaction(ScriptExecutionContext* context, PassRefPtr<IDBTransactionBackendInterface> backend, const Vector<String>& objectStoreNames, IDBTransaction::Mode mode, IDBDatabase* db, IDBOpenDBRequest* openDBRequest) +IDBTransaction::IDBTransaction(ScriptExecutionContext* context, int64_t id, PassRefPtr<IDBTransactionBackendInterface> backend, const Vector<String>& objectStoreNames, IDBTransaction::Mode mode, IDBDatabase* db, IDBOpenDBRequest* openDBRequest) : ActiveDOMObject(context, this) , m_backend(backend) + , m_id(id) , m_database(db) , m_objectStoreNames(objectStoreNames) , m_openDBRequest(openDBRequest) diff --git a/Source/WebCore/Modules/indexeddb/IDBTransaction.h b/Source/WebCore/Modules/indexeddb/IDBTransaction.h index 4c6a0695f..6a970c638 100644 --- a/Source/WebCore/Modules/indexeddb/IDBTransaction.h +++ b/Source/WebCore/Modules/indexeddb/IDBTransaction.h @@ -56,8 +56,8 @@ public: VERSION_CHANGE = 2 }; - static PassRefPtr<IDBTransaction> create(ScriptExecutionContext*, PassRefPtr<IDBTransactionBackendInterface>, const Vector<String>& objectStoreNames, Mode, IDBDatabase*); - static PassRefPtr<IDBTransaction> create(ScriptExecutionContext*, PassRefPtr<IDBTransactionBackendInterface>, const Vector<String>& objectStoreNames, Mode, IDBDatabase*, IDBOpenDBRequest*); + static PassRefPtr<IDBTransaction> create(ScriptExecutionContext*, int64_t, PassRefPtr<IDBTransactionBackendInterface>, const Vector<String>& objectStoreNames, Mode, IDBDatabase*); + static PassRefPtr<IDBTransaction> create(ScriptExecutionContext*, int64_t, PassRefPtr<IDBTransactionBackendInterface>, const Vector<String>& objectStoreNames, Mode, IDBDatabase*, IDBOpenDBRequest*); virtual ~IDBTransaction(); static const AtomicString& modeReadOnly(); @@ -70,6 +70,7 @@ public: static const AtomicString& modeToString(Mode, ExceptionCode&); IDBTransactionBackendInterface* backend() const; + int64_t id() const { return m_id; } bool isActive() const { return m_state == Active; } bool isFinished() const { return m_state == Finished; } bool isReadOnly() const { return m_mode == READ_ONLY; } @@ -122,7 +123,7 @@ public: using RefCounted<IDBTransactionCallbacks>::deref; private: - IDBTransaction(ScriptExecutionContext*, PassRefPtr<IDBTransactionBackendInterface>, const Vector<String>&, Mode, IDBDatabase*, IDBOpenDBRequest*); + IDBTransaction(ScriptExecutionContext*, int64_t, PassRefPtr<IDBTransactionBackendInterface>, const Vector<String>&, Mode, IDBDatabase*, IDBOpenDBRequest*); void enqueueEvent(PassRefPtr<Event>); void closeOpenCursors(); @@ -143,7 +144,9 @@ private: Finished, // No more events will fire and no new requests may be filed. }; + // FIXME: Remove references to the backend when the backend is fully flattened: https://bugs.webkit.org/show_bug.cgi?id=99774 RefPtr<IDBTransactionBackendInterface> m_backend; + int64_t m_id; RefPtr<IDBDatabase> m_database; const Vector<String> m_objectStoreNames; IDBOpenDBRequest* m_openDBRequest; diff --git a/Source/WebCore/Modules/indexeddb/IDBTransactionBackendImpl.cpp b/Source/WebCore/Modules/indexeddb/IDBTransactionBackendImpl.cpp index 50543d5e8..b8c77ed7d 100644 --- a/Source/WebCore/Modules/indexeddb/IDBTransactionBackendImpl.cpp +++ b/Source/WebCore/Modules/indexeddb/IDBTransactionBackendImpl.cpp @@ -39,21 +39,21 @@ namespace WebCore { -PassRefPtr<IDBTransactionBackendImpl> IDBTransactionBackendImpl::create(const Vector<int64_t>& objectStoreIds, unsigned short mode, IDBDatabaseBackendImpl* database) +PassRefPtr<IDBTransactionBackendImpl> IDBTransactionBackendImpl::create(int64_t id, const Vector<int64_t>& objectStoreIds, unsigned short mode, IDBDatabaseBackendImpl* database) { - return adoptRef(new IDBTransactionBackendImpl(objectStoreIds, mode, database)); + return adoptRef(new IDBTransactionBackendImpl(id, objectStoreIds, mode, database)); } -IDBTransactionBackendImpl::IDBTransactionBackendImpl(const Vector<int64_t>& objectStoreIds, unsigned short mode, IDBDatabaseBackendImpl* database) - : m_objectStoreIds(objectStoreIds) +IDBTransactionBackendImpl::IDBTransactionBackendImpl(int64_t id, const Vector<int64_t>& objectStoreIds, unsigned short mode, IDBDatabaseBackendImpl* database) + : m_id(id) + , m_objectStoreIds(objectStoreIds) , m_mode(mode) , m_state(Unused) + , m_commitPending(false) , m_database(database) , m_transaction(database->backingStore().get()) , m_taskTimer(this, &IDBTransactionBackendImpl::taskTimerFired) - , m_taskEventTimer(this, &IDBTransactionBackendImpl::taskEventTimerFired) , m_pendingPreemptiveEvents(0) - , m_pendingEvents(0) { m_database->transactionCoordinator()->didCreateTransaction(this); } @@ -91,6 +91,8 @@ bool IDBTransactionBackendImpl::scheduleTask(TaskType type, PassOwnPtr<ScriptExe if (m_state == Unused) start(); + else if (m_state == Running && !m_taskTimer.isActive()) + m_taskTimer.startOneShot(0); return true; } @@ -115,7 +117,6 @@ void IDBTransactionBackendImpl::abort(PassRefPtr<IDBDatabaseError> error) m_state = Finished; m_taskTimer.stop(); - m_taskEventTimer.stop(); if (wasRunning) m_transaction.rollback(); @@ -153,7 +154,7 @@ bool IDBTransactionBackendImpl::isTaskQueueEmpty() const bool IDBTransactionBackendImpl::hasPendingTasks() const { - return m_pendingEvents || m_pendingPreemptiveEvents || !isTaskQueueEmpty(); + return m_pendingPreemptiveEvents || !isTaskQueueEmpty(); } void IDBTransactionBackendImpl::registerOpenCursor(IDBCursorBackendImpl* cursor) @@ -166,27 +167,6 @@ void IDBTransactionBackendImpl::unregisterOpenCursor(IDBCursorBackendImpl* curso m_openCursors.remove(cursor); } -void IDBTransactionBackendImpl::addPendingEvents(int n) -{ - m_pendingEvents += n; - ASSERT(m_pendingEvents >= 0); -} - -void IDBTransactionBackendImpl::didCompleteTaskEvents() -{ - if (m_state == Finished) - return; - - ASSERT(m_state == Running); - ASSERT(m_pendingEvents); - m_pendingEvents--; - - // A single task has completed and error/success events fired. Schedule - // timer to process another. - if (!m_taskEventTimer.isActive()) - m_taskEventTimer.startOneShot(0); -} - void IDBTransactionBackendImpl::run() { // TransactionCoordinator has started this transaction. Schedule a timer @@ -210,7 +190,13 @@ void IDBTransactionBackendImpl::commit() { IDB_TRACE("IDBTransactionBackendImpl::commit"); + // In multiprocess ports, front-end may have requested a commit but an abort has already + // been initiated asynchronously by the back-end. + if (m_state == Finished) + return; + ASSERT(m_state == Unused || m_state == Running); + m_commitPending = true; // Front-end has requested a commit, but there may be tasks like createIndex which // are considered synchronous by the front-end but are processed asynchronously. @@ -269,31 +255,16 @@ void IDBTransactionBackendImpl::taskTimerFired(Timer<IDBTransactionBackendImpl>* while (!taskQueue->isEmpty() && m_state != Finished) { ASSERT(m_state == Running); OwnPtr<ScriptExecutionContext::Task> task(taskQueue->takeFirst()); - m_pendingEvents++; task->performTask(0); // Event itself may change which queue should be processed next. taskQueue = m_pendingPreemptiveEvents ? &m_preemptiveTaskQueue : &m_taskQueue; } -} - -void IDBTransactionBackendImpl::taskEventTimerFired(Timer<IDBTransactionBackendImpl>*) -{ - IDB_TRACE("IDBTransactionBackendImpl::taskEventTimerFired"); - ASSERT(m_state == Running); - if (!hasPendingTasks()) { - // The last task event has completed and the task - // queue is empty. Commit the transaction. + // If there are no pending tasks, we haven't already committed/aborted, + // and the front-end requested a commit, it is now safe to do so. + if (!hasPendingTasks() && m_state != Finished && m_commitPending) commit(); - return; - } - - // We are still waiting for other events to complete. However, - // the task queue is non-empty and the timer is inactive. - // We can therfore schedule the timer again. - if (!isTaskQueueEmpty() && !m_taskTimer.isActive()) - m_taskTimer.startOneShot(0); } void IDBTransactionBackendImpl::closeOpenCursors() diff --git a/Source/WebCore/Modules/indexeddb/IDBTransactionBackendImpl.h b/Source/WebCore/Modules/indexeddb/IDBTransactionBackendImpl.h index 803ed074a..d2a958506 100644 --- a/Source/WebCore/Modules/indexeddb/IDBTransactionBackendImpl.h +++ b/Source/WebCore/Modules/indexeddb/IDBTransactionBackendImpl.h @@ -44,7 +44,7 @@ class IDBDatabaseBackendImpl; class IDBTransactionBackendImpl : public IDBTransactionBackendInterface { public: - static PassRefPtr<IDBTransactionBackendImpl> create(const Vector<int64_t>&, unsigned short mode, IDBDatabaseBackendImpl*); + static PassRefPtr<IDBTransactionBackendImpl> create(int64_t transactionId, const Vector<int64_t>&, unsigned short mode, IDBDatabaseBackendImpl*); static IDBTransactionBackendImpl* from(IDBTransactionBackendInterface* interface) { return static_cast<IDBTransactionBackendImpl*>(interface); @@ -53,24 +53,24 @@ public: // IDBTransactionBackendInterface virtual PassRefPtr<IDBObjectStoreBackendInterface> objectStore(int64_t, ExceptionCode&); - virtual void didCompleteTaskEvents(); virtual void abort(); virtual void setCallbacks(IDBTransactionCallbacks* callbacks) { m_callbacks = callbacks; } void abort(PassRefPtr<IDBDatabaseError>); void run(); unsigned short mode() const { return m_mode; } + bool isFinished() const { return m_state == Finished; } bool scheduleTask(PassOwnPtr<ScriptExecutionContext::Task> task, PassOwnPtr<ScriptExecutionContext::Task> abortTask = nullptr) { return scheduleTask(NormalTask, task, abortTask); } bool scheduleTask(TaskType, PassOwnPtr<ScriptExecutionContext::Task>, PassOwnPtr<ScriptExecutionContext::Task> abortTask = nullptr); void registerOpenCursor(IDBCursorBackendImpl*); void unregisterOpenCursor(IDBCursorBackendImpl*); - void addPendingEvents(int); void addPreemptiveEvent() { m_pendingPreemptiveEvents++; } void didCompletePreemptiveEvent() { m_pendingPreemptiveEvents--; ASSERT(m_pendingPreemptiveEvents >= 0); } IDBBackingStore::Transaction* backingStoreTransaction() { return &m_transaction; } + int64_t id() const { return m_id; } private: - IDBTransactionBackendImpl(const Vector<int64_t>& objectStoreIds, unsigned short mode, IDBDatabaseBackendImpl*); + IDBTransactionBackendImpl(int64_t id, const Vector<int64_t>& objectStoreIds, unsigned short mode, IDBDatabaseBackendImpl*); enum State { Unused, // Created, but no tasks yet. @@ -86,13 +86,14 @@ private: bool hasPendingTasks() const; void taskTimerFired(Timer<IDBTransactionBackendImpl>*); - void taskEventTimerFired(Timer<IDBTransactionBackendImpl>*); void closeOpenCursors(); + const int64_t m_id; const Vector<int64_t> m_objectStoreIds; const unsigned short m_mode; State m_state; + bool m_commitPending; RefPtr<IDBTransactionCallbacks> m_callbacks; RefPtr<IDBDatabaseBackendImpl> m_database; @@ -105,9 +106,7 @@ private: // FIXME: delete the timer once we have threads instead. Timer<IDBTransactionBackendImpl> m_taskTimer; - Timer<IDBTransactionBackendImpl> m_taskEventTimer; int m_pendingPreemptiveEvents; - int m_pendingEvents; HashSet<IDBCursorBackendImpl*> m_openCursors; }; diff --git a/Source/WebCore/Modules/indexeddb/IDBTransactionBackendInterface.h b/Source/WebCore/Modules/indexeddb/IDBTransactionBackendInterface.h index 2f4cf327a..cc74d1156 100644 --- a/Source/WebCore/Modules/indexeddb/IDBTransactionBackendInterface.h +++ b/Source/WebCore/Modules/indexeddb/IDBTransactionBackendInterface.h @@ -54,7 +54,6 @@ public: }; virtual PassRefPtr<IDBObjectStoreBackendInterface> objectStore(int64_t, ExceptionCode&) = 0; - virtual void didCompleteTaskEvents() = 0; virtual void commit() = 0; virtual void abort() = 0; virtual void setCallbacks(IDBTransactionCallbacks*) = 0; diff --git a/Source/WebCore/Modules/webaudio/AudioContext.cpp b/Source/WebCore/Modules/webaudio/AudioContext.cpp index 078e161ca..714ab520e 100644 --- a/Source/WebCore/Modules/webaudio/AudioContext.cpp +++ b/Source/WebCore/Modules/webaudio/AudioContext.cpp @@ -63,6 +63,7 @@ #if ENABLE(MEDIA_STREAM) #include "MediaStream.h" +#include "MediaStreamAudioDestinationNode.h" #include "MediaStreamAudioSourceNode.h" #endif @@ -430,6 +431,14 @@ PassRefPtr<MediaStreamAudioSourceNode> AudioContext::createMediaStreamSource(Med refNode(node.get()); // context keeps reference until node is disconnected return node; } + +PassRefPtr<MediaStreamAudioDestinationNode> AudioContext::createMediaStreamDestination() +{ + // FIXME: Add support for an optional argument which specifies the number of channels. + // FIXME: The default should probably be stereo instead of mono. + return MediaStreamAudioDestinationNode::create(this, 1); +} + #endif PassRefPtr<ScriptProcessorNode> AudioContext::createScriptProcessor(size_t bufferSize, ExceptionCode& ec) diff --git a/Source/WebCore/Modules/webaudio/AudioContext.h b/Source/WebCore/Modules/webaudio/AudioContext.h index 8046acc98..6da3c12a9 100644 --- a/Source/WebCore/Modules/webaudio/AudioContext.h +++ b/Source/WebCore/Modules/webaudio/AudioContext.h @@ -49,6 +49,7 @@ class AudioBuffer; class AudioBufferCallback; class AudioBufferSourceNode; class MediaElementAudioSourceNode; +class MediaStreamAudioDestinationNode; class MediaStreamAudioSourceNode; class HTMLMediaElement; class ChannelMergerNode; @@ -118,6 +119,7 @@ public: #endif #if ENABLE(MEDIA_STREAM) PassRefPtr<MediaStreamAudioSourceNode> createMediaStreamSource(MediaStream*, ExceptionCode&); + PassRefPtr<MediaStreamAudioDestinationNode> createMediaStreamDestination(); #endif PassRefPtr<GainNode> createGain(); PassRefPtr<BiquadFilterNode> createBiquadFilter(); diff --git a/Source/WebCore/Modules/webaudio/AudioContext.idl b/Source/WebCore/Modules/webaudio/AudioContext.idl index 173313f95..f2d8f4c2b 100644 --- a/Source/WebCore/Modules/webaudio/AudioContext.idl +++ b/Source/WebCore/Modules/webaudio/AudioContext.idl @@ -66,6 +66,7 @@ #if defined(ENABLE_MEDIA_STREAM) && ENABLE_MEDIA_STREAM MediaStreamAudioSourceNode createMediaStreamSource(in MediaStream mediaStream) raises(DOMException); + MediaStreamAudioDestinationNode createMediaStreamDestination(); #endif // Processing nodes diff --git a/Source/WebCore/Modules/webaudio/AudioNode.h b/Source/WebCore/Modules/webaudio/AudioNode.h index 61b5a20b1..30b8eb31c 100644 --- a/Source/WebCore/Modules/webaudio/AudioNode.h +++ b/Source/WebCore/Modules/webaudio/AudioNode.h @@ -64,6 +64,7 @@ public: NodeTypeOscillator, NodeTypeAudioBufferSource, NodeTypeMediaElementAudioSource, + NodeTypeMediaStreamAudioDestination, NodeTypeMediaStreamAudioSource, NodeTypeJavaScript, NodeTypeBiquadFilter, diff --git a/Source/WebCore/Modules/webaudio/MediaStreamAudioDestinationNode.cpp b/Source/WebCore/Modules/webaudio/MediaStreamAudioDestinationNode.cpp new file mode 100644 index 000000000..e745f2f5f --- /dev/null +++ b/Source/WebCore/Modules/webaudio/MediaStreamAudioDestinationNode.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2012, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(WEB_AUDIO) && ENABLE(MEDIA_STREAM) + +#include "MediaStreamAudioDestinationNode.h" + +#include "AudioContext.h" +#include "AudioNodeInput.h" +#include "LocalMediaStream.h" +#include "MediaStreamCenter.h" +#include "RTCPeerConnectionHandler.h" +#include "UUID.h" +#include <wtf/Locker.h> + +namespace WebCore { + +PassRefPtr<MediaStreamAudioDestinationNode> MediaStreamAudioDestinationNode::create(AudioContext* context, size_t numberOfChannels) +{ + return adoptRef(new MediaStreamAudioDestinationNode(context, numberOfChannels)); +} + +MediaStreamAudioDestinationNode::MediaStreamAudioDestinationNode(AudioContext* context, size_t numberOfChannels) + : AudioBasicInspectorNode(context, context->sampleRate()) + , m_mixBus(numberOfChannels, ProcessingSizeInFrames) +{ + setNodeType(NodeTypeMediaStreamAudioDestination); + + m_source = MediaStreamSource::create(ASCIILiteral("WebAudio-") + createCanonicalUUIDString(), MediaStreamSource::TypeAudio, "MediaStreamAudioDestinationNode", MediaStreamSource::ReadyStateLive, true); + MediaStreamSourceVector audioSources; + audioSources.append(m_source); + MediaStreamSourceVector videoSources; + m_stream = LocalMediaStream::create(context->scriptExecutionContext(), audioSources, videoSources); + MediaStreamCenter::instance().didCreateMediaStream(m_stream->descriptor()); + + initialize(); +} + +MediaStreamSource* MediaStreamAudioDestinationNode::mediaStreamSource() +{ + return m_source.get(); +} + +MediaStreamAudioDestinationNode::~MediaStreamAudioDestinationNode() +{ + uninitialize(); +} + +void MediaStreamAudioDestinationNode::process(size_t numberOfFrames) +{ + m_mixBus.copyFrom(*input(0)->bus()); + m_source->consumeAudio(&m_mixBus, numberOfFrames); +} + +void MediaStreamAudioDestinationNode::reset() +{ +} + +} // namespace WebCore + +#endif // ENABLE(WEB_AUDIO) && ENABLE(MEDIA_STREAM) diff --git a/Source/WebCore/Modules/webaudio/MediaStreamAudioDestinationNode.h b/Source/WebCore/Modules/webaudio/MediaStreamAudioDestinationNode.h new file mode 100644 index 000000000..4a9a2765e --- /dev/null +++ b/Source/WebCore/Modules/webaudio/MediaStreamAudioDestinationNode.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2012, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef MediaStreamAudioDestinationNode_h +#define MediaStreamAudioDestinationNode_h + +#if ENABLE(WEB_AUDIO) && ENABLE(MEDIA_STREAM) + +#include "AudioBasicInspectorNode.h" +#include "AudioBus.h" +#include "MediaStream.h" +#include <wtf/OwnPtr.h> +#include <wtf/PassRefPtr.h> + +namespace WebCore { + +class AudioContext; + +class MediaStreamAudioDestinationNode : public AudioBasicInspectorNode { +public: + static PassRefPtr<MediaStreamAudioDestinationNode> create(AudioContext*, size_t numberOfChannels); + + virtual ~MediaStreamAudioDestinationNode(); + + MediaStream* stream() { return m_stream.get(); } + + // AudioNode. + virtual void process(size_t framesToProcess); + virtual void reset(); + + MediaStreamSource* mediaStreamSource(); + +private: + MediaStreamAudioDestinationNode(AudioContext*, size_t numberOfChannels); + + virtual double tailTime() const OVERRIDE { return 0; } + virtual double latencyTime() const OVERRIDE { return 0; } + + // As an audio source, we will never propagate silence. + virtual bool propagatesSilence() const OVERRIDE { return false; } + + RefPtr<MediaStream> m_stream; + RefPtr<MediaStreamSource> m_source; + AudioBus m_mixBus; +}; + +} // namespace WebCore + +#endif // ENABLE(WEB_AUDIO) && ENABLE(MEDIA_STREAM) + +#endif // MediaStreamAudioDestinationNode_h diff --git a/Source/WebCore/platform/PlatformGestureCurve.h b/Source/WebCore/Modules/webaudio/MediaStreamAudioDestinationNode.idl index 06124d860..c71bba41a 100644 --- a/Source/WebCore/platform/PlatformGestureCurve.h +++ b/Source/WebCore/Modules/webaudio/MediaStreamAudioDestinationNode.idl @@ -1,14 +1,14 @@ /* - * Copyright (C) 2012 Google Inc. All rights reserved. + * Copyright (C) 2012, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. + * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED @@ -22,28 +22,9 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef PlatformGestureCurve_h -#define PlatformGestureCurve_h - -namespace WebCore { - -class PlatformGestureCurveTarget; - -// Abstract interface for curves used by ActivePlatformGestureAnimation. A -// PlatformGestureCurve defines the animation parameters as a function of time -// (zero-based), and applies the parameters directly to the target of the -// animation. -class PlatformGestureCurve { -public: - virtual ~PlatformGestureCurve() { } - - // Returns a name of the curve for use in debugging. - virtual const char* debugName() const = 0; - - // Returns false if curve has finished and can no longer be applied. - virtual bool apply(double time, PlatformGestureCurveTarget*) = 0; +[ + Conditional=WEB_AUDIO&MEDIA_STREAM, + JSGenerateToJSObject +] interface MediaStreamAudioDestinationNode : AudioSourceNode { + readonly attribute MediaStream stream; }; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/Modules/websockets/WebSocketChannel.cpp b/Source/WebCore/Modules/websockets/WebSocketChannel.cpp index 4364de2ea..75481b7a8 100644 --- a/Source/WebCore/Modules/websockets/WebSocketChannel.cpp +++ b/Source/WebCore/Modules/websockets/WebSocketChannel.cpp @@ -194,7 +194,7 @@ void WebSocketChannel::fail(const String& reason) ASSERT(!m_suspended); if (m_document) { InspectorInstrumentation::didReceiveWebSocketFrameError(m_document, m_identifier, reason); - m_document->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, reason, m_handshake->clientOrigin()); + m_document->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, "WebSocket connection to '" + m_handshake->url().string() + "' failed: " + reason); } // Hybi-10 specification explicitly states we must not continue to handle incoming data diff --git a/Source/WebCore/Target.pri b/Source/WebCore/Target.pri index c970f5e90..c57d58b20 100644 --- a/Source/WebCore/Target.pri +++ b/Source/WebCore/Target.pri @@ -831,6 +831,7 @@ SOURCES += \ loader/EmptyClients.cpp \ loader/FormState.cpp \ loader/FormSubmission.cpp \ + loader/FrameLoadRequest.cpp \ loader/FrameLoader.cpp \ loader/FrameLoaderStateMachine.cpp \ loader/HistoryController.cpp \ @@ -4081,6 +4082,17 @@ contains(CONFIG, opengl-shims) { DEFINES += QT_OPENGL_SHIMS=1 } +contains(DEFINES, ENABLE_OPENCL=1) { + HEADERS += \ + platform/graphics/gpu/opencl/OpenCLHandle.h \ + platform/graphics/gpu/opencl/FilterContextOpenCL.h + SOURCES += \ + platform/graphics/gpu/opencl/FilterContextOpenCL.cpp \ + platform/graphics/gpu/opencl/OpenCLFESourceAlpha.cpp \ + platform/graphics/gpu/opencl/OpenCLFESourceGraphic.cpp \ + platform/graphics/gpu/opencl/OpenCLFETurbulence.cpp +} + use?(GRAPHICS_SURFACE) { mac { SOURCES += platform/graphics/surfaces/mac/GraphicsSurfaceMac.cpp diff --git a/Source/WebCore/UseV8.cmake b/Source/WebCore/UseV8.cmake index 0b87df5e7..03633cb8b 100644 --- a/Source/WebCore/UseV8.cmake +++ b/Source/WebCore/UseV8.cmake @@ -68,7 +68,6 @@ LIST(APPEND WebCore_SOURCES bindings/v8/V8WindowErrorHandler.cpp bindings/v8/V8WorkerContextErrorHandler.cpp bindings/v8/V8WorkerContextEventListener.cpp - bindings/v8/WorkerContextExecutionProxy.cpp bindings/v8/WorkerScriptController.cpp bindings/v8/WorkerScriptDebugServer.cpp bindings/v8/WorldContextHandle.cpp diff --git a/Source/WebCore/WebCore.exp.in b/Source/WebCore/WebCore.exp.in index 99a044bb3..af91d3d95 100644 --- a/Source/WebCore/WebCore.exp.in +++ b/Source/WebCore/WebCore.exp.in @@ -81,6 +81,9 @@ __ZN7WebCore10ScrollView21setDelegatesScrollingEb __ZN7WebCore10ScrollView23setScrollbarsSuppressedEbb __ZN7WebCore10ScrollView24windowResizerRectChangedEv __ZN7WebCore10ScrollView8addChildEN3WTF10PassRefPtrINS_6WidgetEEE +__ZNK7WebCore10ShadowRoot17hasContentElementEv +__ZNK7WebCore10ShadowRoot18countElementShadowEv +__ZNK7WebCore10ShadowRoot23hasShadowInsertionPointEv __ZN7WebCore10ShadowRoot6createEPNS_7ElementERi __ZN7WebCore10deleteFileERKN3WTF6StringE __ZN7WebCore10setCookiesEPNS_8DocumentERKNS_4KURLERKN3WTF6StringE @@ -107,9 +110,7 @@ __ZN7WebCore11FrameLoader23timeOfLastCompletedLoadEv __ZN7WebCore11FrameLoader26reloadWithOverrideEncodingERKN3WTF6StringE __ZN7WebCore11FrameLoader32setOriginalURLForDownloadRequestERNS_15ResourceRequestE __ZN7WebCore11FrameLoader4initEv -__ZN7WebCore11FrameLoader4loadERKNS_15ResourceRequestERKN3WTF6StringEb -__ZN7WebCore11FrameLoader4loadERKNS_15ResourceRequestERKNS_14SubstituteDataEb -__ZN7WebCore11FrameLoader4loadERKNS_15ResourceRequestEb +__ZN7WebCore11FrameLoader4loadERKNS_16FrameLoadRequestE __ZN7WebCore11FrameLoader6reloadEb __ZN7WebCore11FrameLoader9setOpenerEPNS_5FrameE __ZN7WebCore11HistoryItem10targetItemEv @@ -247,9 +248,11 @@ __ZN7WebCore14DocumentLoader15detachFromFrameEv __ZN7WebCore14DocumentLoader18addArchiveResourceEN3WTF10PassRefPtrINS_15ArchiveResourceEEE __ZN7WebCore14ResourceLoader32didCancelAuthenticationChallengeERKNS_23AuthenticationChallengeE __ZN7WebCore21SerializedScriptValue11deserializeEPN3JSC9ExecStateEPNS1_14JSGlobalObjectEPN3WTF6VectorINS6_6RefPtrINS_11MessagePortEEELm1EEENS_22SerializationErrorModeE +__ZN7WebCore21SerializedScriptValue14createFromWireERKN3WTF6StringE __ZN7WebCore21SerializedScriptValue6createEPN3JSC9ExecStateENS1_7JSValueEPN3WTF6VectorINS5_6RefPtrINS_11MessagePortEEELm1EEEPNS6_INS7_INS5_11ArrayBufferEEELm1EEENS_22SerializationErrorModeE __ZN7WebCore21SerializedScriptValue6createERKN3WTF6StringE __ZN7WebCore21SerializedScriptValue8toStringEv +__ZNK7WebCore21SerializedScriptValue12toWireStringEv __ZN7WebCore4toJSEPN3JSC9ExecStateEPNS_17JSDOMGlobalObjectEPN3WTF11ArrayBufferE __ZN7WebCore14DocumentLoader21addPlugInStreamLoaderEPNS_14ResourceLoaderE __ZN7WebCore14DocumentLoader22addAllArchiveResourcesEPNS_7ArchiveE @@ -431,6 +434,7 @@ __ZN7WebCore16DeviceMotionData12RotationRate6createEbdbdbd __ZN7WebCore16DeviceMotionData6createEN3WTF10PassRefPtrINS0_12AccelerationEEES4_NS2_INS0_12RotationRateEEEbd __ZN7WebCore16FontFallbackList15releaseFontDataEv __ZN7WebCore16FontPlatformDataD1Ev +__ZN7WebCore16FrameLoadRequestC1EPNS_5FrameERKNS_15ResourceRequestERKNS_14SubstituteDataE __ZN7WebCore16HTMLInputElement8setValueERKN3WTF6StringENS_22TextFieldEventBehaviorE __ZN7WebCore16HTMLInputElement13setAutofilledEb __ZN7WebCore16HTMLInputElement15setEditingValueERKN3WTF6StringE @@ -491,6 +495,8 @@ __ZN7WebCore17HistoryController26saveDocumentAndScrollStateEv __ZN7WebCore17HistoryController33restoreScrollPositionAndViewStateEv __ZN7WebCore17JSDOMGlobalObject6s_infoE __ZN7WebCore17languageDidChangeEv +__ZN7WebCore17MouseRelatedEvent7offsetXEv +__ZN7WebCore17MouseRelatedEvent7offsetYEv __ZN7WebCore17RegularExpressionC1ERKN3WTF6StringENS1_19TextCaseSensitivityE __ZN7WebCore17RegularExpressionD1Ev __ZN7WebCore17SubresourceLoader6createEPNS_5FrameEPNS_14CachedResourceERKNS_15ResourceRequestERKNS_21ResourceLoaderOptionsE @@ -690,7 +696,6 @@ __ZN7WebCore30hostNameNeedsEncodingWithRangeEP8NSString8_NSRange __ZN7WebCore30overrideUserPreferredLanguagesERKN3WTF6VectorINS0_6StringELm0EEE __ZN7WebCore31CrossOriginPreflightResultCache5emptyEv __ZN7WebCore31CrossOriginPreflightResultCache6sharedEv -__ZN7WebCore32plainTextToMallocAllocatedBufferEPKNS_5RangeERjbNS_20TextIteratorBehaviorE __ZN7WebCore33stripLeadingAndTrailingHTMLSpacesERKN3WTF6StringE __ZN7WebCore37WidgetHierarchyUpdatesSuspensionScope11moveWidgetsEv __ZN7WebCore37WidgetHierarchyUpdatesSuspensionScope35s_widgetHierarchyUpdateSuspendCountE @@ -1075,6 +1080,9 @@ __ZN7WebCore9PageGroup26setShouldTrackVisitedLinksEb __ZN7WebCore9PageGroup29removeUserStyleSheetFromWorldEPNS_15DOMWrapperWorldERKNS_4KURLE __ZN7WebCore9PageGroup30removeUserStyleSheetsFromWorldEPNS_15DOMWrapperWorldE __ZN7WebCore9PageGroup9pageGroupERKN3WTF6StringE +__ZN7WebCore9Scrollbar10mouseMovedERKNS_18PlatformMouseEventE +__ZN7WebCore9Scrollbar11mouseExitedEv +__ZN7WebCore9Scrollbar12mouseEnteredEv __ZN7WebCore9Scrollbar13setProportionEii __ZN7WebCore9Scrollbar21createNativeScrollbarEPNS_14ScrollableAreaENS_20ScrollbarOrientationENS_20ScrollbarControlSizeE __ZN7WebCore9Scrollbar22maxOverlapBetweenPagesEv @@ -1090,7 +1098,7 @@ __ZN7WebCore9endOfWordERKNS_15VisiblePositionENS_9EWordSideE __ZN7WebCore9fontCacheEv __ZN7WebCore9makeRangeERKNS_15VisiblePositionES2_ __ZN7WebCore9pageCacheEv -__ZN7WebCore9plainTextEPKNS_5RangeENS_20TextIteratorBehaviorE +__ZN7WebCore9plainTextEPKNS_5RangeENS_20TextIteratorBehaviorEb __ZN7WebCore9toElementEN3JSC7JSValueE __ZN7WebCore9unionRectERKN3WTF6VectorINS_9FloatRectELm0EEE __ZNK3JSC8Bindings10RootObject12globalObjectEv @@ -1319,7 +1327,7 @@ __ZNK7WebCore27AuthenticationChallengeBase20previousFailureCountEv __ZNK7WebCore27AuthenticationChallengeBase5errorEv __ZNK7WebCore27AuthenticationChallengeBase6isNullEv __ZNK7WebCore4Font5widthERKNS_7TextRunEPN3WTF7HashSetIPKNS_14SimpleFontDataENS4_7PtrHashIS8_EENS4_10HashTraitsIS8_EEEEPNS_13GlyphOverflowE -__ZNK7WebCore4Font8drawTextEPNS_15GraphicsContextERKNS_7TextRunERKNS_10FloatPointEii +__ZNK7WebCore4Font8drawTextEPNS_15GraphicsContextERKNS_7TextRunERKNS_10FloatPointEiiNS0_24CustomFontNotReadyActionE __ZNK7WebCore4KURL10protocolIsEPKc __ZNK7WebCore4KURL11createCFURLEv __ZNK7WebCore4KURL11isLocalFileEv @@ -1593,6 +1601,8 @@ _wkSignalCFReadStreamHasBytes .objc_class_name_DOMStyleSheet .objc_class_name_DOMStyleSheetList .objc_class_name_DOMTreeWalker +.objc_class_name_WebCoreFullScreenPlaceholderView +.objc_class_name_WebCoreFullScreenWarningView .objc_class_name_WebCoreFullScreenWindow .objc_class_name_WebHTMLConverter .objc_class_name_WebWindowFadeAnimation diff --git a/Source/WebCore/WebCore.gypi b/Source/WebCore/WebCore.gypi index 294885cde..d95a17d8d 100644 --- a/Source/WebCore/WebCore.gypi +++ b/Source/WebCore/WebCore.gypi @@ -920,6 +920,7 @@ 'Modules/webaudio/DynamicsCompressorNode.idl', 'Modules/webaudio/ScriptProcessorNode.idl', 'Modules/webaudio/MediaElementAudioSourceNode.idl', + 'Modules/webaudio/MediaStreamAudioDestinationNode.idl', 'Modules/webaudio/MediaStreamAudioSourceNode.idl', 'Modules/webaudio/OfflineAudioCompletionEvent.idl', 'Modules/webaudio/OscillatorNode.idl', @@ -972,6 +973,7 @@ 'css/WebKitCSSKeyframeRule.idl', 'css/WebKitCSSKeyframesRule.idl', 'css/WebKitCSSMatrix.idl', + 'css/WebKitCSSMixFunctionValue.idl', 'css/WebKitCSSRegionRule.idl', 'css/WebKitCSSTransformValue.idl', 'css/WebKitCSSViewportRule.idl', @@ -1745,6 +1747,8 @@ 'Modules/webaudio/ScriptProcessorNode.h', 'Modules/webaudio/MediaElementAudioSourceNode.cpp', 'Modules/webaudio/MediaElementAudioSourceNode.h', + 'Modules/webaudio/MediaStreamAudioDestinationNode.cpp', + 'Modules/webaudio/MediaStreamAudioDestinationNode.h', 'Modules/webaudio/MediaStreamAudioSourceNode.cpp', 'Modules/webaudio/MediaStreamAudioSourceNode.h', 'Modules/webaudio/OfflineAudioCompletionEvent.cpp', @@ -2331,8 +2335,6 @@ 'bindings/v8/V8WorkerContextErrorHandler.h', 'bindings/v8/V8WorkerContextEventListener.cpp', 'bindings/v8/V8WorkerContextEventListener.h', - 'bindings/v8/WorkerContextExecutionProxy.cpp', - 'bindings/v8/WorkerContextExecutionProxy.h', 'bindings/v8/WorkerScriptController.cpp', 'bindings/v8/WorkerScriptController.h', 'bindings/v8/WorkerScriptDebugServer.cpp', @@ -2950,6 +2952,7 @@ 'loader/FTPDirectoryParser.h', 'loader/FormState.cpp', 'loader/FormSubmission.cpp', + 'loader/FrameLoadRequest.cpp', 'loader/FrameLoader.cpp', 'loader/FrameLoaderStateMachine.cpp', 'loader/HistoryController.cpp', @@ -4446,8 +4449,6 @@ 'html/track/WebVTTTokenizer.h', ], 'webcore_platform_files': [ - 'platform/ActivePlatformGestureAnimation.cpp', - 'platform/ActivePlatformGestureAnimation.h', 'platform/Arena.cpp', 'platform/Arena.h', 'platform/AsyncFileSystem.cpp', @@ -4493,7 +4494,6 @@ 'platform/MemoryPressureHandler.cpp', 'platform/MIMETypeRegistry.cpp', 'platform/Pasteboard.h', - 'platform/PlatformGestureCurve.h', 'platform/PlatformMemoryInstrumentation.cpp', 'platform/PlatformMemoryInstrumentation.h', 'platform/PlatformStrategies.cpp', @@ -4529,12 +4529,8 @@ 'platform/ThreadTimers.cpp', 'platform/ThreadTimers.h', 'platform/Timer.cpp', - 'platform/TouchFlingPlatformGestureCurve.cpp', - 'platform/TouchFlingPlatformGestureCurve.h', 'platform/UUID.cpp', 'platform/UUID.h', - 'platform/WheelFlingPlatformGestureCurve.cpp', - 'platform/WheelFlingPlatformGestureCurve.h', 'platform/Widget.cpp', 'platform/animation/Animation.cpp', 'platform/animation/AnimationList.cpp', @@ -8043,6 +8039,8 @@ '<(PRODUCT_DIR)/DerivedSources/WebCore/JSWebKitCSSKeyframesRule.h', '<(PRODUCT_DIR)/DerivedSources/WebCore/JSWebKitCSSMatrix.cpp', '<(PRODUCT_DIR)/DerivedSources/WebCore/JSWebKitCSSMatrix.h', + '<(PRODUCT_DIR)/DerivedSources/WebCore/JSWebKitCSSMixFunctionValue.cpp', + '<(PRODUCT_DIR)/DerivedSources/WebCore/JSWebKitCSSMixFunctionValue.h', '<(PRODUCT_DIR)/DerivedSources/WebCore/JSWebKitCSSRegionRule.cpp', '<(PRODUCT_DIR)/DerivedSources/WebCore/JSWebKitCSSRegionRule.h', '<(PRODUCT_DIR)/DerivedSources/WebCore/JSWebKitCSSTransformValue.cpp', @@ -8115,11 +8113,8 @@ 'platform/chromium/support/GraphicsContext3DChromium.cpp', 'platform/chromium/support/GraphicsContext3DPrivate.cpp', 'platform/chromium/support/GraphicsContext3DPrivate.h', - 'platform/chromium/support/PlatformGestureCurveFactory.cpp', - 'platform/chromium/support/PlatformGestureCurveFactory.h', 'platform/chromium/support/WebAudioBus.cpp', 'platform/chromium/support/WebData.cpp', - 'platform/chromium/support/WebFlingAnimatorToGestureCurveAdapter.h', 'platform/chromium/support/WebHTTPBody.cpp', 'platform/chromium/support/WebHTTPLoadInfo.cpp', 'platform/chromium/support/WebMediaConstraints.cpp', diff --git a/Source/WebCore/WebCore.order b/Source/WebCore/WebCore.order index f432060d2..c1f90a45d 100644 --- a/Source/WebCore/WebCore.order +++ b/Source/WebCore/WebCore.order @@ -319,7 +319,7 @@ __ZN7WebCore15StringTruncator13rightTruncateERKN3WTF6StringEfRKNS_4FontE __ZN7WebCore8makeRGBAEiiii __ZN7WebCore15GraphicsContext12setFillColorERKNS_5ColorENS_10ColorSpaceE __ZN7WebCore15GraphicsContext20setPlatformFillColorERKNS_5ColorENS_10ColorSpaceE -__ZNK7WebCore4Font8drawTextEPNS_15GraphicsContextERKNS_7TextRunERKNS_10FloatPointEii +__ZNK7WebCore4Font8drawTextEPNS_15GraphicsContextERKNS_7TextRunERKNS_10FloatPointEiiNS0_24CustomFontNotReadyActionE __ZNK7WebCore4Font14drawSimpleTextEPNS_15GraphicsContextERKNS_7TextRunERKNS_10FloatPointEii __ZNK7WebCore4Font33getGlyphsAndAdvancesForSimpleTextERKNS_7TextRunEiiRNS_11GlyphBufferENS0_20ForTextEmphasisOrNotE __ZN7WebCore11GlyphBuffer3addEtPKNS_14SimpleFontDataEfPKNS_9FloatSizeE diff --git a/Source/WebCore/WebCore.pri b/Source/WebCore/WebCore.pri index f0a40422e..67e12c066 100644 --- a/Source/WebCore/WebCore.pri +++ b/Source/WebCore/WebCore.pri @@ -294,6 +294,12 @@ unix|win32-g++* { QMAKE_PKGCONFIG_REQUIRES = QtCore QtGui QtNetwork QtWidgets } +contains(DEFINES, ENABLE_OPENCL=1) { + LIBS += -lOpenCL + + INCLUDEPATH += $$SOURCE_DIR/platform/graphics/gpu/opencl +} + # Disable C++0x mode in WebCore for those who enabled it in their Qt's mkspec *-g++*:QMAKE_CXXFLAGS -= -std=c++0x -std=gnu++0x diff --git a/Source/WebCore/WebCore.vcproj/WebCore.vcproj b/Source/WebCore/WebCore.vcproj/WebCore.vcproj index de6c19ddc..f055d22ea 100755 --- a/Source/WebCore/WebCore.vcproj/WebCore.vcproj +++ b/Source/WebCore/WebCore.vcproj/WebCore.vcproj @@ -23178,6 +23178,62 @@ >
</File>
<File
+ RelativePath="$(ConfigurationBuildDir)\obj\$(ProjectName)\DerivedSources\JSWebKitCSSMixFunctionValue.cpp"
+ >
+ <FileConfiguration
+ Name="Debug|Win32"
+ ExcludedFromBuild="true"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ ExcludedFromBuild="true"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug_Cairo_CFLite|Win32"
+ ExcludedFromBuild="true"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release_Cairo_CFLite|Win32"
+ ExcludedFromBuild="true"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug_All|Win32"
+ ExcludedFromBuild="true"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Production|Win32"
+ ExcludedFromBuild="true"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="$(ConfigurationBuildDir)\obj\$(ProjectName)\DerivedSources\JSWebKitCSSMixFunctionValue.h"
+ >
+ </File>
+ <File
RelativePath="$(ConfigurationBuildDir)\obj\$(ProjectName)\DerivedSources\JSWebKitCSSRegionRule.cpp"
>
<FileConfiguration
@@ -27590,6 +27646,10 @@ >
</File>
<File
+ RelativePath="..\loader\FrameLoadRequest.cpp"
+ >
+ </File>
+ <File
RelativePath="..\loader\FrameLoadRequest.h"
>
</File>
diff --git a/Source/WebCore/WebCore.xcodeproj/project.pbxproj b/Source/WebCore/WebCore.xcodeproj/project.pbxproj index cd7327aba..b2d5756cc 100644 --- a/Source/WebCore/WebCore.xcodeproj/project.pbxproj +++ b/Source/WebCore/WebCore.xcodeproj/project.pbxproj @@ -363,6 +363,8 @@ 150B923915F08DC400E10986 /* WebKitCSSArrayFunctionValue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 150B923715F08DC400E10986 /* WebKitCSSArrayFunctionValue.cpp */; }; 150B923A15F08DC400E10986 /* WebKitCSSArrayFunctionValue.h in Headers */ = {isa = PBXBuildFile; fileRef = 150B923815F08DC400E10986 /* WebKitCSSArrayFunctionValue.h */; }; 15B3FC1915FB217800A81BCB /* CustomFilterArrayParameter.h in Headers */ = {isa = PBXBuildFile; fileRef = 15B3FC1715FB217800A81BCB /* CustomFilterArrayParameter.h */; }; + 15B8B7C81652C5220036EF55 /* JSWebKitCSSMixFunctionValue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 15B8B7C61652C5220036EF55 /* JSWebKitCSSMixFunctionValue.cpp */; }; + 15B8B7C91652C5220036EF55 /* JSWebKitCSSMixFunctionValue.h in Headers */ = {isa = PBXBuildFile; fileRef = 15B8B7C71652C5220036EF55 /* JSWebKitCSSMixFunctionValue.h */; }; 15C7708D100D3C6B005BA267 /* ValidityState.h in Headers */ = {isa = PBXBuildFile; fileRef = 15C7708A100D3C6A005BA267 /* ValidityState.h */; }; 15C7708E100D3C6B005BA267 /* ValidityState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 15C7708B100D3C6A005BA267 /* ValidityState.cpp */; }; 15C77093100D3CA8005BA267 /* JSValidityState.h in Headers */ = {isa = PBXBuildFile; fileRef = 15C77091100D3CA8005BA267 /* JSValidityState.h */; }; @@ -2995,6 +2997,7 @@ 86243D0111BC31F700CC006A /* JSArrayBufferViewHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = 86243D0011BC31F700CC006A /* JSArrayBufferViewHelper.h */; }; 86512EDE154A2AEF00A90426 /* PerformanceResourceTiming.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 86512EDB154A2AEE00A90426 /* PerformanceResourceTiming.cpp */; }; 86512EDF154A2AEF00A90426 /* PerformanceResourceTiming.h in Headers */ = {isa = PBXBuildFile; fileRef = 86512EDC154A2AEF00A90426 /* PerformanceResourceTiming.h */; }; + 86BA766E166427A8005BE5D1 /* FrameLoadRequest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 86BA766D166427A8005BE5D1 /* FrameLoadRequest.cpp */; }; 86BE340015058CB200CE0FD8 /* PerformanceEntry.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 86BE33FA15058CB200CE0FD8 /* PerformanceEntry.cpp */; }; 86BE340115058CB200CE0FD8 /* PerformanceEntry.h in Headers */ = {isa = PBXBuildFile; fileRef = 86BE33FB15058CB200CE0FD8 /* PerformanceEntry.h */; }; 86BE340315058CB200CE0FD8 /* PerformanceEntryList.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 86BE33FD15058CB200CE0FD8 /* PerformanceEntryList.cpp */; }; @@ -5925,6 +5928,10 @@ CDB859F7160D48A400E5B07F /* MediaKeyEvent.cpp in Sources */ = {isa = PBXBuildFile; fileRef = CDB859F4160D489900E5B07F /* MediaKeyEvent.cpp */; }; CDB859FA160D494900E5B07F /* JSMediaKeyEvent.cpp in Sources */ = {isa = PBXBuildFile; fileRef = CDB859F8160D493E00E5B07F /* JSMediaKeyEvent.cpp */; }; CDB859FB160D494F00E5B07F /* JSMediaKeyError.cpp in Sources */ = {isa = PBXBuildFile; fileRef = CDB859F0160D42DD00E5B07F /* JSMediaKeyError.cpp */; }; + CDC69DDA16371FD4007C38DF /* WebCoreFullScreenPlaceholderView.h in Headers */ = {isa = PBXBuildFile; fileRef = CDC69DD816371FD3007C38DF /* WebCoreFullScreenPlaceholderView.h */; settings = {ATTRIBUTES = (Private, ); }; }; + CDC69DDB16371FD4007C38DF /* WebCoreFullScreenPlaceholderView.mm in Sources */ = {isa = PBXBuildFile; fileRef = CDC69DD916371FD3007C38DF /* WebCoreFullScreenPlaceholderView.mm */; }; + CDC69DD61632026C007C38DF /* WebCoreFullScreenWarningView.h in Headers */ = {isa = PBXBuildFile; fileRef = CDC69DD41632026C007C38DF /* WebCoreFullScreenWarningView.h */; settings = {ATTRIBUTES = (Private, ); }; }; + CDC69DD71632026C007C38DF /* WebCoreFullScreenWarningView.mm in Sources */ = {isa = PBXBuildFile; fileRef = CDC69DD51632026C007C38DF /* WebCoreFullScreenWarningView.mm */; }; CDD525D7145B6DD0008D204D /* JSHTMLMediaElementCustom.cpp in Sources */ = {isa = PBXBuildFile; fileRef = CDF65CCC145B6AFE00C4C7AA /* JSHTMLMediaElementCustom.cpp */; }; CDEA763014608A53008B31F1 /* PlatformClockCA.cpp in Sources */ = {isa = PBXBuildFile; fileRef = CDEA762E146084DE008B31F1 /* PlatformClockCA.cpp */; }; CDEA76341460B56F008B31F1 /* ClockGeneric.cpp in Sources */ = {isa = PBXBuildFile; fileRef = CDEA76321460AE29008B31F1 /* ClockGeneric.cpp */; }; @@ -7485,6 +7492,8 @@ 150B923715F08DC400E10986 /* WebKitCSSArrayFunctionValue.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WebKitCSSArrayFunctionValue.cpp; sourceTree = "<group>"; }; 150B923815F08DC400E10986 /* WebKitCSSArrayFunctionValue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebKitCSSArrayFunctionValue.h; sourceTree = "<group>"; }; 15B3FC1715FB217800A81BCB /* CustomFilterArrayParameter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CustomFilterArrayParameter.h; path = filters/CustomFilterArrayParameter.h; sourceTree = "<group>"; }; + 15B8B7C61652C5220036EF55 /* JSWebKitCSSMixFunctionValue.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSWebKitCSSMixFunctionValue.cpp; sourceTree = "<group>"; }; + 15B8B7C71652C5220036EF55 /* JSWebKitCSSMixFunctionValue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSWebKitCSSMixFunctionValue.h; sourceTree = "<group>"; }; 15C77089100D3C6A005BA267 /* ValidityState.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ValidityState.idl; sourceTree = "<group>"; }; 15C7708A100D3C6A005BA267 /* ValidityState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ValidityState.h; sourceTree = "<group>"; }; 15C7708B100D3C6A005BA267 /* ValidityState.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ValidityState.cpp; sourceTree = "<group>"; }; @@ -10236,6 +10245,7 @@ 86512EDB154A2AEE00A90426 /* PerformanceResourceTiming.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PerformanceResourceTiming.cpp; sourceTree = "<group>"; }; 86512EDC154A2AEF00A90426 /* PerformanceResourceTiming.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PerformanceResourceTiming.h; sourceTree = "<group>"; }; 86512EDD154A2AEF00A90426 /* PerformanceResourceTiming.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PerformanceResourceTiming.idl; sourceTree = "<group>"; }; + 86BA766D166427A8005BE5D1 /* FrameLoadRequest.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FrameLoadRequest.cpp; sourceTree = "<group>"; }; 86BE33FA15058CB200CE0FD8 /* PerformanceEntry.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PerformanceEntry.cpp; sourceTree = "<group>"; }; 86BE33FB15058CB200CE0FD8 /* PerformanceEntry.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PerformanceEntry.h; sourceTree = "<group>"; }; 86BE33FC15058CB200CE0FD8 /* PerformanceEntry.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PerformanceEntry.idl; sourceTree = "<group>"; }; @@ -13346,6 +13356,10 @@ CDB859F8160D493E00E5B07F /* JSMediaKeyEvent.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSMediaKeyEvent.cpp; sourceTree = "<group>"; }; CDB859F9160D493E00E5B07F /* JSMediaKeyEvent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSMediaKeyEvent.h; sourceTree = "<group>"; }; CDBD93BA1333BD4B002570E3 /* fullscreenQuickTime.css */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.css; path = fullscreenQuickTime.css; sourceTree = "<group>"; }; + CDC69DD816371FD3007C38DF /* WebCoreFullScreenPlaceholderView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebCoreFullScreenPlaceholderView.h; sourceTree = "<group>"; }; + CDC69DD916371FD3007C38DF /* WebCoreFullScreenPlaceholderView.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WebCoreFullScreenPlaceholderView.mm; sourceTree = "<group>"; }; + CDC69DD41632026C007C38DF /* WebCoreFullScreenWarningView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebCoreFullScreenWarningView.h; sourceTree = "<group>"; }; + CDC69DD51632026C007C38DF /* WebCoreFullScreenWarningView.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WebCoreFullScreenWarningView.mm; sourceTree = "<group>"; }; CDCE5CD014633BC900D47CCA /* EventTargetFactory.in */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = EventTargetFactory.in; sourceTree = "<group>"; }; CDEA762C14608224008B31F1 /* Clock.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Clock.h; sourceTree = "<group>"; }; CDEA762E146084DE008B31F1 /* PlatformClockCA.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PlatformClockCA.cpp; sourceTree = "<group>"; }; @@ -15847,6 +15861,10 @@ BCE659E50EA92FB2007E4533 /* ThemeMac.h */, BCE659E80EA92FFA007E4533 /* ThemeMac.mm */, 51DF6D7F0B92A18E00C2DC85 /* ThreadCheck.mm */, + CDC69DD816371FD3007C38DF /* WebCoreFullScreenPlaceholderView.h */, + CDC69DD916371FD3007C38DF /* WebCoreFullScreenPlaceholderView.mm */, + CDC69DD41632026C007C38DF /* WebCoreFullScreenWarningView.h */, + CDC69DD51632026C007C38DF /* WebCoreFullScreenWarningView.mm */, CD127DEA14F3097900E84779 /* WebCoreFullScreenWindow.h */, CD127DEB14F3097900E84779 /* WebCoreFullScreenWindow.mm */, 371941951566B37200A276D8 /* WebCoreNSCellExtras.h */, @@ -19073,6 +19091,8 @@ 316FE0700E6CCBEE00BF6088 /* JSWebKitCSSKeyframesRule.h */, 4983913D0F1E767500C23782 /* JSWebKitCSSMatrix.cpp */, 4983913E0F1E767500C23782 /* JSWebKitCSSMatrix.h */, + 15B8B7C61652C5220036EF55 /* JSWebKitCSSMixFunctionValue.cpp */, + 15B8B7C71652C5220036EF55 /* JSWebKitCSSMixFunctionValue.h */, 8ACC24CD148E24B200EFCC0D /* JSWebKitCSSRegionRule.cpp */, 8ACC24CE148E24B200EFCC0D /* JSWebKitCSSRegionRule.h */, 31611E580E1C4DE000F6A579 /* JSWebKitCSSTransformValue.cpp */, @@ -20824,6 +20844,7 @@ D000EBA011BDAFD400C47726 /* FrameLoaderStateMachine.cpp */, D000EBA111BDAFD400C47726 /* FrameLoaderStateMachine.h */, 93B77A370ADD792500EA4B81 /* FrameLoaderTypes.h */, + 86BA766D166427A8005BE5D1 /* FrameLoadRequest.cpp */, 658436850AE01B7400E53753 /* FrameLoadRequest.h */, 628D214D12131EF40055DCFC /* FrameNetworkingContext.h */, 51C81B870C4422F70019ECE3 /* FTPDirectoryParser.cpp */, @@ -25634,6 +25655,8 @@ FD581FB51520F93B003A7A75 /* WaveTable.h in Headers */, 29A812490FBB9CA900510293 /* WebAccessibilityObjectWrapper.h in Headers */, 93F199A808245E59001E9ABC /* WebCoreFrameView.h in Headers */, + CDC69DDA16371FD4007C38DF /* WebCoreFullScreenPlaceholderView.h in Headers */, + CDC69DD61632026C007C38DF /* WebCoreFullScreenWarningView.h in Headers */, CD127DEE14F3098400E84779 /* WebCoreFullScreenWindow.h in Headers */, BC53D911114310CC000D817E /* WebCoreJSClientData.h in Headers */, 93F199BB08245E59001E9ABC /* WebCoreKeyboardUIMode.h in Headers */, @@ -25812,6 +25835,7 @@ 447958041643B49A001E0A7F /* ParsedContentType.h in Headers */, FB2C15C3165D649D0039C9F8 /* CachedSVGDocumentReference.h in Headers */, 31741AAD16636609008A5B7E /* SimulatedClickOptions.h in Headers */, + 15B8B7C91652C5220036EF55 /* JSWebKitCSSMixFunctionValue.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -28750,6 +28774,8 @@ FD7F299613D4C0CB00AD9535 /* WaveShaperProcessor.cpp in Sources */, FD581FB41520F93B003A7A75 /* WaveTable.cpp in Sources */, 29A8124A0FBB9CA900510293 /* WebAccessibilityObjectWrapper.mm in Sources */, + CDC69DDB16371FD4007C38DF /* WebCoreFullScreenPlaceholderView.mm in Sources */, + CDC69DD71632026C007C38DF /* WebCoreFullScreenWarningView.mm in Sources */, CD127DED14F3097D00E84779 /* WebCoreFullScreenWindow.mm in Sources */, F3BFC9D315C177EC004244E5 /* WebCoreMemoryInstrumentation.cpp in Sources */, 371941961566B37200A276D8 /* WebCoreNSCellExtras.m in Sources */, @@ -28911,6 +28937,8 @@ 1E50084816516AD800B7E098 /* RenderThemeMacShared.mm in Sources */, CD7E05221651C28200C1201F /* WebCoreAVFResourceLoader.mm in Sources */, 447958051643B4B2001E0A7F /* ParsedContentType.cpp in Sources */, + 15B8B7C81652C5220036EF55 /* JSWebKitCSSMixFunctionValue.cpp in Sources */, + 86BA766E166427A8005BE5D1 /* FrameLoadRequest.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Source/WebCore/accessibility/AccessibilityObject.cpp b/Source/WebCore/accessibility/AccessibilityObject.cpp index 7dd1336bd..f5c2a4407 100644 --- a/Source/WebCore/accessibility/AccessibilityObject.cpp +++ b/Source/WebCore/accessibility/AccessibilityObject.cpp @@ -840,7 +840,7 @@ String AccessibilityObject::stringForVisiblePositionRange(const VisiblePositionR if (!listMarkerText.isEmpty()) builder.append(listMarkerText); - builder.append(it.characters(), it.length()); + it.appendTextToStringBuilder(builder); } else { // locate the node and starting offset for this replaced range int exception = 0; diff --git a/Source/WebCore/bindings/js/JSCSSValueCustom.cpp b/Source/WebCore/bindings/js/JSCSSValueCustom.cpp index 7ce457faf..8046583f5 100644 --- a/Source/WebCore/bindings/js/JSCSSValueCustom.cpp +++ b/Source/WebCore/bindings/js/JSCSSValueCustom.cpp @@ -39,6 +39,11 @@ #include "WebKitCSSFilterValue.h" #endif +#if ENABLE(CSS_SHADERS) +#include "JSWebKitCSSMixFunctionValue.h" +#include "WebKitCSSMixFunctionValue.h" +#endif + #if ENABLE(SVG) #include "JSSVGColor.h" #include "JSSVGPaint.h" @@ -94,6 +99,10 @@ JSValue toJS(ExecState* exec, JSDOMGlobalObject* globalObject, CSSValue* value) else if (value->isWebKitCSSFilterValue()) wrapper = CREATE_DOM_WRAPPER(exec, globalObject, WebKitCSSFilterValue, value); #endif +#if ENABLE(CSS_SHADERS) + else if (value->isWebKitCSSMixFunctionValue()) + wrapper = CREATE_DOM_WRAPPER(exec, globalObject, WebKitCSSMixFunctionValue, value); +#endif else if (value->isValueList()) wrapper = CREATE_DOM_WRAPPER(exec, globalObject, CSSValueList, value); #if ENABLE(SVG) diff --git a/Source/WebCore/bindings/js/SerializedScriptValue.cpp b/Source/WebCore/bindings/js/SerializedScriptValue.cpp index 45812bb21..7dc9aed0b 100644 --- a/Source/WebCore/bindings/js/SerializedScriptValue.cpp +++ b/Source/WebCore/bindings/js/SerializedScriptValue.cpp @@ -1840,19 +1840,6 @@ PassRefPtr<SerializedScriptValue> SerializedScriptValue::create(JSC::ExecState* return SerializedScriptValue::create(exec, value, 0, 0); } -String SerializedScriptValue::toWireString() const -{ - return CloneDeserializer::toWireString(m_data); -} - -PassRefPtr<SerializedScriptValue> SerializedScriptValue::createFromWire(const String& value) -{ - Vector<uint8_t> buffer; - if (!writeLittleEndian(buffer, value.impl()->characters(), value.length())) - return 0; - return adoptRef(new SerializedScriptValue(buffer)); -} - PassRefPtr<SerializedScriptValue> SerializedScriptValue::numberValue(double value) { Vector<uint8_t> buffer; @@ -1866,6 +1853,19 @@ JSValue SerializedScriptValue::deserialize(JSC::ExecState* exec, JSC::JSGlobalOb } #endif +String SerializedScriptValue::toWireString() const +{ + return CloneDeserializer::toWireString(m_data); +} + +PassRefPtr<SerializedScriptValue> SerializedScriptValue::createFromWire(const String& value) +{ + Vector<uint8_t> buffer; + if (!writeLittleEndian(buffer, value.impl()->characters(), value.length())) + return 0; + return adoptRef(new SerializedScriptValue(buffer)); +} + PassRefPtr<SerializedScriptValue> SerializedScriptValue::create(JSContextRef originContext, JSValueRef apiValue, MessagePortArray* messagePorts, ArrayBufferArray* arrayBuffers, JSValueRef* exception) diff --git a/Source/WebCore/bindings/js/SerializedScriptValue.h b/Source/WebCore/bindings/js/SerializedScriptValue.h index d94a86759..ecca82067 100644 --- a/Source/WebCore/bindings/js/SerializedScriptValue.h +++ b/Source/WebCore/bindings/js/SerializedScriptValue.h @@ -73,7 +73,6 @@ public: static PassRefPtr<SerializedScriptValue> create(JSContextRef, JSValueRef, JSValueRef* exception); static PassRefPtr<SerializedScriptValue> create(const String&); - static PassRefPtr<SerializedScriptValue> createFromWire(const String& value) { return create(value); } static PassRefPtr<SerializedScriptValue> adopt(Vector<uint8_t>& buffer) { return adoptRef(new SerializedScriptValue(buffer)); @@ -85,7 +84,6 @@ public: static PassRefPtr<SerializedScriptValue> booleanValue(bool value); String toString(); - String toWireString() { return toString(); } JSC::JSValue deserialize(JSC::ExecState*, JSC::JSGlobalObject*, MessagePortArray*, SerializationErrorMode = Throwing); JSValueRef deserialize(JSContextRef, JSValueRef* exception, MessagePortArray*); @@ -100,12 +98,13 @@ public: #if ENABLE(INDEXED_DATABASE) static PassRefPtr<SerializedScriptValue> create(JSC::ExecState*, JSC::JSValue); - static PassRefPtr<SerializedScriptValue> createFromWire(const String& data); - String toWireString() const; static PassRefPtr<SerializedScriptValue> numberValue(double value); JSC::JSValue deserialize(JSC::ExecState*, JSC::JSGlobalObject*); #endif + static PassRefPtr<SerializedScriptValue> createFromWire(const String& data); + String toWireString() const; + ~SerializedScriptValue(); private: diff --git a/Source/WebCore/bindings/scripts/CodeGeneratorV8.pm b/Source/WebCore/bindings/scripts/CodeGeneratorV8.pm index 8d56bb682..8adb0ceff 100644 --- a/Source/WebCore/bindings/scripts/CodeGeneratorV8.pm +++ b/Source/WebCore/bindings/scripts/CodeGeneratorV8.pm @@ -478,10 +478,17 @@ END if ($interfaceName eq "HTMLElement") { push(@headerContent, <<END); friend v8::Handle<v8::Object> createV8HTMLWrapper(HTMLElement*, v8::Handle<v8::Object> creationContext, v8::Isolate*); + friend v8::Handle<v8::Object> createV8HTMLDirectWrapper(HTMLElement*, v8::Handle<v8::Object> creationContext, v8::Isolate*); END } elsif ($interfaceName eq "SVGElement") { push(@headerContent, <<END); friend v8::Handle<v8::Object> createV8SVGWrapper(SVGElement*, v8::Handle<v8::Object> creationContext, v8::Isolate*); + friend v8::Handle<v8::Object> createV8SVGDirectWrapper(SVGElement*, v8::Handle<v8::Object> creationContext, v8::Isolate*); + friend v8::Handle<v8::Object> createV8SVGFallbackWrapper(SVGElement*, v8::Handle<v8::Object> creationContext, v8::Isolate*); +END + } elsif ($interfaceName eq "HTMLUnknownElement") { + push(@headerContent, <<END); + friend v8::Handle<v8::Object> createV8HTMLFallbackWrapper(HTMLUnknownElement*, v8::Handle<v8::Object> creationContext, v8::Isolate*); END } elsif ($interfaceName eq "Element") { push(@headerContent, <<END); @@ -586,10 +593,11 @@ inline v8::Handle<v8::Value> toV8Fast(${nativeType}* impl, const v8::AccessorInf // in an isolated world. The fastest way we know how to do that is to check // whether the holder's inline wrapper is the same wrapper we see in the // v8::AccessorInfo. - v8::Handle<v8::Object> wrapper = (holder->wrapper() == info.Holder()) ? impl->wrapper() : DOMDataStore::getNode(impl, info.GetIsolate()); + v8::Handle<v8::Object> holderWrapper = info.Holder(); + v8::Handle<v8::Object> wrapper = (holder->wrapper() == holderWrapper) ? impl->wrapper() : DOMDataStore::getNode(impl, info.GetIsolate()); if (!wrapper.IsEmpty()) return wrapper; - return wrap(impl, info.Holder(), info.GetIsolate()); + return wrap(impl, holderWrapper, info.GetIsolate()); } END } @@ -1001,8 +1009,8 @@ END } if ($useExceptions) { - if ($nativeType =~ /^V8Parameter/) { - push(@implContentDecls, " " . ConvertToV8Parameter($attribute->signature, $nativeType, "v", $getterString) . ";\n"); + if ($nativeType =~ /^V8StringResource/) { + push(@implContentDecls, " " . ConvertToV8StringResource($attribute->signature, $nativeType, "v", $getterString) . ";\n"); } else { push(@implContentDecls, " $nativeType v = $getterString;\n"); } @@ -1222,8 +1230,8 @@ END my $namespace = $codeGenerator->NamespaceForAttributeName($interfaceName, $contentAttributeName); AddToImplIncludes("${namespace}.h"); push(@implContentDecls, " Element* imp = V8Element::toNative(info.Holder());\n"); - push(@implContentDecls, " AtomicString v = toWebCoreAtomicStringWithNullCheck(value);\n"); - push(@implContentDecls, " imp->setAttribute(${namespace}::${contentAttributeName}Attr, v);\n"); + push(@implContentDecls, " V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<WithNullCheck>, stringResource, value);\n"); + push(@implContentDecls, " imp->setAttribute(${namespace}::${contentAttributeName}Attr, stringResource);\n"); push(@implContentDecls, "}\n\n"); push(@implContentDecls, "#endif // ${conditionalString}\n\n") if $conditionalString; return; @@ -1247,8 +1255,8 @@ END my $value = JSValueToNative($attribute->signature, "value", "info.GetIsolate()"); my $arrayType = $codeGenerator->GetArrayType($nativeType); - if ($nativeType =~ /^V8Parameter/) { - push(@implContentDecls, " " . ConvertToV8Parameter($attribute->signature, $nativeType, "v", $value, "VOID") . "\n"); + if ($nativeType =~ /^V8StringResource/) { + push(@implContentDecls, " " . ConvertToV8StringResource($attribute->signature, $nativeType, "v", $value, "VOID") . "\n"); } elsif ($arrayType) { push(@implContentDecls, " Vector<$arrayType> v = $value;\n"); } else { @@ -1374,7 +1382,8 @@ static v8::Handle<v8::Value> ${functionName}EventListenerCallback(const v8::Argu INC_STATS("DOM.${interfaceName}.${functionName}EventListener()"); RefPtr<EventListener> listener = V8DOMWrapper::getEventListener(args[1], false, ListenerFind${lookupType}); if (listener) { - V8${interfaceName}::toNative(args.Holder())->${functionName}EventListener(toWebCoreAtomicString(args[0]), listener${passRefPtrHandling}, args[2]->BooleanValue()); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithNullCheck>, stringResource, args[0]); + V8${interfaceName}::toNative(args.Holder())->${functionName}EventListener(stringResource, listener${passRefPtrHandling}, args[2]->BooleanValue()); END if ($requiresHiddenDependency) { push(@implContentDecls, <<END); @@ -1745,7 +1754,7 @@ sub GenerateParametersCheck my $nativeValue = "${parameterName}NativeValue"; my $paramType = $parameter->type; $parameterCheckString .= " $paramType $parameterName = 0;\n"; - $parameterCheckString .= " EXCEPTION_BLOCK(double, $nativeValue, args[$paramIndex]->NumberValue());\n"; + $parameterCheckString .= " V8TRYCATCH(double, $nativeValue, args[$paramIndex]->NumberValue());\n"; $parameterCheckString .= " if (!isnan($nativeValue))\n"; $parameterCheckString .= " $parameterName = clampTo<$paramType>($nativeValue);\n"; } elsif ($parameter->type eq "SerializedScriptValue") { @@ -1807,11 +1816,11 @@ sub GenerateParametersCheck $parameterCheckString .= " $parameterName.append(V8${argType}::toNative(v8::Handle<v8::Object>::Cast(args[i])));\n"; $parameterCheckString .= " }\n"; } else { - $parameterCheckString .= " EXCEPTION_BLOCK(Vector<$nativeElementType>, $parameterName, toNativeArguments<$nativeElementType>(args, $paramIndex));\n"; + $parameterCheckString .= " V8TRYCATCH(Vector<$nativeElementType>, $parameterName, toNativeArguments<$nativeElementType>(args, $paramIndex));\n"; } - } elsif ($nativeType =~ /^V8Parameter/) { + } elsif ($nativeType =~ /^V8StringResource/) { my $value = JSValueToNative($parameter, "MAYBE_MISSING_PARAMETER(args, $paramIndex, $parameterDefaultPolicy)", "args.GetIsolate()"); - $parameterCheckString .= " " . ConvertToV8Parameter($parameter, $nativeType, $parameterName, $value) . "\n"; + $parameterCheckString .= " " . ConvertToV8StringResource($parameter, $nativeType, $parameterName, $value) . "\n"; } else { # If the "StrictTypeChecking" extended attribute is present, and the argument's type is an # interface type, then if the incoming value does not implement that interface, a TypeError @@ -1827,7 +1836,7 @@ sub GenerateParametersCheck $parameterCheckString .= " return throwTypeError(0, args.GetIsolate());\n"; } } - $parameterCheckString .= " EXCEPTION_BLOCK($nativeType, $parameterName, " . + $parameterCheckString .= " V8TRYCATCH($nativeType, $parameterName, " . JSValueToNative($parameter, "MAYBE_MISSING_PARAMETER(args, $paramIndex, $parameterDefaultPolicy)", "args.GetIsolate()") . ");\n"; if ($nativeType eq 'Dictionary') { $parameterCheckString .= " if (!$parameterName.isUndefinedOrNull() && !$parameterName.isObject())\n"; @@ -2029,10 +2038,10 @@ END if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, args[0]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, type, args[0]); ${interfaceName}Init eventInit; if (args.Length() >= 2) { - EXCEPTION_BLOCK(Dictionary, options, Dictionary(args[1], args.GetIsolate())); + V8TRYCATCH(Dictionary, options, Dictionary(args[1], args.GetIsolate())); if (!fill${interfaceName}Init(eventInit, options)) return v8Undefined(); } @@ -3654,7 +3663,7 @@ sub GetNativeTypeFromSignature $type = GetNativeType($type, $parameterIndex >= 0 ? 1 : 0); - if ($parameterIndex >= 0 && $type eq "V8Parameter") { + if ($parameterIndex >= 0 && $type eq "V8StringResource") { # FIXME: This implements [TreatNullAs=NullString] and [TreatUndefinedAs=NullString], # but the Web IDL spec requires [TreatNullAs=EmptyString] and [TreatUndefinedAs=EmptyString]. my $mode = ""; @@ -3710,7 +3719,7 @@ sub GetNativeType return $type; } - return "V8Parameter" if ($type eq "DOMString" or $type eq "DOMUserData") and $isParameter; + return "V8StringResource" if ($type eq "DOMString" or $type eq "DOMUserData") and $isParameter; return "int" if $type eq "int"; return "int" if $type eq "short" or $type eq "unsigned short"; return "unsigned" if $type eq "unsigned long"; @@ -4195,7 +4204,7 @@ sub WriteData @headerContent = (); } -sub ConvertToV8Parameter +sub ConvertToV8StringResource { my $signature = shift; my $nativeType = shift; @@ -4203,9 +4212,9 @@ sub ConvertToV8Parameter my $value = shift; my $suffix = shift; - die "Wrong native type passed: $nativeType" unless $nativeType =~ /^V8Parameter/; + die "Wrong native type passed: $nativeType" unless $nativeType =~ /^V8StringResource/; if ($signature->type eq "DOMString") { - my $macro = "STRING_TO_V8PARAMETER_EXCEPTION_BLOCK"; + my $macro = "V8TRYCATCH_FOR_V8STRINGRESOURCE"; $macro .= "_$suffix" if $suffix; return "$macro($nativeType, $variableName, $value);" } else { diff --git a/Source/WebCore/bindings/scripts/test/V8/V8Float64Array.cpp b/Source/WebCore/bindings/scripts/test/V8/V8Float64Array.cpp index 1ba1396a3..ff3f1590c 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8Float64Array.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8Float64Array.cpp @@ -54,7 +54,7 @@ static v8::Handle<v8::Value> fooCallback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); Float64Array* imp = V8Float64Array::toNative(args.Holder()); - EXCEPTION_BLOCK(Float32Array*, array, V8Float32Array::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Float32Array::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(Float32Array*, array, V8Float32Array::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Float32Array::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); return toV8(imp->foo(array), args.Holder(), args.GetIsolate()); } diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestActiveDOMObject.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestActiveDOMObject.cpp index 41b576de9..99ad41f8d 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestActiveDOMObject.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestActiveDOMObject.cpp @@ -54,7 +54,7 @@ static v8::Handle<v8::Value> excitingFunctionCallback(const v8::Arguments& args) TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder()); if (!BindingSecurity::shouldAllowAccessToFrame(BindingState::instance(), imp->frame())) return v8Undefined(); - EXCEPTION_BLOCK(Node*, nextChild, V8Node::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(Node*, nextChild, V8Node::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->excitingFunction(nextChild); return v8Undefined(); } @@ -65,7 +65,7 @@ static v8::Handle<v8::Value> postMessageCallback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, message, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, message, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->postMessage(message); return v8Undefined(); } diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp index fe292e2eb..d26710975 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp @@ -44,7 +44,7 @@ static v8::Handle<v8::Value> anotherFunctionCallback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestCustomNamedGetter* imp = V8TestCustomNamedGetter::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->anotherFunction(str); return v8Undefined(); } diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestEventConstructor.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestEventConstructor.cpp index 26a7fc753..7d687307e 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestEventConstructor.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestEventConstructor.cpp @@ -72,10 +72,10 @@ v8::Handle<v8::Value> V8TestEventConstructor::constructorCallback(const v8::Argu if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, args[0]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, type, args[0]); TestEventConstructorInit eventInit; if (args.Length() >= 2) { - EXCEPTION_BLOCK(Dictionary, options, Dictionary(args[1], args.GetIsolate())); + V8TRYCATCH(Dictionary, options, Dictionary(args[1], args.GetIsolate())); if (!fillTestEventConstructorInit(eventInit, options)) return v8Undefined(); } diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestEventTarget.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestEventTarget.cpp index 42705b4cb..4ceb25e71 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestEventTarget.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestEventTarget.cpp @@ -49,7 +49,7 @@ static v8::Handle<v8::Value> itemCallback(const v8::Arguments& args) TestEventTarget* imp = V8TestEventTarget::toNative(args.Holder()); ExceptionCode ec = 0; { - EXCEPTION_BLOCK(int, index, toUInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, index, toUInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); if (UNLIKELY(index < 0)) { ec = INDEX_SIZE_ERR; goto fail; @@ -65,7 +65,8 @@ static v8::Handle<v8::Value> addEventListenerCallback(const v8::Arguments& args) INC_STATS("DOM.TestEventTarget.addEventListener()"); RefPtr<EventListener> listener = V8DOMWrapper::getEventListener(args[1], false, ListenerFindOrCreate); if (listener) { - V8TestEventTarget::toNative(args.Holder())->addEventListener(toWebCoreAtomicString(args[0]), listener, args[2]->BooleanValue()); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithNullCheck>, stringResource, args[0]); + V8TestEventTarget::toNative(args.Holder())->addEventListener(stringResource, listener, args[2]->BooleanValue()); createHiddenDependency(args.Holder(), args[1], V8TestEventTarget::eventListenerCacheIndex); } return v8Undefined(); @@ -76,7 +77,8 @@ static v8::Handle<v8::Value> removeEventListenerCallback(const v8::Arguments& ar INC_STATS("DOM.TestEventTarget.removeEventListener()"); RefPtr<EventListener> listener = V8DOMWrapper::getEventListener(args[1], false, ListenerFindOnly); if (listener) { - V8TestEventTarget::toNative(args.Holder())->removeEventListener(toWebCoreAtomicString(args[0]), listener.get(), args[2]->BooleanValue()); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithNullCheck>, stringResource, args[0]); + V8TestEventTarget::toNative(args.Holder())->removeEventListener(stringResource, listener.get(), args[2]->BooleanValue()); removeHiddenDependency(args.Holder(), args[1], V8TestEventTarget::eventListenerCacheIndex); } return v8Undefined(); @@ -90,7 +92,7 @@ static v8::Handle<v8::Value> dispatchEventCallback(const v8::Arguments& args) TestEventTarget* imp = V8TestEventTarget::toNative(args.Holder()); ExceptionCode ec = 0; { - EXCEPTION_BLOCK(Event*, evt, V8Event::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Event::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(Event*, evt, V8Event::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Event::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); bool result = imp->dispatchEvent(evt, ec); if (UNLIKELY(ec)) goto fail; diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestInterface.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestInterface.cpp index 5b6b7c047..7be3d4193 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestInterface.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestInterface.cpp @@ -71,7 +71,7 @@ static v8::Handle<v8::Value> supplementalStaticAttrAttrGetter(v8::Local<v8::Stri static void supplementalStaticAttrAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.TestInterface.supplementalStaticAttr._set"); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, v, value); TestSupplemental::setSupplementalStaticAttr(v); return; } @@ -106,7 +106,7 @@ static void supplementalStr2AttrSetter(v8::Local<v8::String> name, v8::Local<v8: { INC_STATS("DOM.TestInterface.supplementalStr2._set"); TestInterface* imp = V8TestInterface::toNative(info.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, v, value); TestSupplemental::setSupplementalStr2(imp, v); return; } @@ -159,8 +159,8 @@ static v8::Handle<v8::Value> supplementalMethod2Callback(const v8::Arguments& ar TestInterface* imp = V8TestInterface::toNative(args.Holder()); ExceptionCode ec = 0; { - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); - EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0); ScriptExecutionContext* scriptContext = getScriptExecutionContext(); RefPtr<TestObj> result = TestSupplemental::supplementalMethod2(scriptContext, imp, strArg, objArg, ec); if (UNLIKELY(ec)) @@ -252,8 +252,8 @@ v8::Handle<v8::Value> V8TestInterface::constructorCallback(const v8::Arguments& return throwNotEnoughArgumentsError(args.GetIsolate()); ExceptionCode ec = 0; - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); ScriptExecutionContext* context = getScriptExecutionContext(); diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp index 9e0e2fc38..0291de76b 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp @@ -45,7 +45,7 @@ static v8::Handle<v8::Value> methodCallback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestMediaQueryListListener* imp = V8TestMediaQueryListListener::toNative(args.Holder()); - EXCEPTION_BLOCK(RefPtr<MediaQueryListListener>, listener, MediaQueryListListener::create(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(RefPtr<MediaQueryListListener>, listener, MediaQueryListListener::create(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->method(listener); return v8Undefined(); } diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestNamedConstructor.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestNamedConstructor.cpp index ab0bb6b62..954cca7cc 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestNamedConstructor.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestNamedConstructor.cpp @@ -61,9 +61,9 @@ static v8::Handle<v8::Value> V8TestNamedConstructorConstructorCallback(const v8: return throwNotEnoughArgumentsError(args.GetIsolate()); ExceptionCode ec = 0; - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str3, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str3, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); RefPtr<TestNamedConstructor> impl = TestNamedConstructor::createForJSConstructor(document, str1, str2, str3, ec); v8::Handle<v8::Object> wrapper = args.Holder(); diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestNode.h b/Source/WebCore/bindings/scripts/test/V8/V8TestNode.h index 9acb1e451..238454d57 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestNode.h +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestNode.h @@ -88,10 +88,11 @@ inline v8::Handle<v8::Value> toV8Fast(TestNode* impl, const v8::AccessorInfo& in // in an isolated world. The fastest way we know how to do that is to check // whether the holder's inline wrapper is the same wrapper we see in the // v8::AccessorInfo. - v8::Handle<v8::Object> wrapper = (holder->wrapper() == info.Holder()) ? impl->wrapper() : DOMDataStore::getNode(impl, info.GetIsolate()); + v8::Handle<v8::Object> holderWrapper = info.Holder(); + v8::Handle<v8::Object> wrapper = (holder->wrapper() == holderWrapper) ? impl->wrapper() : DOMDataStore::getNode(impl, info.GetIsolate()); if (!wrapper.IsEmpty()) return wrapper; - return wrap(impl, info.Holder(), info.GetIsolate()); + return wrap(impl, holderWrapper, info.GetIsolate()); } inline v8::Handle<v8::Value> toV8(PassRefPtr< TestNode > impl, v8::Handle<v8::Object> creationContext = v8::Handle<v8::Object>(), v8::Isolate* isolate = 0) diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestObj.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestObj.cpp index 4c0cd3a0d..b8e6b1555 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestObj.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestObj.cpp @@ -124,7 +124,7 @@ static v8::Handle<v8::Value> staticStringAttrAttrGetter(v8::Local<v8::String> na static void staticStringAttrAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.TestObj.staticStringAttr._set"); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, v, value); TestObj::setStaticStringAttr(v); return; } @@ -220,7 +220,7 @@ static void stringAttrAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value { INC_STATS("DOM.TestObj.stringAttr._set"); TestObj* imp = V8TestObj::toNative(info.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, v, value); imp->setStringAttr(v); return; } @@ -286,7 +286,7 @@ static void reflectedStringAttrAttrSetter(v8::Local<v8::String> name, v8::Local< { INC_STATS("DOM.TestObj.reflectedStringAttr._set"); TestObj* imp = V8TestObj::toNative(info.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<WithNullCheck>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<WithNullCheck>, v, value); imp->setAttribute(WebCore::HTMLNames::reflectedstringattrAttr, v); return; } @@ -350,7 +350,7 @@ static void reflectedURLAttrAttrSetter(v8::Local<v8::String> name, v8::Local<v8: { INC_STATS("DOM.TestObj.reflectedURLAttr._set"); TestObj* imp = V8TestObj::toNative(info.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<WithNullCheck>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<WithNullCheck>, v, value); imp->setAttribute(WebCore::HTMLNames::reflectedurlattrAttr, v); return; } @@ -366,7 +366,7 @@ static void reflectedStringAttrAttrSetter(v8::Local<v8::String> name, v8::Local< { INC_STATS("DOM.TestObj.reflectedStringAttr._set"); TestObj* imp = V8TestObj::toNative(info.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<WithNullCheck>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<WithNullCheck>, v, value); imp->setAttribute(WebCore::HTMLNames::customContentStringAttrAttr, v); return; } @@ -414,7 +414,7 @@ static void reflectedCustomURLAttrAttrSetter(v8::Local<v8::String> name, v8::Loc { INC_STATS("DOM.TestObj.reflectedCustomURLAttr._set"); TestObj* imp = V8TestObj::toNative(info.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<WithNullCheck>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<WithNullCheck>, v, value); imp->setAttribute(WebCore::HTMLNames::customContentURLAttrAttr, v); return; } @@ -489,7 +489,7 @@ static void stringAttrWithGetterExceptionAttrSetter(v8::Local<v8::String> name, { INC_STATS("DOM.TestObj.stringAttrWithGetterException._set"); TestObj* imp = V8TestObj::toNative(info.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, v, value); imp->setStringAttrWithGetterException(v); return; } @@ -505,7 +505,7 @@ static void stringAttrWithSetterExceptionAttrSetter(v8::Local<v8::String> name, { INC_STATS("DOM.TestObj.stringAttrWithSetterException._set"); TestObj* imp = V8TestObj::toNative(info.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(V8Parameter<>, v, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, v, value); ExceptionCode ec = 0; imp->setStringAttrWithSetterException(v, ec); if (UNLIKELY(ec)) @@ -1056,9 +1056,9 @@ static v8::Handle<v8::Value> voidMethodWithArgsCallback(const v8::Arguments& arg if (args.Length() < 3) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); - EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); + V8TRYCATCH(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); imp->voidMethodWithArgs(longArg, strArg, objArg); return v8Undefined(); } @@ -1076,9 +1076,9 @@ static v8::Handle<v8::Value> longMethodWithArgsCallback(const v8::Arguments& arg if (args.Length() < 3) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); - EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); + V8TRYCATCH(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); return v8Integer(imp->longMethodWithArgs(longArg, strArg, objArg), args.GetIsolate()); } @@ -1096,9 +1096,9 @@ static v8::Handle<v8::Value> objMethodWithArgsCallback(const v8::Arguments& args if (args.Length() < 3) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); - EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); + V8TRYCATCH(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); return toV8(imp->objMethodWithArgs(longArg, strArg, objArg), args.Holder(), args.GetIsolate()); } @@ -1108,7 +1108,7 @@ static v8::Handle<v8::Value> methodWithSequenceArgCallback(const v8::Arguments& if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(Vector<ScriptProfile>, sequenceArg, toNativeArray<ScriptProfile>(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(Vector<ScriptProfile>, sequenceArg, toNativeArray<ScriptProfile>(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->methodWithSequenceArg(sequenceArg); return v8Undefined(); } @@ -1119,7 +1119,7 @@ static v8::Handle<v8::Value> methodReturningSequenceCallback(const v8::Arguments if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); return v8Array(imp->methodReturningSequence(longArg), args.GetIsolate()); } @@ -1131,8 +1131,8 @@ static v8::Handle<v8::Value> methodThatRequiresAllArgsAndThrowsCallback(const v8 TestObj* imp = V8TestObj::toNative(args.Holder()); ExceptionCode ec = 0; { - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); - EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0); RefPtr<TestObj> result = imp->methodThatRequiresAllArgsAndThrows(strArg, objArg, ec); if (UNLIKELY(ec)) goto fail; @@ -1162,7 +1162,7 @@ static v8::Handle<v8::Value> idbKeyCallback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(RefPtr<IDBKey>, key, createIDBKeyFromValue(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(RefPtr<IDBKey>, key, createIDBKeyFromValue(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->idbKey(key.get()); return v8Undefined(); } @@ -1173,10 +1173,10 @@ static v8::Handle<v8::Value> optionsObjectCallback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(Dictionary, oo, Dictionary(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined), args.GetIsolate())); + V8TRYCATCH(Dictionary, oo, Dictionary(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined), args.GetIsolate())); if (!oo.isUndefinedOrNull() && !oo.isObject()) return throwTypeError("Not an object.", args.GetIsolate()); - EXCEPTION_BLOCK(Dictionary, ooo, Dictionary(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined), args.GetIsolate())); + V8TRYCATCH(Dictionary, ooo, Dictionary(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined), args.GetIsolate())); if (!ooo.isUndefinedOrNull() && !ooo.isObject()) return throwTypeError("Not an object.", args.GetIsolate()); imp->optionsObject(oo, ooo); @@ -1203,7 +1203,8 @@ static v8::Handle<v8::Value> addEventListenerCallback(const v8::Arguments& args) INC_STATS("DOM.TestObj.addEventListener()"); RefPtr<EventListener> listener = V8DOMWrapper::getEventListener(args[1], false, ListenerFindOrCreate); if (listener) { - V8TestObj::toNative(args.Holder())->addEventListener(toWebCoreAtomicString(args[0]), listener, args[2]->BooleanValue()); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithNullCheck>, stringResource, args[0]); + V8TestObj::toNative(args.Holder())->addEventListener(stringResource, listener, args[2]->BooleanValue()); createHiddenDependency(args.Holder(), args[1], V8TestObj::eventListenerCacheIndex); } return v8Undefined(); @@ -1214,7 +1215,8 @@ static v8::Handle<v8::Value> removeEventListenerCallback(const v8::Arguments& ar INC_STATS("DOM.TestObj.removeEventListener()"); RefPtr<EventListener> listener = V8DOMWrapper::getEventListener(args[1], false, ListenerFindOnly); if (listener) { - V8TestObj::toNative(args.Holder())->removeEventListener(toWebCoreAtomicString(args[0]), listener.get(), args[2]->BooleanValue()); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithNullCheck>, stringResource, args[0]); + V8TestObj::toNative(args.Holder())->removeEventListener(stringResource, listener.get(), args[2]->BooleanValue()); removeHiddenDependency(args.Holder(), args[1], V8TestObj::eventListenerCacheIndex); } return v8Undefined(); @@ -1389,7 +1391,7 @@ static v8::Handle<v8::Value> methodWithOptionalArgCallback(const v8::Arguments& imp->methodWithOptionalArg(); return v8Undefined(); } - EXCEPTION_BLOCK(int, opt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, opt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->methodWithOptionalArg(opt); return v8Undefined(); } @@ -1400,12 +1402,12 @@ static v8::Handle<v8::Value> methodWithNonOptionalArgAndOptionalArgCallback(cons if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); if (args.Length() <= 1) { imp->methodWithNonOptionalArgAndOptionalArg(nonOpt); return v8Undefined(); } - EXCEPTION_BLOCK(int, opt, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))); + V8TRYCATCH(int, opt, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))); imp->methodWithNonOptionalArgAndOptionalArg(nonOpt, opt); return v8Undefined(); } @@ -1416,17 +1418,17 @@ static v8::Handle<v8::Value> methodWithNonOptionalArgAndTwoOptionalArgsCallback( if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); if (args.Length() <= 1) { imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt); return v8Undefined(); } - EXCEPTION_BLOCK(int, opt1, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))); + V8TRYCATCH(int, opt1, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))); if (args.Length() <= 2) { imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1); return v8Undefined(); } - EXCEPTION_BLOCK(int, opt2, toInt32(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))); + V8TRYCATCH(int, opt2, toInt32(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))); imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1, opt2); return v8Undefined(); } @@ -1439,7 +1441,7 @@ static v8::Handle<v8::Value> methodWithOptionalStringCallback(const v8::Argument imp->methodWithOptionalString(); return v8Undefined(); } - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->methodWithOptionalString(str); return v8Undefined(); } @@ -1448,7 +1450,7 @@ static v8::Handle<v8::Value> methodWithOptionalStringIsUndefinedCallback(const v { INC_STATS("DOM.TestObj.methodWithOptionalStringIsUndefined"); TestObj* imp = V8TestObj::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->methodWithOptionalStringIsUndefined(str); return v8Undefined(); } @@ -1457,7 +1459,7 @@ static v8::Handle<v8::Value> methodWithOptionalStringIsNullStringCallback(const { INC_STATS("DOM.TestObj.methodWithOptionalStringIsNullString"); TestObj* imp = V8TestObj::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsNullString)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsNullString)); imp->methodWithOptionalStringIsNullString(str); return v8Undefined(); } @@ -1481,7 +1483,7 @@ static v8::Handle<v8::Value> methodWithNonCallbackArgAndCallbackArgCallback(cons if (args.Length() < 2) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, nonCallback, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, nonCallback, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); if (args.Length() <= 1 || !args[1]->IsFunction()) return throwTypeError(0, args.GetIsolate()); RefPtr<TestCallback> callback = V8TestCallback::create(args[1], getScriptExecutionContext()); @@ -1544,8 +1546,8 @@ static v8::Handle<v8::Value> overloadedMethod1Callback(const v8::Arguments& args if (args.Length() < 2) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); + V8TRYCATCH(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); imp->overloadedMethod(objArg, strArg); return v8Undefined(); } @@ -1556,12 +1558,12 @@ static v8::Handle<v8::Value> overloadedMethod2Callback(const v8::Arguments& args if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); if (args.Length() <= 1) { imp->overloadedMethod(objArg); return v8Undefined(); } - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))); imp->overloadedMethod(objArg, longArg); return v8Undefined(); } @@ -1572,7 +1574,7 @@ static v8::Handle<v8::Value> overloadedMethod3Callback(const v8::Arguments& args if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->overloadedMethod(strArg); return v8Undefined(); } @@ -1583,7 +1585,7 @@ static v8::Handle<v8::Value> overloadedMethod4Callback(const v8::Arguments& args if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(longArg); return v8Undefined(); } @@ -1607,7 +1609,7 @@ static v8::Handle<v8::Value> overloadedMethod6Callback(const v8::Arguments& args if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(RefPtr<DOMStringList>, listArg, toDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(RefPtr<DOMStringList>, listArg, toDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(listArg); return v8Undefined(); } @@ -1618,7 +1620,7 @@ static v8::Handle<v8::Value> overloadedMethod7Callback(const v8::Arguments& args if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(RefPtr<DOMStringList>, arrayArg, toDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(RefPtr<DOMStringList>, arrayArg, toDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(arrayArg); return v8Undefined(); } @@ -1629,7 +1631,7 @@ static v8::Handle<v8::Value> overloadedMethod8Callback(const v8::Arguments& args if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->overloadedMethod(objArg); return v8Undefined(); } @@ -1640,7 +1642,7 @@ static v8::Handle<v8::Value> overloadedMethod9Callback(const v8::Arguments& args if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(RefPtr<DOMStringList>, arrayArg, toDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(RefPtr<DOMStringList>, arrayArg, toDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(arrayArg); return v8Undefined(); } @@ -1651,7 +1653,7 @@ static v8::Handle<v8::Value> overloadedMethod10Callback(const v8::Arguments& arg if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(Vector<unsigned long>, arrayArg, toNativeArray<unsigned long>(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(Vector<unsigned long>, arrayArg, toNativeArray<unsigned long>(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(arrayArg); return v8Undefined(); } @@ -1662,7 +1664,7 @@ static v8::Handle<v8::Value> overloadedMethod11Callback(const v8::Arguments& arg if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->overloadedMethod(strArg); return v8Undefined(); } @@ -1710,7 +1712,7 @@ static v8::Handle<v8::Value> classMethodWithOptionalCallback(const v8::Arguments if (args.Length() <= 0) { return v8Integer(TestObj::classMethodWithOptional(), args.GetIsolate()); } - EXCEPTION_BLOCK(int, arg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, arg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); return v8Integer(TestObj::classMethodWithOptional(arg), args.GetIsolate()); } @@ -1721,7 +1723,7 @@ static v8::Handle<v8::Value> overloadedMethod11Callback(const v8::Arguments& arg INC_STATS("DOM.TestObj.overloadedMethod11"); if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); - EXCEPTION_BLOCK(int, arg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, arg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); TestObj::overloadedMethod1(arg); return v8Undefined(); } @@ -1735,7 +1737,7 @@ static v8::Handle<v8::Value> overloadedMethod12Callback(const v8::Arguments& arg INC_STATS("DOM.TestObj.overloadedMethod12"); if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, type, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); TestObj::overloadedMethod1(type); return v8Undefined(); } @@ -1765,11 +1767,11 @@ static v8::Handle<v8::Value> classMethodWithClampCallback(const v8::Arguments& a return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); unsigned short objArgsShort = 0; - EXCEPTION_BLOCK(double, objArgsShortNativeValue, args[0]->NumberValue()); + V8TRYCATCH(double, objArgsShortNativeValue, args[0]->NumberValue()); if (!isnan(objArgsShortNativeValue)) objArgsShort = clampTo<unsigned short>(objArgsShortNativeValue); unsigned long objArgsLong = 0; - EXCEPTION_BLOCK(double, objArgsLongNativeValue, args[1]->NumberValue()); + V8TRYCATCH(double, objArgsLongNativeValue, args[1]->NumberValue()); if (!isnan(objArgsLongNativeValue)) objArgsLong = clampTo<unsigned long>(objArgsLongNativeValue); imp->classMethodWithClamp(objArgsShort, objArgsLong); @@ -1782,7 +1784,7 @@ static v8::Handle<v8::Value> enabledAtRuntimeMethod1Callback(const v8::Arguments if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->enabledAtRuntimeMethod1(longArg); return v8Undefined(); } @@ -1793,7 +1795,7 @@ static v8::Handle<v8::Value> enabledAtRuntimeMethod2Callback(const v8::Arguments if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->enabledAtRuntimeMethod2(longArg); return v8Undefined(); } @@ -1804,7 +1806,7 @@ static v8::Handle<v8::Value> enabledPerContextMethod1Callback(const v8::Argument if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->enabledPerContextMethod1(longArg); return v8Undefined(); } @@ -1815,7 +1817,7 @@ static v8::Handle<v8::Value> enabledPerContextMethod2Callback(const v8::Argument if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(int, longArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->enabledPerContextMethod2(longArg); return v8Undefined(); } @@ -1828,7 +1830,7 @@ static v8::Handle<v8::Value> stringArrayFunctionCallback(const v8::Arguments& ar TestObj* imp = V8TestObj::toNative(args.Holder()); ExceptionCode ec = 0; { - EXCEPTION_BLOCK(RefPtr<DOMStringList>, values, toDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); + V8TRYCATCH(RefPtr<DOMStringList>, values, toDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); RefPtr<DOMStringList> result = imp->stringArrayFunction(values, ec); if (UNLIKELY(ec)) goto fail; @@ -1861,7 +1863,7 @@ static v8::Handle<v8::Value> convert1Callback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(a*, value, V8a::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8a::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(a*, value, V8a::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8a::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert1(value); return v8Undefined(); } @@ -1872,7 +1874,7 @@ static v8::Handle<v8::Value> convert2Callback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(b*, value, V8b::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8b::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(b*, value, V8b::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8b::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert2(value); return v8Undefined(); } @@ -1883,7 +1885,7 @@ static v8::Handle<v8::Value> convert4Callback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(d*, value, V8d::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8d::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(d*, value, V8d::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8d::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert4(value); return v8Undefined(); } @@ -1894,7 +1896,7 @@ static v8::Handle<v8::Value> convert5Callback(const v8::Arguments& args) if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(e*, value, V8e::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8e::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(e*, value, V8e::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8e::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert5(value); return v8Undefined(); } @@ -1929,9 +1931,9 @@ static v8::Handle<v8::Value> strictFunctionCallback(const v8::Arguments& args) TestObj* imp = V8TestObj::toNative(args.Holder()); ExceptionCode ec = 0; { - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); - EXCEPTION_BLOCK(float, a, static_cast<float>(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)->NumberValue())); - EXCEPTION_BLOCK(int, b, toInt32(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH(float, a, static_cast<float>(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)->NumberValue())); + V8TRYCATCH(int, b, toInt32(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))); RefPtr<bool> result = imp->strictFunction(str, a, b, ec); if (UNLIKELY(ec)) goto fail; @@ -1947,8 +1949,8 @@ static v8::Handle<v8::Value> variadicStringMethodCallback(const v8::Arguments& a if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, head, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); - EXCEPTION_BLOCK(Vector<String>, tail, toNativeArguments<String>(args, 1)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, head, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH(Vector<String>, tail, toNativeArguments<String>(args, 1)); imp->variadicStringMethod(head, tail); return v8Undefined(); } @@ -1959,8 +1961,8 @@ static v8::Handle<v8::Value> variadicDoubleMethodCallback(const v8::Arguments& a if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(double, head, static_cast<double>(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)->NumberValue())); - EXCEPTION_BLOCK(Vector<double>, tail, toNativeArguments<double>(args, 1)); + V8TRYCATCH(double, head, static_cast<double>(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)->NumberValue())); + V8TRYCATCH(Vector<double>, tail, toNativeArguments<double>(args, 1)); imp->variadicDoubleMethod(head, tail); return v8Undefined(); } @@ -1971,7 +1973,7 @@ static v8::Handle<v8::Value> variadicNodeMethodCallback(const v8::Arguments& arg if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); - EXCEPTION_BLOCK(Node*, head, V8Node::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(Node*, head, V8Node::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); Vector<RefPtr<Node> > tail; for (int i = 1; i < args.Length(); ++i) { if (!V8Node::HasInstance(args[i])) diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestOverloadedConstructors.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestOverloadedConstructors.cpp index b0fed9cd7..0c78f772f 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestOverloadedConstructors.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestOverloadedConstructors.cpp @@ -49,7 +49,7 @@ v8::Handle<v8::Value> V8TestOverloadedConstructors::constructor1Callback(const v { INC_STATS("DOM.TestOverloadedConstructors.Constructor1"); - EXCEPTION_BLOCK(ArrayBuffer*, arrayBuffer, V8ArrayBuffer::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8ArrayBuffer::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(ArrayBuffer*, arrayBuffer, V8ArrayBuffer::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8ArrayBuffer::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); RefPtr<TestOverloadedConstructors> impl = TestOverloadedConstructors::create(arrayBuffer); v8::Handle<v8::Object> wrapper = args.Holder(); @@ -62,7 +62,7 @@ v8::Handle<v8::Value> V8TestOverloadedConstructors::constructor2Callback(const v { INC_STATS("DOM.TestOverloadedConstructors.Constructor2"); - EXCEPTION_BLOCK(ArrayBufferView*, arrayBufferView, V8ArrayBufferView::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8ArrayBufferView::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(ArrayBufferView*, arrayBufferView, V8ArrayBufferView::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8ArrayBufferView::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); RefPtr<TestOverloadedConstructors> impl = TestOverloadedConstructors::create(arrayBufferView); v8::Handle<v8::Object> wrapper = args.Holder(); @@ -75,7 +75,7 @@ v8::Handle<v8::Value> V8TestOverloadedConstructors::constructor3Callback(const v { INC_STATS("DOM.TestOverloadedConstructors.Constructor3"); - EXCEPTION_BLOCK(Blob*, blob, V8Blob::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Blob::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); + V8TRYCATCH(Blob*, blob, V8Blob::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Blob::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); RefPtr<TestOverloadedConstructors> impl = TestOverloadedConstructors::create(blob); v8::Handle<v8::Object> wrapper = args.Holder(); @@ -88,7 +88,7 @@ v8::Handle<v8::Value> V8TestOverloadedConstructors::constructor4Callback(const v { INC_STATS("DOM.TestOverloadedConstructors.Constructor4"); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, string, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, string, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); RefPtr<TestOverloadedConstructors> impl = TestOverloadedConstructors::create(string); v8::Handle<v8::Object> wrapper = args.Holder(); diff --git a/Source/WebCore/bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp b/Source/WebCore/bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp index 2532f1e68..59686d709 100644 --- a/Source/WebCore/bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp +++ b/Source/WebCore/bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp @@ -218,7 +218,7 @@ v8::Handle<v8::Value> V8TestSerializedScriptValueInterface::constructorCallback( return args.Holder(); if (args.Length() < 2) return throwNotEnoughArgumentsError(args.GetIsolate()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, hello, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, hello, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); MessagePortArray messagePortArrayTransferList; ArrayBufferArray arrayBufferArrayTransferList; if (args.Length() > 2) { diff --git a/Source/WebCore/bindings/v8/DOMWrapperWorld.cpp b/Source/WebCore/bindings/v8/DOMWrapperWorld.cpp index 0e9433b95..91470a745 100644 --- a/Source/WebCore/bindings/v8/DOMWrapperWorld.cpp +++ b/Source/WebCore/bindings/v8/DOMWrapperWorld.cpp @@ -137,6 +137,7 @@ static int temporaryWorldId = DOMWrapperWorld::uninitializedWorldId-1; PassRefPtr<DOMWrapperWorld> DOMWrapperWorld::ensureIsolatedWorld(int worldId, int extensionGroup) { ASSERT(worldId != mainWorldId); + ASSERT(worldId >= uninitializedWorldId); WorldMap& map = isolatedWorldMap(); if (worldId == uninitializedWorldId) diff --git a/Source/WebCore/bindings/v8/DOMWrapperWorld.h b/Source/WebCore/bindings/v8/DOMWrapperWorld.h index 0ed826c19..d625fe76c 100644 --- a/Source/WebCore/bindings/v8/DOMWrapperWorld.h +++ b/Source/WebCore/bindings/v8/DOMWrapperWorld.h @@ -96,6 +96,8 @@ public: bool isMainWorld() const { return m_worldId == mainWorldId; } bool isIsolatedWorld() const { return isIsolatedWorldId(m_worldId); } + bool createdFromUnitializedWorld() const { return m_worldId < uninitializedWorldId; } + int worldId() const { return m_worldId; } int extensionGroup() const { return m_extensionGroup; } DOMDataStore* isolatedWorldDOMDataStore() const diff --git a/Source/WebCore/bindings/v8/NPV8Object.cpp b/Source/WebCore/bindings/v8/NPV8Object.cpp index e941e631f..b27dcb2ab 100644 --- a/Source/WebCore/bindings/v8/NPV8Object.cpp +++ b/Source/WebCore/bindings/v8/NPV8Object.cpp @@ -80,16 +80,17 @@ static void freeV8NPObject(NPObject* npObject) int v8ObjectHash = v8NpObject->v8Object->GetIdentityHash(); ASSERT(v8ObjectHash); V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash); - ASSERT(iter != v8NPObjectMap->end()); - V8NPObjectVector& objects = iter->value; - for (size_t index = 0; index < objects.size(); ++index) { - if (objects.at(index) == v8NpObject) { - objects.remove(index); - break; + if (iter != v8NPObjectMap->end()) { + V8NPObjectVector& objects = iter->value; + for (size_t index = 0; index < objects.size(); ++index) { + if (objects.at(index) == v8NpObject) { + objects.remove(index); + break; + } } + if (objects.isEmpty()) + v8NPObjectMap->remove(v8ObjectHash); } - if (objects.isEmpty()) - v8NPObjectMap->remove(v8ObjectHash); } v8NpObject->v8Object.Dispose(); v8NpObject->v8Object.Clear(); @@ -144,29 +145,33 @@ NPObject* npCreateV8ScriptObject(NPP npp, v8::Handle<v8::Object> object, DOMWind } } - int v8ObjectHash = object->GetIdentityHash(); - ASSERT(v8ObjectHash); - V8NPObjectMap* v8NPObjectMap = V8PerContextData::from(object->CreationContext())->v8NPObjectMap(); - V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash); - if (iter != v8NPObjectMap->end()) { - V8NPObjectVector& objects = iter->value; - for (size_t index = 0; index < objects.size(); ++index) { - V8NPObject* v8npObject = objects.at(index); - if (v8npObject->rootObject == root) { - ASSERT(v8npObject->v8Object == object); - _NPN_RetainObject(&v8npObject->object); - return reinterpret_cast<NPObject*>(v8npObject); + V8NPObjectVector* objectVector = 0; + if (V8PerContextData* perContextData = V8PerContextData::from(object->CreationContext())) { + int v8ObjectHash = object->GetIdentityHash(); + ASSERT(v8ObjectHash); + V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap(); + V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash); + if (iter != v8NPObjectMap->end()) { + V8NPObjectVector& objects = iter->value; + for (size_t index = 0; index < objects.size(); ++index) { + V8NPObject* v8npObject = objects.at(index); + if (v8npObject->rootObject == root) { + ASSERT(v8npObject->v8Object == object); + _NPN_RetainObject(&v8npObject->object); + return reinterpret_cast<NPObject*>(v8npObject); + } } + } else { + iter = v8NPObjectMap->set(v8ObjectHash, V8NPObjectVector()).iterator; + objectVector = &iter->value; } - } else { - iter = v8NPObjectMap->set(v8ObjectHash, V8NPObjectVector()).iterator; } - V8NPObject* v8npObject = reinterpret_cast<V8NPObject*>(_NPN_CreateObject(npp, &V8NPObjectClass)); v8npObject->v8Object = v8::Persistent<v8::Object>::New(object); v8npObject->rootObject = root; - iter->value.append(v8npObject); + if (objectVector) + objectVector->append(v8npObject); return reinterpret_cast<NPObject*>(v8npObject); } diff --git a/Source/WebCore/bindings/v8/ScheduledAction.cpp b/Source/WebCore/bindings/v8/ScheduledAction.cpp index 81c586e51..4271f9ee6 100644 --- a/Source/WebCore/bindings/v8/ScheduledAction.cpp +++ b/Source/WebCore/bindings/v8/ScheduledAction.cpp @@ -45,7 +45,6 @@ #include "V8GCController.h" #include "V8RecursionScope.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" #include "WorkerThread.h" namespace WebCore { diff --git a/Source/WebCore/bindings/v8/ScriptController.cpp b/Source/WebCore/bindings/v8/ScriptController.cpp index 5adf3a090..716c26304 100644 --- a/Source/WebCore/bindings/v8/ScriptController.cpp +++ b/Source/WebCore/bindings/v8/ScriptController.cpp @@ -47,9 +47,7 @@ #include "NPV8Object.h" #include "Node.h" #include "NotImplemented.h" -#include "npruntime_impl.h" -#include "npruntime_priv.h" -#include "PlatformSupport.h" +#include "PluginViewBase.h" #include "ScriptCallStack.h" #include "ScriptCallStackFactory.h" #include "ScriptRunner.h" @@ -67,6 +65,8 @@ #include "V8NPObject.h" #include "V8RecursionScope.h" #include "Widget.h" +#include "npruntime_impl.h" +#include "npruntime_priv.h" #include <wtf/CurrentTime.h> #include <wtf/StdLibExtras.h> #include <wtf/StringExtras.h> @@ -434,22 +434,38 @@ void ScriptController::finishedWithEvent(Event* event) { } +static inline v8::Local<v8::Context> contextForWorld(ScriptController* scriptController, DOMWrapperWorld* world) +{ + return v8::Local<v8::Context>::New(scriptController->windowShell(world)->context()); +} + v8::Local<v8::Context> ScriptController::currentWorldContext() { - if (v8::Context::InContext()) { - v8::Handle<v8::Context> context = v8::Context::GetEntered(); - if (DOMWrapperWorld::isolated(context)) { - if (m_frame == toFrameIfNotDetached(context)) - return v8::Local<v8::Context>::New(context); - return v8::Local<v8::Context>(); - } - } - return v8::Local<v8::Context>::New(windowShell(mainThreadNormalWorld())->context()); + if (!v8::Context::InContext()) + return contextForWorld(this, mainThreadNormalWorld()); + + v8::Handle<v8::Context> context = v8::Context::GetEntered(); + DOMWrapperWorld* isolatedWorld = DOMWrapperWorld::isolated(context); + if (!isolatedWorld) + return contextForWorld(this, mainThreadNormalWorld()); + + Frame* frame = toFrameIfNotDetached(context); + if (!m_frame) + return v8::Local<v8::Context>(); + + if (m_frame == frame) + return v8::Local<v8::Context>::New(context); + + // FIXME: Need to handle weak isolated worlds correctly. + if (isolatedWorld->createdFromUnitializedWorld()) + return v8::Local<v8::Context>(); + + return contextForWorld(this, isolatedWorld); } v8::Local<v8::Context> ScriptController::mainWorldContext() { - return v8::Local<v8::Context>::New(windowShell(mainThreadNormalWorld())->context()); + return contextForWorld(this, mainThreadNormalWorld()); } v8::Local<v8::Context> ScriptController::mainWorldContext(Frame* frame) @@ -457,7 +473,7 @@ v8::Local<v8::Context> ScriptController::mainWorldContext(Frame* frame) if (!frame) return v8::Local<v8::Context>(); - return frame->script()->mainWorldContext(); + return contextForWorld(frame->script(), mainThreadNormalWorld()); } // Create a V8 object with an interceptor of NPObjectPropertyGetter. @@ -505,10 +521,10 @@ PassScriptInstance ScriptController::createScriptInstanceForWidget(Widget* widge { ASSERT(widget); - if (widget->isFrameView()) + if (!widget->isPluginViewBase()) return 0; - NPObject* npObject = PlatformSupport::pluginScriptableObject(widget); + NPObject* npObject = static_cast<PluginViewBase*>(widget)->scriptableObject(); if (!npObject) return 0; diff --git a/Source/WebCore/bindings/v8/ScriptState.cpp b/Source/WebCore/bindings/v8/ScriptState.cpp index 8a0580bcd..722232a33 100644 --- a/Source/WebCore/bindings/v8/ScriptState.cpp +++ b/Source/WebCore/bindings/v8/ScriptState.cpp @@ -39,7 +39,6 @@ #include "V8HiddenPropertyName.h" #include "V8WorkerContext.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" #include "WorkerScriptController.h" #include <v8.h> #include <wtf/Assertions.h> @@ -142,13 +141,12 @@ ScriptState* scriptStateFromPage(DOMWrapperWorld*, Page* page) #if ENABLE(WORKERS) ScriptState* scriptStateFromWorkerContext(WorkerContext* workerContext) { - WorkerContextExecutionProxy* proxy = workerContext->script()->proxy(); - if (!proxy) + WorkerScriptController* script = workerContext->script(); + if (!script) return 0; v8::HandleScope handleScope; - v8::Local<v8::Context> context = proxy->context(); - return ScriptState::forContext(context); + return ScriptState::forContext(script->context()); } #endif diff --git a/Source/WebCore/bindings/v8/V8AbstractEventListener.cpp b/Source/WebCore/bindings/v8/V8AbstractEventListener.cpp index 6edd4bff5..0188d063b 100644 --- a/Source/WebCore/bindings/v8/V8AbstractEventListener.cpp +++ b/Source/WebCore/bindings/v8/V8AbstractEventListener.cpp @@ -43,7 +43,6 @@ #include "V8HiddenPropertyName.h" #include "V8Utilities.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" namespace WebCore { diff --git a/Source/WebCore/bindings/v8/V8Binding.cpp b/Source/WebCore/bindings/v8/V8Binding.cpp index e50d464f0..0a11ff238 100644 --- a/Source/WebCore/bindings/v8/V8Binding.cpp +++ b/Source/WebCore/bindings/v8/V8Binding.cpp @@ -47,7 +47,7 @@ #include "V8XPathNSResolver.h" #include "WebCoreMemoryInstrumentation.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" +#include "WorkerScriptController.h" #include "WorldContextHandle.h" #include "XPathNSResolver.h" #include <wtf/MathExtras.h> @@ -100,7 +100,7 @@ static String v8NonStringValueToWebCoreString(v8::Handle<v8::Value> object) { ASSERT(!object->IsString()); if (object->IsInt32()) - return int32ToWebCoreString(object->Int32Value()); + return int32ToWebCoreString<String>(object->Int32Value()); v8::TryCatch block; v8::Handle<v8::String> v8String = object->ToString(); @@ -311,8 +311,8 @@ v8::Local<v8::Context> toV8Context(ScriptExecutionContext* context, const WorldC return worldContext.adjustedContext(frame->script()); #if ENABLE(WORKERS) } else if (context->isWorkerContext()) { - if (WorkerContextExecutionProxy* proxy = static_cast<WorkerContext*>(context)->script()->proxy()) - return proxy->context(); + if (WorkerScriptController* script = static_cast<WorkerContext*>(context)->script()) + return script->context(); #endif } return v8::Local<v8::Context>(); diff --git a/Source/WebCore/bindings/v8/V8Binding.h b/Source/WebCore/bindings/v8/V8Binding.h index eaba5d074..5d2e06090 100644 --- a/Source/WebCore/bindings/v8/V8Binding.h +++ b/Source/WebCore/bindings/v8/V8Binding.h @@ -248,14 +248,14 @@ namespace WebCore { v8::Local<v8::Value> v8Value(v8::Local<v8::Value>::New(value)); v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(v8Value); - EXCEPTION_BLOCK(v8::Local<v8::Value>, lengthValue, object->Get(v8::String::New("length"))); + V8TRYCATCH(v8::Local<v8::Value>, lengthValue, object->Get(v8::String::New("length"))); if (lengthValue->IsUndefined() || lengthValue->IsNull()) { throwTypeError(); return v8Undefined(); } - EXCEPTION_BLOCK(uint32_t, sequenceLength, lengthValue->Int32Value()); + V8TRYCATCH(uint32_t, sequenceLength, lengthValue->Int32Value()); length = sequenceLength; return v8Value; diff --git a/Source/WebCore/bindings/v8/V8BindingMacros.h b/Source/WebCore/bindings/v8/V8BindingMacros.h index f4cab8b85..6ca58c3f7 100644 --- a/Source/WebCore/bindings/v8/V8BindingMacros.h +++ b/Source/WebCore/bindings/v8/V8BindingMacros.h @@ -44,7 +44,7 @@ enum ParameterDefaultPolicy { DefaultIsNullString }; -#define EXCEPTION_BLOCK(type, var, value) \ +#define V8TRYCATCH(type, var, value) \ type var; \ { \ v8::TryCatch block; \ @@ -53,12 +53,12 @@ enum ParameterDefaultPolicy { return block.ReThrow(); \ } -#define STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(type, var, value) \ +#define V8TRYCATCH_FOR_V8STRINGRESOURCE(type, var, value) \ type var(value); \ if (!var.prepare()) \ return v8::Undefined(); -#define STRING_TO_V8PARAMETER_EXCEPTION_BLOCK_VOID(type, var, value) \ +#define V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(type, var, value) \ type var(value); \ if (!var.prepare()) \ return; diff --git a/Source/WebCore/bindings/v8/V8DOMWrapper.cpp b/Source/WebCore/bindings/v8/V8DOMWrapper.cpp index f6efc8817..0251abc2f 100644 --- a/Source/WebCore/bindings/v8/V8DOMWrapper.cpp +++ b/Source/WebCore/bindings/v8/V8DOMWrapper.cpp @@ -56,7 +56,6 @@ #include "V8WorkerContextEventListener.h" #include "WebGLContextAttributes.h" #include "WebGLUniformLocation.h" -#include "WorkerContextExecutionProxy.h" #include "WrapperTypeInfo.h" #include <algorithm> #include <utility> diff --git a/Source/WebCore/bindings/v8/V8StringResource.cpp b/Source/WebCore/bindings/v8/V8StringResource.cpp index 371391d2b..df9c8a0c3 100644 --- a/Source/WebCore/bindings/v8/V8StringResource.cpp +++ b/Source/WebCore/bindings/v8/V8StringResource.cpp @@ -190,6 +190,8 @@ String int32ToWebCoreStringFast(int value) // Most numbers used are <= 100. Even if they aren't used there's very little cost in using the space. const int kLowNumbers = 100; + + // FIXME: Store lowNumbers in V8PerIsolateData so that workers can also use them. DEFINE_STATIC_LOCAL(Vector<AtomicString>, lowNumbers, (kLowNumbers + 1)); String webCoreString; if (0 <= value && value <= kLowNumbers) { @@ -204,7 +206,7 @@ String int32ToWebCoreStringFast(int value) return webCoreString; } -String int32ToWebCoreString(int value) +template<> String int32ToWebCoreString<String>(int value) { // If we are on the main thread (this should always true for non-workers), call the faster one. if (isMainThread()) @@ -212,4 +214,9 @@ String int32ToWebCoreString(int value) return String::number(value); } +template<> AtomicString int32ToWebCoreString<AtomicString>(int value) +{ + return AtomicString(int32ToWebCoreString<String>(value)); +} + } // namespace WebCore diff --git a/Source/WebCore/bindings/v8/V8StringResource.h b/Source/WebCore/bindings/v8/V8StringResource.h index a863ac349..926f185ee 100644 --- a/Source/WebCore/bindings/v8/V8StringResource.h +++ b/Source/WebCore/bindings/v8/V8StringResource.h @@ -142,23 +142,23 @@ enum ExternalMode { template <typename StringType> StringType v8StringToWebCoreString(v8::Handle<v8::String>, ExternalMode); -String int32ToWebCoreString(int value); +template <typename StringType> +StringType int32ToWebCoreString(int value); -// V8Parameter is an adapter class that converts V8 values to Strings +// V8StringResource is an adapter class that converts V8 values to Strings // or AtomicStrings as appropriate, using multiple typecast operators. -enum V8ParameterMode { +enum V8StringResourceMode { DefaultMode, WithNullCheck, WithUndefinedOrNullCheck }; -template <V8ParameterMode Mode = DefaultMode> -class V8Parameter { +template <V8StringResourceMode Mode = DefaultMode> +class V8StringResource { public: - V8Parameter(v8::Local<v8::Value> object) + V8StringResource(v8::Local<v8::Value> object) : m_v8Object(object) , m_mode(Externalize) - , m_string() { } @@ -169,17 +169,10 @@ public: private: bool prepareBase() { - if (m_v8Object.IsEmpty()) - return true; - - if (LIKELY(m_v8Object->IsString())) + ASSERT(!m_v8Object.IsEmpty()); + if (LIKELY(m_v8Object->IsString() || m_v8Object->IsInt32())) return true; - if (LIKELY(m_v8Object->IsInt32())) { - setString(int32ToWebCoreString(m_v8Object->Int32Value())); - return true; - } - m_mode = DoNotExternalize; v8::TryCatch block; m_v8Object = m_v8Object->ToString(); @@ -191,46 +184,41 @@ private: return true; } - v8::Local<v8::Value> object() { return m_v8Object; } - - void setString(const String& string) - { - m_string = string; - m_v8Object.Clear(); // To signal that String is ready. - } - template <class StringType> StringType toString() { - if (LIKELY(!m_v8Object.IsEmpty())) - return v8StringToWebCoreString<StringType>(m_v8Object.As<v8::String>(), m_mode); - - return StringType(m_string); + if (m_v8Object.IsEmpty()) + return StringType(); + if (m_v8Object->IsInt32()) + return int32ToWebCoreString<StringType>(m_v8Object->Int32Value()); + ASSERT(m_v8Object->IsString()); + return v8StringToWebCoreString<StringType>(m_v8Object.As<v8::String>(), m_mode); } v8::Local<v8::Value> m_v8Object; ExternalMode m_mode; - String m_string; }; -template<> inline bool V8Parameter<DefaultMode>::prepare() +template<> inline bool V8StringResource<DefaultMode>::prepare() { + if (m_v8Object.IsEmpty()) + return true; return prepareBase(); } -template<> inline bool V8Parameter<WithNullCheck>::prepare() +template<> inline bool V8StringResource<WithNullCheck>::prepare() { - if (object().IsEmpty() || object()->IsNull()) { - setString(String()); + if (m_v8Object.IsEmpty() || m_v8Object->IsNull()) { + m_v8Object.Clear(); return true; } return prepareBase(); } -template<> inline bool V8Parameter<WithUndefinedOrNullCheck>::prepare() +template<> inline bool V8StringResource<WithUndefinedOrNullCheck>::prepare() { - if (object().IsEmpty() || object()->IsNull() || object()->IsUndefined()) { - setString(String()); + if (m_v8Object.IsEmpty() || m_v8Object->IsNull() || m_v8Object->IsUndefined()) { + m_v8Object.Clear(); return true; } return prepareBase(); diff --git a/Source/WebCore/bindings/v8/V8WorkerContextEventListener.cpp b/Source/WebCore/bindings/v8/V8WorkerContextEventListener.cpp index 74aa03c57..3bdaaf3c7 100644 --- a/Source/WebCore/bindings/v8/V8WorkerContextEventListener.cpp +++ b/Source/WebCore/bindings/v8/V8WorkerContextEventListener.cpp @@ -41,17 +41,10 @@ #include "V8GCController.h" #include "V8RecursionScope.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" +#include "WorkerScriptController.h" namespace WebCore { -static WorkerContextExecutionProxy* workerProxy(ScriptExecutionContext* context) -{ - ASSERT(context->isWorkerContext()); - WorkerContext* workerContext = static_cast<WorkerContext*>(context); - return workerContext->script()->proxy(); -} - V8WorkerContextEventListener::V8WorkerContextEventListener(v8::Local<v8::Object> listener, bool isInline, const WorldContextHandle& worldContext) : V8EventListener(listener, isInline, worldContext) { @@ -68,11 +61,12 @@ void V8WorkerContextEventListener::handleEvent(ScriptExecutionContext* context, v8::HandleScope handleScope; - WorkerContextExecutionProxy* proxy = workerProxy(context); - if (!proxy) + ASSERT(context->isWorkerContext()); + WorkerScriptController* script = static_cast<WorkerContext*>(context)->script(); + if (!script) return; - v8::Handle<v8::Context> v8Context = proxy->context(); + v8::Handle<v8::Context> v8Context = script->context(); if (v8Context.IsEmpty()) return; diff --git a/Source/WebCore/bindings/v8/V8WorkerContextEventListener.h b/Source/WebCore/bindings/v8/V8WorkerContextEventListener.h index 68015e062..de61e9bdf 100644 --- a/Source/WebCore/bindings/v8/V8WorkerContextEventListener.h +++ b/Source/WebCore/bindings/v8/V8WorkerContextEventListener.h @@ -40,7 +40,6 @@ namespace WebCore { class Event; - class WorkerContextExecutionProxy; class V8WorkerContextEventListener : public V8EventListener { public: diff --git a/Source/WebCore/bindings/v8/WorkerContextExecutionProxy.cpp b/Source/WebCore/bindings/v8/WorkerContextExecutionProxy.cpp deleted file mode 100644 index 9be359580..000000000 --- a/Source/WebCore/bindings/v8/WorkerContextExecutionProxy.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (C) 2009, 2011 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#include "config.h" - -#if ENABLE(WORKERS) - -#include "WorkerContextExecutionProxy.h" - -#include "DedicatedWorkerContext.h" -#include "Event.h" -#include "ScriptCallStack.h" -#include "ScriptRunner.h" -#include "ScriptSourceCode.h" -#include "SharedWorker.h" -#include "SharedWorkerContext.h" -#include "V8Binding.h" -#include "V8DOMWindowShell.h" -#include "V8DedicatedWorkerContext.h" -#include "V8GCController.h" -#include "V8Initializer.h" -#include "V8ObjectConstructor.h" -#include "V8PerContextData.h" -#include "V8RecursionScope.h" -#include "V8SharedWorkerContext.h" -#include "Worker.h" -#include "WorkerContext.h" -#include "WorkerScriptController.h" -#include "WrapperTypeInfo.h" -#include <wtf/text/CString.h> - -namespace WebCore { - -WorkerContextExecutionProxy::WorkerContextExecutionProxy(WorkerContext* workerContext) - : m_workerContext(workerContext) - , m_disableEvalPending(String()) -{ - V8Initializer::initializeWorker(); -} - -WorkerContextExecutionProxy::~WorkerContextExecutionProxy() -{ - dispose(); -} - -void WorkerContextExecutionProxy::dispose() -{ - m_perContextData.clear(); - m_context.clear(); -} - -bool WorkerContextExecutionProxy::initializeIfNeeded() -{ - // Bail out if the context has already been initialized. - if (!m_context.isEmpty()) - return true; - - // Create a new environment - v8::Persistent<v8::ObjectTemplate> globalTemplate; - m_context.adopt(v8::Context::New(0, globalTemplate)); - if (m_context.isEmpty()) - return false; - - // Starting from now, use local context only. - v8::Local<v8::Context> context = v8::Local<v8::Context>::New(m_context.get()); - - v8::Context::Scope scope(context); - - m_perContextData = V8PerContextData::create(m_context.get()); - if (!m_perContextData->init()) { - dispose(); - return false; - } - - // Set DebugId for the new context. - context->SetEmbedderData(0, v8::String::New("worker")); - - // Create a new JS object and use it as the prototype for the shadow global object. - WrapperTypeInfo* contextType = &V8DedicatedWorkerContext::info; -#if ENABLE(SHARED_WORKERS) - if (!m_workerContext->isDedicatedWorkerContext()) - contextType = &V8SharedWorkerContext::info; -#endif - v8::Handle<v8::Function> workerContextConstructor = m_perContextData->constructorForType(contextType); - v8::Local<v8::Object> jsWorkerContext = V8ObjectConstructor::newInstance(workerContextConstructor); - // Bail out if allocation failed. - if (jsWorkerContext.IsEmpty()) { - dispose(); - return false; - } - - // Wrap the object. - V8DOMWrapper::createDOMWrapper(PassRefPtr<WorkerContext>(m_workerContext), contextType, jsWorkerContext); - - // Insert the object instance as the prototype of the shadow object. - v8::Handle<v8::Object> globalObject = v8::Handle<v8::Object>::Cast(m_context->Global()->GetPrototype()); - globalObject->SetPrototype(jsWorkerContext); - - return true; -} - -ScriptValue WorkerContextExecutionProxy::evaluate(const String& script, const String& fileName, const TextPosition& scriptStartPosition, WorkerContextExecutionState* state) -{ - V8GCController::checkMemoryUsage(); - - v8::HandleScope hs; - - if (!initializeIfNeeded()) - return ScriptValue(); - - if (!m_disableEvalPending.isEmpty()) { - m_context->AllowCodeGenerationFromStrings(false); - m_context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_disableEvalPending)); - m_disableEvalPending = String(); - } - - v8::Context::Scope scope(m_context.get()); - - v8::TryCatch exceptionCatcher; - - v8::Local<v8::String> scriptString = v8ExternalString(script); - v8::Handle<v8::Script> compiledScript = ScriptSourceCode::compileScript(scriptString, fileName, scriptStartPosition); - v8::Local<v8::Value> result = ScriptRunner::runCompiledScript(compiledScript, m_workerContext); - - if (!exceptionCatcher.CanContinue()) { - m_workerContext->script()->forbidExecution(); - return ScriptValue(); - } - - if (exceptionCatcher.HasCaught()) { - v8::Local<v8::Message> message = exceptionCatcher.Message(); - state->hadException = true; - state->errorMessage = toWebCoreString(message->Get()); - state->lineNumber = message->GetLineNumber(); - state->sourceURL = toWebCoreString(message->GetScriptResourceName()); - if (m_workerContext->sanitizeScriptError(state->errorMessage, state->lineNumber, state->sourceURL)) - state->exception = throwError(v8GeneralError, state->errorMessage.utf8().data()); - else - state->exception = ScriptValue(exceptionCatcher.Exception()); - - exceptionCatcher.Reset(); - } else - state->hadException = false; - - if (result.IsEmpty() || result->IsUndefined()) - return ScriptValue(); - - return ScriptValue(result); -} - -void WorkerContextExecutionProxy::setEvalAllowed(bool enable, const String& errorMessage) -{ - m_disableEvalPending = enable ? String() : errorMessage; -} - -} // namespace WebCore - -#endif // ENABLE(WORKERS) diff --git a/Source/WebCore/bindings/v8/WorkerContextExecutionProxy.h b/Source/WebCore/bindings/v8/WorkerContextExecutionProxy.h deleted file mode 100644 index 8890eccde..000000000 --- a/Source/WebCore/bindings/v8/WorkerContextExecutionProxy.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2009 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#ifndef WorkerContextExecutionProxy_h -#define WorkerContextExecutionProxy_h - -#if ENABLE(WORKERS) - -#include "ScriptValue.h" -#include <v8.h> -#include <wtf/text/TextPosition.h> -#include <wtf/OwnPtr.h> -#include <wtf/Vector.h> - -namespace WebCore { - - class Event; - class EventTarget; - class V8PerContextData; - class WorkerContext; - struct WrapperTypeInfo; - - struct WorkerContextExecutionState { - WorkerContextExecutionState() - : hadException(false) - , lineNumber(0) - { - } - - bool hadException; - ScriptValue exception; - String errorMessage; - int lineNumber; - String sourceURL; - }; - - class WorkerContextExecutionProxy { - public: - explicit WorkerContextExecutionProxy(WorkerContext*); - ~WorkerContextExecutionProxy(); - - // Alow use of eval() and is equivalents in scripts. - void setEvalAllowed(bool enable, const String& errorMessage); - - // Evaluate a script file in the current execution environment. - ScriptValue evaluate(const String& script, const String& fileName, const TextPosition& scriptStartPosition, WorkerContextExecutionState*); - - // Returns a local handle of the context. - v8::Local<v8::Context> context() { return v8::Local<v8::Context>::New(m_context.get()); } - - private: - void initIsolate(); - bool initializeIfNeeded(); - void dispose(); - - WorkerContext* m_workerContext; - ScopedPersistent<v8::Context> m_context; - OwnPtr<V8PerContextData> m_perContextData; - String m_disableEvalPending; - }; - -} // namespace WebCore - -#endif // ENABLE(WORKERS) - -#endif // WorkerContextExecutionProxy_h diff --git a/Source/WebCore/bindings/v8/WorkerScriptController.cpp b/Source/WebCore/bindings/v8/WorkerScriptController.cpp index 628f51b60..e0ff6c759 100644 --- a/Source/WebCore/bindings/v8/WorkerScriptController.cpp +++ b/Source/WebCore/bindings/v8/WorkerScriptController.cpp @@ -36,11 +36,14 @@ #include "DOMTimer.h" #include "ScriptCallStack.h" +#include "ScriptRunner.h" #include "ScriptSourceCode.h" #include "ScriptValue.h" +#include "V8DedicatedWorkerContext.h" +#include "V8Initializer.h" +#include "V8SharedWorkerContext.h" #include "V8WorkerContext.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" #include "WorkerObjectProxy.h" #include "WorkerThread.h" #include <v8.h> @@ -62,7 +65,8 @@ WorkerScriptController::WorkerScriptController(WorkerContext* workerContext) m_isolate->Enter(); m_domDataStore = adoptPtr(new DOMDataStore(DOMDataStore::Worker)); data->setDOMDataStore(m_domDataStore.get()); - m_proxy = adoptPtr(new WorkerContextExecutionProxy(workerContext)); + + V8Initializer::initializeWorker(); } WorkerScriptController::~WorkerScriptController() @@ -74,15 +78,111 @@ WorkerScriptController::~WorkerScriptController() // See http://webkit.org/b/83104#c14 for why this is here. WebKit::Platform::current()->didStopWorkerRunLoop(WebKit::WebWorkerRunLoop(&m_workerContext->thread()->runLoop())); #endif - m_proxy.clear(); + disposeContext(); V8PerIsolateData::dispose(m_isolate); m_isolate->Exit(); m_isolate->Dispose(); } -void WorkerScriptController::evaluate(const ScriptSourceCode& sourceCode) +void WorkerScriptController::disposeContext() { - evaluate(sourceCode, 0); + m_perContextData.clear(); + m_context.clear(); +} + +bool WorkerScriptController::initializeContextIfNeeded() +{ + if (!m_context.isEmpty()) + return true; + + v8::Persistent<v8::ObjectTemplate> globalTemplate; + m_context.adopt(v8::Context::New(0, globalTemplate)); + if (m_context.isEmpty()) + return false; + + // Starting from now, use local context only. + v8::Local<v8::Context> context = v8::Local<v8::Context>::New(m_context.get()); + + v8::Context::Scope scope(context); + + m_perContextData = V8PerContextData::create(m_context.get()); + if (!m_perContextData->init()) { + disposeContext(); + return false; + } + + // Set DebugId for the new context. + context->SetEmbedderData(0, v8::String::New("worker")); + + // Create a new JS object and use it as the prototype for the shadow global object. + WrapperTypeInfo* contextType = &V8DedicatedWorkerContext::info; +#if ENABLE(SHARED_WORKERS) + if (!m_workerContext->isDedicatedWorkerContext()) + contextType = &V8SharedWorkerContext::info; +#endif + v8::Handle<v8::Function> workerContextConstructor = m_perContextData->constructorForType(contextType); + v8::Local<v8::Object> jsWorkerContext = V8ObjectConstructor::newInstance(workerContextConstructor); + if (jsWorkerContext.IsEmpty()) { + disposeContext(); + return false; + } + + V8DOMWrapper::createDOMWrapper(PassRefPtr<WorkerContext>(m_workerContext), contextType, jsWorkerContext); + + // Insert the object instance as the prototype of the shadow object. + v8::Handle<v8::Object> globalObject = v8::Handle<v8::Object>::Cast(m_context->Global()->GetPrototype()); + globalObject->SetPrototype(jsWorkerContext); + + return true; +} + +ScriptValue WorkerScriptController::evaluate(const String& script, const String& fileName, const TextPosition& scriptStartPosition, WorkerContextExecutionState* state) +{ + V8GCController::checkMemoryUsage(); + + v8::HandleScope handleScope; + + if (!initializeContextIfNeeded()) + return ScriptValue(); + + if (!m_disableEvalPending.isEmpty()) { + m_context->AllowCodeGenerationFromStrings(false); + m_context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_disableEvalPending)); + m_disableEvalPending = String(); + } + + v8::Context::Scope scope(m_context.get()); + + v8::TryCatch block; + + v8::Local<v8::String> scriptString = v8ExternalString(script); + v8::Handle<v8::Script> compiledScript = ScriptSourceCode::compileScript(scriptString, fileName, scriptStartPosition); + v8::Local<v8::Value> result = ScriptRunner::runCompiledScript(compiledScript, m_workerContext); + + if (!block.CanContinue()) { + m_workerContext->script()->forbidExecution(); + return ScriptValue(); + } + + if (block.HasCaught()) { + v8::Local<v8::Message> message = block.Message(); + state->hadException = true; + state->errorMessage = toWebCoreString(message->Get()); + state->lineNumber = message->GetLineNumber(); + state->sourceURL = toWebCoreString(message->GetScriptResourceName()); + if (m_workerContext->sanitizeScriptError(state->errorMessage, state->lineNumber, state->sourceURL)) + state->exception = throwError(v8GeneralError, state->errorMessage.utf8().data()); + else + state->exception = ScriptValue(block.Exception()); + + block.Reset(); + } else + state->hadException = false; + + if (result.IsEmpty() || result->IsUndefined()) + return ScriptValue(); + + return ScriptValue(result); } void WorkerScriptController::evaluate(const ScriptSourceCode& sourceCode, ScriptValue* exception) @@ -91,7 +191,7 @@ void WorkerScriptController::evaluate(const ScriptSourceCode& sourceCode, Script return; WorkerContextExecutionState state; - m_proxy->evaluate(sourceCode.source(), sourceCode.url().string(), sourceCode.startPosition(), &state); + evaluate(sourceCode.source(), sourceCode.url().string(), sourceCode.startPosition(), &state); if (state.hadException) { if (exception) *exception = state.exception; @@ -133,7 +233,7 @@ bool WorkerScriptController::isExecutionForbidden() const void WorkerScriptController::disableEval(const String& errorMessage) { - m_proxy->setEvalAllowed(false, errorMessage); + m_disableEvalPending = errorMessage; } void WorkerScriptController::setException(const ScriptValue& exception) diff --git a/Source/WebCore/bindings/v8/WorkerScriptController.h b/Source/WebCore/bindings/v8/WorkerScriptController.h index e08eb9d9f..d0a62100d 100644 --- a/Source/WebCore/bindings/v8/WorkerScriptController.h +++ b/Source/WebCore/bindings/v8/WorkerScriptController.h @@ -33,29 +33,41 @@ #if ENABLE(WORKERS) +#include "ScriptValue.h" #include "V8Binding.h" - #include <v8.h> #include <wtf/OwnPtr.h> #include <wtf/Threading.h> +#include <wtf/text/TextPosition.h> namespace WebCore { class ScriptSourceCode; class ScriptValue; class WorkerContext; - class WorkerContextExecutionProxy; + + struct WorkerContextExecutionState { + WorkerContextExecutionState() + : hadException(false) + , lineNumber(0) + { + } + + bool hadException; + ScriptValue exception; + String errorMessage; + int lineNumber; + String sourceURL; + }; class WorkerScriptController { public: WorkerScriptController(WorkerContext*); ~WorkerScriptController(); - WorkerContextExecutionProxy* proxy() { return m_proxy.get(); } WorkerContext* workerContext() { return m_workerContext; } - void evaluate(const ScriptSourceCode&); - void evaluate(const ScriptSourceCode&, ScriptValue* exception); + void evaluate(const ScriptSourceCode&, ScriptValue* = 0); void setException(const ScriptValue&); @@ -77,10 +89,21 @@ namespace WebCore { // Returns WorkerScriptController for the currently executing context. 0 will be returned if the current executing context is not the worker context. static WorkerScriptController* controllerForContext(); + // Evaluate a script file in the current execution environment. + ScriptValue evaluate(const String& script, const String& fileName, const TextPosition& scriptStartPosition, WorkerContextExecutionState*); + + // Returns a local handle of the context. + v8::Local<v8::Context> context() { return v8::Local<v8::Context>::New(m_context.get()); } + private: + bool initializeContextIfNeeded(); + void disposeContext(); + WorkerContext* m_workerContext; - OwnPtr<WorkerContextExecutionProxy> m_proxy; v8::Isolate* m_isolate; + ScopedPersistent<v8::Context> m_context; + OwnPtr<V8PerContextData> m_perContextData; + String m_disableEvalPending; OwnPtr<DOMDataStore> m_domDataStore; bool m_executionForbidden; bool m_executionScheduledToTerminate; diff --git a/Source/WebCore/bindings/v8/WorkerScriptDebugServer.cpp b/Source/WebCore/bindings/v8/WorkerScriptDebugServer.cpp index 3c25ad8c5..29775fc8b 100644 --- a/Source/WebCore/bindings/v8/WorkerScriptDebugServer.cpp +++ b/Source/WebCore/bindings/v8/WorkerScriptDebugServer.cpp @@ -35,7 +35,6 @@ #include "ScriptDebugListener.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" #include "WorkerDebuggerAgent.h" #include "WorkerThread.h" #include <v8.h> @@ -66,11 +65,6 @@ void WorkerScriptDebugServer::addListener(ScriptDebugListener* listener) ASSERT(!m_debuggerScript.get()->IsUndefined()); v8::Debug::SetDebugEventListener2(&WorkerScriptDebugServer::v8DebugEventCallback, v8::External::New(this)); - // TODO: Should we remove |proxy|? It looks like unused now. - WorkerContextExecutionProxy* proxy = m_workerContext->script()->proxy(); - if (!proxy) - return; - v8::Handle<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.get()->Get(v8::String::New("getWorkerScripts"))); v8::Handle<v8::Value> argv[] = { v8Undefined() }; v8::Handle<v8::Value> value = getScriptsFunction->Call(m_debuggerScript.get(), 0, argv); diff --git a/Source/WebCore/bindings/v8/custom/V8BlobCustom.cpp b/Source/WebCore/bindings/v8/custom/V8BlobCustom.cpp index 4e5dc9698..e00111ea6 100644 --- a/Source/WebCore/bindings/v8/custom/V8BlobCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8BlobCustom.cpp @@ -71,15 +71,15 @@ v8::Handle<v8::Value> V8Blob::constructorCallbackCustom(const v8::Arguments& arg if (!args[1]->IsObject()) return throwTypeError("Second argument of the constructor is not of type Object", args.GetIsolate()); - EXCEPTION_BLOCK(Dictionary, dictionary, Dictionary(args[1], args.GetIsolate())); + V8TRYCATCH(Dictionary, dictionary, Dictionary(args[1], args.GetIsolate())); - EXCEPTION_BLOCK(bool, containsEndings, dictionary.get("endings", endings)); + V8TRYCATCH(bool, containsEndings, dictionary.get("endings", endings)); if (containsEndings) { if (endings != "transparent" && endings != "native") return throwTypeError("The endings property must be either \"transparent\" or \"native\"", args.GetIsolate()); } - EXCEPTION_BLOCK(bool, containsType, dictionary.get("type", type)); + V8TRYCATCH(bool, containsType, dictionary.get("type", type)); UNUSED_PARAM(containsType); if (!type.containsOnlyASCII()) return throwError(v8SyntaxError, "type must consist of ASCII characters", args.GetIsolate()); @@ -90,7 +90,7 @@ v8::Handle<v8::Value> V8Blob::constructorCallbackCustom(const v8::Arguments& arg BlobBuilder blobBuilder; - EXCEPTION_BLOCK(v8::Local<v8::Array>, blobParts, v8::Local<v8::Array>::Cast(firstArg)); + V8TRYCATCH(v8::Local<v8::Array>, blobParts, v8::Local<v8::Array>::Cast(firstArg)); uint32_t length = blobParts->Length(); for (uint32_t i = 0; i < length; ++i) { @@ -112,7 +112,7 @@ v8::Handle<v8::Value> V8Blob::constructorCallbackCustom(const v8::Arguments& arg ASSERT(blob); blobBuilder.append(blob); } else { - EXCEPTION_BLOCK(String, stringValue, toWebCoreString(item)); + V8TRYCATCH(String, stringValue, toWebCoreString(item)); blobBuilder.append(stringValue, endings); } } diff --git a/Source/WebCore/bindings/v8/custom/V8CSSValueCustom.cpp b/Source/WebCore/bindings/v8/custom/V8CSSValueCustom.cpp index 98df22280..551e87718 100644 --- a/Source/WebCore/bindings/v8/custom/V8CSSValueCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8CSSValueCustom.cpp @@ -39,6 +39,11 @@ #include "V8WebKitCSSFilterValue.h" #endif +#if ENABLE(CSS_SHADERS) +#include "V8WebKitCSSMixFunctionValue.h" +#include "WebKitCSSMixFunctionValue.h" +#endif + #if ENABLE(SVG) #include "V8SVGColor.h" #include "V8SVGPaint.h" @@ -55,6 +60,10 @@ v8::Handle<v8::Object> wrap(CSSValue* impl, v8::Handle<v8::Object> creationConte if (impl->isWebKitCSSFilterValue()) return wrap(static_cast<WebKitCSSFilterValue*>(impl), creationContext, isolate); #endif +#if ENABLE(CSS_SHADERS) + if (impl->isWebKitCSSMixFunctionValue()) + return wrap(static_cast<WebKitCSSMixFunctionValue*>(impl), creationContext, isolate); +#endif if (impl->isValueList()) return wrap(static_cast<CSSValueList*>(impl), creationContext, isolate); if (impl->isPrimitiveValue()) diff --git a/Source/WebCore/bindings/v8/custom/V8ConsoleCustom.cpp b/Source/WebCore/bindings/v8/custom/V8ConsoleCustom.cpp index 19e6e785a..c35f03f22 100644 --- a/Source/WebCore/bindings/v8/custom/V8ConsoleCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8ConsoleCustom.cpp @@ -64,7 +64,7 @@ v8::Handle<v8::Value> V8Console::profileCallback(const v8::Arguments& args) { INC_STATS("DOM.Console.profile"); Console* imp = V8Console::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, title, args[0]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithUndefinedOrNullCheck>, title, args[0]); imp->profile(title, ScriptState::current()); return v8Undefined(); } @@ -73,7 +73,7 @@ v8::Handle<v8::Value> V8Console::profileEndCallback(const v8::Arguments& args) { INC_STATS("DOM.Console.profileEnd"); Console* imp = V8Console::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, title, args[0]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithUndefinedOrNullCheck>, title, args[0]); imp->profileEnd(title, ScriptState::current()); return v8Undefined(); } diff --git a/Source/WebCore/bindings/v8/custom/V8DOMWindowCustom.cpp b/Source/WebCore/bindings/v8/custom/V8DOMWindowCustom.cpp index 79a6c0c67..84c668532 100644 --- a/Source/WebCore/bindings/v8/custom/V8DOMWindowCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8DOMWindowCustom.cpp @@ -324,7 +324,7 @@ static v8::Handle<v8::Value> handlePostMessageCallback(const v8::Arguments& args if (!extractTransferables(args[transferablesArgIndex], portArray, arrayBufferArray, args.GetIsolate())) return v8::Undefined(); } - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, targetOrigin, args[targetOriginArgIndex]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithUndefinedOrNullCheck>, targetOrigin, args[targetOriginArgIndex]); bool didThrow = false; RefPtr<SerializedScriptValue> message = diff --git a/Source/WebCore/bindings/v8/custom/V8DataViewCustom.cpp b/Source/WebCore/bindings/v8/custom/V8DataViewCustom.cpp index 9f45b26b1..b1080a34c 100644 --- a/Source/WebCore/bindings/v8/custom/V8DataViewCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8DataViewCustom.cpp @@ -62,7 +62,7 @@ v8::Handle<v8::Value> V8DataView::getInt8Callback(const v8::Arguments& args) DataView* imp = V8DataView::toNative(args.Holder()); ExceptionCode ec = 0; - EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0])); + V8TRYCATCH(unsigned, byteOffset, toUInt32(args[0])); int8_t result = imp->getInt8(byteOffset, ec); if (UNLIKELY(ec)) return setDOMException(ec, args.GetIsolate()); @@ -77,7 +77,7 @@ v8::Handle<v8::Value> V8DataView::getUint8Callback(const v8::Arguments& args) DataView* imp = V8DataView::toNative(args.Holder()); ExceptionCode ec = 0; - EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0])); + V8TRYCATCH(unsigned, byteOffset, toUInt32(args[0])); uint8_t result = imp->getUint8(byteOffset, ec); if (UNLIKELY(ec)) return setDOMException(ec, args.GetIsolate()); @@ -92,8 +92,8 @@ v8::Handle<v8::Value> V8DataView::setInt8Callback(const v8::Arguments& args) DataView* imp = V8DataView::toNative(args.Holder()); ExceptionCode ec = 0; - EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0])); - EXCEPTION_BLOCK(int, value, toInt32(args[1])); + V8TRYCATCH(unsigned, byteOffset, toUInt32(args[0])); + V8TRYCATCH(int, value, toInt32(args[1])); imp->setInt8(byteOffset, static_cast<int8_t>(value), ec); if (UNLIKELY(ec)) return setDOMException(ec, args.GetIsolate()); @@ -108,8 +108,8 @@ v8::Handle<v8::Value> V8DataView::setUint8Callback(const v8::Arguments& args) DataView* imp = V8DataView::toNative(args.Holder()); ExceptionCode ec = 0; - EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0])); - EXCEPTION_BLOCK(int, value, toInt32(args[1])); + V8TRYCATCH(unsigned, byteOffset, toUInt32(args[0])); + V8TRYCATCH(int, value, toInt32(args[1])); imp->setUint8(byteOffset, static_cast<uint8_t>(value), ec); if (UNLIKELY(ec)) return setDOMException(ec, args.GetIsolate()); diff --git a/Source/WebCore/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp b/Source/WebCore/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp index ff68c3414..7d18a44aa 100644 --- a/Source/WebCore/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp @@ -35,7 +35,6 @@ #include <wtf/ArrayBuffer.h> #include "DedicatedWorkerContext.h" -#include "WorkerContextExecutionProxy.h" #include "V8Binding.h" #include "V8Utilities.h" #include "V8WorkerContextEventListener.h" diff --git a/Source/WebCore/bindings/v8/custom/V8DeviceMotionEventCustom.cpp b/Source/WebCore/bindings/v8/custom/V8DeviceMotionEventCustom.cpp index 83ff773b7..a94dcea44 100644 --- a/Source/WebCore/bindings/v8/custom/V8DeviceMotionEventCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8DeviceMotionEventCustom.cpp @@ -164,7 +164,7 @@ v8::Handle<v8::Value> V8DeviceMotionEvent::intervalAccessorGetter(v8::Local<v8:: v8::Handle<v8::Value> V8DeviceMotionEvent::initDeviceMotionEventCallback(const v8::Arguments& args) { DeviceMotionEvent* imp = V8DeviceMotionEvent::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, args[0]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, type, args[0]); bool bubbles = args[1]->BooleanValue(); bool cancelable = args[2]->BooleanValue(); RefPtr<DeviceMotionData::Acceleration> acceleration = readAccelerationArgument(args[3]); diff --git a/Source/WebCore/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp b/Source/WebCore/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp index c6861bae9..88d9b43ad 100644 --- a/Source/WebCore/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp @@ -78,7 +78,7 @@ v8::Handle<v8::Value> V8DeviceOrientationEvent::absoluteAccessorGetter(v8::Local v8::Handle<v8::Value> V8DeviceOrientationEvent::initDeviceOrientationEventCallback(const v8::Arguments& args) { DeviceOrientationEvent* imp = V8DeviceOrientationEvent::toNative(args.Holder()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, args[0]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, type, args[0]); bool bubbles = args[1]->BooleanValue(); bool cancelable = args[2]->BooleanValue(); // If alpha, beta, gamma or absolute are null or undefined, mark them as not provided. diff --git a/Source/WebCore/bindings/v8/custom/V8DocumentCustom.cpp b/Source/WebCore/bindings/v8/custom/V8DocumentCustom.cpp index 212582c5f..15f045a4c 100644 --- a/Source/WebCore/bindings/v8/custom/V8DocumentCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8DocumentCustom.cpp @@ -84,7 +84,7 @@ v8::Handle<v8::Value> V8Document::evaluateCallback(const v8::Arguments& args) if (V8XPathResult::HasInstance(args[4])) inResult = V8XPathResult::toNative(v8::Handle<v8::Object>::Cast(args[4])); - EXCEPTION_BLOCK(RefPtr<XPathResult>, result, document->evaluate(expression, contextNode.get(), resolver.get(), type, inResult.get(), ec)); + V8TRYCATCH(RefPtr<XPathResult>, result, document->evaluate(expression, contextNode.get(), resolver.get(), type, inResult.get(), ec)); if (ec) return setDOMException(ec, args.GetIsolate()); diff --git a/Source/WebCore/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp b/Source/WebCore/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp index 5441ff6e4..c9cc0fea2 100644 --- a/Source/WebCore/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp @@ -105,7 +105,7 @@ v8::Handle<v8::Value> V8HTMLOptionsCollection::addCallback(const v8::Arguments& imp->add(option, ec); else { bool ok; - EXCEPTION_BLOCK(int, index, toInt32(args[1], ok)); + V8TRYCATCH(int, index, toInt32(args[1], ok)); if (!ok) ec = TYPE_MISMATCH_ERR; else diff --git a/Source/WebCore/bindings/v8/custom/V8HistoryCustom.cpp b/Source/WebCore/bindings/v8/custom/V8HistoryCustom.cpp index 3cd666de3..d2534c137 100644 --- a/Source/WebCore/bindings/v8/custom/V8HistoryCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8HistoryCustom.cpp @@ -65,8 +65,8 @@ v8::Handle<v8::Value> V8History::pushStateCallback(const v8::Arguments& args) if (didThrow) return v8::Undefined(); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, title, args[1]); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, url, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithUndefinedOrNullCheck>, title, args[1]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithUndefinedOrNullCheck>, url, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); ExceptionCode ec = 0; History* history = V8History::toNative(args.Holder()); @@ -82,8 +82,8 @@ v8::Handle<v8::Value> V8History::replaceStateCallback(const v8::Arguments& args) if (didThrow) return v8::Undefined(); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, title, args[1]); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, url, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithUndefinedOrNullCheck>, title, args[1]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<WithUndefinedOrNullCheck>, url, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); ExceptionCode ec = 0; History* history = V8History::toNative(args.Holder()); diff --git a/Source/WebCore/bindings/v8/custom/V8IntentCustom.cpp b/Source/WebCore/bindings/v8/custom/V8IntentCustom.cpp index 10da78d82..f52d77c33 100644 --- a/Source/WebCore/bindings/v8/custom/V8IntentCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8IntentCustom.cpp @@ -48,7 +48,7 @@ v8::Handle<v8::Value> V8Intent::constructorCallbackCustom(const v8::Arguments& a if (args.Length() == 1) { // Use the dictionary constructor. This block will return if the // argument isn't a valid Dictionary. - EXCEPTION_BLOCK(Dictionary, options, Dictionary(args[0], args.GetIsolate())); + V8TRYCATCH(Dictionary, options, Dictionary(args[0], args.GetIsolate())); ExceptionCode ec = 0; RefPtr<Intent> impl = Intent::create(ScriptState::current(), options, ec); if (ec) @@ -60,8 +60,8 @@ v8::Handle<v8::Value> V8Intent::constructorCallbackCustom(const v8::Arguments& a } ExceptionCode ec = 0; - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, action, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, action, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, type, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); MessagePortArray messagePortArrayTransferList; ArrayBufferArray arrayBufferArrayTransferList; if (args.Length() > 3) { diff --git a/Source/WebCore/bindings/v8/custom/V8MessageChannelCustom.cpp b/Source/WebCore/bindings/v8/custom/V8MessageChannelCustom.cpp index 1fde8dacd..8b11d38e0 100644 --- a/Source/WebCore/bindings/v8/custom/V8MessageChannelCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8MessageChannelCustom.cpp @@ -38,7 +38,6 @@ #include "V8MessagePort.h" #include "V8Utilities.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" #include <wtf/RefPtr.h> diff --git a/Source/WebCore/bindings/v8/custom/V8MessagePortCustom.cpp b/Source/WebCore/bindings/v8/custom/V8MessagePortCustom.cpp index 5c0a1f5db..c35c99875 100644 --- a/Source/WebCore/bindings/v8/custom/V8MessagePortCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8MessagePortCustom.cpp @@ -37,7 +37,6 @@ #include "V8Binding.h" #include "V8MessagePort.h" #include "V8Utilities.h" -#include "WorkerContextExecutionProxy.h" namespace WebCore { diff --git a/Source/WebCore/bindings/v8/custom/V8SQLTransactionCustom.cpp b/Source/WebCore/bindings/v8/custom/V8SQLTransactionCustom.cpp index 593acbb94..b6bc6aca2 100644 --- a/Source/WebCore/bindings/v8/custom/V8SQLTransactionCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8SQLTransactionCustom.cpp @@ -53,7 +53,7 @@ v8::Handle<v8::Value> V8SQLTransaction::executeSqlCallback(const v8::Arguments& if (args.Length() == 0) return setDOMException(SYNTAX_ERR, args.GetIsolate()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, statement, args[0]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, statement, args[0]); Vector<SQLValue> sqlValues; @@ -63,7 +63,7 @@ v8::Handle<v8::Value> V8SQLTransaction::executeSqlCallback(const v8::Arguments& uint32_t sqlArgsLength = 0; v8::Local<v8::Object> sqlArgsObject = args[1]->ToObject(); - EXCEPTION_BLOCK(v8::Local<v8::Value>, length, sqlArgsObject->Get(v8::String::New("length"))); + V8TRYCATCH(v8::Local<v8::Value>, length, sqlArgsObject->Get(v8::String::New("length"))); if (isUndefinedOrNull(length)) sqlArgsLength = sqlArgsObject->GetPropertyNames()->Length(); @@ -72,15 +72,15 @@ v8::Handle<v8::Value> V8SQLTransaction::executeSqlCallback(const v8::Arguments& for (unsigned int i = 0; i < sqlArgsLength; ++i) { v8::Handle<v8::Integer> key = v8Integer(i, args.GetIsolate()); - EXCEPTION_BLOCK(v8::Local<v8::Value>, value, sqlArgsObject->Get(key)); + V8TRYCATCH(v8::Local<v8::Value>, value, sqlArgsObject->Get(key)); if (value.IsEmpty() || value->IsNull()) sqlValues.append(SQLValue()); else if (value->IsNumber()) { - EXCEPTION_BLOCK(double, sqlValue, value->NumberValue()); + V8TRYCATCH(double, sqlValue, value->NumberValue()); sqlValues.append(SQLValue(sqlValue)); } else { - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, sqlValue, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, sqlValue, value); sqlValues.append(SQLValue(sqlValue)); } } diff --git a/Source/WebCore/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp b/Source/WebCore/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp index 1ab662678..8b14ee8ac 100644 --- a/Source/WebCore/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp @@ -53,7 +53,7 @@ v8::Handle<v8::Value> V8SQLTransactionSync::executeSqlCallback(const v8::Argumen if (!args.Length()) return setDOMException(SYNTAX_ERR, args.GetIsolate()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, statement, args[0]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, statement, args[0]); Vector<SQLValue> sqlValues; @@ -63,7 +63,7 @@ v8::Handle<v8::Value> V8SQLTransactionSync::executeSqlCallback(const v8::Argumen uint32_t sqlArgsLength = 0; v8::Local<v8::Object> sqlArgsObject = args[1]->ToObject(); - EXCEPTION_BLOCK(v8::Local<v8::Value>, length, sqlArgsObject->Get(v8::String::New("length"))); + V8TRYCATCH(v8::Local<v8::Value>, length, sqlArgsObject->Get(v8::String::New("length"))); if (isUndefinedOrNull(length)) sqlArgsLength = sqlArgsObject->GetPropertyNames()->Length(); @@ -72,15 +72,15 @@ v8::Handle<v8::Value> V8SQLTransactionSync::executeSqlCallback(const v8::Argumen for (unsigned int i = 0; i < sqlArgsLength; ++i) { v8::Handle<v8::Integer> key = v8Integer(i, args.GetIsolate()); - EXCEPTION_BLOCK(v8::Local<v8::Value>, value, sqlArgsObject->Get(key)); + V8TRYCATCH(v8::Local<v8::Value>, value, sqlArgsObject->Get(key)); if (value.IsEmpty() || value->IsNull()) sqlValues.append(SQLValue()); else if (value->IsNumber()) { - EXCEPTION_BLOCK(double, sqlValue, value->NumberValue()); + V8TRYCATCH(double, sqlValue, value->NumberValue()); sqlValues.append(SQLValue(sqlValue)); } else { - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, sqlValue, value); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, sqlValue, value); sqlValues.append(SQLValue(sqlValue)); } } diff --git a/Source/WebCore/bindings/v8/custom/V8SVGLengthCustom.cpp b/Source/WebCore/bindings/v8/custom/V8SVGLengthCustom.cpp index f494adcb0..83185bf49 100644 --- a/Source/WebCore/bindings/v8/custom/V8SVGLengthCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8SVGLengthCustom.cpp @@ -89,7 +89,7 @@ v8::Handle<v8::Value> V8SVGLength::convertToSpecifiedUnitsCallback(const v8::Arg SVGLength& imp = wrapper->propertyReference(); ExceptionCode ec = 0; - EXCEPTION_BLOCK(int, unitType, toUInt32(args[0])); + V8TRYCATCH(int, unitType, toUInt32(args[0])); SVGLengthContext lengthContext(wrapper->contextElement()); imp.convertToSpecifiedUnits(unitType, lengthContext, ec); if (UNLIKELY(ec)) diff --git a/Source/WebCore/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp b/Source/WebCore/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp index 4156832d2..4c43c0f6d 100644 --- a/Source/WebCore/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp @@ -308,7 +308,7 @@ v8::Handle<v8::Value> V8WebGLRenderingContext::getExtensionCallback(const v8::Ar WebGLRenderingContext* imp = V8WebGLRenderingContext::toNative(args.Holder()); if (args.Length() < 1) return throwNotEnoughArgumentsError(args.GetIsolate()); - STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, args[0]); + V8TRYCATCH_FOR_V8STRINGRESOURCE(V8StringResource<>, name, args[0]); WebGLExtension* extension = imp->getExtension(name); return toV8Object(extension, args.Holder(), args.GetIsolate()); } diff --git a/Source/WebCore/bindings/v8/custom/V8WorkerContextCustom.cpp b/Source/WebCore/bindings/v8/custom/V8WorkerContextCustom.cpp index 58aa1ea9d..149912ae1 100644 --- a/Source/WebCore/bindings/v8/custom/V8WorkerContextCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8WorkerContextCustom.cpp @@ -43,7 +43,7 @@ #include "V8WorkerContextEventListener.h" #include "WebSocket.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" +#include "WorkerScriptController.h" namespace WebCore { @@ -59,11 +59,11 @@ v8::Handle<v8::Value> SetTimeoutOrInterval(const v8::Arguments& args, bool singl int32_t timeout = argumentCount >= 2 ? args[1]->Int32Value() : 0; int timerId; - WorkerContextExecutionProxy* proxy = workerContext->script()->proxy(); - if (!proxy) + WorkerScriptController* script = workerContext->script(); + if (!script) return v8::Undefined(); - v8::Handle<v8::Context> v8Context = proxy->context(); + v8::Handle<v8::Context> v8Context = script->context(); if (function->IsString()) { if (ContentSecurityPolicy* policy = workerContext->contentSecurityPolicy()) { if (!policy->allowEval()) @@ -98,7 +98,7 @@ v8::Handle<v8::Value> V8WorkerContext::importScriptsCallback(const v8::Arguments Vector<String> urls; for (int i = 0; i < args.Length(); i++) { - EXCEPTION_BLOCK(v8::Handle<v8::String>, scriptUrl, args[i]->ToString()); + V8TRYCATCH(v8::Handle<v8::String>, scriptUrl, args[i]->ToString()); if (scriptUrl.IsEmpty()) return v8::Undefined(); urls.append(toWebCoreString(scriptUrl)); @@ -134,11 +134,11 @@ v8::Handle<v8::Value> toV8(WorkerContext* impl, v8::Handle<v8::Object> creationC if (!impl) return v8NullWithCheck(isolate); - WorkerContextExecutionProxy* proxy = impl->script()->proxy(); - if (!proxy) + WorkerScriptController* script = impl->script(); + if (!script) return v8NullWithCheck(isolate); - v8::Handle<v8::Object> global = proxy->context()->Global(); + v8::Handle<v8::Object> global = script->context()->Global(); ASSERT(!global.IsEmpty()); return global; } diff --git a/Source/WebCore/bindings/v8/custom/V8WorkerCustom.cpp b/Source/WebCore/bindings/v8/custom/V8WorkerCustom.cpp index 0c105fee5..e45581914 100644 --- a/Source/WebCore/bindings/v8/custom/V8WorkerCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8WorkerCustom.cpp @@ -42,7 +42,6 @@ #include "V8Binding.h" #include "V8Utilities.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" namespace WebCore { diff --git a/Source/WebCore/bindings/v8/custom/V8XMLHttpRequestCustom.cpp b/Source/WebCore/bindings/v8/custom/V8XMLHttpRequestCustom.cpp index 9218f6a9e..f82067830 100644 --- a/Source/WebCore/bindings/v8/custom/V8XMLHttpRequestCustom.cpp +++ b/Source/WebCore/bindings/v8/custom/V8XMLHttpRequestCustom.cpp @@ -44,7 +44,6 @@ #include "V8HTMLDocument.h" #include "V8Utilities.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" #include "XMLHttpRequest.h" namespace WebCore { diff --git a/Source/WebCore/bridge/objc/objc_header.h b/Source/WebCore/bridge/objc/objc_header.h index 07954a1a1..2c9c69014 100644 --- a/Source/WebCore/bridge/objc/objc_header.h +++ b/Source/WebCore/bridge/objc/objc_header.h @@ -30,7 +30,7 @@ #include <objc/objc.h> #include <objc/objc-class.h> -#include <objc/objc-runtime.h> +#include <objc/runtime.h> typedef Class ClassStructPtr; typedef id ObjectStructPtr; diff --git a/Source/WebCore/css/CSSComputedStyleDeclaration.cpp b/Source/WebCore/css/CSSComputedStyleDeclaration.cpp index b127aa96a..4bc7b084f 100644 --- a/Source/WebCore/css/CSSComputedStyleDeclaration.cpp +++ b/Source/WebCore/css/CSSComputedStyleDeclaration.cpp @@ -296,7 +296,6 @@ static const CSSPropertyID computedProperties[] = { CSSPropertyWebkitMarqueeIncrement, CSSPropertyWebkitMarqueeRepetition, CSSPropertyWebkitMarqueeStyle, - CSSPropertyWebkitMaskAttachment, CSSPropertyWebkitMaskBoxImage, CSSPropertyWebkitMaskBoxImageOutset, CSSPropertyWebkitMaskBoxImageRepeat, @@ -1540,9 +1539,8 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert return list.release(); } - case CSSPropertyBackgroundAttachment: - case CSSPropertyWebkitMaskAttachment: { - const FillLayer* layers = propertyID == CSSPropertyWebkitMaskAttachment ? style->maskLayers() : style->backgroundLayers(); + case CSSPropertyBackgroundAttachment: { + const FillLayer* layers = style->backgroundLayers(); if (!layers->next()) return cssValuePool().createValue(layers->attachment()); @@ -1715,9 +1713,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert case CSSPropertyWebkitColumnRuleWidth: return zoomAdjustedPixelValue(style->columnRuleWidth(), style.get()); case CSSPropertyWebkitColumnSpan: - if (style->columnSpan()) - return cssValuePool().createIdentifierValue(CSSValueAll); - return cssValuePool().createValue(1, CSSPrimitiveValue::CSS_NUMBER); + return cssValuePool().createIdentifierValue(style->columnSpan() ? CSSValueAll : CSSValueNone); case CSSPropertyWebkitColumnBreakAfter: return cssValuePool().createValue(style->columnBreakAfter()); case CSSPropertyWebkitColumnBreakBefore: diff --git a/Source/WebCore/css/CSSParser.cpp b/Source/WebCore/css/CSSParser.cpp index 7ca155c5b..43a89e424 100644 --- a/Source/WebCore/css/CSSParser.cpp +++ b/Source/WebCore/css/CSSParser.cpp @@ -1086,8 +1086,16 @@ static bool parseKeywordValue(StylePropertySet* declaration, CSSPropertyID prope { ASSERT(!string.isEmpty()); - if (!isKeywordPropertyID(propertyId)) - return false; + if (!isKeywordPropertyID(propertyId)) { + // All properties accept the values of "initial" and "inherit". + String lowerCaseString = string.lower(); + if (lowerCaseString != "initial" && lowerCaseString != "inherit") + return false; + + // Parse initial/inherit shorthands using the CSSParser. + if (shorthandForProperty(propertyId).length()) + return false; + } CSSParserString cssString; cssString.init(string); @@ -1689,6 +1697,22 @@ inline PassRefPtr<CSSPrimitiveValue> CSSParser::parseValidPrimitive(int identifi return 0; } +void CSSParser::addExpandedPropertyForValue(CSSPropertyID propId, PassRefPtr<CSSValue> prpValue, bool important) +{ + const StylePropertyShorthand& shorthand = shorthandForProperty(propId); + unsigned shorthandLength = shorthand.length(); + if (!shorthandLength) { + addProperty(propId, prpValue, important); + return; + } + + RefPtr<CSSValue> value = prpValue; + ShorthandScope scope(this, propId); + const CSSPropertyID* longhands = shorthand.properties(); + for (unsigned i = 0; i < shorthandLength; ++i) + addProperty(longhands[i], value, important); +} + bool CSSParser::parseValue(CSSPropertyID propId, bool important) { if (!m_valueList) @@ -1710,13 +1734,13 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important) if (id == CSSValueInherit) { if (num != 1) return false; - addProperty(propId, cssValuePool().createInheritedValue(), important); + addExpandedPropertyForValue(propId, cssValuePool().createInheritedValue(), important); return true; } else if (id == CSSValueInitial) { if (num != 1) return false; - addProperty(propId, cssValuePool().createExplicitInitialValue(), important); + addExpandedPropertyForValue(propId, cssValuePool().createExplicitInitialValue(), important); return true; } @@ -1947,7 +1971,6 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important) case CSSPropertyBackgroundRepeat: case CSSPropertyBackgroundRepeatX: case CSSPropertyBackgroundRepeatY: - case CSSPropertyWebkitMaskAttachment: case CSSPropertyWebkitMaskClip: case CSSPropertyWebkitMaskComposite: case CSSPropertyWebkitMaskImage: @@ -2497,8 +2520,8 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important) if (id == CSSValueNormal || id == CSSValueReverse) validPrimitive = true; break; - case CSSPropertyWebkitColumnSpan: // all | 1 - if (id == CSSValueAll) + case CSSPropertyWebkitColumnSpan: // none | all | 1 (will be dropped in the unprefixed property) + if (id == CSSValueAll || id == CSSValueNone) validPrimitive = true; else validPrimitive = validUnit(value, FNumber | FNonNeg) && value->fValue == 1; @@ -2599,9 +2622,8 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important) } case CSSPropertyWebkitMask: { const CSSPropertyID properties[] = { CSSPropertyWebkitMaskImage, CSSPropertyWebkitMaskRepeat, - CSSPropertyWebkitMaskAttachment, CSSPropertyWebkitMaskPosition, - CSSPropertyWebkitMaskOrigin, CSSPropertyWebkitMaskClip }; - return parseFillShorthand(propId, properties, 6, important); + CSSPropertyWebkitMaskPosition, CSSPropertyWebkitMaskOrigin, CSSPropertyWebkitMaskClip, CSSPropertyWebkitMaskSize }; + return parseFillShorthand(propId, properties, WTF_ARRAY_LENGTH(properties), important); } case CSSPropertyBorder: // [ 'border-width' || 'border-style' || <color> ] | inherit @@ -2948,7 +2970,7 @@ bool CSSParser::parseFillShorthand(CSSPropertyID propId, const CSSPropertyID* pr RefPtr<CSSValue> repeatYValue; bool foundClip = false; int i; - bool foundBackgroundPositionCSSProperty = false; + bool foundPositionCSSProperty = false; while (m_valueList->current()) { CSSParserValue* val = m_valueList->current(); @@ -2978,19 +3000,19 @@ bool CSSParser::parseFillShorthand(CSSPropertyID propId, const CSSPropertyID* pr break; } - bool backgroundSizeCSSPropertyExpected = false; - if ((val->unit == CSSParserValue::Operator && val->iValue == '/') && foundBackgroundPositionCSSProperty) { - backgroundSizeCSSPropertyExpected = true; + bool sizeCSSPropertyExpected = false; + if ((val->unit == CSSParserValue::Operator && val->iValue == '/') && foundPositionCSSProperty) { + sizeCSSPropertyExpected = true; m_valueList->next(); } - foundBackgroundPositionCSSProperty = false; + foundPositionCSSProperty = false; bool found = false; for (i = 0; !found && i < numProperties; ++i) { - if (backgroundSizeCSSPropertyExpected && properties[i] != CSSPropertyBackgroundSize) + if (sizeCSSPropertyExpected && (properties[i] != CSSPropertyBackgroundSize && properties[i] != CSSPropertyWebkitMaskSize)) continue; - if (!backgroundSizeCSSPropertyExpected && properties[i] == CSSPropertyBackgroundSize) + if (!sizeCSSPropertyExpected && (properties[i] == CSSPropertyBackgroundSize || properties[i] == CSSPropertyWebkitMaskSize)) continue; if (!parsedProperty[i]) { @@ -3017,8 +3039,8 @@ bool CSSParser::parseFillShorthand(CSSPropertyID propId, const CSSPropertyID* pr addFillValue(clipValue, val1.release()); foundClip = true; } - if (properties[i] == CSSPropertyBackgroundPosition) - foundBackgroundPositionCSSProperty = true; + if (properties[i] == CSSPropertyBackgroundPosition || properties[i] == CSSPropertyWebkitMaskPosition) + foundPositionCSSProperty = true; } } } @@ -3038,7 +3060,7 @@ bool CSSParser::parseFillShorthand(CSSPropertyID propId, const CSSPropertyID* pr addFillValue(positionYValue, cssValuePool().createImplicitInitialValue()); if (properties[i] == CSSPropertyBackgroundRepeat || properties[i] == CSSPropertyWebkitMaskRepeat) addFillValue(repeatYValue, cssValuePool().createImplicitInitialValue()); - if ((properties[i] == CSSPropertyBackgroundOrigin || properties[i] == CSSPropertyWebkitMaskOrigin)) { + if (properties[i] == CSSPropertyBackgroundOrigin || properties[i] == CSSPropertyWebkitMaskOrigin) { // If background-origin wasn't present, then reset background-clip also. addFillValue(clipValue, cssValuePool().createImplicitInitialValue()); } @@ -4067,7 +4089,6 @@ bool CSSParser::parseFillProperty(CSSPropertyID propId, CSSPropertyID& propId1, m_valueList->next(); break; case CSSPropertyBackgroundAttachment: - case CSSPropertyWebkitMaskAttachment: if (val->id == CSSValueScroll || val->id == CSSValueFixed || val->id == CSSValueLocal) { currValue = cssValuePool().createIdentifierValue(val->id); m_valueList->next(); diff --git a/Source/WebCore/css/CSSParser.h b/Source/WebCore/css/CSSParser.h index 2b0d85419..d12f72bc5 100644 --- a/Source/WebCore/css/CSSParser.h +++ b/Source/WebCore/css/CSSParser.h @@ -92,6 +92,7 @@ public: void addProperty(CSSPropertyID, PassRefPtr<CSSValue>, bool important, bool implicit = false); void rollbackLastProperties(int num); bool hasProperties() const { return !m_parsedProperties.isEmpty(); } + void addExpandedPropertyForValue(CSSPropertyID propId, PassRefPtr<CSSValue>, bool); bool parseValue(CSSPropertyID, bool important); bool parseShorthand(CSSPropertyID, const StylePropertyShorthand&, bool important); diff --git a/Source/WebCore/css/CSSPrimitiveValueMappings.h b/Source/WebCore/css/CSSPrimitiveValueMappings.h index 22f9fb707..db10acadd 100644 --- a/Source/WebCore/css/CSSPrimitiveValueMappings.h +++ b/Source/WebCore/css/CSSPrimitiveValueMappings.h @@ -149,26 +149,32 @@ template<> inline CSSPrimitiveValue::operator LineClampValue() const template<> inline CSSPrimitiveValue::CSSPrimitiveValue(ColumnSpan columnSpan) : CSSValue(PrimitiveClass) { + m_primitiveUnitType = CSS_IDENT; switch (columnSpan) { case ColumnSpanAll: - m_primitiveUnitType = CSS_IDENT; m_value.ident = CSSValueAll; break; - case ColumnSpanOne: - m_primitiveUnitType = CSS_NUMBER; - m_value.num = 1; + case ColumnSpanNone: + m_value.ident = CSSValueNone; break; } } template<> inline CSSPrimitiveValue::operator ColumnSpan() const { - if (m_primitiveUnitType == CSS_IDENT && m_value.ident == CSSValueAll) - return ColumnSpanAll; + // Map 1 to none for compatibility reasons. if (m_primitiveUnitType == CSS_NUMBER && m_value.num == 1) - return ColumnSpanOne; + return ColumnSpanNone; + + switch (m_value.ident) { + case CSSValueAll: + return ColumnSpanAll; + case CSSValueNone: + return ColumnSpanNone; + } + ASSERT_NOT_REACHED(); - return ColumnSpanOne; + return ColumnSpanNone; } diff --git a/Source/WebCore/css/CSSProperty.cpp b/Source/WebCore/css/CSSProperty.cpp index 6128a1097..13d0b19e3 100644 --- a/Source/WebCore/css/CSSProperty.cpp +++ b/Source/WebCore/css/CSSProperty.cpp @@ -596,7 +596,6 @@ bool CSSProperty::isInheritedProperty(CSSPropertyID propertyID) case CSSPropertyWebkitMarqueeSpeed: case CSSPropertyWebkitMarqueeStyle: case CSSPropertyWebkitMask: - case CSSPropertyWebkitMaskAttachment: case CSSPropertyWebkitMaskBoxImage: case CSSPropertyWebkitMaskBoxImageOutset: case CSSPropertyWebkitMaskBoxImageRepeat: diff --git a/Source/WebCore/css/CSSPropertyNames.in b/Source/WebCore/css/CSSPropertyNames.in index ca359b521..d958c6b69 100644 --- a/Source/WebCore/css/CSSPropertyNames.in +++ b/Source/WebCore/css/CSSPropertyNames.in @@ -318,7 +318,6 @@ z-index -webkit-marquee-speed -webkit-marquee-style -webkit-mask --webkit-mask-attachment -webkit-mask-box-image -webkit-mask-box-image-outset -webkit-mask-box-image-repeat diff --git a/Source/WebCore/css/SelectorChecker.cpp b/Source/WebCore/css/SelectorChecker.cpp index 38d41f784..d4841ca02 100644 --- a/Source/WebCore/css/SelectorChecker.cpp +++ b/Source/WebCore/css/SelectorChecker.cpp @@ -523,10 +523,9 @@ SelectorChecker::SelectorMatch SelectorChecker::checkSelector(const SelectorChec return checkSelector(nextContext, ignoreDynamicPseudo); case CSSSelector::DirectAdjacent: - if (m_mode == ResolvingStyle && context.element->parentElement()) { - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : context.element->parentNode()->renderStyle(); - if (parentStyle) - parentStyle->setChildrenAffectedByDirectAdjacentRules(); + if (m_mode == ResolvingStyle) { + if (Element* parentElement = context.element->parentElement()) + parentElement->setChildrenAffectedByDirectAdjacentRules(); } nextContext.element = context.element->previousElementSibling(); if (!nextContext.element) @@ -537,10 +536,9 @@ SelectorChecker::SelectorMatch SelectorChecker::checkSelector(const SelectorChec return checkSelector(nextContext, ignoreDynamicPseudo); case CSSSelector::IndirectAdjacent: - if (m_mode == ResolvingStyle && context.element->parentElement()) { - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : context.element->parentNode()->renderStyle(); - if (parentStyle) - parentStyle->setChildrenAffectedByForwardPositionalRules(); + if (m_mode == ResolvingStyle) { + if (Element* parentElement = context.element->parentElement()) + parentElement->setChildrenAffectedByForwardPositionalRules(); } nextContext.element = context.element->previousElementSibling(); nextContext.isSubSelector = false; @@ -814,6 +812,7 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c } } if (m_mode == ResolvingStyle) { + element->setStyleAffectedByEmpty(); if (context.elementStyle) context.elementStyle->setEmptyState(result); else if (element->renderStyle() && (element->document()->styleSheetCollection()->usesSiblingRules() || element->renderStyle()->unique())) @@ -823,13 +822,11 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c } case CSSSelector::PseudoFirstChild: // first-child matches the first child that is an element - if (element->parentElement()) { + if (Element* parentElement = element->parentElement()) { bool result = siblingTraversalStrategy.isFirstChild(element); if (m_mode == ResolvingStyle) { RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle(); - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : element->parentNode()->renderStyle(); - if (parentStyle) - parentStyle->setChildrenAffectedByFirstChildRules(); + parentElement->setChildrenAffectedByFirstChildRules(); if (result && childStyle) childStyle->setFirstChildState(); } @@ -838,13 +835,10 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c break; case CSSSelector::PseudoFirstOfType: // first-of-type matches the first element of its type - if (element->parentElement()) { + if (Element* parentElement = element->parentElement()) { bool result = siblingTraversalStrategy.isFirstOfType(element, element->tagQName()); - if (m_mode == ResolvingStyle) { - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : element->parentNode()->renderStyle(); - if (parentStyle) - parentStyle->setChildrenAffectedByForwardPositionalRules(); - } + if (m_mode == ResolvingStyle) + parentElement->setChildrenAffectedByForwardPositionalRules(); return result; } break; @@ -854,9 +848,7 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c bool result = parentElement->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element); if (m_mode == ResolvingStyle) { RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle(); - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : parentElement->renderStyle(); - if (parentStyle) - parentStyle->setChildrenAffectedByLastChildRules(); + parentElement->setChildrenAffectedByLastChildRules(); if (result && childStyle) childStyle->setLastChildState(); } @@ -866,11 +858,8 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c case CSSSelector::PseudoLastOfType: // last-of-type matches the last element of its type if (Element* parentElement = element->parentElement()) { - if (m_mode == ResolvingStyle) { - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : parentElement->renderStyle(); - if (parentStyle) - parentStyle->setChildrenAffectedByBackwardPositionalRules(); - } + if (m_mode == ResolvingStyle) + parentElement->setChildrenAffectedByBackwardPositionalRules(); if (!parentElement->isFinishedParsingChildren()) return false; return siblingTraversalStrategy.isLastOfType(element, element->tagQName()); @@ -882,11 +871,8 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c bool onlyChild = firstChild && parentElement->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element); if (m_mode == ResolvingStyle) { RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle(); - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : parentElement->renderStyle(); - if (parentStyle) { - parentStyle->setChildrenAffectedByFirstChildRules(); - parentStyle->setChildrenAffectedByLastChildRules(); - } + parentElement->setChildrenAffectedByFirstChildRules(); + parentElement->setChildrenAffectedByLastChildRules(); if (firstChild && childStyle) childStyle->setFirstChildState(); if (onlyChild && childStyle) @@ -899,11 +885,8 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c // FIXME: This selector is very slow. if (Element* parentElement = element->parentElement()) { if (m_mode == ResolvingStyle) { - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : parentElement->renderStyle(); - if (parentStyle) { - parentStyle->setChildrenAffectedByForwardPositionalRules(); - parentStyle->setChildrenAffectedByBackwardPositionalRules(); - } + parentElement->setChildrenAffectedByForwardPositionalRules(); + parentElement->setChildrenAffectedByBackwardPositionalRules(); } if (!parentElement->isFinishedParsingChildren()) return false; @@ -917,11 +900,10 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c int count = 1 + siblingTraversalStrategy.countElementsBefore(element); if (m_mode == ResolvingStyle) { RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle(); - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : parentElement->renderStyle(); + element->setChildIndex(count); if (childStyle) - childStyle->setChildIndex(count); - if (parentStyle) - parentStyle->setChildrenAffectedByForwardPositionalRules(); + childStyle->setUnique(); + parentElement->setChildrenAffectedByForwardPositionalRules(); } if (selector->matchNth(count)) @@ -933,11 +915,8 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c break; if (Element* parentElement = element->parentElement()) { int count = 1 + siblingTraversalStrategy.countElementsOfTypeBefore(element, element->tagQName()); - if (m_mode == ResolvingStyle) { - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : parentElement->renderStyle(); - if (parentStyle) - parentStyle->setChildrenAffectedByForwardPositionalRules(); - } + if (m_mode == ResolvingStyle) + parentElement->setChildrenAffectedByForwardPositionalRules(); if (selector->matchNth(count)) return true; @@ -947,11 +926,8 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c if (!selector->parseNth()) break; if (Element* parentElement = element->parentElement()) { - if (m_mode == ResolvingStyle) { - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : parentElement->renderStyle(); - if (parentStyle) - parentStyle->setChildrenAffectedByBackwardPositionalRules(); - } + if (m_mode == ResolvingStyle) + parentElement->setChildrenAffectedByBackwardPositionalRules(); if (!parentElement->isFinishedParsingChildren()) return false; int count = 1 + siblingTraversalStrategy.countElementsAfter(element); @@ -963,11 +939,8 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c if (!selector->parseNth()) break; if (Element* parentElement = element->parentElement()) { - if (m_mode == ResolvingStyle) { - RenderStyle* parentStyle = context.elementStyle ? context.elementParentStyle : parentElement->renderStyle(); - if (parentStyle) - parentStyle->setChildrenAffectedByBackwardPositionalRules(); - } + if (m_mode == ResolvingStyle) + parentElement->setChildrenAffectedByBackwardPositionalRules(); if (!parentElement->isFinishedParsingChildren()) return false; @@ -1005,10 +978,12 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c // ...except if :visited matching is disabled for ancestor/sibling matching. return element->isLink() && context.visitedMatchType == VisitedMatchEnabled; case CSSSelector::PseudoDrag: - if (context.elementStyle) - context.elementStyle->setAffectedByDragRules(true); - else if (element->renderStyle()) - element->renderStyle()->setAffectedByDragRules(true); + if (m_mode == ResolvingStyle) { + if (context.elementStyle) + context.elementStyle->setAffectedByDrag(); + else + element->setChildrenAffectedByDrag(true); + } if (element->renderer() && element->renderer()->isDragging()) return true; break; @@ -1018,10 +993,12 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c // If we're in quirks mode, then hover should never match anchors with no // href and *:hover should not match anything. This is important for sites like wsj.com. if (m_strictParsing || context.isSubSelector || (selector->hasTag() && !element->hasTagName(aTag)) || element->isLink()) { - if (context.elementStyle) - context.elementStyle->setAffectedByHoverRules(true); - else if (element->renderStyle()) - element->renderStyle()->setAffectedByHoverRules(true); + if (m_mode == ResolvingStyle) { + if (context.elementStyle) + context.elementStyle->setAffectedByHover(); + else + element->setChildrenAffectedByHover(true); + } if (element->hovered() || InspectorInstrumentation::forcePseudoState(element, CSSSelector::PseudoHover)) return true; } @@ -1030,10 +1007,12 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c // If we're in quirks mode, then :active should never match anchors with no // href and *:active should not match anything. if (m_strictParsing || context.isSubSelector || (selector->hasTag() && !element->hasTagName(aTag)) || element->isLink()) { - if (context.elementStyle) - context.elementStyle->setAffectedByActiveRules(true); - else if (element->renderStyle()) - element->renderStyle()->setAffectedByActiveRules(true); + if (m_mode == ResolvingStyle) { + if (context.elementStyle) + context.elementStyle->setAffectedByActive(); + else + element->setChildrenAffectedByActive(true); + } if (element->active() || InspectorInstrumentation::forcePseudoState(element, CSSSelector::PseudoActive)) return true; } @@ -1052,13 +1031,9 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c return !element->isEnabledFormControl(); break; case CSSSelector::PseudoReadOnly: - if (!element || !element->isFormControlElement()) - return false; - return element->isTextFormControl() && element->shouldMatchReadOnlySelector(); + return element && element->shouldMatchReadOnlySelector(); case CSSSelector::PseudoReadWrite: - if (!element || !element->isFormControlElement()) - return false; - return element->isTextFormControl() && element->shouldMatchReadWriteSelector(); + return element && element->shouldMatchReadWriteSelector(); case CSSSelector::PseudoOptional: return element && element->isOptionalFormControl(); case CSSSelector::PseudoRequired: @@ -1072,7 +1047,7 @@ bool SelectorChecker::checkOneSelector(const SelectorCheckingContext& context, c if (!element) return false; element->document()->setContainsValidityStyleRules(); - return (element->willValidate() && !element->isValidFormControlElement()) || element->hasUnacceptableValue(); + return element->willValidate() && !element->isValidFormControlElement(); case CSSSelector::PseudoChecked: { if (!element) diff --git a/Source/WebCore/css/SiblingTraversalStrategies.h b/Source/WebCore/css/SiblingTraversalStrategies.h index e583e6c13..bebfef8e5 100644 --- a/Source/WebCore/css/SiblingTraversalStrategies.h +++ b/Source/WebCore/css/SiblingTraversalStrategies.h @@ -80,8 +80,7 @@ inline int DOMSiblingTraversalStrategy::countElementsBefore(Element* element) co { int count = 0; for (const Element* sibling = element->previousElementSibling(); sibling; sibling = sibling->previousElementSibling()) { - RenderStyle* s = sibling->renderStyle(); - unsigned index = s ? s->childIndex() : 0; + unsigned index = sibling->childIndex(); if (index) { count += index; break; diff --git a/Source/WebCore/css/StyleBuilder.cpp b/Source/WebCore/css/StyleBuilder.cpp index 968b96f84..ea4766f5b 100644 --- a/Source/WebCore/css/StyleBuilder.cpp +++ b/Source/WebCore/css/StyleBuilder.cpp @@ -2021,7 +2021,6 @@ StyleBuilder::StyleBuilder() setPropertyHandler(CSSPropertyWebkitMarginTopCollapse, CSSPropertyWebkitMarginBeforeCollapse); setPropertyHandler(CSSPropertyWebkitMarqueeDirection, ApplyPropertyDefault<EMarqueeDirection, &RenderStyle::marqueeDirection, EMarqueeDirection, &RenderStyle::setMarqueeDirection, EMarqueeDirection, &RenderStyle::initialMarqueeDirection>::createHandler()); setPropertyHandler(CSSPropertyWebkitMarqueeStyle, ApplyPropertyDefault<EMarqueeBehavior, &RenderStyle::marqueeBehavior, EMarqueeBehavior, &RenderStyle::setMarqueeBehavior, EMarqueeBehavior, &RenderStyle::initialMarqueeBehavior>::createHandler()); - setPropertyHandler(CSSPropertyWebkitMaskAttachment, ApplyPropertyFillLayer<EFillAttachment, CSSPropertyWebkitMaskAttachment, MaskFillLayer, &RenderStyle::accessMaskLayers, &RenderStyle::maskLayers, &FillLayer::isAttachmentSet, &FillLayer::attachment, &FillLayer::setAttachment, &FillLayer::clearAttachment, &FillLayer::initialFillAttachment, &CSSToStyleMap::mapFillAttachment>::createHandler()); setPropertyHandler(CSSPropertyWebkitMaskBoxImage, ApplyPropertyBorderImage<BorderMask, CSSPropertyWebkitMaskBoxImage, &RenderStyle::maskBoxImage, &RenderStyle::setMaskBoxImage>::createHandler()); setPropertyHandler(CSSPropertyWebkitMaskBoxImageOutset, ApplyPropertyBorderImageModifier<BorderMask, Outset>::createHandler()); setPropertyHandler(CSSPropertyWebkitMaskBoxImageRepeat, ApplyPropertyBorderImageModifier<BorderMask, Repeat>::createHandler()); diff --git a/Source/WebCore/css/StylePropertySet.cpp b/Source/WebCore/css/StylePropertySet.cpp index c3f6dc80d..f662ccacf 100644 --- a/Source/WebCore/css/StylePropertySet.cpp +++ b/Source/WebCore/css/StylePropertySet.cpp @@ -60,6 +60,13 @@ static size_t sizeForImmutableStylePropertySetWithPropertyCount(unsigned count) return sizeof(ImmutableStylePropertySet) - sizeof(void*) + sizeof(CSSValue*) * count + sizeof(StylePropertyMetadata) * count; } +static bool isInitialOrInherit(const String& value) +{ + DEFINE_STATIC_LOCAL(String, initial, ("initial")); + DEFINE_STATIC_LOCAL(String, inherit, ("inherit")); + return value.length() == 7 && (value == initial || value == inherit); +} + PassRefPtr<StylePropertySet> StylePropertySet::createImmutable(const CSSProperty* properties, unsigned count, CSSParserMode cssParserMode) { void* slot = WTF::fastMalloc(sizeForImmutableStylePropertySetWithPropertyCount(count)); @@ -218,14 +225,16 @@ String StylePropertySet::borderSpacingValue(const StylePropertyShorthand& shorth return horizontalValueCSSText + ' ' + verticalValueCSSText; } -bool StylePropertySet::appendFontLonghandValueIfExplicit(CSSPropertyID propertyID, StringBuilder& result) const +bool StylePropertySet::appendFontLonghandValueIfExplicit(CSSPropertyID propertyID, StringBuilder& result, String& commonValue) const { int foundPropertyIndex = findPropertyIndex(propertyID); if (foundPropertyIndex == -1) return false; // All longhands must have at least implicit values if "font" is specified. - if (propertyAt(foundPropertyIndex).isImplicit()) + if (propertyAt(foundPropertyIndex).isImplicit()) { + commonValue = String(); return true; + } char prefix = '\0'; switch (propertyID) { @@ -245,7 +254,10 @@ bool StylePropertySet::appendFontLonghandValueIfExplicit(CSSPropertyID propertyI if (prefix && !result.isEmpty()) result.append(prefix); - result.append(propertyAt(foundPropertyIndex).value()->cssText()); + String value = propertyAt(foundPropertyIndex).value()->cssText(); + result.append(value); + if (!commonValue.isNull() && commonValue != value) + commonValue = String(); return true; } @@ -260,22 +272,25 @@ String StylePropertySet::fontValue() const if (fontSizeProperty.isImplicit()) return emptyString(); + String commonValue = fontSizeProperty.value()->cssText(); StringBuilder result; bool success = true; - success &= appendFontLonghandValueIfExplicit(CSSPropertyFontStyle, result); - success &= appendFontLonghandValueIfExplicit(CSSPropertyFontVariant, result); - success &= appendFontLonghandValueIfExplicit(CSSPropertyFontWeight, result); + success &= appendFontLonghandValueIfExplicit(CSSPropertyFontStyle, result, commonValue); + success &= appendFontLonghandValueIfExplicit(CSSPropertyFontVariant, result, commonValue); + success &= appendFontLonghandValueIfExplicit(CSSPropertyFontWeight, result, commonValue); if (!result.isEmpty()) result.append(' '); result.append(fontSizeProperty.value()->cssText()); - success &= appendFontLonghandValueIfExplicit(CSSPropertyLineHeight, result); - success &= appendFontLonghandValueIfExplicit(CSSPropertyFontFamily, result); + success &= appendFontLonghandValueIfExplicit(CSSPropertyLineHeight, result, commonValue); + success &= appendFontLonghandValueIfExplicit(CSSPropertyFontFamily, result, commonValue); if (!success) { // An invalid "font" value has been built (should never happen, as at least implicit values // for mandatory longhands are always found in the style), report empty value instead. ASSERT_NOT_REACHED(); return emptyString(); } + if (isInitialOrInherit(commonValue)) + return commonValue; return result.toString(); } @@ -298,8 +313,17 @@ String StylePropertySet::get4Values(const StylePropertyShorthand& shorthand) con // All 4 properties must be specified. if (!top.value() || !right.value() || !bottom.value() || !left.value()) return String(); - if (top.value()->isInitialValue() || right.value()->isInitialValue() || bottom.value()->isInitialValue() || left.value()->isInitialValue()) + + if (top.isInherited() && right.isInherited() && bottom.isInherited() && left.isInherited()) + return getValueName(CSSValueInherit); + + if (top.value()->isInitialValue() || right.value()->isInitialValue() || bottom.value()->isInitialValue() || left.value()->isInitialValue()) { + if (top.value()->isInitialValue() && right.value()->isInitialValue() && bottom.value()->isInitialValue() && left.value()->isInitialValue() && !top.isImplicit()) { + // All components are "initial" and "top" is not implicit. + return getValueName(CSSValueInitial); + } return String(); + } if (top.isImportant() != right.isImportant() || right.isImportant() != bottom.isImportant() || bottom.isImportant() != left.isImportant()) return String(); @@ -344,6 +368,9 @@ String StylePropertySet::getLayeredShorthandValue(const StylePropertyShorthand& } } + String commonValue; + bool commonValueInitialized = false; + // Now stitch the properties together. Implicit initial values are flagged as such and // can safely be omitted. for (size_t i = 0; i < numLayers; i++) { @@ -351,7 +378,7 @@ String StylePropertySet::getLayeredShorthandValue(const StylePropertyShorthand& bool useRepeatXShorthand = false; bool useRepeatYShorthand = false; bool useSingleWordShorthand = false; - bool foundBackgroundPositionYCSSProperty = false; + bool foundPositionYCSSProperty = false; for (unsigned j = 0; j < size; j++) { RefPtr<CSSValue> value; if (values[j]) { @@ -372,10 +399,12 @@ String StylePropertySet::getLayeredShorthandValue(const StylePropertyShorthand& // We need to report background-repeat as it was written in the CSS. If the property is implicit, // then it was written with only one value. Here we figure out which value that was so we can // report back correctly. - if (shorthand.properties()[j] == CSSPropertyBackgroundRepeatX && isPropertyImplicit(shorthand.properties()[j])) { + if ((shorthand.properties()[j] == CSSPropertyBackgroundRepeatX && isPropertyImplicit(shorthand.properties()[j])) + || (shorthand.properties()[j] == CSSPropertyWebkitMaskRepeatX && isPropertyImplicit(shorthand.properties()[j]))) { // BUG 49055: make sure the value was not reset in the layer check just above. - if (j < size - 1 && shorthand.properties()[j + 1] == CSSPropertyBackgroundRepeatY && value) { + if ((j < size - 1 && shorthand.properties()[j + 1] == CSSPropertyBackgroundRepeatY && value) + || (j < size - 1 && shorthand.properties()[j + 1] == CSSPropertyWebkitMaskRepeatY && value)) { RefPtr<CSSValue> yValue; RefPtr<CSSValue> nextValue = values[j + 1]; if (nextValue->isValueList()) @@ -400,12 +429,15 @@ String StylePropertySet::getLayeredShorthandValue(const StylePropertyShorthand& } } + String valueText; if (value && !value->isImplicitInitialValue()) { if (!layerResult.isEmpty()) layerResult.append(' '); - if (foundBackgroundPositionYCSSProperty && shorthand.properties()[j] == CSSPropertyBackgroundSize) + if (foundPositionYCSSProperty + && (shorthand.properties()[j] == CSSPropertyBackgroundSize || shorthand.properties()[j] == CSSPropertyWebkitMaskSize)) layerResult.appendLiteral("/ "); - if (!foundBackgroundPositionYCSSProperty && shorthand.properties()[j] == CSSPropertyBackgroundSize) + if (!foundPositionYCSSProperty + && (shorthand.properties()[j] == CSSPropertyBackgroundSize || shorthand.properties()[j] == CSSPropertyWebkitMaskSize)) continue; if (useRepeatXShorthand) { @@ -414,15 +446,29 @@ String StylePropertySet::getLayeredShorthandValue(const StylePropertyShorthand& } else if (useRepeatYShorthand) { useRepeatYShorthand = false; layerResult.append(getValueName(CSSValueRepeatY)); - } else if (useSingleWordShorthand) { - useSingleWordShorthand = false; - layerResult.append(value->cssText()); - } else - layerResult.append(value->cssText()); - - if (shorthand.properties()[j] == CSSPropertyBackgroundPositionY) - foundBackgroundPositionYCSSProperty = true; + } else { + if (useSingleWordShorthand) + useSingleWordShorthand = false; + valueText = value->cssText(); + layerResult.append(valueText); + } + + if (shorthand.properties()[j] == CSSPropertyBackgroundPositionY + || shorthand.properties()[j] == CSSPropertyWebkitMaskPositionY) { + foundPositionYCSSProperty = true; + + // background-position is a special case: if only the first offset is specified, + // the second one defaults to "center", not the same value. + if (commonValueInitialized && commonValue != "initial" && commonValue != "inherit") + commonValue = String(); + } } + + if (!commonValueInitialized) { + commonValue = valueText; + commonValueInitialized = true; + } else if (!commonValue.isNull() && commonValue != valueText) + commonValue = String(); } if (!layerResult.isEmpty()) { @@ -431,6 +477,10 @@ String StylePropertySet::getLayeredShorthandValue(const StylePropertyShorthand& result.append(layerResult); } } + + if (isInitialOrInherit(commonValue)) + return commonValue; + if (result.isEmpty()) return String(); return result.toString(); @@ -438,19 +488,28 @@ String StylePropertySet::getLayeredShorthandValue(const StylePropertyShorthand& String StylePropertySet::getShorthandValue(const StylePropertyShorthand& shorthand) const { + String commonValue; StringBuilder result; for (unsigned i = 0; i < shorthand.length(); ++i) { if (!isPropertyImplicit(shorthand.properties()[i])) { RefPtr<CSSValue> value = getPropertyCSSValue(shorthand.properties()[i]); if (!value) return String(); + String valueText = value->cssText(); + if (!i) + commonValue = valueText; + else if (!commonValue.isNull() && commonValue != valueText) + commonValue = String(); if (value->isInitialValue()) continue; if (!result.isEmpty()) result.append(' '); - result.append(value->cssText()); - } + result.append(valueText); + } else + commonValue = String(); } + if (isInitialOrInherit(commonValue)) + return commonValue; if (result.isEmpty()) return String(); return result.toString(); @@ -485,6 +544,7 @@ String StylePropertySet::getCommonValue(const StylePropertyShorthand& shorthand) String StylePropertySet::borderPropertyValue(CommonValueMode valueMode) const { const StylePropertyShorthand properties[3] = { borderWidthShorthand(), borderStyleShorthand(), borderColorShorthand() }; + String commonValue; StringBuilder result; for (size_t i = 0; i < WTF_ARRAY_LENGTH(properties); ++i) { String value = getCommonValue(properties[i]); @@ -494,12 +554,18 @@ String StylePropertySet::borderPropertyValue(CommonValueMode valueMode) const ASSERT(valueMode == OmitUncommonValues); continue; } + if (!i) + commonValue = value; + else if (!commonValue.isNull() && commonValue != value) + commonValue = String(); if (value == "initial") continue; if (!result.isEmpty()) result.append(' '); result.append(value); } + if (isInitialOrInherit(commonValue)) + return commonValue; return result.isEmpty() ? String() : result.toString(); } @@ -796,7 +862,6 @@ String StylePropertySet::asText() const case CSSPropertyWebkitMaskRepeatY: case CSSPropertyWebkitMaskImage: case CSSPropertyWebkitMaskRepeat: - case CSSPropertyWebkitMaskAttachment: case CSSPropertyWebkitMaskPosition: case CSSPropertyWebkitMaskClip: case CSSPropertyWebkitMaskOrigin: diff --git a/Source/WebCore/css/StylePropertySet.h b/Source/WebCore/css/StylePropertySet.h index cbe7f1897..456f7ef2e 100644 --- a/Source/WebCore/css/StylePropertySet.h +++ b/Source/WebCore/css/StylePropertySet.h @@ -197,7 +197,7 @@ private: String get4Values(const StylePropertyShorthand&) const; String borderSpacingValue(const StylePropertyShorthand&) const; String fontValue() const; - bool appendFontLonghandValueIfExplicit(CSSPropertyID, StringBuilder& result) const; + bool appendFontLonghandValueIfExplicit(CSSPropertyID, StringBuilder& result, String& value) const; bool removeShorthandProperty(CSSPropertyID); bool propertyMatches(const PropertyReference&) const; diff --git a/Source/WebCore/css/StylePropertyShorthand.cpp b/Source/WebCore/css/StylePropertyShorthand.cpp index 38a91e3ba..b518e987c 100644 --- a/Source/WebCore/css/StylePropertyShorthand.cpp +++ b/Source/WebCore/css/StylePropertyShorthand.cpp @@ -370,11 +370,11 @@ const StylePropertyShorthand& webkitMaskShorthand() { static const CSSPropertyID maskProperties[] = { CSSPropertyWebkitMaskImage, - CSSPropertyWebkitMaskRepeatX, - CSSPropertyWebkitMaskRepeatY, - CSSPropertyWebkitMaskAttachment, CSSPropertyWebkitMaskPositionX, CSSPropertyWebkitMaskPositionY, + CSSPropertyWebkitMaskSize, + CSSPropertyWebkitMaskRepeatX, + CSSPropertyWebkitMaskRepeatY, CSSPropertyWebkitMaskOrigin, CSSPropertyWebkitMaskClip }; diff --git a/Source/WebCore/css/StyleResolver.cpp b/Source/WebCore/css/StyleResolver.cpp index 30dbc56b6..c6d033241 100644 --- a/Source/WebCore/css/StyleResolver.cpp +++ b/Source/WebCore/css/StyleResolver.cpp @@ -716,7 +716,7 @@ void StyleResolver::sortAndTransferMatchedRules(MatchResult& result) bool swapVisitedUnvisited = InspectorInstrumentation::forcePseudoState(m_element, CSSSelector::PseudoVisited); for (unsigned i = 0; i < m_matchedRules.size(); i++) { if (m_style && m_matchedRules[i]->containsUncommonAttributeSelector()) - m_style->setAffectedByUncommonAttributeSelectors(); + m_style->setUnique(); unsigned linkMatchType = m_matchedRules[i]->linkMatchType(); if (swapVisitedUnvisited && linkMatchType && linkMatchType != SelectorChecker::MatchAll) linkMatchType = (linkMatchType == SelectorChecker::MatchVisited) ? SelectorChecker::MatchLink : SelectorChecker::MatchVisited; @@ -1176,8 +1176,6 @@ bool StyleResolver::canShareStyleWithElement(StyledElement* element) const #endif if (element->isLink() != m_element->isLink()) return false; - if (style->affectedByUncommonAttributeSelectors()) - return false; if (element->hovered() != m_element->hovered()) return false; if (element->active() != m_element->active()) @@ -1249,12 +1247,14 @@ inline StyledElement* StyleResolver::findSiblingForStyleSharing(Node* node, unsi return static_cast<StyledElement*>(node); } -static inline bool parentStylePreventsSharing(const RenderStyle* parentStyle) +static inline bool parentElementPreventsSharing(const Element* parentElement) { - return parentStyle->childrenAffectedByPositionalRules() - || parentStyle->childrenAffectedByFirstChildRules() - || parentStyle->childrenAffectedByLastChildRules() - || parentStyle->childrenAffectedByDirectAdjacentRules(); + if (!parentElement) + return false; + return parentElement->childrenAffectedByPositionalRules() + || parentElement->childrenAffectedByFirstChildRules() + || parentElement->childrenAffectedByLastChildRules() + || parentElement->childrenAffectedByDirectAdjacentRules(); } RenderStyle* StyleResolver::locateSharedStyle() @@ -1271,7 +1271,7 @@ RenderStyle* StyleResolver::locateSharedStyle() // Ids stop style sharing if they show up in the stylesheets. if (m_styledElement->hasID() && m_features.idsInRules.contains(m_styledElement->idForStyleResolution().impl())) return 0; - if (parentStylePreventsSharing(m_parentStyle)) + if (parentElementPreventsSharing(m_element->parentElement())) return 0; if (m_styledElement->hasScopedHTMLStyleChild()) return 0; @@ -1306,7 +1306,7 @@ RenderStyle* StyleResolver::locateSharedStyle() if (styleSharingCandidateMatchesHostRules()) return 0; // Tracking child index requires unique style for each node. This may get set by the sibling rule match above. - if (parentStylePreventsSharing(m_parentStyle)) + if (parentElementPreventsSharing(m_element->parentElement())) return 0; return shareElement->renderStyle(); } @@ -1398,7 +1398,7 @@ PassRefPtr<RenderStyle> StyleResolver::styleForDocument(Document* document, CSSF documentStyle->setPageScaleTransform(frame ? frame->frameScaleFactor() : 1); documentStyle->setLocale(document->contentLanguage()); } - // FIXME: This overrides any -webkit-user-modify inherited from the parent iframe. + // This overrides any -webkit-user-modify inherited from the parent iframe. documentStyle->setUserModify(document->inDesignMode() ? READ_WRITE : READ_ONLY); Element* docElement = document->documentElement(); @@ -3190,7 +3190,7 @@ void StyleResolver::applyProperty(CSSPropertyID id, CSSValue* value) m_style->resetColumnRule(); return; case CSSPropertyWebkitMarquee: - if (!m_parentNode || !value->isInheritedValue()) + if (!isInherit) return; m_style->setMarqueeDirection(m_parentStyle->marqueeDirection()); m_style->setMarqueeIncrement(m_parentStyle->marqueeIncrement()); @@ -3776,7 +3776,6 @@ void StyleResolver::applyProperty(CSSPropertyID id, CSSValue* value) case CSSPropertyWebkitLineSnap: case CSSPropertyWebkitMarqueeDirection: case CSSPropertyWebkitMarqueeStyle: - case CSSPropertyWebkitMaskAttachment: case CSSPropertyWebkitMaskBoxImage: case CSSPropertyWebkitMaskBoxImageOutset: case CSSPropertyWebkitMaskBoxImageRepeat: @@ -3958,7 +3957,7 @@ void StyleResolver::checkForGenericFamilyChange(RenderStyle* style, RenderStyle* size = fontSizeForKeyword(m_checker.document(), CSSValueXxSmall + childFont.keywordSize() - 1, childFont.useFixedDefaultSize()); else { Settings* settings = documentSettings(); - float fixedScaleFactor = settings + float fixedScaleFactor = (settings && settings->defaultFixedFontSize() && settings->defaultFontSize()) ? static_cast<float>(settings->defaultFixedFontSize()) / settings->defaultFontSize() : 1; size = parentFont.useFixedDefaultSize() ? diff --git a/Source/WebCore/css/WebKitCSSMixFunctionValue.idl b/Source/WebCore/css/WebKitCSSMixFunctionValue.idl new file mode 100644 index 000000000..6026816a3 --- /dev/null +++ b/Source/WebCore/css/WebKitCSSMixFunctionValue.idl @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +[ + Conditional=CSS_SHADERS, +] interface WebKitCSSMixFunctionValue : CSSValueList { +}; + diff --git a/Source/WebCore/css/mediaControlsChromium.css b/Source/WebCore/css/mediaControlsChromium.css index 4eef10909..fa45b6fb1 100644 --- a/Source/WebCore/css/mediaControlsChromium.css +++ b/Source/WebCore/css/mediaControlsChromium.css @@ -168,6 +168,11 @@ input[type="range"]::-webkit-media-slider-container { background-color: transparent; /* Background drawing is managed by C++ code to draw ranges. */ } +/* The negative right margin causes the track to overflow its container. */ +input[type="range"]::-webkit-media-slider-container > div { + margin-right: -14px; +} + input[type="range"]::-webkit-media-slider-thumb { margin-left: -7px; margin-right: -7px; diff --git a/Source/WebCore/css/mediaControlsChromiumAndroid.css b/Source/WebCore/css/mediaControlsChromiumAndroid.css index 8fcdca23b..f3aced951 100644 --- a/Source/WebCore/css/mediaControlsChromiumAndroid.css +++ b/Source/WebCore/css/mediaControlsChromiumAndroid.css @@ -185,6 +185,11 @@ input[type="range"]::-webkit-media-slider-container { background-color: transparent; } +/* The negative right margin causes the track to overflow its container. */ +input[type="range"]::-webkit-media-slider-container > div { + margin-right: -14px; +} + input[type="range"]::-webkit-media-slider-thumb { margin-left: -7px; margin-right: -7px; diff --git a/Source/WebCore/dom/ContainerNode.cpp b/Source/WebCore/dom/ContainerNode.cpp index 20f9c4c00..f3c6abd38 100644 --- a/Source/WebCore/dom/ContainerNode.cpp +++ b/Source/WebCore/dom/ContainerNode.cpp @@ -38,6 +38,7 @@ #include "LoaderStrategy.h" #include "MemoryCache.h" #include "MutationEvent.h" +#include "NodeRenderStyle.h" #include "ResourceLoadScheduler.h" #include "Page.h" #include "PlatformStrategies.h" @@ -132,6 +133,70 @@ ContainerNode::~ContainerNode() removeAllChildren(); } +static inline bool isChildTypeAllowed(ContainerNode* newParent, Node* child) +{ + if (!child->isDocumentFragment()) + return newParent->childTypeAllowed(child->nodeType()); + + for (Node* node = child->firstChild(); node; node = node->nextSibling()) { + if (!newParent->childTypeAllowed(node->nodeType())) + return false; + } + return true; +} + +static inline ExceptionCode checkAcceptChild(ContainerNode* newParent, Node* newChild, Node* oldChild) +{ + // Not mentioned in spec: throw NOT_FOUND_ERR if newChild is null + if (!newChild) + return NOT_FOUND_ERR; + + // Goes common casae fast path if possible. + if ((newChild->isElementNode() || newChild->isTextNode()) && newParent->isElementNode()) { + ASSERT(!newParent->isReadOnlyNode()); + ASSERT(!newParent->isDocumentTypeNode()); + ASSERT(isChildTypeAllowed(newParent, newChild)); + if (newChild->contains(newParent)) + return HIERARCHY_REQUEST_ERR; + return 0; + } + + if (newParent->isReadOnlyNode()) + return NO_MODIFICATION_ALLOWED_ERR; + if (newChild->inDocument() && newChild->isDocumentTypeNode()) + return HIERARCHY_REQUEST_ERR; + if (newChild->contains(newParent)) + return HIERARCHY_REQUEST_ERR; + + if (oldChild && newParent->isDocumentNode()) { + if (!static_cast<Document*>(newParent)->canReplaceChild(newChild, oldChild)) + return HIERARCHY_REQUEST_ERR; + } else if (!isChildTypeAllowed(newParent, newChild)) + return HIERARCHY_REQUEST_ERR; + + return 0; +} + +static inline bool checkAddChild(ContainerNode* newParent, Node* newChild, ExceptionCode& ec) +{ + if (ExceptionCode code = checkAcceptChild(newParent, newChild, 0)) { + ec = code; + return false; + } + + return true; +} + +static inline bool checkReplaceChild(ContainerNode* newParent, Node* newChild, Node* oldChild, ExceptionCode& ec) +{ + if (ExceptionCode code = checkAcceptChild(newParent, newChild, oldChild)) { + ec = code; + return false; + } + + return true; +} + bool ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode& ec, bool shouldLazyAttach) { // Check that this node is not "floating". @@ -147,8 +212,7 @@ bool ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, Exce return appendChild(newChild, ec, shouldLazyAttach); // Make sure adding the new child is OK. - checkAddChild(newChild.get(), ec); - if (ec) + if (!checkAddChild(this, newChild.get(), ec)) return false; // NOT_FOUND_ERR: Raised if refChild is not a child of this node @@ -263,13 +327,17 @@ bool ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, Exce if (oldChild == newChild) // nothing to do return true; + if (!oldChild) { + ec = NOT_FOUND_ERR; + return false; + } + // Make sure replacing the old child with the new is ok - checkReplaceChild(newChild.get(), oldChild, ec); - if (ec) + if (!checkReplaceChild(this, newChild.get(), oldChild, ec)) return false; // NOT_FOUND_ERR: Raised if oldChild is not a child of this node. - if (!oldChild || oldChild->parentNode() != this) { + if (oldChild->parentNode() != this) { ec = NOT_FOUND_ERR; return false; } @@ -290,8 +358,7 @@ bool ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, Exce return true; // Does this one more time because removeChild() fires a MutationEvent. - checkReplaceChild(newChild.get(), oldChild, ec); - if (ec) + if (!checkReplaceChild(this, newChild.get(), oldChild, ec)) return false; NodeVector targets; @@ -300,8 +367,7 @@ bool ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, Exce return false; // Does this yet another check because collectChildrenAndRemoveFromOldParent() fires a MutationEvent. - checkReplaceChild(newChild.get(), oldChild, ec); - if (ec) + if (!checkReplaceChild(this, newChild.get(), oldChild, ec)) return false; InspectorInstrumentation::willInsertDOMNode(document(), this); @@ -559,8 +625,7 @@ bool ContainerNode::appendChild(PassRefPtr<Node> newChild, ExceptionCode& ec, bo ec = 0; // Make sure adding the new child is ok - checkAddChild(newChild.get(), ec); - if (ec) + if (!checkAddChild(this, newChild.get(), ec)) return false; if (newChild == m_lastChild) // nothing to do @@ -887,10 +952,10 @@ void ContainerNode::setActive(bool down, bool pause) // note that we need to recalc the style // FIXME: Move to Element if (renderer()) { - bool reactsToPress = renderer()->style()->affectedByActiveRules(); + bool reactsToPress = renderStyle()->affectedByActive() || (isElementNode() && toElement(this)->childrenAffectedByActive()); if (reactsToPress) setNeedsStyleRecalc(); - if (renderer() && renderer()->style()->hasAppearance()) { + if (renderStyle()->hasAppearance()) { if (renderer()->theme()->stateChanged(renderer(), PressedState)) reactsToPress = true; } @@ -908,9 +973,9 @@ void ContainerNode::setActive(bool down, bool pause) // Do an immediate repaint. if (renderer()) renderer()->repaint(true); - + // FIXME: Find a substitute for usleep for Win32. - // Better yet, come up with a way of doing this that doesn't use this sort of thing at all. + // Better yet, come up with a way of doing this that doesn't use this sort of thing at all. #ifdef HAVE_FUNC_USLEEP // Now pause for a small amount of time (1/10th of a second from before we repainted in the pressed state) double remainingTime = 0.1 - (currentTime() - startTime); @@ -930,7 +995,7 @@ void ContainerNode::setHovered(bool over) // note that we need to recalc the style // FIXME: Move to Element if (renderer()) { - if (renderer()->style()->affectedByHoverRules()) + if (renderStyle()->affectedByHover() || (isElementNode() && toElement(this)->childrenAffectedByHover())) setNeedsStyleRecalc(); if (renderer() && renderer()->style()->hasAppearance()) renderer()->theme()->stateChanged(renderer(), HoverState); diff --git a/Source/WebCore/dom/Document.cpp b/Source/WebCore/dom/Document.cpp index 33c2d05a9..db74d55de 100644 --- a/Source/WebCore/dom/Document.cpp +++ b/Source/WebCore/dom/Document.cpp @@ -571,9 +571,6 @@ Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML) for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++) m_nodeListCounts[i] = 0; - for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_collections); i++) - m_collections[i] = 0; - InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter); } @@ -648,9 +645,6 @@ Document::~Document() m_weakReference->clear(); - if (m_mediaQueryMatcher) - m_mediaQueryMatcher->documentDestroyed(); - clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_cachedResourceLoader. // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages @@ -669,9 +663,6 @@ Document::~Document() for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++) ASSERT(!m_nodeListCounts[i]); - for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_collections); i++) - ASSERT(!m_collections[i]); - m_document = 0; InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter); @@ -2142,6 +2133,9 @@ void Document::detach() // callers of Document::detach(). m_frame = 0; m_renderArena.clear(); + + if (m_mediaQueryMatcher) + m_mediaQueryMatcher->documentDestroyed(); } void Document::prepareForDestruction() @@ -3459,7 +3453,7 @@ void Document::setCSSTarget(Element* n) } } -void Document::registerNodeListCache(LiveNodeListBase* list) +void Document::registerNodeList(LiveNodeListBase* list) { if (list->hasIdNameCache()) m_nodeListCounts[InvalidateOnIdNameAttrChange]++; @@ -3468,7 +3462,7 @@ void Document::registerNodeListCache(LiveNodeListBase* list) m_listsInvalidatedAtDocument.add(list); } -void Document::unregisterNodeListCache(LiveNodeListBase* list) +void Document::unregisterNodeList(LiveNodeListBase* list) { if (list->hasIdNameCache()) m_nodeListCounts[InvalidateOnIdNameAttrChange]--; @@ -4334,108 +4328,65 @@ bool Document::hasSVGRootNode() const } #endif -// FIXME: This caching mechanism should be merged that of LiveNodeList in NodeRareData. -PassRefPtr<HTMLCollection> Document::cachedCollection(CollectionType type) -{ - ASSERT(static_cast<unsigned>(type) < NumUnnamedDocumentCachedTypes); - if (m_collections[type]) - return m_collections[type]; - - RefPtr<HTMLCollection> collection; - if (type == DocAll) - collection = HTMLAllCollection::create(this); - else - collection = HTMLCollection::create(this, type); - m_collections[type] = collection.get(); - - return collection.release(); -} - -void Document::removeCachedHTMLCollection(HTMLCollection* collection, CollectionType type) +PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type) { - ASSERT_UNUSED(collection, m_collections[type] == collection); - m_collections[type] = 0; + return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type); } PassRefPtr<HTMLCollection> Document::images() { - return cachedCollection(DocImages); + return ensureCachedCollection(DocImages); } PassRefPtr<HTMLCollection> Document::applets() { - return cachedCollection(DocApplets); + return ensureCachedCollection(DocApplets); } PassRefPtr<HTMLCollection> Document::embeds() { - return cachedCollection(DocEmbeds); + return ensureCachedCollection(DocEmbeds); } PassRefPtr<HTMLCollection> Document::plugins() { // This is an alias for embeds() required for the JS DOM bindings. - return cachedCollection(DocEmbeds); + return ensureCachedCollection(DocEmbeds); } PassRefPtr<HTMLCollection> Document::scripts() { - return cachedCollection(DocScripts); + return ensureCachedCollection(DocScripts); } PassRefPtr<HTMLCollection> Document::links() { - return cachedCollection(DocLinks); + return ensureCachedCollection(DocLinks); } PassRefPtr<HTMLCollection> Document::forms() { - return cachedCollection(DocForms); + return ensureCachedCollection(DocForms); } PassRefPtr<HTMLCollection> Document::anchors() { - return cachedCollection(DocAnchors); + return ensureCachedCollection(DocAnchors); } PassRefPtr<HTMLCollection> Document::all() { - return cachedCollection(DocAll); + return ensureCachedCollection(DocAll); } PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name) { - NamedCollectionMap::AddResult result = m_windowNamedItemCollections.add(name, 0); - if (!result.isNewEntry) - return result.iterator->value; - - RefPtr<HTMLNameCollection> collection = HTMLNameCollection::create(this, WindowNamedItems, name); - result.iterator->value = collection.get(); - return collection.release(); + return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLNameCollection>(this, WindowNamedItems, name); } PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name) { - NamedCollectionMap::AddResult result = m_documentNamedItemCollections.add(name, 0); - if (!result.isNewEntry) - return result.iterator->value; - - RefPtr<HTMLNameCollection> collection = HTMLNameCollection::create(this, DocumentNamedItems, name); - result.iterator->value = collection.get(); - return collection.release(); -} - -// FIXME: This caching mechanism should be merged that of LiveNodeList in NodeRareData. -void Document::removeWindowNamedItemCache(HTMLCollection* collection, const AtomicString& name) -{ - ASSERT_UNUSED(collection, m_windowNamedItemCollections.get(name) == collection); - m_windowNamedItemCollections.remove(name); -} - -void Document::removeDocumentNamedItemCache(HTMLCollection* collection, const AtomicString& name) -{ - ASSERT_UNUSED(collection, m_documentNamedItemCollections.get(name) == collection); - m_documentNamedItemCollections.remove(name); + return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLNameCollection>(this, DocumentNamedItems, name); } void Document::finishedParsing() @@ -5891,8 +5842,6 @@ void Document::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const info.addMember(m_xmlEncoding); info.addMember(m_xmlVersion); info.addMember(m_contentLanguage); - info.addMember(m_documentNamedItemCollections); - info.addMember(m_windowNamedItemCollections); #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION) info.addMember(m_annotatedRegions); #endif diff --git a/Source/WebCore/dom/Document.h b/Source/WebCore/dom/Document.h index 075b00e9b..4e2671611 100644 --- a/Source/WebCore/dom/Document.h +++ b/Source/WebCore/dom/Document.h @@ -441,12 +441,9 @@ public: PassRefPtr<HTMLCollection> anchors(); PassRefPtr<HTMLCollection> scripts(); PassRefPtr<HTMLCollection> all(); - void removeCachedHTMLCollection(HTMLCollection*, CollectionType); PassRefPtr<HTMLCollection> windowNamedItems(const AtomicString& name); PassRefPtr<HTMLCollection> documentNamedItems(const AtomicString& name); - void removeWindowNamedItemCache(HTMLCollection*, const AtomicString&); - void removeDocumentNamedItemCache(HTMLCollection*, const AtomicString&); // Other methods (not part of DOM) bool isHTMLDocument() const { return m_isHTML; } @@ -718,8 +715,8 @@ public: bool hasPendingForcedStyleRecalc() const; void styleRecalcTimerFired(Timer<Document>*); - void registerNodeListCache(LiveNodeListBase*); - void unregisterNodeListCache(LiveNodeListBase*); + void registerNodeList(LiveNodeListBase*); + void unregisterNodeList(LiveNodeListBase*); bool shouldInvalidateNodeListCaches(const QualifiedName* attrName = 0) const; void invalidateNodeListCaches(const QualifiedName* attrName); @@ -735,6 +732,7 @@ public: void nodeChildrenWillBeRemoved(ContainerNode*); // nodeWillBeRemoved is only safe when removing one node at a time. void nodeWillBeRemoved(Node*); + bool canReplaceChild(Node* newChild, Node* oldChild); void textInserted(Node*, unsigned offset, unsigned length); void textRemoved(Node*, unsigned offset, unsigned length); @@ -1199,7 +1197,6 @@ private: virtual NodeType nodeType() const; virtual bool childTypeAllowed(NodeType) const; virtual PassRefPtr<Node> cloneNode(bool deep); - virtual bool canReplaceChild(Node* newChild, Node* oldChild); virtual void refScriptExecutionContext() { ref(); } virtual void derefScriptExecutionContext() { deref(); } @@ -1238,7 +1235,7 @@ private: PageVisibilityState visibilityState() const; #endif - PassRefPtr<HTMLCollection> cachedCollection(CollectionType); + PassRefPtr<HTMLCollection> ensureCachedCollection(CollectionType); #if ENABLE(FULLSCREEN_API) void clearFullscreenElementStack(); @@ -1410,11 +1407,6 @@ private: HashSet<LiveNodeListBase*> m_listsInvalidatedAtDocument; unsigned m_nodeListCounts[numNodeListInvalidationTypes]; - HTMLCollection* m_collections[NumUnnamedDocumentCachedTypes]; - typedef HashMap<AtomicString, HTMLNameCollection*> NamedCollectionMap; - NamedCollectionMap m_documentNamedItemCollections; - NamedCollectionMap m_windowNamedItemCollections; - RefPtr<XPathEvaluator> m_xpathEvaluator; #if ENABLE(SVG) diff --git a/Source/WebCore/dom/DocumentFragment.cpp b/Source/WebCore/dom/DocumentFragment.cpp index f7cfadfcc..48af10fe1 100644 --- a/Source/WebCore/dom/DocumentFragment.cpp +++ b/Source/WebCore/dom/DocumentFragment.cpp @@ -40,7 +40,7 @@ DocumentFragment::DocumentFragment(Document* document, ConstructionType construc PassRefPtr<DocumentFragment> DocumentFragment::create(Document* document) { - return adoptRef(new DocumentFragment(document)); + return adoptRef(new DocumentFragment(document, Node::CreateDocumentFragment)); } String DocumentFragment::nodeName() const diff --git a/Source/WebCore/dom/DocumentFragment.h b/Source/WebCore/dom/DocumentFragment.h index 3af5f1b28..81aeb8ad8 100644 --- a/Source/WebCore/dom/DocumentFragment.h +++ b/Source/WebCore/dom/DocumentFragment.h @@ -46,6 +46,7 @@ private: virtual NodeType nodeType() const; virtual PassRefPtr<Node> cloneNode(bool deep); virtual bool childTypeAllowed(NodeType) const; + virtual bool documentFragmentIsShadowRoot() const OVERRIDE { return false; } }; } //namespace diff --git a/Source/WebCore/dom/Element.cpp b/Source/WebCore/dom/Element.cpp index a4f7d72af..b7d0e5993 100644 --- a/Source/WebCore/dom/Element.cpp +++ b/Source/WebCore/dom/Element.cpp @@ -305,18 +305,19 @@ bool Element::hasAttribute(const QualifiedName& name) const const AtomicString& Element::getAttribute(const QualifiedName& name) const { - if (UNLIKELY(name == styleAttr) && attributeData() && attributeData()->m_styleAttributeIsDirty) + if (!attributeData()) + return nullAtom; + + if (UNLIKELY(name == styleAttr && attributeData()->m_styleAttributeIsDirty)) updateStyleAttribute(); #if ENABLE(SVG) - if (UNLIKELY(!areSVGAttributesValid())) + if (UNLIKELY(attributeData()->m_animatedSVGAttributesAreDirty)) updateAnimatedSVGAttribute(name); #endif - if (attributeData()) { - if (const Attribute* attribute = getAttributeItem(name)) - return attribute->value(); - } + if (const Attribute* attribute = getAttributeItem(name)) + return attribute->value(); return nullAtom; } @@ -660,24 +661,24 @@ static inline bool shouldIgnoreAttributeCase(const Element* e) const AtomicString& Element::getAttribute(const AtomicString& name) const { + if (!attributeData()) + return nullAtom; + bool ignoreCase = shouldIgnoreAttributeCase(this); // Update the 'style' attribute if it's invalid and being requested: - if (attributeData() && attributeData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(name, styleAttr.localName(), ignoreCase)) + if (attributeData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(name, styleAttr.localName(), ignoreCase)) updateStyleAttribute(); #if ENABLE(SVG) - if (!areSVGAttributesValid()) { + if (attributeData()->m_animatedSVGAttributesAreDirty) { // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well. updateAnimatedSVGAttribute(QualifiedName(nullAtom, name, nullAtom)); } #endif - if (attributeData()) { - if (const Attribute* attribute = attributeData()->getAttributeItem(name, ignoreCase)) - return attribute->value(); - } - + if (const Attribute* attribute = attributeData()->getAttributeItem(name, ignoreCase)) + return attribute->value(); return nullAtom; } @@ -824,49 +825,23 @@ static inline bool classStringHasClassName(const AtomicString& newClassString) return classStringHasClassName(newClassString.characters16(), length); } -struct HasSelectorForClassStyleFunctor { - explicit HasSelectorForClassStyleFunctor(StyleResolver* resolver) - : styleResolver(resolver) - { } - - bool operator()(const AtomicString& className) const - { - return styleResolver->hasSelectorForClass(className); - } - - StyleResolver* styleResolver; -}; - -struct HasSelectorForClassDistributionFunctor { - explicit HasSelectorForClassDistributionFunctor(ElementShadow* elementShadow) - : elementShadow(elementShadow) - { } - - bool operator()(const AtomicString& className) const - { - return elementShadow->selectRuleFeatureSet().hasSelectorForClass(className); - } - - ElementShadow* elementShadow; -}; - -template<typename Functor> -static bool checkFunctorForClassChange(const SpaceSplitString& changedClasses, Functor functor) +template<typename Checker> +static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker) { unsigned changedSize = changedClasses.size(); for (unsigned i = 0; i < changedSize; ++i) { - if (functor(changedClasses[i])) + if (checker.hasSelectorForClass(changedClasses[i])) return true; } return false; } -template<typename Functor> -static bool checkFunctorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, Functor functor) +template<typename Checker> +static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker) { unsigned oldSize = oldClasses.size(); if (!oldSize) - return checkFunctorForClassChange(newClasses, functor); + return checkSelectorForClassChange(newClasses, checker); BitVector remainingClassBits; remainingClassBits.ensureSize(oldSize); // Class vectors tend to be very short. This is faster than using a hash table. @@ -878,39 +853,19 @@ static bool checkFunctorForClassChange(const SpaceSplitString& oldClasses, const continue; } } - if (functor(newClasses[i])) + if (checker.hasSelectorForClass(newClasses[i])) return true; } for (unsigned i = 0; i < oldSize; ++i) { // If the bit is not set the the corresponding class has been removed. if (remainingClassBits.quickGet(i)) continue; - if (functor(oldClasses[i])) + if (checker.hasSelectorForClass(oldClasses[i])) return true; } return false; } -static inline bool checkNeedsStyleInvalidationForClassChange(const SpaceSplitString& changedClasses, StyleResolver* styleResolver) -{ - return checkFunctorForClassChange(changedClasses, HasSelectorForClassStyleFunctor(styleResolver)); -} - -static inline bool checkNeedsStyleInvalidationForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, StyleResolver* styleResolver) -{ - return checkFunctorForClassChange(oldClasses, newClasses, HasSelectorForClassStyleFunctor(styleResolver)); -} - -static inline bool checkNeedsDistributionInvalidationForClassChange(const SpaceSplitString& changedClasses, ElementShadow* elementShadow) -{ - return checkFunctorForClassChange(changedClasses, HasSelectorForClassDistributionFunctor(elementShadow)); -} - -static inline bool checkNeedsDistributionInvalidationForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, ElementShadow* elementShadow) -{ - return checkFunctorForClassChange(oldClasses, newClasses, HasSelectorForClassDistributionFunctor(elementShadow)); -} - void Element::classAttributeChanged(const AtomicString& newClassString) { StyleResolver* styleResolver = document()->styleResolverIfExists(); @@ -925,10 +880,10 @@ void Element::classAttributeChanged(const AtomicString& newClassString) attributeData->setClass(newClassString, shouldFoldCase); const SpaceSplitString& newClasses = attributeData->classNames(); - shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForClassChange(oldClasses, newClasses, styleResolver); + shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, *styleResolver); } else if (const ElementAttributeData* attributeData = this->attributeData()) { const SpaceSplitString& oldClasses = attributeData->classNames(); - shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForClassChange(oldClasses, styleResolver); + shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, *styleResolver); attributeData->clearClass(); } @@ -963,11 +918,11 @@ bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* el const bool shouldFoldCase = document()->inQuirksMode(); const SpaceSplitString& oldClasses = attributeData->classNames(); const SpaceSplitString newClasses(newClassString, shouldFoldCase); - if (checkNeedsDistributionInvalidationForClassChange(oldClasses, newClasses, elementShadow)) + if (checkSelectorForClassChange(oldClasses, newClasses, elementShadow->selectRuleFeatureSet())) return true; } else if (const ElementAttributeData* attributeData = this->attributeData()) { const SpaceSplitString& oldClasses = attributeData->classNames(); - if (checkNeedsDistributionInvalidationForClassChange(oldClasses, elementShadow)) + if (checkSelectorForClassChange(oldClasses, elementShadow->selectRuleFeatureSet())) return true; } } @@ -1197,34 +1152,34 @@ void Element::createRendererIfNeeded() void Element::attach() { suspendPostAttachCallbacks(); - WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates; - - createRendererIfNeeded(); + { + WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates; + createRendererIfNeeded(); - StyleResolverParentPusher parentPusher(this); + StyleResolverParentPusher parentPusher(this); - if (parentElement() && parentElement()->isInCanvasSubtree()) - setIsInCanvasSubtree(true); + if (parentElement() && parentElement()->isInCanvasSubtree()) + setIsInCanvasSubtree(true); - // When a shadow root exists, it does the work of attaching the children. - if (ElementShadow* shadow = this->shadow()) { - parentPusher.push(); - shadow->attach(); - } else { - if (firstChild()) + // When a shadow root exists, it does the work of attaching the children. + if (ElementShadow* shadow = this->shadow()) { parentPusher.push(); - } - ContainerNode::attach(); + shadow->attach(); + } else { + if (firstChild()) + parentPusher.push(); + } + ContainerNode::attach(); - if (hasRareData()) { - ElementRareData* data = elementRareData(); - if (data->needsFocusAppearanceUpdateSoonAfterAttach()) { - if (isFocusable() && document()->focusedNode() == this) - document()->updateFocusAppearanceSoon(false /* don't restore selection */); - data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false); + if (hasRareData()) { + ElementRareData* data = elementRareData(); + if (data->needsFocusAppearanceUpdateSoonAfterAttach()) { + if (isFocusable() && document()->focusedNode() == this) + document()->updateFocusAppearanceSoon(false /* don't restore selection */); + data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false); + } } } - resumePostAttachCallbacks(); } @@ -1243,6 +1198,7 @@ void Element::detach() ElementRareData* data = elementRareData(); data->setIsInCanvasSubtree(false); data->resetComputedStyle(); + data->resetDynamicRestyleObservations(); } if (ElementShadow* shadow = this->shadow()) { @@ -1310,15 +1266,12 @@ void Element::recalcStyle(StyleChange change) // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer. RefPtr<RenderStyle> currentStyle(renderStyle()); bool hasParentStyle = parentNodeForRenderingAndStyle() ? static_cast<bool>(parentNodeForRenderingAndStyle()->renderStyle()) : false; - bool hasDirectAdjacentRules = currentStyle && currentStyle->childrenAffectedByDirectAdjacentRules(); - bool hasIndirectAdjacentRules = currentStyle && currentStyle->childrenAffectedByForwardPositionalRules(); + bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules(); + bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules(); if ((change > NoChange || needsStyleRecalc())) { - if (hasRareData()) { - ElementRareData* data = elementRareData(); - data->resetComputedStyle(); - data->setStyleAffectedByEmpty(false); - } + if (hasRareData()) + elementRareData()->resetComputedStyle(); } if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) { RefPtr<RenderStyle> newStyle = styleForRenderer(); @@ -1335,27 +1288,6 @@ void Element::recalcStyle(StyleChange change) return; } - if (currentStyle) { - // Preserve "affected by" bits that were propagated to us from descendants in the case where we didn't do a full - // style change (e.g., only inline style changed). - if (currentStyle->affectedByHoverRules()) - newStyle->setAffectedByHoverRules(true); - if (currentStyle->affectedByActiveRules()) - newStyle->setAffectedByActiveRules(true); - if (currentStyle->affectedByDragRules()) - newStyle->setAffectedByDragRules(true); - if (currentStyle->childrenAffectedByForwardPositionalRules()) - newStyle->setChildrenAffectedByForwardPositionalRules(); - if (currentStyle->childrenAffectedByBackwardPositionalRules()) - newStyle->setChildrenAffectedByBackwardPositionalRules(); - if (currentStyle->childrenAffectedByFirstChildRules()) - newStyle->setChildrenAffectedByFirstChildRules(); - if (currentStyle->childrenAffectedByLastChildRules()) - newStyle->setChildrenAffectedByLastChildRules(); - if (currentStyle->childrenAffectedByDirectAdjacentRules()) - newStyle->setChildrenAffectedByDirectAdjacentRules(); - } - if (RenderObject* renderer = this->renderer()) { if (ch != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || styleChangeType() == SyntheticStyleChange) renderer->setAnimatableStyle(newStyle.get()); @@ -1483,7 +1415,7 @@ static void checkForEmptyStyleChange(Element* element, RenderStyle* style) if (!style && !element->styleAffectedByEmpty()) return; - if (!style || (style->affectedByEmpty() && (!style->emptyState() || element->hasChildNodes()))) + if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes()))) element->setNeedsStyleRecalc(); } @@ -1493,13 +1425,13 @@ static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool fin // :empty selector. checkForEmptyStyleChange(e, style); - if (!style || (e->needsStyleRecalc() && style->childrenAffectedByPositionalRules())) + if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules())) return; // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time. // In the DOM case, we only need to do something if |afterChange| is not 0. // |afterChange| is 0 in the parser case, so it works out that we'll skip this block. - if (style->childrenAffectedByFirstChildRules() && afterChange) { + if (e->childrenAffectedByFirstChildRules() && afterChange) { // Find our new first child. Node* newFirstChild = 0; for (newFirstChild = e->firstChild(); newFirstChild && !newFirstChild->isElementNode(); newFirstChild = newFirstChild->nextSibling()) {}; @@ -1522,7 +1454,7 @@ static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool fin // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time. // In the DOM case, we only need to do something if |afterChange| is not 0. - if (style->childrenAffectedByLastChildRules() && beforeChange) { + if (e->childrenAffectedByLastChildRules() && beforeChange) { // Find our new last child. Node* newLastChild = 0; for (newLastChild = e->lastChild(); newLastChild && !newLastChild->isElementNode(); newLastChild = newLastChild->previousSibling()) {}; @@ -1545,7 +1477,7 @@ static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool fin // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element // that could be affected by this DOM change. - if (style->childrenAffectedByDirectAdjacentRules() && afterChange) { + if (e->childrenAffectedByDirectAdjacentRules() && afterChange) { Node* firstElementAfterInsertion = 0; for (firstElementAfterInsertion = afterChange; firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode(); @@ -1561,8 +1493,8 @@ static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool fin // |afterChange| is 0 in the parser callback case, so we won't do any work for the forward case if we don't have to. // For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids // here. recalcStyle will then force a walk of the children when it sees that this has happened. - if ((style->childrenAffectedByForwardPositionalRules() && afterChange) || - (style->childrenAffectedByBackwardPositionalRules() && beforeChange)) + if ((e->childrenAffectedByForwardPositionalRules() && afterChange) + || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) e->setNeedsStyleRecalc(); } @@ -1969,9 +1901,115 @@ void Element::setStyleAffectedByEmpty() ensureElementRareData()->setStyleAffectedByEmpty(true); } -bool Element::styleAffectedByEmpty() const +void Element::setChildrenAffectedByHover(bool value) +{ + if (value || hasRareData()) + ensureElementRareData()->setChildrenAffectedByHover(value); +} + +void Element::setChildrenAffectedByActive(bool value) +{ + if (value || hasRareData()) + ensureElementRareData()->setChildrenAffectedByActive(value); +} + +void Element::setChildrenAffectedByDrag(bool value) +{ + if (value || hasRareData()) + ensureElementRareData()->setChildrenAffectedByDrag(value); +} + +void Element::setChildrenAffectedByFirstChildRules() +{ + ensureElementRareData()->setChildrenAffectedByFirstChildRules(true); +} + +void Element::setChildrenAffectedByLastChildRules() +{ + ensureElementRareData()->setChildrenAffectedByLastChildRules(true); +} + +void Element::setChildrenAffectedByDirectAdjacentRules() +{ + ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true); +} + +void Element::setChildrenAffectedByForwardPositionalRules() +{ + ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true); +} + +void Element::setChildrenAffectedByBackwardPositionalRules() +{ + ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true); +} + +void Element::setChildIndex(unsigned index) +{ + ElementRareData* rareData = ensureElementRareData(); + if (RenderStyle* style = renderStyle()) + style->setUnique(); + rareData->setChildIndex(index); +} + +bool Element::rareDataStyleAffectedByEmpty() const +{ + ASSERT(hasRareData()); + return elementRareData()->styleAffectedByEmpty(); +} + +bool Element::rareDataChildrenAffectedByHover() const +{ + ASSERT(hasRareData()); + return elementRareData()->childrenAffectedByHover(); +} + +bool Element::rareDataChildrenAffectedByActive() const +{ + ASSERT(hasRareData()); + return elementRareData()->childrenAffectedByActive(); +} + +bool Element::rareDataChildrenAffectedByDrag() const +{ + ASSERT(hasRareData()); + return elementRareData()->childrenAffectedByDrag(); +} + +bool Element::rareDataChildrenAffectedByFirstChildRules() const +{ + ASSERT(hasRareData()); + return elementRareData()->childrenAffectedByFirstChildRules(); +} + +bool Element::rareDataChildrenAffectedByLastChildRules() const +{ + ASSERT(hasRareData()); + return elementRareData()->childrenAffectedByLastChildRules(); +} + +bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const +{ + ASSERT(hasRareData()); + return elementRareData()->childrenAffectedByDirectAdjacentRules(); +} + +bool Element::rareDataChildrenAffectedByForwardPositionalRules() const +{ + ASSERT(hasRareData()); + return elementRareData()->childrenAffectedByForwardPositionalRules(); +} + +bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const +{ + ASSERT(hasRareData()); + return elementRareData()->childrenAffectedByBackwardPositionalRules(); +} + +unsigned Element::rareDataChildIndex() const { - return hasRareData() && elementRareData()->styleAffectedByEmpty(); + ASSERT(hasRareData()); + return elementRareData()->childIndex(); } void Element::setIsInCanvasSubtree(bool isInCanvasSubtree) @@ -2430,41 +2468,30 @@ void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type) { - return ensureElementRareData()->ensureCachedHTMLCollection(this, type); -} - -PassRefPtr<HTMLCollection> ElementRareData::ensureCachedHTMLCollection(Element* element, CollectionType type) -{ if (HTMLCollection* collection = cachedHTMLCollection(type)) return collection; RefPtr<HTMLCollection> collection; if (type == TableRows) { - ASSERT(element->hasTagName(tableTag)); - return ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(element, type); + ASSERT(hasTagName(tableTag)); + return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type); } else if (type == SelectOptions) { - ASSERT(element->hasTagName(selectTag)); - return ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(element, type); + ASSERT(hasTagName(selectTag)); + return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type); } else if (type == FormControls) { - ASSERT(element->hasTagName(formTag) || element->hasTagName(fieldsetTag)); - return ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(element, type); + ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag)); + return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type); #if ENABLE(MICRODATA) } else if (type == ItemProperties) { - return ensureNodeLists()->addCacheWithAtomicName<HTMLPropertiesCollection>(element, type); + return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLPropertiesCollection>(this, type); #endif } - return ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(element, type); + return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type); } HTMLCollection* Element::cachedHTMLCollection(CollectionType type) { - return hasRareData() ? elementRareData()->cachedHTMLCollection(type) : 0; -} - -void Element::removeCachedHTMLCollection(HTMLCollection* collection, CollectionType type) -{ - ASSERT(hasRareData()); - elementRareData()->removeCachedHTMLCollection(collection, type); + return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0; } IntSize Element::savedLayerScrollOffset() const diff --git a/Source/WebCore/dom/Element.h b/Source/WebCore/dom/Element.h index 82339c96b..a24594f5e 100644 --- a/Source/WebCore/dom/Element.h +++ b/Source/WebCore/dom/Element.h @@ -286,8 +286,29 @@ public: RenderStyle* computedStyle(PseudoId = NOPSEUDO); + // Methods for indicating the style is affected by dynamic updates (e.g., children changing, our position changing in our sibling list, etc.) + bool styleAffectedByEmpty() const { return hasRareData() && rareDataStyleAffectedByEmpty(); } + bool childrenAffectedByHover() const { return hasRareData() && rareDataChildrenAffectedByHover(); } + bool childrenAffectedByActive() const { return hasRareData() && rareDataChildrenAffectedByActive(); } + bool childrenAffectedByDrag() const { return hasRareData() && rareDataChildrenAffectedByDrag(); } + bool childrenAffectedByPositionalRules() const { return hasRareData() && (rareDataChildrenAffectedByForwardPositionalRules() || rareDataChildrenAffectedByBackwardPositionalRules()); } + bool childrenAffectedByFirstChildRules() const { return hasRareData() && rareDataChildrenAffectedByFirstChildRules(); } + bool childrenAffectedByLastChildRules() const { return hasRareData() && rareDataChildrenAffectedByLastChildRules(); } + bool childrenAffectedByDirectAdjacentRules() const { return hasRareData() && rareDataChildrenAffectedByDirectAdjacentRules(); } + bool childrenAffectedByForwardPositionalRules() const { return hasRareData() && rareDataChildrenAffectedByForwardPositionalRules(); } + bool childrenAffectedByBackwardPositionalRules() const { return hasRareData() && rareDataChildrenAffectedByBackwardPositionalRules(); } + unsigned childIndex() const { return hasRareData() ? rareDataChildIndex() : 0; } + void setStyleAffectedByEmpty(); - bool styleAffectedByEmpty() const; + void setChildrenAffectedByHover(bool); + void setChildrenAffectedByActive(bool); + void setChildrenAffectedByDrag(bool); + void setChildrenAffectedByFirstChildRules(); + void setChildrenAffectedByLastChildRules(); + void setChildrenAffectedByDirectAdjacentRules(); + void setChildrenAffectedByForwardPositionalRules(); + void setChildrenAffectedByBackwardPositionalRules(); + void setChildIndex(unsigned); void setIsInCanvasSubtree(bool); bool isInCanvasSubtree() const; @@ -383,7 +404,6 @@ public: virtual bool isDefaultButtonForForm() const { return false; } virtual bool willValidate() const { return false; } virtual bool isValidFormControlElement() { return false; } - virtual bool hasUnacceptableValue() const { return false; } virtual bool isInRange() const { return false; } virtual bool isOutOfRange() const { return false; } virtual bool isFrameElementBase() const { return false; } @@ -521,6 +541,16 @@ private: QualifiedName m_tagName; virtual OwnPtr<NodeRareData> createRareData(); + bool rareDataStyleAffectedByEmpty() const; + bool rareDataChildrenAffectedByHover() const; + bool rareDataChildrenAffectedByActive() const; + bool rareDataChildrenAffectedByDrag() const; + bool rareDataChildrenAffectedByFirstChildRules() const; + bool rareDataChildrenAffectedByLastChildRules() const; + bool rareDataChildrenAffectedByDirectAdjacentRules() const; + bool rareDataChildrenAffectedByForwardPositionalRules() const; + bool rareDataChildrenAffectedByBackwardPositionalRules() const; + unsigned rareDataChildIndex() const; SpellcheckAttributeState spellcheckAttributeState() const; @@ -743,11 +773,14 @@ inline Attribute* Element::getAttributeItem(const QualifiedName& name) inline void Element::updateInvalidAttributes() const { - if (attributeData() && attributeData()->m_styleAttributeIsDirty) + if (!attributeData()) + return; + + if (attributeData()->m_styleAttributeIsDirty) updateStyleAttribute(); #if ENABLE(SVG) - if (!areSVGAttributesValid()) + if (attributeData()->m_animatedSVGAttributesAreDirty) updateAnimatedSVGAttribute(anyQName()); #endif } diff --git a/Source/WebCore/dom/Element.idl b/Source/WebCore/dom/Element.idl index 8769c63e6..a1424c9ab 100644 --- a/Source/WebCore/dom/Element.idl +++ b/Source/WebCore/dom/Element.idl @@ -122,7 +122,7 @@ // ShadowAware API #if defined(ENABLE_SHADOW_DOM) && ENABLE_SHADOW_DOM [Reflect, V8EnabledAtRuntime=shadowDOM] attribute DOMString pseudo; - [V8EnabledAtRuntime=shadowDOM] ShadowRoot createShadowRoot() raises(DOMException); + [V8EnabledAtRuntime=shadowDOM, ImplementedAs=createShadowRoot] ShadowRoot webkitCreateShadowRoot() raises(DOMException); #endif // DOM 4 diff --git a/Source/WebCore/dom/ElementAttributeData.cpp b/Source/WebCore/dom/ElementAttributeData.cpp index e47ed52c4..460730301 100644 --- a/Source/WebCore/dom/ElementAttributeData.cpp +++ b/Source/WebCore/dom/ElementAttributeData.cpp @@ -36,7 +36,7 @@ struct SameSizeAsElementAttributeData : public RefCounted<SameSizeAsElementAttri void* refPtrs[3]; }; -COMPILE_ASSERT(sizeof(ElementAttributeData) == sizeof(ElementAttributeData), element_attribute_data_should_stay_small); +COMPILE_ASSERT(sizeof(ElementAttributeData) == sizeof(SameSizeAsElementAttributeData), element_attribute_data_should_stay_small); static size_t sizeForImmutableElementAttributeDataWithAttributeCount(unsigned count) { @@ -86,6 +86,9 @@ ElementAttributeData::ElementAttributeData(const ElementAttributeData& other, bo , m_arraySize(isMutable ? 0 : other.length()) , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty) , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty) +#if ENABLE(SVG) + , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty) +#endif , m_classNames(other.m_classNames) , m_idForStyleResolution(other.m_idForStyleResolution) { diff --git a/Source/WebCore/dom/ElementAttributeData.h b/Source/WebCore/dom/ElementAttributeData.h index 1979da9d0..dd0556eed 100644 --- a/Source/WebCore/dom/ElementAttributeData.h +++ b/Source/WebCore/dom/ElementAttributeData.h @@ -90,6 +90,9 @@ protected: , m_arraySize(0) , m_presentationAttributeStyleIsDirty(false) , m_styleAttributeIsDirty(false) +#if ENABLE(SVG) + , m_animatedSVGAttributesAreDirty(false) +#endif { } ElementAttributeData(unsigned arraySize) @@ -97,14 +100,20 @@ protected: , m_arraySize(arraySize) , m_presentationAttributeStyleIsDirty(false) , m_styleAttributeIsDirty(false) +#if ENABLE(SVG) + , m_animatedSVGAttributesAreDirty(false) +#endif { } ElementAttributeData(const ElementAttributeData&, bool isMutable); unsigned m_isMutable : 1; - unsigned m_arraySize : 29; + unsigned m_arraySize : 28; mutable unsigned m_presentationAttributeStyleIsDirty : 1; mutable unsigned m_styleAttributeIsDirty : 1; +#if ENABLE(SVG) + mutable unsigned m_animatedSVGAttributesAreDirty : 1; +#endif mutable RefPtr<StylePropertySet> m_inlineStyle; mutable SpaceSplitString m_classNames; @@ -115,6 +124,9 @@ private: friend class StyledElement; friend class ImmutableElementAttributeData; friend class MutableElementAttributeData; +#if ENABLE(SVG) + friend class SVGElement; +#endif Attribute* getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase); const Attribute* getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const; diff --git a/Source/WebCore/dom/ElementRareData.h b/Source/WebCore/dom/ElementRareData.h index 4501f192b..9e4ef1bdb 100644 --- a/Source/WebCore/dom/ElementRareData.h +++ b/Source/WebCore/dom/ElementRareData.h @@ -24,9 +24,7 @@ #include "ClassList.h" #include "DatasetDOMStringMap.h" -#include "Element.h" #include "ElementShadow.h" -#include "HTMLCollection.h" #include "NamedNodeMap.h" #include "NodeRareData.h" #include "StyleInheritedData.h" @@ -34,14 +32,13 @@ namespace WebCore { -class HTMLCollection; - class ElementRareData : public NodeRareData { public: ElementRareData(); virtual ~ElementRareData(); void resetComputedStyle(); + void resetDynamicRestyleObservations(); using NodeRareData::needsFocusAppearanceUpdateSoonAfterAttach; using NodeRareData::setNeedsFocusAppearanceUpdateSoonAfterAttach; @@ -57,18 +54,24 @@ public: using NodeRareData::isInTopLayer; using NodeRareData::setIsInTopLayer; #endif - - PassRefPtr<HTMLCollection> ensureCachedHTMLCollection(Element*, CollectionType); - HTMLCollection* cachedHTMLCollection(CollectionType type) - { - return nodeLists() ? nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0; - } - - void removeCachedHTMLCollection(HTMLCollection* collection, CollectionType type) - { - ASSERT(nodeLists()); - nodeLists()->removeCacheWithAtomicName(collection, type); - } + using NodeRareData::childrenAffectedByHover; + using NodeRareData::setChildrenAffectedByHover; + using NodeRareData::childrenAffectedByActive; + using NodeRareData::setChildrenAffectedByActive; + using NodeRareData::childrenAffectedByDrag; + using NodeRareData::setChildrenAffectedByDrag; + using NodeRareData::childrenAffectedByFirstChildRules; + using NodeRareData::setChildrenAffectedByFirstChildRules; + using NodeRareData::childrenAffectedByLastChildRules; + using NodeRareData::setChildrenAffectedByLastChildRules; + using NodeRareData::childrenAffectedByDirectAdjacentRules; + using NodeRareData::setChildrenAffectedByDirectAdjacentRules; + using NodeRareData::childrenAffectedByForwardPositionalRules; + using NodeRareData::setChildrenAffectedByForwardPositionalRules; + using NodeRareData::childrenAffectedByBackwardPositionalRules; + using NodeRareData::setChildrenAffectedByBackwardPositionalRules; + using NodeRareData::childIndex; + using NodeRareData::setChildIndex; virtual void reportMemoryUsage(MemoryObjectInfo*) const OVERRIDE; @@ -101,7 +104,22 @@ inline ElementRareData::~ElementRareData() inline void ElementRareData::resetComputedStyle() { m_computedStyle.clear(); + setStyleAffectedByEmpty(false); + setChildIndex(0); } +inline void ElementRareData::resetDynamicRestyleObservations() +{ + setChildrenAffectedByHover(false); + setChildrenAffectedByActive(false); + setChildrenAffectedByDrag(false); + setChildrenAffectedByFirstChildRules(false); + setChildrenAffectedByLastChildRules(false); + setChildrenAffectedByDirectAdjacentRules(false); + setChildrenAffectedByForwardPositionalRules(false); + setChildrenAffectedByBackwardPositionalRules(false); } + +} // namespace + #endif // ElementRareData_h diff --git a/Source/WebCore/dom/LiveNodeList.h b/Source/WebCore/dom/LiveNodeList.h index 20a103d72..5b5368e94 100644 --- a/Source/WebCore/dom/LiveNodeList.h +++ b/Source/WebCore/dom/LiveNodeList.h @@ -66,6 +66,15 @@ public: ASSERT(m_invalidationType == static_cast<unsigned>(invalidationType)); ASSERT(m_collectionType == static_cast<unsigned>(collectionType)); ASSERT(!m_overridesItemAfter || !isNodeList(collectionType)); + + if (collectionType != ChildNodeListType) + document()->registerNodeList(this); + } + + virtual ~LiveNodeListBase() + { + if (type() != ChildNodeListType) + document()->unregisterNodeList(this); } virtual void reportMemoryUsage(MemoryObjectInfo*) const; @@ -186,16 +195,7 @@ public: LiveNodeList(PassRefPtr<Node> ownerNode, CollectionType collectionType, NodeListInvalidationType invalidationType, NodeListRootType rootType = NodeListIsRootedAtNode) : LiveNodeListBase(ownerNode.get(), rootType, invalidationType, collectionType == ChildNodeListType, collectionType, DoesNotOverrideItemAfter) - { - if (collectionType != ChildNodeListType) - document()->registerNodeListCache(this); - } - - virtual ~LiveNodeList() - { - if (type() != ChildNodeListType) - document()->unregisterNodeListCache(this); - } + { } virtual Node* namedItem(const AtomicString&) const OVERRIDE; virtual bool nodeMatches(Element*) const = 0; diff --git a/Source/WebCore/dom/NameNodeList.h b/Source/WebCore/dom/NameNodeList.h index 8d8512b1c..a7f7c1470 100644 --- a/Source/WebCore/dom/NameNodeList.h +++ b/Source/WebCore/dom/NameNodeList.h @@ -33,8 +33,9 @@ namespace WebCore { // NodeList which lists all Nodes in a Element with a given "name" attribute class NameNodeList : public LiveNodeList { public: - static PassRefPtr<NameNodeList> create(PassRefPtr<Node> rootNode, const AtomicString& name) + static PassRefPtr<NameNodeList> create(PassRefPtr<Node> rootNode, CollectionType type, const AtomicString& name) { + ASSERT_UNUSED(type, type == NameNodeListType); return adoptRef(new NameNodeList(rootNode, name)); } diff --git a/Source/WebCore/dom/Node.cpp b/Source/WebCore/dom/Node.cpp index 85014c94f..9f08903c1 100644 --- a/Source/WebCore/dom/Node.cpp +++ b/Source/WebCore/dom/Node.cpp @@ -345,12 +345,6 @@ Node::StyleChange Node::diff(const RenderStyle* s1, const RenderStyle* s2, Docum else if (s1->hasExplicitlyInheritedProperties() || s2->hasExplicitlyInheritedProperties()) ch = Inherit; - // For nth-child and other positional rules, treat styles as different if they have - // changed positionally in the DOM. This way subsequent sibling resolutions won't be confused - // by the wrong child index and evaluate to incorrect results. - if (ch == NoChange && s1->childIndex() != s2->childIndex()) - ch = NoInherit; - // If the pseudoStyles have changed, we want any StyleChange that is not NoChange // because setStyle will do the right thing with anything else. if (ch == NoChange && s1->hasAnyPublicPseudoStyles()) { @@ -954,6 +948,12 @@ bool Node::isMouseFocusable() const return isFocusable(); } +bool Node::documentFragmentIsShadowRoot() const +{ + ASSERT_NOT_REACHED(); + return false; +} + Node* Node::focusDelegate() { return this; @@ -1152,82 +1152,6 @@ void Node::checkSetPrefix(const AtomicString& prefix, ExceptionCode& ec) // Attribute-specific checks are in Attr::setPrefix(). } -static bool isChildTypeAllowed(Node* newParent, Node* child) -{ - if (child->nodeType() != Node::DOCUMENT_FRAGMENT_NODE) { - if (!newParent->childTypeAllowed(child->nodeType())) - return false; - return true; - } - - for (Node *n = child->firstChild(); n; n = n->nextSibling()) { - if (!newParent->childTypeAllowed(n->nodeType())) - return false; - } - return true; -} - -bool Node::canReplaceChild(Node* newChild, Node*) -{ - return isChildTypeAllowed(this, newChild); -} - -static void checkAcceptChild(Node* newParent, Node* newChild, ExceptionCode& ec) -{ - // Not mentioned in spec: throw NOT_FOUND_ERR if newChild is null - if (!newChild) { - ec = NOT_FOUND_ERR; - return; - } - - if (newParent->isReadOnlyNode()) { - ec = NO_MODIFICATION_ALLOWED_ERR; - return; - } - - if (newChild->inDocument() && newChild->nodeType() == Node::DOCUMENT_TYPE_NODE) { - ec = HIERARCHY_REQUEST_ERR; - return; - } - - // HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the - // newChild node, or if the node to append is one of this node's ancestors. - - if (newChild->contains(newParent)) { - ec = HIERARCHY_REQUEST_ERR; - return; - } -} - -void Node::checkReplaceChild(Node* newChild, Node* oldChild, ExceptionCode& ec) -{ - if (!oldChild) { - ec = NOT_FOUND_ERR; - return; - } - - checkAcceptChild(this, newChild, ec); - if (ec) - return; - - if (!canReplaceChild(newChild, oldChild)) { - ec = HIERARCHY_REQUEST_ERR; - return; - } -} - -void Node::checkAddChild(Node *newChild, ExceptionCode& ec) -{ - checkAcceptChild(this, newChild, ec); - if (ec) - return; - - if (!isChildTypeAllowed(this, newChild)) { - ec = HIERARCHY_REQUEST_ERR; - return; - } -} - bool Node::isDescendantOf(const Node *other) const { // Return true if other is an ancestor of this, otherwise false @@ -1995,7 +1919,7 @@ unsigned short Node::compareDocumentPosition(Node* otherNode) // If the nodes have different owning documents, they must be disconnected. Note that we avoid // comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug). if (start1->inDocument() != start2->inDocument() || - start1->document() != start2->document()) + start1->treeScope() != start2->treeScope()) return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC; // We need to find a common ancestor container, and then compare the indices of the two immediate children. diff --git a/Source/WebCore/dom/Node.h b/Source/WebCore/dom/Node.h index d3ab3bb78..6593f78e2 100644 --- a/Source/WebCore/dom/Node.h +++ b/Source/WebCore/dom/Node.h @@ -98,7 +98,7 @@ class PropertyNodeList; typedef int ExceptionCode; -const int nodeStyleChangeShift = 19; +const int nodeStyleChangeShift = 17; // SyntheticStyleChange means that we need to go through the entire style change logic even though // no style property has actually changed. It is used to restructure the tree when, for instance, @@ -233,8 +233,10 @@ public: virtual bool isCharacterDataNode() const { return false; } virtual bool isFrameOwnerElement() const { return false; } virtual bool isPluginElement() const { return false; } + virtual bool documentFragmentIsShadowRoot() const; bool isDocumentNode() const; - bool isShadowRoot() const { return getFlag(IsShadowRootFlag); } + bool isDocumentFragment() const { return getFlag(IsDocumentFragmentFlag); } + bool isShadowRoot() const { return isDocumentFragment() && documentFragmentIsShadowRoot(); } bool isInsertionPoint() const { return getFlag(IsInsertionPointFlag); } bool inNamedFlow() const { return getFlag(InNamedFlowFlag); } bool hasCustomCallbacks() const { return getFlag(HasCustomCallbacksFlag); } @@ -454,6 +456,7 @@ public: } bool isReadOnlyNode() const { return nodeType() == ENTITY_REFERENCE_NODE; } + bool isDocumentTypeNode() const { return nodeType() == DOCUMENT_TYPE_NODE; } virtual bool childTypeAllowed(NodeType) const { return false; } unsigned childNodeCount() const; Node* childNode(unsigned index) const; @@ -487,13 +490,6 @@ public: bool contains(const Node*) const; bool containsIncludingShadowDOM(Node*); - // This method is used to do strict error-checking when adding children via - // the public DOM API (e.g., appendChild()). - void checkAddChild(Node* newChild, ExceptionCode&); // Error-checking when adding via the DOM API - - void checkReplaceChild(Node* newChild, Node* oldChild, ExceptionCode&); - virtual bool canReplaceChild(Node* newChild, Node* oldChild); - // Used to determine whether range offsets use characters or node indices. virtual bool offsetInCharacters() const; // Number of DOM 16-bit units contained in node. Note that rendered text length can be different - e.g. because of @@ -699,39 +695,33 @@ private: IsHoveredFlag = 1 << 11, InActiveChainFlag = 1 << 12, HasRareDataFlag = 1 << 13, - IsShadowRootFlag = 1 << 14, + IsDocumentFragmentFlag = 1 << 14, // These bits are used by derived classes, pulled up here so they can // be stored in the same memory word as the Node bits above. IsParsingChildrenFinishedFlag = 1 << 15, // Element #if ENABLE(SVG) - AreSVGAttributesValidFlag = 1 << 16, // Element - IsSynchronizingSVGAttributesFlag = 1 << 17, // SVGElement - HasSVGRareDataFlag = 1 << 18, // SVGElement + HasSVGRareDataFlag = 1 << 16, // SVGElement #endif StyleChangeMask = 1 << nodeStyleChangeShift | 1 << (nodeStyleChangeShift + 1), - SelfOrAncestorHasDirAutoFlag = 1 << 21, + SelfOrAncestorHasDirAutoFlag = 1 << 19, - HasNameOrIsEditingTextFlag = 1 << 22, + HasNameOrIsEditingTextFlag = 1 << 20, - InNamedFlowFlag = 1 << 23, - HasSyntheticAttrChildNodesFlag = 1 << 24, - HasCustomCallbacksFlag = 1 << 25, - HasScopedHTMLStyleChildFlag = 1 << 26, - HasEventTargetDataFlag = 1 << 27, - V8CollectableDuringMinorGCFlag = 1 << 28, - IsInsertionPointFlag = 1 << 29, + InNamedFlowFlag = 1 << 21, + HasSyntheticAttrChildNodesFlag = 1 << 22, + HasCustomCallbacksFlag = 1 << 23, + HasScopedHTMLStyleChildFlag = 1 << 24, + HasEventTargetDataFlag = 1 << 25, + V8CollectableDuringMinorGCFlag = 1 << 26, + IsInsertionPointFlag = 1 << 27, -#if ENABLE(SVG) - DefaultNodeFlags = IsParsingChildrenFinishedFlag | AreSVGAttributesValidFlag, -#else - DefaultNodeFlags = IsParsingChildrenFinishedFlag, -#endif + DefaultNodeFlags = IsParsingChildrenFinishedFlag }; - // 2 bits remaining + // 4 bits remaining bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; } void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); } @@ -744,7 +734,8 @@ protected: CreateText = DefaultNodeFlags | IsTextFlag, CreateContainer = DefaultNodeFlags | IsContainerFlag, CreateElement = CreateContainer | IsElementFlag, - CreateShadowRoot = CreateContainer | IsShadowRootFlag, + CreateShadowRoot = CreateContainer | IsDocumentFragmentFlag, + CreateDocumentFragment = CreateContainer | IsDocumentFragmentFlag, CreateStyledElement = CreateElement | IsStyledElementFlag, CreateHTMLElement = CreateStyledElement | IsHTMLFlag, CreateFrameOwnerElement = CreateHTMLElement | HasCustomCallbacksFlag, @@ -840,12 +831,6 @@ protected: void clearIsParsingChildrenFinished() { clearFlag(IsParsingChildrenFinishedFlag); } #if ENABLE(SVG) - bool areSVGAttributesValid() const { return getFlag(AreSVGAttributesValidFlag); } - void setAreSVGAttributesValid() const { setFlag(AreSVGAttributesValidFlag); } - void clearAreSVGAttributesValid() { clearFlag(AreSVGAttributesValidFlag); } - bool isSynchronizingSVGAttributes() const { return getFlag(IsSynchronizingSVGAttributesFlag); } - void setIsSynchronizingSVGAttributes() const { setFlag(IsSynchronizingSVGAttributesFlag); } - void clearIsSynchronizingSVGAttributes() const { clearFlag(IsSynchronizingSVGAttributesFlag); } bool hasSVGRareData() const { return getFlag(HasSVGRareDataFlag); } void setHasSVGRareData() { setFlag(HasSVGRareDataFlag); } void clearHasSVGRareData() { clearFlag(HasSVGRareDataFlag); } @@ -867,7 +852,7 @@ inline void addSubresourceURL(ListHashSet<KURL>& urls, const KURL& url) inline ContainerNode* Node::parentNode() const { - return getFlag(IsShadowRootFlag) ? 0 : parent(); + return isShadowRoot() ? 0 : parent(); } inline void Node::setParentOrHostNode(ContainerNode* parent) @@ -882,7 +867,7 @@ inline ContainerNode* Node::parentOrHostNode() const inline ContainerNode* Node::parentNodeGuaranteedHostFree() const { - ASSERT(!getFlag(IsShadowRootFlag)); + ASSERT(!isShadowRoot()); return parentOrHostNode(); } diff --git a/Source/WebCore/dom/NodeRareData.h b/Source/WebCore/dom/NodeRareData.h index 65959f78b..ac551c3a2 100644 --- a/Source/WebCore/dom/NodeRareData.h +++ b/Source/WebCore/dom/NodeRareData.h @@ -70,13 +70,13 @@ public: if (!result.isNewEntry) return static_cast<T*>(result.iterator->value); - RefPtr<T> list = T::create(node, name); + RefPtr<T> list = T::create(node, collectionType, name); result.iterator->value = list.get(); return list.release(); } template<typename T> - PassRefPtr<T> addCacheWithAtomicName(Element* node, CollectionType collectionType) + PassRefPtr<T> addCacheWithAtomicName(Node* node, CollectionType collectionType) { NodeListAtomicNameCacheMap::AddResult result = m_atomicNameCaches.add(namedNodeListKey(collectionType, starAtom), 0); if (!result.isNewEntry) @@ -155,23 +155,23 @@ public: NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end(); for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it) { LiveNodeListBase* list = it->value; - oldDocument->unregisterNodeListCache(list); - newDocument->registerNodeListCache(list); + oldDocument->unregisterNodeList(list); + newDocument->registerNodeList(list); } NodeListNameCacheMap::const_iterator nameCacheEnd = m_nameCaches.end(); for (NodeListNameCacheMap::const_iterator it = m_nameCaches.begin(); it != nameCacheEnd; ++it) { LiveNodeListBase* list = it->value; - oldDocument->unregisterNodeListCache(list); - newDocument->registerNodeListCache(list); + oldDocument->unregisterNodeList(list); + newDocument->registerNodeList(list); } TagNodeListCacheNS::const_iterator tagEnd = m_tagNodeListCacheNS.end(); for (TagNodeListCacheNS::const_iterator it = m_tagNodeListCacheNS.begin(); it != tagEnd; ++it) { LiveNodeListBase* list = it->value; ASSERT(!list->isRootedAtDocument()); - oldDocument->unregisterNodeListCache(list); - newDocument->registerNodeListCache(list); + oldDocument->unregisterNodeList(list); + newDocument->registerNodeList(list); } } } @@ -183,14 +183,12 @@ private: std::pair<unsigned char, AtomicString> namedNodeListKey(CollectionType type, const AtomicString& name) { - ASSERT(type >= FirstNodeCollectionType); - return std::pair<unsigned char, AtomicString>(type - FirstNodeCollectionType, name); + return std::pair<unsigned char, AtomicString>(type, name); } std::pair<unsigned char, String> namedNodeListKey(CollectionType type, const String& name) { - ASSERT(type >= FirstNodeCollectionType); - return std::pair<unsigned char, String>(type - FirstNodeCollectionType, name); + return std::pair<unsigned char, String>(type, name); } NodeListAtomicNameCacheMap m_atomicNameCaches; @@ -205,6 +203,7 @@ public: : m_treeScope(0) , m_childNodeList(0) , m_tabIndex(0) + , m_childIndex(0) , m_tabIndexWasSetExplicitly(false) , m_isFocused(false) , m_needsFocusAppearanceUpdateSoonAfterAttach(false) @@ -216,6 +215,14 @@ public: #if ENABLE(DIALOG_ELEMENT) , m_isInTopLayer(false) #endif + , m_childrenAffectedByHover(false) + , m_childrenAffectedByActive(false) + , m_childrenAffectedByDrag(false) + , m_childrenAffectedByFirstChildRules(false) + , m_childrenAffectedByLastChildRules(false) + , m_childrenAffectedByDirectAdjacentRules(false) + , m_childrenAffectedByForwardPositionalRules(false) + , m_childrenAffectedByBackwardPositionalRules(false) { } @@ -338,12 +345,32 @@ protected: bool isInTopLayer() const { return m_isInTopLayer; } void setIsInTopLayer(bool value) { m_isInTopLayer = value; } #endif + bool childrenAffectedByHover() const { return m_childrenAffectedByHover; } + void setChildrenAffectedByHover(bool value) { m_childrenAffectedByHover = value; } + bool childrenAffectedByActive() const { return m_childrenAffectedByActive; } + void setChildrenAffectedByActive(bool value) { m_childrenAffectedByActive = value; } + bool childrenAffectedByDrag() const { return m_childrenAffectedByDrag; } + void setChildrenAffectedByDrag(bool value) { m_childrenAffectedByDrag = value; } + + bool childrenAffectedByFirstChildRules() const { return m_childrenAffectedByFirstChildRules; } + void setChildrenAffectedByFirstChildRules(bool value) { m_childrenAffectedByFirstChildRules = value; } + bool childrenAffectedByLastChildRules() const { return m_childrenAffectedByLastChildRules; } + void setChildrenAffectedByLastChildRules(bool value) { m_childrenAffectedByLastChildRules = value; } + bool childrenAffectedByDirectAdjacentRules() const { return m_childrenAffectedByDirectAdjacentRules; } + void setChildrenAffectedByDirectAdjacentRules(bool value) { m_childrenAffectedByDirectAdjacentRules = value; } + bool childrenAffectedByForwardPositionalRules() const { return m_childrenAffectedByForwardPositionalRules; } + void setChildrenAffectedByForwardPositionalRules(bool value) { m_childrenAffectedByForwardPositionalRules = value; } + bool childrenAffectedByBackwardPositionalRules() const { return m_childrenAffectedByBackwardPositionalRules; } + void setChildrenAffectedByBackwardPositionalRules(bool value) { m_childrenAffectedByBackwardPositionalRules = value; } + unsigned childIndex() const { return m_childIndex; } + void setChildIndex(unsigned index) { m_childIndex = index; } private: TreeScope* m_treeScope; OwnPtr<NodeListsNodeData> m_nodeLists; ChildNodeList* m_childNodeList; short m_tabIndex; + unsigned short m_childIndex; bool m_tabIndexWasSetExplicitly : 1; bool m_isFocused : 1; bool m_needsFocusAppearanceUpdateSoonAfterAttach : 1; @@ -355,6 +382,17 @@ private: #if ENABLE(DIALOG_ELEMENT) bool m_isInTopLayer : 1; #endif + bool m_childrenAffectedByHover : 1; + bool m_childrenAffectedByActive : 1; + bool m_childrenAffectedByDrag : 1; + // Bits for dynamic child matching. + // We optimize for :first-child and :last-child. The other positional child selectors like nth-child or + // *-child-of-type, we will just give up and re-evaluate whenever children change at all. + bool m_childrenAffectedByFirstChildRules : 1; + bool m_childrenAffectedByLastChildRules : 1; + bool m_childrenAffectedByDirectAdjacentRules : 1; + bool m_childrenAffectedByForwardPositionalRules : 1; + bool m_childrenAffectedByBackwardPositionalRules : 1; #if ENABLE(MUTATION_OBSERVERS) OwnPtr<Vector<OwnPtr<MutationObserverRegistration> > > m_mutationObserverRegistry; diff --git a/Source/WebCore/dom/NodeRenderingContext.cpp b/Source/WebCore/dom/NodeRenderingContext.cpp index 9bbf60aba..1482fc44a 100644 --- a/Source/WebCore/dom/NodeRenderingContext.cpp +++ b/Source/WebCore/dom/NodeRenderingContext.cpp @@ -86,8 +86,8 @@ RenderObject* NodeRenderingContext::nextRenderer() const ComposedShadowTreeWalker walker(m_node); for (walker.nextSibling(); walker.get(); walker.nextSibling()) { if (RenderObject* renderer = walker.get()->renderer()) { - // Do not return elements that are attached to a different flow-thread. - if (renderer->style() && !renderer->style()->flowThread().isEmpty()) + // Renderers for elements attached to a flow thread should be skipped because they are parented differently. + if (renderer->node()->isElementNode() && renderer->style() && !renderer->style()->flowThread().isEmpty()) continue; return renderer; } @@ -110,8 +110,8 @@ RenderObject* NodeRenderingContext::previousRenderer() const ComposedShadowTreeWalker walker(m_node); for (walker.previousSibling(); walker.get(); walker.previousSibling()) { if (RenderObject* renderer = walker.get()->renderer()) { - // Do not return elements that are attached to a different flow-thread. - if (renderer->style() && !renderer->style()->flowThread().isEmpty()) + // Renderers for elements attached to a flow thread should be skipped because they are parented differently. + if (renderer->node()->isElementNode() && renderer->style() && !renderer->style()->flowThread().isEmpty()) continue; return renderer; } @@ -217,11 +217,9 @@ void NodeRenderingContext::createRendererForElementIfNeeded() moveToFlowThreadIfNeeded(); - if (!element->rendererIsNeeded(*this)) { - if (m_style->affectedByEmpty()) - element->setStyleAffectedByEmpty(); + if (!element->rendererIsNeeded(*this)) return; - } + RenderObject* parentRenderer = this->parentRenderer(); RenderObject* nextRenderer = this->nextRenderer(); @@ -238,6 +236,11 @@ void NodeRenderingContext::createRendererForElementIfNeeded() newRenderer->destroy(); return; } + + // Make sure the RenderObject already knows it is going to be added to a RenderFlowThread before we set the style + // for the first time. Otherwise code using inRenderFlowThread() in the styleWillChange and styleDidChange will fail. + newRenderer->setInRenderFlowThread(parentRenderer->inRenderFlowThread()); + element->setRenderer(newRenderer); newRenderer->setAnimatableStyle(m_style.release()); // setAnimatableStyle() can depend on renderer() already being set. @@ -274,6 +277,11 @@ void NodeRenderingContext::createRendererForTextIfNeeded() newRenderer->destroy(); return; } + + // Make sure the RenderObject already knows it is going to be added to a RenderFlowThread before we set the style + // for the first time. Otherwise code using inRenderFlowThread() in the styleWillChange and styleDidChange will fail. + newRenderer->setInRenderFlowThread(parentRenderer->inRenderFlowThread()); + RenderObject* nextRenderer = this->nextRenderer(); textNode->setRenderer(newRenderer); // Parent takes care of the animations, no need to call setAnimatableStyle. diff --git a/Source/WebCore/dom/ShadowRoot.cpp b/Source/WebCore/dom/ShadowRoot.cpp index f3c0646d0..55eb28f50 100644 --- a/Source/WebCore/dom/ShadowRoot.cpp +++ b/Source/WebCore/dom/ShadowRoot.cpp @@ -55,19 +55,23 @@ namespace WebCore { +struct SameSizeAsShadowRoot : public DocumentFragment, public TreeScope, public DoublyLinkedListNode<ShadowRoot> { + void* pointers[3]; + unsigned countersAndFlags[1]; +}; + +COMPILE_ASSERT(sizeof(ShadowRoot) == sizeof(SameSizeAsShadowRoot), shadowroot_should_stay_small); + ShadowRoot::ShadowRoot(Document* document) : DocumentFragment(document, CreateShadowRoot) , TreeScope(this) , m_prev(0) , m_next(0) + , m_numberOfStyles(0) , m_applyAuthorStyles(false) , m_resetStyleInheritance(false) + , m_isAuthorShadowRoot(false) , m_registeredWithParentShadowRoot(false) - , m_insertionPointAssignedTo(0) - , m_numberOfShadowElementChildren(0) - , m_numberOfContentElementChildren(0) - , m_numberOfElementShadowChildren(0) - , m_numberOfStyles(0) { ASSERT(document); @@ -286,6 +290,20 @@ void ShadowRoot::removedFrom(ContainerNode* insertionPoint) DocumentFragment::removedFrom(insertionPoint); } +InsertionPoint* ShadowRoot::assignedTo() const +{ + if (!distributionData()) + return 0; + + return distributionData()->insertionPointAssignedTo(); +} + +void ShadowRoot::setAssignedTo(InsertionPoint* insertionPoint) +{ + ASSERT(!assignedTo() || !insertionPoint); + ensureDistributionData()->setInsertionPointAssignedTo(insertionPoint); +} + void ShadowRoot::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) { GuardOrphanShadowRoot({ }); @@ -294,6 +312,14 @@ void ShadowRoot::childrenChanged(bool changedByParser, Node* beforeChange, Node* owner()->invalidateDistribution(); } +const Vector<InsertionPoint*>& ShadowRoot::insertionPointList() +{ + typedef Vector<InsertionPoint*> InsertionPointVector; + DEFINE_STATIC_LOCAL(InsertionPointVector, emptyVector, ()); + + return distributionData() ? distributionData()->ensureInsertionPointList(this) : emptyVector; +} + void ShadowRoot::registerScopedHTMLStyleChild() { ++m_numberOfStyles; @@ -307,6 +333,77 @@ void ShadowRoot::unregisterScopedHTMLStyleChild() setHasScopedHTMLStyleChild(m_numberOfStyles > 0); } +inline ShadowRootContentDistributionData* ShadowRoot::ensureDistributionData() +{ + if (m_distributionData) + return m_distributionData.get(); + + m_distributionData = adoptPtr(new ShadowRootContentDistributionData); + return m_distributionData.get(); +} + +void ShadowRoot::registerShadowElement() +{ + ensureDistributionData()->incrementNumberOfShadowElementChildren(); +} + +void ShadowRoot::unregisterShadowElement() +{ + distributionData()->decrementNumberOfShadowElementChildren(); +} + +bool ShadowRoot::hasShadowInsertionPoint() const +{ + if (!distributionData()) + return false; + + return distributionData()->hasShadowElementChildren(); +} + +void ShadowRoot::registerContentElement() +{ + ensureDistributionData()->incrementNumberOfContentElementChildren(); +} + +void ShadowRoot::unregisterContentElement() +{ + distributionData()->decrementNumberOfContentElementChildren(); +} + +bool ShadowRoot::hasContentElement() const +{ + if (!distributionData()) + return false; + + return distributionData()->hasContentElementChildren(); +} + +void ShadowRoot::registerElementShadow() +{ + ensureDistributionData()->incrementNumberOfElementShadowChildren(); +} + +void ShadowRoot::unregisterElementShadow() +{ + ASSERT(hasElementShadow()); + distributionData()->decrementNumberOfElementShadowChildren(); +} + +bool ShadowRoot::hasElementShadow() const +{ + if (!distributionData()) + return false; + + return distributionData()->hasElementShadowChildren(); +} + +unsigned ShadowRoot::countElementShadow() const +{ + if (!distributionData()) + return 0; + + return distributionData()->numberOfElementShadowChildren(); +} void ShadowRoot::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const { @@ -315,7 +412,7 @@ void ShadowRoot::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const TreeScope::reportMemoryUsage(memoryObjectInfo); info.addMember(m_prev); info.addMember(m_next); - info.addMember(m_insertionPointAssignedTo); + info.addMember(m_distributionData); } } diff --git a/Source/WebCore/dom/ShadowRoot.h b/Source/WebCore/dom/ShadowRoot.h index 0675427ec..0434f253f 100644 --- a/Source/WebCore/dom/ShadowRoot.h +++ b/Source/WebCore/dom/ShadowRoot.h @@ -39,8 +39,9 @@ namespace WebCore { class Document; class DOMSelection; -class InsertionPoint; class ElementShadow; +class InsertionPoint; +class ShadowRootContentDistributionData; class ShadowRoot : public DocumentFragment, public TreeScope, public DoublyLinkedListNode<ShadowRoot> { friend class WTF::DoublyLinkedListNode<ShadowRoot>; @@ -90,18 +91,20 @@ public: InsertionPoint* assignedTo() const; void setAssignedTo(InsertionPoint*); - void registerShadowElement() { ++m_numberOfShadowElementChildren; } - void unregisterShadowElement() { --m_numberOfShadowElementChildren; } - bool hasShadowInsertionPoint() const { return m_numberOfShadowElementChildren > 0; } + void registerShadowElement(); + void unregisterShadowElement(); + bool hasShadowInsertionPoint() const; + + void registerContentElement(); + void unregisterContentElement(); + bool hasContentElement() const; - void registerContentElement() { ++m_numberOfContentElementChildren; } - void unregisterContentElement() { --m_numberOfContentElementChildren; } - bool hasContentElement() const { return m_numberOfContentElementChildren > 0; } + void registerElementShadow(); + void unregisterElementShadow(); + bool hasElementShadow() const; + unsigned countElementShadow() const; - void registerElementShadow() { ++m_numberOfElementShadowChildren; } - void unregisterElementShadow() { ASSERT(hasElementShadow()); --m_numberOfElementShadowChildren; } - bool hasElementShadow() const { return m_numberOfElementShadowChildren > 0; } - size_t countElementShadow() const { return m_numberOfElementShadowChildren; } + const Vector<InsertionPoint*>& insertionPointList(); virtual void registerScopedHTMLStyleChild() OVERRIDE; virtual void unregisterScopedHTMLStyleChild() OVERRIDE; @@ -119,20 +122,22 @@ private: virtual PassRefPtr<Node> cloneNode(bool deep); virtual bool childTypeAllowed(NodeType) const; virtual void childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) OVERRIDE; + virtual bool documentFragmentIsShadowRoot() const OVERRIDE { return true; } void setType(ShadowRootType type) { m_isAuthorShadowRoot = type == AuthorShadowRoot; } + ShadowRootContentDistributionData* distributionData() { return m_distributionData.get(); } + const ShadowRootContentDistributionData* distributionData() const { return m_distributionData.get(); } + ShadowRootContentDistributionData* ensureDistributionData(); + ShadowRoot* m_prev; ShadowRoot* m_next; - bool m_applyAuthorStyles : 1; - bool m_resetStyleInheritance : 1; - bool m_isAuthorShadowRoot : 1; - bool m_registeredWithParentShadowRoot : 1; - InsertionPoint* m_insertionPointAssignedTo; - size_t m_numberOfShadowElementChildren; - size_t m_numberOfContentElementChildren; - size_t m_numberOfElementShadowChildren; - size_t m_numberOfStyles; + OwnPtr<ShadowRootContentDistributionData> m_distributionData; + unsigned m_numberOfStyles : 28; + unsigned m_applyAuthorStyles : 1; + unsigned m_resetStyleInheritance : 1; + unsigned m_isAuthorShadowRoot : 1; + unsigned m_registeredWithParentShadowRoot : 1; }; inline Element* ShadowRoot::host() const @@ -145,17 +150,6 @@ inline void ShadowRoot::setHost(Element* host) setParentOrHostNode(host); } -inline InsertionPoint* ShadowRoot::assignedTo() const -{ - return m_insertionPointAssignedTo; -} - -inline void ShadowRoot::setAssignedTo(InsertionPoint* insertionPoint) -{ - ASSERT(!m_insertionPointAssignedTo || !insertionPoint); - m_insertionPointAssignedTo = insertionPoint; -} - inline bool ShadowRoot::isUsedForRendering() const { return isYoungest() || assignedTo(); diff --git a/Source/WebCore/dom/TagNodeList.h b/Source/WebCore/dom/TagNodeList.h index 95c0f5da4..a0c1651ca 100644 --- a/Source/WebCore/dom/TagNodeList.h +++ b/Source/WebCore/dom/TagNodeList.h @@ -38,8 +38,9 @@ namespace WebCore { return adoptRef(new TagNodeList(rootNode, namespaceURI, localName)); } - static PassRefPtr<TagNodeList> create(PassRefPtr<Node> rootNode, const AtomicString& localName) + static PassRefPtr<TagNodeList> create(PassRefPtr<Node> rootNode, CollectionType type, const AtomicString& localName) { + ASSERT_UNUSED(type, type == TagNodeListType); return adoptRef(new TagNodeList(rootNode, starAtom, localName)); } @@ -56,8 +57,9 @@ namespace WebCore { class HTMLTagNodeList : public TagNodeList { public: - static PassRefPtr<HTMLTagNodeList> create(PassRefPtr<Node> rootNode, const AtomicString& localName) + static PassRefPtr<HTMLTagNodeList> create(PassRefPtr<Node> rootNode, CollectionType type, const AtomicString& localName) { + ASSERT_UNUSED(type, type == TagNodeListType); return adoptRef(new HTMLTagNodeList(rootNode, localName)); } diff --git a/Source/WebCore/dom/TreeScope.cpp b/Source/WebCore/dom/TreeScope.cpp index cc593c620..6b2fb30d9 100644 --- a/Source/WebCore/dom/TreeScope.cpp +++ b/Source/WebCore/dom/TreeScope.cpp @@ -1,5 +1,6 @@ /* * Copyright (C) 2011 Google Inc. All Rights Reserved. + * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -51,12 +52,18 @@ namespace WebCore { +struct SameSizeAsTreeScope { + virtual ~SameSizeAsTreeScope(); + void* pointers[7]; +}; + +COMPILE_ASSERT(sizeof(TreeScope) == sizeof(SameSizeAsTreeScope), treescope_should_stay_small); + using namespace HTMLNames; TreeScope::TreeScope(ContainerNode* rootNode) : m_rootNode(rootNode) , m_parentTreeScope(0) - , m_shouldCacheLabelsByForAttribute(false) , m_idTargetObserverRegistry(IdTargetObserverRegistry::create()) { ASSERT(rootNode); @@ -91,18 +98,24 @@ Element* TreeScope::getElementById(const AtomicString& elementId) const { if (elementId.isEmpty()) return 0; - return m_elementsById.getElementById(elementId.impl(), this); + if (!m_elementsById) + return 0; + return m_elementsById->getElementById(elementId.impl(), this); } void TreeScope::addElementById(const AtomicString& elementId, Element* element) { - m_elementsById.add(elementId.impl(), element); + if (!m_elementsById) + m_elementsById = adoptPtr(new DocumentOrderedMap); + m_elementsById->add(elementId.impl(), element); m_idTargetObserverRegistry->notifyObservers(elementId); } void TreeScope::removeElementById(const AtomicString& elementId, Element* element) { - m_elementsById.remove(elementId.impl(), element); + if (!m_elementsById) + return; + m_elementsById->remove(elementId.impl(), element); m_idTargetObserverRegistry->notifyObservers(elementId); } @@ -125,42 +138,54 @@ void TreeScope::addImageMap(HTMLMapElement* imageMap) AtomicStringImpl* name = imageMap->getName().impl(); if (!name) return; - m_imageMapsByName.add(name, imageMap); + if (!m_imageMapsByName) + m_imageMapsByName = adoptPtr(new DocumentOrderedMap); + m_imageMapsByName->add(name, imageMap); } void TreeScope::removeImageMap(HTMLMapElement* imageMap) { + if (!m_imageMapsByName) + return; AtomicStringImpl* name = imageMap->getName().impl(); if (!name) return; - m_imageMapsByName.remove(name, imageMap); + m_imageMapsByName->remove(name, imageMap); } HTMLMapElement* TreeScope::getImageMap(const String& url) const { if (url.isNull()) return 0; + if (!m_imageMapsByName) + return 0; size_t hashPos = url.find('#'); String name = (hashPos == notFound ? url : url.substring(hashPos + 1)).impl(); if (rootNode()->document()->isHTMLDocument()) - return static_cast<HTMLMapElement*>(m_imageMapsByName.getElementByLowercasedMapName(AtomicString(name.lower()).impl(), this)); - return static_cast<HTMLMapElement*>(m_imageMapsByName.getElementByMapName(AtomicString(name).impl(), this)); + return static_cast<HTMLMapElement*>(m_imageMapsByName->getElementByLowercasedMapName(AtomicString(name.lower()).impl(), this)); + return static_cast<HTMLMapElement*>(m_imageMapsByName->getElementByMapName(AtomicString(name).impl(), this)); } void TreeScope::addLabel(const AtomicString& forAttributeValue, HTMLLabelElement* element) { - m_labelsByForAttribute.add(forAttributeValue.impl(), element); + ASSERT(m_labelsByForAttribute); + m_labelsByForAttribute->add(forAttributeValue.impl(), element); } void TreeScope::removeLabel(const AtomicString& forAttributeValue, HTMLLabelElement* element) { - m_labelsByForAttribute.remove(forAttributeValue.impl(), element); + ASSERT(m_labelsByForAttribute); + m_labelsByForAttribute->remove(forAttributeValue.impl(), element); } HTMLLabelElement* TreeScope::labelElementForId(const AtomicString& forAttributeValue) { - if (!m_shouldCacheLabelsByForAttribute) { - m_shouldCacheLabelsByForAttribute = true; + if (forAttributeValue.isEmpty()) + return 0; + + if (!m_labelsByForAttribute) { + // Populate the map on first access. + m_labelsByForAttribute = adoptPtr(new DocumentOrderedMap); for (Node* node = rootNode(); node; node = node->traverseNextNode()) { if (node->hasTagName(labelTag)) { HTMLLabelElement* label = static_cast<HTMLLabelElement*>(node); @@ -171,10 +196,7 @@ HTMLLabelElement* TreeScope::labelElementForId(const AtomicString& forAttributeV } } - if (forAttributeValue.isEmpty()) - return 0; - - return static_cast<HTMLLabelElement*>(m_labelsByForAttribute.getElementByLabelForAttribute(forAttributeValue.impl(), this)); + return static_cast<HTMLLabelElement*>(m_labelsByForAttribute->getElementByLabelForAttribute(forAttributeValue.impl(), this)); } DOMSelection* TreeScope::getSelection() const diff --git a/Source/WebCore/dom/TreeScope.h b/Source/WebCore/dom/TreeScope.h index 4a034a2d1..cb6690dc6 100644 --- a/Source/WebCore/dom/TreeScope.h +++ b/Source/WebCore/dom/TreeScope.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2011 Google Inc. All Rights Reserved. + * Copyright (C) 2012 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -64,7 +65,7 @@ public: HTMLMapElement* getImageMap(const String& url) const; // For accessibility. - bool shouldCacheLabelsByForAttribute() const { return m_shouldCacheLabelsByForAttribute; } + bool shouldCacheLabelsByForAttribute() const { return m_labelsByForAttribute; } void addLabel(const AtomicString& forAttributeValue, HTMLLabelElement*); void removeLabel(const AtomicString& forAttributeValue, HTMLLabelElement*); HTMLLabelElement* labelElementForId(const AtomicString& forAttributeValue); @@ -100,11 +101,9 @@ private: ContainerNode* m_rootNode; TreeScope* m_parentTreeScope; - DocumentOrderedMap m_elementsById; - DocumentOrderedMap m_imageMapsByName; - - DocumentOrderedMap m_labelsByForAttribute; - bool m_shouldCacheLabelsByForAttribute; + OwnPtr<DocumentOrderedMap> m_elementsById; + OwnPtr<DocumentOrderedMap> m_imageMapsByName; + OwnPtr<DocumentOrderedMap> m_labelsByForAttribute; OwnPtr<IdTargetObserverRegistry> m_idTargetObserverRegistry; @@ -114,12 +113,12 @@ private: inline bool TreeScope::hasElementWithId(AtomicStringImpl* id) const { ASSERT(id); - return m_elementsById.contains(id); + return m_elementsById && m_elementsById->contains(id); } inline bool TreeScope::containsMultipleElementsWithId(const AtomicString& id) const { - return m_elementsById.containsMultiple(id.impl()); + return m_elementsById && m_elementsById->containsMultiple(id.impl()); } TreeScope* commonTreeScope(Node*, Node*); diff --git a/Source/WebCore/dom/ViewportArguments.cpp b/Source/WebCore/dom/ViewportArguments.cpp index e1ade63d1..eae6820a9 100644 --- a/Source/WebCore/dom/ViewportArguments.cpp +++ b/Source/WebCore/dom/ViewportArguments.cpp @@ -175,14 +175,20 @@ ViewportAttributes ViewportArguments::resolve(const FloatSize& initialViewportSi resultWidth = compareIgnoringAuto(resultWidth, deviceSize.width() / compareIgnoringAuto(resultZoom, resultMaxZoom, min), max); resultHeight = compareIgnoringAuto(resultHeight, deviceSize.height() / compareIgnoringAuto(resultZoom, resultMaxZoom, min), max); } + + resultWidth = max<float>(1, resultWidth); + resultHeight = max<float>(1, resultHeight); } - // Clamp values to valid range. - resultWidth = clampLengthValue(resultWidth); - resultHeight = clampLengthValue(resultHeight); - resultZoom = clampScaleValue(resultZoom); - resultMinZoom = clampScaleValue(resultMinZoom); - resultMaxZoom = clampScaleValue(resultMaxZoom); + if (type != ViewportArguments::CSSDeviceAdaptation && type != ViewportArguments::Implicit) { + // Clamp values to a valid range, but not for @viewport since is + // not mandated by the specification. + resultWidth = clampLengthValue(resultWidth); + resultHeight = clampLengthValue(resultHeight); + resultZoom = clampScaleValue(resultZoom); + resultMinZoom = clampScaleValue(resultMinZoom); + resultMaxZoom = clampScaleValue(resultMaxZoom); + } ViewportAttributes result; result.orientation = orientation; @@ -229,9 +235,12 @@ ViewportAttributes ViewportArguments::resolve(const FloatSize& initialViewportSi if (resultHeight == ViewportArguments::ValueAuto) resultHeight = resultWidth * (initialViewportSize.height() / initialViewportSize.width()); - // Extend width and height to fill the visual viewport for the resolved initial-scale. - resultWidth = max<float>(resultWidth, initialViewportSize.width() / result.initialScale); - resultHeight = max<float>(resultHeight, initialViewportSize.height() / result.initialScale); + if (type == ViewportArguments::ViewportMeta) { + // Extend width and height to fill the visual viewport for the resolved initial-scale. + resultWidth = max<float>(resultWidth, initialViewportSize.width() / result.initialScale); + resultHeight = max<float>(resultHeight, initialViewportSize.height() / result.initialScale); + } + result.layoutSize.setWidth(resultWidth); result.layoutSize.setHeight(resultHeight); diff --git a/Source/WebCore/dom/WebKitNamedFlow.cpp b/Source/WebCore/dom/WebKitNamedFlow.cpp index b9debd9dd..ab26302f1 100644 --- a/Source/WebCore/dom/WebKitNamedFlow.cpp +++ b/Source/WebCore/dom/WebKitNamedFlow.cpp @@ -196,9 +196,12 @@ EventTargetData* WebKitNamedFlow::ensureEventTargetData() void WebKitNamedFlow::dispatchRegionLayoutUpdateEvent() { ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden()); - ASSERT(m_parentFlowThread); - RefPtr<Event> event = UIEvent::create(eventNames().webkitregionlayoutupdateEvent, false, false, m_parentFlowThread->document()->defaultView(), 0); + // If the flow is in the "NULL" state the event should not be dispatched any more. + if (flowState() == FlowStateNull) + return; + + RefPtr<Event> event = UIEvent::create(eventNames().webkitregionlayoutupdateEvent, false, false, m_flowManager->document()->defaultView(), 0); dispatchEvent(event); } diff --git a/Source/WebCore/dom/make_names.pl b/Source/WebCore/dom/make_names.pl index 715ba56e4..201f45f44 100755 --- a/Source/WebCore/dom/make_names.pl +++ b/Source/WebCore/dom/make_names.pl @@ -1070,7 +1070,7 @@ static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namesp { Settings* settings = element->document()->settings(); if (!MediaPlayer::isAvailable() || (settings && !settings->isMediaEnabled())) - return wrap(element, creationContext, isolate); + return createV8$parameters{namespace}DirectWrapper(element, creationContext, isolate); return wrap(static_cast<${JSInterfaceName}*>(element), creationContext, isolate); } @@ -1082,7 +1082,7 @@ END static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { if (!ContextFeatures::${contextConditional}Enabled(element->document())) - return wrap(to$parameters{fallbackInterfaceName}(element), creationContext, isolate); + return createV8$parameters{namespace}FallbackWrapper(to$parameters{fallbackInterfaceName}(element), creationContext, isolate); return wrap(static_cast<${JSInterfaceName}*>(element), creationContext, isolate); } END @@ -1093,7 +1093,7 @@ END static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { if (!RuntimeEnabledFeatures::${runtimeConditional}Enabled()) - return wrap(to$parameters{fallbackInterfaceName}(element), creationContext, isolate); + return createV8$parameters{namespace}FallbackWrapper(to$parameters{fallbackInterfaceName}(element), creationContext, isolate); return wrap(static_cast<${JSInterfaceName}*>(element), creationContext, isolate); } END @@ -1331,6 +1331,8 @@ END ; } elsif ($wrapperFactoryType eq "V8") { print F <<END +#include <V8$parameters{namespace}Element.h> +#include <V8$parameters{fallbackInterfaceName}.h> #include <v8.h> namespace WebCore { @@ -1338,6 +1340,14 @@ namespace WebCore { class $parameters{namespace}Element; v8::Handle<v8::Object> createV8$parameters{namespace}Wrapper($parameters{namespace}Element*, v8::Handle<v8::Object> creationContext, v8::Isolate*); + inline v8::Handle<v8::Object> createV8$parameters{namespace}DirectWrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) + { + return V8$parameters{namespace}Element::createWrapper(element, creationContext, isolate); + } + inline v8::Handle<v8::Object> createV8$parameters{namespace}FallbackWrapper($parameters{fallbackInterfaceName}* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) + { + return V8$parameters{fallbackInterfaceName}::createWrapper(element, creationContext, isolate); + } } END ; diff --git a/Source/WebCore/editing/TextIterator.cpp b/Source/WebCore/editing/TextIterator.cpp index 789a3fabb..a2ac20f7a 100644 --- a/Source/WebCore/editing/TextIterator.cpp +++ b/Source/WebCore/editing/TextIterator.cpp @@ -462,6 +462,26 @@ void TextIterator::advance() } } +UChar TextIterator::characterAt(unsigned index) const +{ + ASSERT(index < static_cast<unsigned>(length())); + if (!(index < static_cast<unsigned>(length()))) + return 0; + + if (!m_textCharacters) + return string()[startOffset() + index]; + + return m_textCharacters[index]; +} + +void TextIterator::appendTextToStringBuilder(StringBuilder& builder) const +{ + if (!m_textCharacters) + builder.append(string(), startOffset(), length()); + else + builder.append(characters(), length()); +} + bool TextIterator::handleTextNode() { if (m_fullyClippedStack.top() && !m_ignoresStyleVisibility) @@ -1007,7 +1027,7 @@ void TextIterator::emitText(Node* textNode, RenderObject* renderObject, int text { RenderText* renderer = toRenderText(renderObject); m_text = m_emitsOriginalText ? renderer->originalText() : (m_emitsTextWithoutTranscoding ? renderer->textWithoutTranscoding() : renderer->text()); - ASSERT(m_text.characters()); + ASSERT(!m_text.isEmpty()); ASSERT(0 <= textStartOffset && textStartOffset < static_cast<int>(m_text.length())); ASSERT(0 <= textEndOffset && textEndOffset <= static_cast<int>(m_text.length())); ASSERT(textStartOffset <= textEndOffset); @@ -1016,7 +1036,7 @@ void TextIterator::emitText(Node* textNode, RenderObject* renderObject, int text m_positionOffsetBaseNode = 0; m_positionStartOffset = textStartOffset; m_positionEndOffset = textEndOffset; - m_textCharacters = m_text.characters() + textStartOffset; + m_textCharacters = 0; m_textLength = textEndOffset - textStartOffset; m_lastCharacter = m_text[textEndOffset - 1]; @@ -2439,7 +2459,7 @@ PassRefPtr<Range> TextIterator::rangeFromLocationAndLength(ContainerNode* scope, if (foundEnd) { // FIXME: This is a workaround for the fact that the end of a run is often at the wrong // position for emitted '\n's. - if (len == 1 && it.characters()[0] == '\n') { + if (len == 1 && it.characterAt(0) == '\n') { scope->document()->updateLayoutIgnorePendingStylesheets(); it.advance(); if (!it.atEnd()) { @@ -2531,82 +2551,38 @@ bool TextIterator::getLocationAndLengthFromRange(Element* scope, const Range* ra } // -------- - -UChar* plainTextToMallocAllocatedBuffer(const Range* r, unsigned& bufferLength, bool isDisplayString, TextIteratorBehavior defaultBehavior) -{ - UChar* result = 0; +String plainText(const Range* r, TextIteratorBehavior defaultBehavior, bool isDisplayString) +{ // The initial buffer size can be critical for performance: https://bugs.webkit.org/show_bug.cgi?id=81192 static const unsigned cMaxSegmentSize = 1 << 15; - bufferLength = 0; - typedef pair<UChar*, unsigned> TextSegment; - OwnPtr<Vector<TextSegment> > textSegments; - Vector<UChar> textBuffer; - textBuffer.reserveInitialCapacity(cMaxSegmentSize); + + unsigned bufferLength = 0; + StringBuilder builder; + builder.reserveCapacity(cMaxSegmentSize); TextIteratorBehavior behavior = defaultBehavior; if (!isDisplayString) behavior = static_cast<TextIteratorBehavior>(behavior | TextIteratorEmitsTextsWithoutTranscoding); for (TextIterator it(r, behavior); !it.atEnd(); it.advance()) { - if (textBuffer.size() && textBuffer.size() + it.length() > cMaxSegmentSize) { - UChar* newSegmentBuffer = static_cast<UChar*>(malloc(textBuffer.size() * sizeof(UChar))); - if (!newSegmentBuffer) - goto exit; - memcpy(newSegmentBuffer, textBuffer.data(), textBuffer.size() * sizeof(UChar)); - if (!textSegments) - textSegments = adoptPtr(new Vector<TextSegment>); - textSegments->append(make_pair(newSegmentBuffer, (unsigned)textBuffer.size())); - textBuffer.clear(); - } - textBuffer.append(it.characters(), it.length()); + if (builder.capacity() < builder.length() + it.length()) + builder.reserveCapacity(builder.capacity() + cMaxSegmentSize); + + it.appendTextToStringBuilder(builder); bufferLength += it.length(); } if (!bufferLength) - return 0; - - // Since we know the size now, we can make a single buffer out of the pieces with one big alloc - result = static_cast<UChar*>(malloc(bufferLength * sizeof(UChar))); - if (!result) - goto exit; + return emptyString(); - { - UChar* resultPos = result; - if (textSegments) { - unsigned size = textSegments->size(); - for (unsigned i = 0; i < size; ++i) { - const TextSegment& segment = textSegments->at(i); - memcpy(resultPos, segment.first, segment.second * sizeof(UChar)); - resultPos += segment.second; - } - } - memcpy(resultPos, textBuffer.data(), textBuffer.size() * sizeof(UChar)); - } + String result = builder.toString(); -exit: - if (textSegments) { - unsigned size = textSegments->size(); - for (unsigned i = 0; i < size; ++i) - free(textSegments->at(i).first); - } - if (isDisplayString && r->ownerDocument()) - r->ownerDocument()->displayBufferModifiedByEncoding(result, bufferLength); + r->ownerDocument()->displayStringModifiedByEncoding(result); return result; } -String plainText(const Range* r, TextIteratorBehavior defaultBehavior) -{ - unsigned length; - UChar* buf = plainTextToMallocAllocatedBuffer(r, length, false, defaultBehavior); - if (!buf) - return ""; - String result(buf, length); - free(buf); - return result; -} - static inline bool isAllCollapsibleWhitespace(const String& string) { const UChar* characters = string.characters(); diff --git a/Source/WebCore/editing/TextIterator.h b/Source/WebCore/editing/TextIterator.h index ec531aa59..b01fe594c 100644 --- a/Source/WebCore/editing/TextIterator.h +++ b/Source/WebCore/editing/TextIterator.h @@ -60,8 +60,7 @@ inline bool isCollapsibleWhitespace(UChar c) } } -String plainText(const Range*, TextIteratorBehavior defaultBehavior = TextIteratorDefaultBehavior); -UChar* plainTextToMallocAllocatedBuffer(const Range*, unsigned& bufferLength, bool isDisplayString, TextIteratorBehavior = TextIteratorDefaultBehavior); +String plainText(const Range*, TextIteratorBehavior defaultBehavior = TextIteratorDefaultBehavior, bool isDisplayString = false); PassRefPtr<Range> findPlainText(const Range*, const String&, FindOptions); class BitStack { @@ -94,7 +93,9 @@ public: void advance(); int length() const { return m_textLength; } - const UChar* characters() const { return m_textCharacters; } + const UChar* characters() const { return m_textCharacters ? m_textCharacters : m_text.characters() + startOffset(); } + UChar characterAt(unsigned index) const; + void appendTextToStringBuilder(StringBuilder&) const; PassRefPtr<Range> range() const; Node* node() const; @@ -105,6 +106,8 @@ public: static PassRefPtr<Range> subrange(Range* entireRange, int characterOffset, int characterCount); private: + int startOffset() const { return m_positionStartOffset; } + const String& string() const { return m_text; } void exitNode(); bool shouldRepresentNodeOffsetZero(); bool shouldEmitSpaceBeforeAndAfterNode(Node*); @@ -139,7 +142,7 @@ private: mutable Node* m_positionOffsetBaseNode; mutable int m_positionStartOffset; mutable int m_positionEndOffset; - const UChar* m_textCharacters; + const UChar* m_textCharacters; // If null, then use m_text for character data. int m_textLength; // Hold string m_textCharacters points to so we ensure it won't be deleted. String m_text; diff --git a/Source/WebCore/html/BaseDateAndTimeInputType.cpp b/Source/WebCore/html/BaseDateAndTimeInputType.cpp index 00a1ffc38..2ad9fea79 100644 --- a/Source/WebCore/html/BaseDateAndTimeInputType.cpp +++ b/Source/WebCore/html/BaseDateAndTimeInputType.cpp @@ -180,5 +180,10 @@ String BaseDateAndTimeInputType::sanitizeValue(const String& proposedValue) cons return typeMismatchFor(proposedValue) ? String() : proposedValue; } +bool BaseDateAndTimeInputType::supportsReadOnly() const +{ + return true; +} + } // namespace WebCore #endif diff --git a/Source/WebCore/html/BaseDateAndTimeInputType.h b/Source/WebCore/html/BaseDateAndTimeInputType.h index 63b26723e..bcc7b2310 100644 --- a/Source/WebCore/html/BaseDateAndTimeInputType.h +++ b/Source/WebCore/html/BaseDateAndTimeInputType.h @@ -66,6 +66,7 @@ private: virtual String serializeWithMilliseconds(double) const; virtual String localizeValue(const String&) const OVERRIDE; virtual String convertFromVisibleValue(const String&) const OVERRIDE; + virtual bool supportsReadOnly() const OVERRIDE; }; } // namespace WebCore diff --git a/Source/WebCore/html/BaseMultipleFieldsDateAndTimeInputType.cpp b/Source/WebCore/html/BaseMultipleFieldsDateAndTimeInputType.cpp index 4bd7cde2c..b55e9a5a7 100644 --- a/Source/WebCore/html/BaseMultipleFieldsDateAndTimeInputType.cpp +++ b/Source/WebCore/html/BaseMultipleFieldsDateAndTimeInputType.cpp @@ -41,6 +41,7 @@ #include "HTMLInputElement.h" #include "HTMLOptionElement.h" #include "KeyboardEvent.h" +#include "LocalizedStrings.h" #include "Page.h" #include "PickerIndicatorElement.h" #include "PlatformLocale.h" @@ -168,6 +169,11 @@ BaseMultipleFieldsDateAndTimeInputType::~BaseMultipleFieldsDateAndTimeInputType( m_pickerIndicatorElement->removePickerIndicatorOwner(); } +String BaseMultipleFieldsDateAndTimeInputType::badInputText() const +{ + return validationMessageBadInputForDateTimeText(); +} + void BaseMultipleFieldsDateAndTimeInputType::blur() { if (m_dateTimeEditElement) @@ -273,6 +279,11 @@ void BaseMultipleFieldsDateAndTimeInputType::handleKeydownEvent(KeyboardEvent* e forwardEvent(event); } +bool BaseMultipleFieldsDateAndTimeInputType::hasBadInput() const +{ + return element()->value().isEmpty() && m_dateTimeEditElement && m_dateTimeEditElement->anyEditableFieldsHaveValues(); +} + bool BaseMultipleFieldsDateAndTimeInputType::isKeyboardFocusable(KeyboardEvent*) const { return false; @@ -325,8 +336,10 @@ FormControlState BaseMultipleFieldsDateAndTimeInputType::saveFormControlState() void BaseMultipleFieldsDateAndTimeInputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior) { InputType::setValue(sanitizedValue, valueChanged, eventBehavior); - if (valueChanged || (sanitizedValue.isEmpty() && m_dateTimeEditElement && m_dateTimeEditElement->anyEditableFieldsHaveValues())) + if (valueChanged || (sanitizedValue.isEmpty() && m_dateTimeEditElement && m_dateTimeEditElement->anyEditableFieldsHaveValues())) { updateInnerTextValue(); + element()->setNeedsValidityCheck(); + } } bool BaseMultipleFieldsDateAndTimeInputType::shouldUseInputMethod() const diff --git a/Source/WebCore/html/BaseMultipleFieldsDateAndTimeInputType.h b/Source/WebCore/html/BaseMultipleFieldsDateAndTimeInputType.h index b5acc9e6b..bd41fffef 100644 --- a/Source/WebCore/html/BaseMultipleFieldsDateAndTimeInputType.h +++ b/Source/WebCore/html/BaseMultipleFieldsDateAndTimeInputType.h @@ -73,6 +73,7 @@ private: virtual bool setupDateTimeChooserParameters(DateTimeChooserParameters&) OVERRIDE FINAL; // InputType functions + virtual String badInputText() const OVERRIDE; virtual void blur() OVERRIDE FINAL; virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const OVERRIDE FINAL; virtual void createShadowSubtree() OVERRIDE FINAL; @@ -81,6 +82,7 @@ private: virtual void focus(bool restorePreviousSelection) OVERRIDE FINAL; virtual void forwardEvent(Event*) OVERRIDE FINAL; virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE FINAL; + virtual bool hasBadInput() const OVERRIDE; virtual bool hasCustomFocusLogic() const OVERRIDE FINAL; virtual bool isKeyboardFocusable(KeyboardEvent*) const OVERRIDE FINAL; virtual bool isMouseFocusable() const OVERRIDE FINAL; diff --git a/Source/WebCore/html/CollectionType.h b/Source/WebCore/html/CollectionType.h index f43d5df0d..9ec75c054 100644 --- a/Source/WebCore/html/CollectionType.h +++ b/Source/WebCore/html/CollectionType.h @@ -26,8 +26,7 @@ namespace WebCore { enum CollectionType { - // unnamed collection types cached in the document - + // Unnamed HTMLCollection types cached in the document. DocImages, // all <img> elements in the document DocApplets, // all <object> and <applet> elements DocEmbeds, // all <embed> elements @@ -35,16 +34,13 @@ enum CollectionType { DocLinks, // all <a> _and_ <area> elements with a value for href DocAnchors, // all <a> elements with a value for name DocScripts, // all <script> elements - DocAll, // "all" elements (IE) - // named collection types cached in the document - + // Named collection types cached in the document. WindowNamedItems, DocumentNamedItems, - // types not cached in the document; these are types that can't be used on a document - + // Unnamed HTMLCollection types cached in elements. NodeChildren, // first-level children (IE) TableTBodies, // all <tbody> elements in this table TSectionRows, // all row elements in this table section @@ -54,15 +50,12 @@ enum CollectionType { SelectedOptions, DataListOptions, MapAreas, - #if ENABLE(MICRODATA) ItemProperties, // Microdata item properties in the document #endif - FormControls, - // Live node lists. - + // Live NodeList. ChildNodeListType, ClassNodeListType, NameNodeListType, @@ -73,22 +66,8 @@ enum CollectionType { PropertyNodeListType, }; -static const CollectionType FirstUnnamedDocumentCachedType = DocImages; -static const unsigned NumUnnamedDocumentCachedTypes = WindowNamedItems - DocImages; - -static const CollectionType FirstNodeCollectionType = NodeChildren; static const CollectionType FirstNodeListType = ChildNodeListType; -inline bool isUnnamedDocumentCachedType(CollectionType type) -{ - return static_cast<unsigned>(type) < NumUnnamedDocumentCachedTypes; -} - -inline bool isNodeCollectionType(CollectionType type) -{ - return type >= FirstNodeCollectionType; -} - inline bool isNodeList(CollectionType type) { return type >= FirstNodeListType; diff --git a/Source/WebCore/html/FormAssociatedElement.cpp b/Source/WebCore/html/FormAssociatedElement.cpp index 3d889783e..8dfdae096 100644 --- a/Source/WebCore/html/FormAssociatedElement.cpp +++ b/Source/WebCore/html/FormAssociatedElement.cpp @@ -189,6 +189,11 @@ bool FormAssociatedElement::customError() const return element->willValidate() && !m_customValidationMessage.isEmpty(); } +bool FormAssociatedElement::hasBadInput() const +{ + return false; +} + bool FormAssociatedElement::patternMismatch() const { return false; @@ -222,7 +227,7 @@ bool FormAssociatedElement::typeMismatch() const bool FormAssociatedElement::valid() const { bool someError = typeMismatch() || stepMismatch() || rangeUnderflow() || rangeOverflow() - || tooLong() || patternMismatch() || valueMissing() || customError(); + || tooLong() || patternMismatch() || valueMissing() || hasBadInput() || customError(); return !someError; } diff --git a/Source/WebCore/html/FormAssociatedElement.h b/Source/WebCore/html/FormAssociatedElement.h index 390e0ee75..d1dc9a59c 100644 --- a/Source/WebCore/html/FormAssociatedElement.h +++ b/Source/WebCore/html/FormAssociatedElement.h @@ -77,6 +77,7 @@ public: // Override functions for patterMismatch, rangeOverflow, rangerUnderflow, // stepMismatch, tooLong and valueMissing must call willValidate method. + virtual bool hasBadInput() const; virtual bool patternMismatch() const; virtual bool rangeOverflow() const; virtual bool rangeUnderflow() const; diff --git a/Source/WebCore/html/HTMLCollection.cpp b/Source/WebCore/html/HTMLCollection.cpp index df20954de..278f7931a 100644 --- a/Source/WebCore/html/HTMLCollection.cpp +++ b/Source/WebCore/html/HTMLCollection.cpp @@ -29,6 +29,7 @@ #include "HTMLObjectElement.h" #include "HTMLOptionElement.h" #include "NodeList.h" +#include "NodeRareData.h" #if ENABLE(MICRODATA) #include "HTMLPropertiesCollection.h" @@ -179,7 +180,6 @@ HTMLCollection::HTMLCollection(Node* ownerNode, CollectionType type, ItemAfterOv : LiveNodeListBase(ownerNode, rootTypeFromCollectionType(type), invalidationTypeExcludingIdAndNameAttributes(type), WebCore::shouldOnlyIncludeDirectChildren(type), type, itemAfterOverrideType) { - document()->registerNodeListCache(this); } PassRefPtr<HTMLCollection> HTMLCollection::create(Node* base, CollectionType type) @@ -189,16 +189,9 @@ PassRefPtr<HTMLCollection> HTMLCollection::create(Node* base, CollectionType typ HTMLCollection::~HTMLCollection() { - if (isUnnamedDocumentCachedType(type())) { - ASSERT(base()->isDocumentNode()); - static_cast<Document*>(base())->removeCachedHTMLCollection(this, type()); - } else if (isNodeCollectionType(type())) { - ASSERT(base()->isElementNode()); - toElement(base())->removeCachedHTMLCollection(this, type()); - } else // HTMLNameCollection removes cache by itself. - ASSERT(type() == WindowNamedItems || type() == DocumentNamedItems); - - document()->unregisterNodeListCache(this); + // HTMLNameCollection removes cache by itself. + if (type() != WindowNamedItems && type() != DocumentNamedItems) + ownerNode()->nodeLists()->removeCacheWithAtomicName(this, type()); } static inline bool isAcceptableElement(CollectionType type, Element* element) diff --git a/Source/WebCore/html/HTMLFontElement.cpp b/Source/WebCore/html/HTMLFontElement.cpp index a5bc8de31..1bad02e73 100644 --- a/Source/WebCore/html/HTMLFontElement.cpp +++ b/Source/WebCore/html/HTMLFontElement.cpp @@ -51,13 +51,14 @@ PassRefPtr<HTMLFontElement> HTMLFontElement::create(const QualifiedName& tagName } // http://www.whatwg.org/specs/web-apps/current-work/multipage/rendering.html#fonts-and-colors -static bool parseFontSize(const String& input, int& size) +template <typename CharacterType> +static bool parseFontSize(const CharacterType* characters, unsigned length, int& size) { // Step 1 // Step 2 - const UChar* position = input.characters(); - const UChar* end = position + input.length(); + const CharacterType* position = characters; + const CharacterType* end = characters + length; // Step 3 while (position < end) { @@ -106,7 +107,12 @@ static bool parseFontSize(const String& input, int& size) return false; // Step 8 - int value = charactersToIntStrict(digits.characters(), digits.length()); + int value; + + if (digits.is8Bit()) + value = charactersToIntStrict(digits.characters8(), digits.length()); + else + value = charactersToIntStrict(digits.characters16(), digits.length()); // Step 9 if (mode == RelativePlus) @@ -126,6 +132,17 @@ static bool parseFontSize(const String& input, int& size) return true; } +static bool parseFontSize(const String& input, int& size) +{ + if (input.isEmpty()) + return false; + + if (input.is8Bit()) + return parseFontSize(input.characters8(), input.length(), size); + + return parseFontSize(input.characters16(), input.length(), size); +} + bool HTMLFontElement::cssValueFromFontSizeNumber(const String& s, int& size) { int num = 0; diff --git a/Source/WebCore/html/HTMLFormControlElement.cpp b/Source/WebCore/html/HTMLFormControlElement.cpp index 9b19f8c4d..d433946e8 100644 --- a/Source/WebCore/html/HTMLFormControlElement.cpp +++ b/Source/WebCore/html/HTMLFormControlElement.cpp @@ -172,8 +172,11 @@ static bool shouldAutofocus(HTMLFormControlElement* element) return false; if (element->document()->ignoreAutofocus()) return false; - if (element->document()->isSandboxed(SandboxAutomaticFeatures)) + if (element->document()->isSandboxed(SandboxAutomaticFeatures)) { + // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists. + element->document()->addConsoleMessage(HTMLMessageSource, LogMessageType, ErrorMessageLevel, "Blocked autofocusing on a form control because the form's frame is sandboxed and the 'allow-script' permission is not set."); return false; + } if (element->hasAutofocused()) return false; @@ -459,16 +462,6 @@ void HTMLFormControlElement::setCustomValidity(const String& error) setNeedsValidityCheck(); } -bool HTMLFormControlElement::shouldMatchReadOnlySelector() const -{ - return readOnly(); -} - -bool HTMLFormControlElement::shouldMatchReadWriteSelector() const -{ - return !readOnly(); -} - bool HTMLFormControlElement::validationMessageShadowTreeContains(Node* node) const { return m_validationMessage && m_validationMessage->shadowTreeContains(node); diff --git a/Source/WebCore/html/HTMLFormControlElement.h b/Source/WebCore/html/HTMLFormControlElement.h index ec6e885f5..185b37d92 100644 --- a/Source/WebCore/html/HTMLFormControlElement.h +++ b/Source/WebCore/html/HTMLFormControlElement.h @@ -81,8 +81,6 @@ public: virtual const AtomicString& formControlType() const OVERRIDE = 0; virtual bool isEnabledFormControl() const { return !disabled(); } - virtual bool shouldMatchReadOnlySelector() const OVERRIDE; - virtual bool shouldMatchReadWriteSelector() const OVERRIDE; virtual bool canTriggerImplicitSubmission() const { return false; } diff --git a/Source/WebCore/html/HTMLFormControlsCollection.cpp b/Source/WebCore/html/HTMLFormControlsCollection.cpp index e73520901..aac92ba46 100644 --- a/Source/WebCore/html/HTMLFormControlsCollection.cpp +++ b/Source/WebCore/html/HTMLFormControlsCollection.cpp @@ -36,13 +36,13 @@ using namespace HTMLNames; // Since the collections are to be "live", we have to do the // calculation every time if anything has changed. -HTMLFormControlsCollection::HTMLFormControlsCollection(Element* base) +HTMLFormControlsCollection::HTMLFormControlsCollection(Node* base) : HTMLCollection(base, FormControls, OverridesItemAfter) { ASSERT(base->hasTagName(formTag) || base->hasTagName(fieldsetTag)); } -PassRefPtr<HTMLFormControlsCollection> HTMLFormControlsCollection::create(Element* base, CollectionType) +PassRefPtr<HTMLFormControlsCollection> HTMLFormControlsCollection::create(Node* base, CollectionType) { return adoptRef(new HTMLFormControlsCollection(base)); } diff --git a/Source/WebCore/html/HTMLFormControlsCollection.h b/Source/WebCore/html/HTMLFormControlsCollection.h index 7846a504e..cef0f14d5 100644 --- a/Source/WebCore/html/HTMLFormControlsCollection.h +++ b/Source/WebCore/html/HTMLFormControlsCollection.h @@ -37,14 +37,14 @@ class QualifiedName; class HTMLFormControlsCollection : public HTMLCollection { public: - static PassRefPtr<HTMLFormControlsCollection> create(Element*, CollectionType); + static PassRefPtr<HTMLFormControlsCollection> create(Node*, CollectionType); virtual ~HTMLFormControlsCollection(); virtual Node* namedItem(const AtomicString& name) const; private: - HTMLFormControlsCollection(Element*); + HTMLFormControlsCollection(Node*); virtual void updateNameCache() const; diff --git a/Source/WebCore/html/HTMLInputElement.cpp b/Source/WebCore/html/HTMLInputElement.cpp index 4cae786f1..124af4e60 100644 --- a/Source/WebCore/html/HTMLInputElement.cpp +++ b/Source/WebCore/html/HTMLInputElement.cpp @@ -266,6 +266,11 @@ bool HTMLInputElement::valueMissing() const return willValidate() && m_inputType->valueMissing(value()); } +bool HTMLInputElement::hasBadInput() const +{ + return willValidate() && m_inputType->hasBadInput(); +} + bool HTMLInputElement::patternMismatch() const { return willValidate() && m_inputType->patternMismatch(value()); @@ -1391,11 +1396,6 @@ String HTMLInputElement::localizeValue(const String& proposedValue) const return m_inputType->localizeValue(proposedValue); } -bool HTMLInputElement::hasUnacceptableValue() const -{ - return m_inputType->hasUnacceptableValue(); -} - bool HTMLInputElement::isInRange() const { return m_inputType->isInRange(value()); @@ -1438,6 +1438,16 @@ bool HTMLInputElement::isRequiredFormControl() const return m_inputType->supportsRequired() && required(); } +bool HTMLInputElement::shouldMatchReadOnlySelector() const +{ + return m_inputType->supportsReadOnly() && readOnly(); +} + +bool HTMLInputElement::shouldMatchReadWriteSelector() const +{ + return m_inputType->supportsReadOnly() && !readOnly(); +} + void HTMLInputElement::addSearchResult() { m_inputType->addSearchResult(); diff --git a/Source/WebCore/html/HTMLInputElement.h b/Source/WebCore/html/HTMLInputElement.h index b0ac6ae96..f98b019f6 100644 --- a/Source/WebCore/html/HTMLInputElement.h +++ b/Source/WebCore/html/HTMLInputElement.h @@ -55,6 +55,7 @@ public: virtual bool shouldAutocomplete() const; // For ValidityState + virtual bool hasBadInput() const OVERRIDE; virtual bool patternMismatch() const OVERRIDE; virtual bool rangeUnderflow() const OVERRIDE; virtual bool rangeOverflow() const; @@ -288,6 +289,8 @@ public: static Vector<FileChooserFileInfo> filesFromFileInputFormControlState(const FormControlState&); + virtual bool shouldMatchReadOnlySelector() const OVERRIDE; + virtual bool shouldMatchReadWriteSelector() const OVERRIDE; virtual void setRangeText(const String& replacement, ExceptionCode&) OVERRIDE; virtual void setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionCode&) OVERRIDE; @@ -355,8 +358,6 @@ private: virtual bool isURLAttribute(const Attribute&) const OVERRIDE; - virtual bool hasUnacceptableValue() const; - virtual bool isInRange() const; virtual bool isOutOfRange() const; diff --git a/Source/WebCore/html/HTMLMediaElement.cpp b/Source/WebCore/html/HTMLMediaElement.cpp index 027dd21d9..732b91717 100644 --- a/Source/WebCore/html/HTMLMediaElement.cpp +++ b/Source/WebCore/html/HTMLMediaElement.cpp @@ -316,6 +316,10 @@ HTMLMediaElement::~HTMLMediaElement() if (m_mediaController) m_mediaController->removeMediaElement(this); +#if ENABLE(MEDIA_SOURCE) + setSourceState(MediaSource::closedKeyword()); +#endif + removeElementFromDocumentMap(this, document()); } @@ -676,16 +680,14 @@ String HTMLMediaElement::canPlayType(const String& mimeType, const String& keySy return canPlay; } -void HTMLMediaElement::load(ExceptionCode& ec) +void HTMLMediaElement::load() { RefPtr<HTMLMediaElement> protect(this); // loadInternal may result in a 'beforeload' event, which can make arbitrary DOM mutations. LOG(Media, "HTMLMediaElement::load()"); - if (userGestureRequiredForLoad() && !ScriptController::processingUserGesture()) { - ec = INVALID_STATE_ERR; + if (userGestureRequiredForLoad() && !ScriptController::processingUserGesture()) return; - } m_loadInitiatedByUserGesture = ScriptController::processingUserGesture(); if (m_loadInitiatedByUserGesture) @@ -2996,6 +2998,22 @@ void HTMLMediaElement::configureTextTrackGroup(const TrackGroup& group) const } } +void HTMLMediaElement::toggleTrackAtIndex(int index, bool exclusive) +{ + TextTrackList* trackList = textTracks(); + if (!trackList || !trackList->length()) + return; + + for (int i = 0, length = trackList->length(); i < length; ++i) { + TextTrack* track = trackList->item(i); + track->setShowingByDefault(false); + if (i == index) + track->setMode(TextTrack::showingKeyword()); + else if (exclusive || index == HTMLMediaElement::textTracksOffIndex()) + track->setMode(TextTrack::disabledKeyword()); + } +} + void HTMLMediaElement::configureTextTracks() { TrackGroup captionAndSubtitleTracks(TrackGroup::CaptionsAndSubtitles); @@ -3752,6 +3770,11 @@ void HTMLMediaElement::userCancelledLoad() void HTMLMediaElement::clearMediaPlayer(int flags) { #if !ENABLE(PLUGIN_PROXY_FOR_VIDEO) + +#if ENABLE(MEDIA_SOURCE) + setSourceState(MediaSource::closedKeyword()); +#endif + m_player.clear(); #endif stopPeriodicTimers(); @@ -3815,8 +3838,7 @@ void HTMLMediaElement::resume() // m_error is only left at MEDIA_ERR_ABORTED when the document becomes inactive (it is set to // MEDIA_ERR_ABORTED while the abortEvent is being sent, but cleared immediately afterwards). // This behavior is not specified but it seems like a sensible thing to do. - ExceptionCode ec; - load(ec); + load(); } if (renderer()) diff --git a/Source/WebCore/html/HTMLMediaElement.h b/Source/WebCore/html/HTMLMediaElement.h index c53129d62..80549c262 100644 --- a/Source/WebCore/html/HTMLMediaElement.h +++ b/Source/WebCore/html/HTMLMediaElement.h @@ -134,7 +134,7 @@ public: void setPreload(const String&); PassRefPtr<TimeRanges> buffered() const; - void load(ExceptionCode&); + void load(); String canPlayType(const String& mimeType, const String& keySystem = String(), const KURL& = KURL()) const; // ready state @@ -245,6 +245,9 @@ public: void configureTextTracks(); void configureTextTrackGroup(const TrackGroup&) const; + void toggleTrackAtIndex(int index, bool exclusive = true); + static int textTracksOffIndex() { return -1; } + bool userPrefersCaptions() const; bool userIsInterestedInThisTrackKind(String) const; bool textTracksAreReady() const; diff --git a/Source/WebCore/html/HTMLMediaElement.idl b/Source/WebCore/html/HTMLMediaElement.idl index ece0f5348..2ece5acaa 100644 --- a/Source/WebCore/html/HTMLMediaElement.idl +++ b/Source/WebCore/html/HTMLMediaElement.idl @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007, 2010, 2011 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2010, 2011, 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -43,8 +43,7 @@ readonly attribute unsigned short networkState; attribute DOMString preload; readonly attribute TimeRanges buffered; -void load() - raises (DOMException); +void load(); #if defined(ENABLE_ENCRYPTED_MEDIA) && ENABLE_ENCRYPTED_MEDIA DOMString canPlayType(in [Optional=DefaultIsUndefined] DOMString type, in [Optional=DefaultIsUndefined, TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem); #else diff --git a/Source/WebCore/html/HTMLNameCollection.cpp b/Source/WebCore/html/HTMLNameCollection.cpp index 36c7350a4..9e48527e9 100644 --- a/Source/WebCore/html/HTMLNameCollection.cpp +++ b/Source/WebCore/html/HTMLNameCollection.cpp @@ -27,12 +27,13 @@ #include "HTMLDocument.h" #include "HTMLNames.h" #include "HTMLObjectElement.h" +#include "NodeRareData.h" namespace WebCore { using namespace HTMLNames; -HTMLNameCollection::HTMLNameCollection(Document* document, CollectionType type, const AtomicString& name) +HTMLNameCollection::HTMLNameCollection(Node* document, CollectionType type, const AtomicString& name) : HTMLCollection(document, type, OverridesItemAfter) , m_name(name) { @@ -43,10 +44,8 @@ HTMLNameCollection::~HTMLNameCollection() ASSERT(base()); ASSERT(base()->isDocumentNode()); ASSERT(type() == WindowNamedItems || type() == DocumentNamedItems); - if (type() == WindowNamedItems) - static_cast<Document*>(base())->removeWindowNamedItemCache(this, m_name); - else - static_cast<Document*>(base())->removeDocumentNamedItemCache(this, m_name); + + ownerNode()->nodeLists()->removeCacheWithAtomicName(this, type(), m_name); } Element* HTMLNameCollection::virtualItemAfter(unsigned& offsetInArray, Element* previous) const diff --git a/Source/WebCore/html/HTMLNameCollection.h b/Source/WebCore/html/HTMLNameCollection.h index 4a7afebb7..1fb85b994 100644 --- a/Source/WebCore/html/HTMLNameCollection.h +++ b/Source/WebCore/html/HTMLNameCollection.h @@ -33,7 +33,7 @@ class Document; class HTMLNameCollection : public HTMLCollection { public: - static PassRefPtr<HTMLNameCollection> create(Document* document, CollectionType type, const AtomicString& name) + static PassRefPtr<HTMLNameCollection> create(Node* document, CollectionType type, const AtomicString& name) { return adoptRef(new HTMLNameCollection(document, type, name)); } @@ -41,7 +41,7 @@ public: ~HTMLNameCollection(); private: - HTMLNameCollection(Document*, CollectionType, const AtomicString& name); + HTMLNameCollection(Node*, CollectionType, const AtomicString& name); virtual Element* virtualItemAfter(unsigned& offsetInArray, Element*) const OVERRIDE; diff --git a/Source/WebCore/html/HTMLOptionElement.h b/Source/WebCore/html/HTMLOptionElement.h index 1bcb9433c..19f569b97 100644 --- a/Source/WebCore/html/HTMLOptionElement.h +++ b/Source/WebCore/html/HTMLOptionElement.h @@ -92,8 +92,6 @@ private: String collectOptionInnerText() const; - String m_value; - String m_label; bool m_disabled; bool m_isSelected; RefPtr<RenderStyle> m_style; diff --git a/Source/WebCore/html/HTMLOptionsCollection.cpp b/Source/WebCore/html/HTMLOptionsCollection.cpp index 06dda7a25..75b707e55 100644 --- a/Source/WebCore/html/HTMLOptionsCollection.cpp +++ b/Source/WebCore/html/HTMLOptionsCollection.cpp @@ -27,13 +27,13 @@ namespace WebCore { -HTMLOptionsCollection::HTMLOptionsCollection(Element* select) +HTMLOptionsCollection::HTMLOptionsCollection(Node* select) : HTMLCollection(select, SelectOptions, DoesNotOverrideItemAfter) { ASSERT(select->hasTagName(HTMLNames::selectTag)); } -PassRefPtr<HTMLOptionsCollection> HTMLOptionsCollection::create(Element* select, CollectionType) +PassRefPtr<HTMLOptionsCollection> HTMLOptionsCollection::create(Node* select, CollectionType) { return adoptRef(new HTMLOptionsCollection(select)); } diff --git a/Source/WebCore/html/HTMLOptionsCollection.h b/Source/WebCore/html/HTMLOptionsCollection.h index 46e450df2..d76580fe7 100644 --- a/Source/WebCore/html/HTMLOptionsCollection.h +++ b/Source/WebCore/html/HTMLOptionsCollection.h @@ -35,7 +35,7 @@ typedef int ExceptionCode; class HTMLOptionsCollection : public HTMLCollection { public: - static PassRefPtr<HTMLOptionsCollection> create(Element*, CollectionType); + static PassRefPtr<HTMLOptionsCollection> create(Node*, CollectionType); void add(PassRefPtr<HTMLOptionElement>, ExceptionCode&); void add(PassRefPtr<HTMLOptionElement>, int index, ExceptionCode&); @@ -47,7 +47,7 @@ public: void setLength(unsigned, ExceptionCode&); private: - HTMLOptionsCollection(Element*); + HTMLOptionsCollection(Node*); }; } //namespace diff --git a/Source/WebCore/html/HTMLPlugInElement.cpp b/Source/WebCore/html/HTMLPlugInElement.cpp index bd99dbfd7..e2902ad71 100644 --- a/Source/WebCore/html/HTMLPlugInElement.cpp +++ b/Source/WebCore/html/HTMLPlugInElement.cpp @@ -201,7 +201,7 @@ void HTMLPlugInElement::defaultEventHandler(Event* event) toRenderEmbeddedObject(r)->handleUnavailablePluginIndicatorEvent(event); return; } - if (r->isSnapshottedPlugIn() && displayState() < Playing) { + if (r->isSnapshottedPlugIn() && displayState() < PlayingWithPendingMouseClick) { toRenderSnapshottedPlugIn(r)->handleEvent(event); return; } diff --git a/Source/WebCore/html/HTMLPlugInElement.h b/Source/WebCore/html/HTMLPlugInElement.h index 379324f70..5a62d54f3 100644 --- a/Source/WebCore/html/HTMLPlugInElement.h +++ b/Source/WebCore/html/HTMLPlugInElement.h @@ -51,11 +51,13 @@ public: enum DisplayState { WaitingForSnapshot, DisplayingSnapshot, + PlayingWithPendingMouseClick, Playing }; DisplayState displayState() const { return m_displayState; } void setDisplayState(DisplayState state) { m_displayState = state; } virtual void updateSnapshot(PassRefPtr<Image>) { } + virtual void dispatchPendingMouseClick() { } #if ENABLE(NETSCAPE_PLUGIN_API) NPObject* getNPObject(); diff --git a/Source/WebCore/html/HTMLPlugInImageElement.cpp b/Source/WebCore/html/HTMLPlugInImageElement.cpp index b809a1340..421ac1b0f 100644 --- a/Source/WebCore/html/HTMLPlugInImageElement.cpp +++ b/Source/WebCore/html/HTMLPlugInImageElement.cpp @@ -27,6 +27,7 @@ #include "HTMLImageLoader.h" #include "HTMLNames.h" #include "Image.h" +#include "MouseEvent.h" #include "NodeRenderStyle.h" #include "Page.h" #include "RenderEmbeddedObject.h" @@ -38,6 +39,9 @@ namespace WebCore { +// This delay should not exceed the snapshot delay in PluginView.cpp +static const double simulatedMouseClickTimerDelay = .75; + HTMLPlugInImageElement::HTMLPlugInImageElement(const QualifiedName& tagName, Document* document, bool createdByParser, PreferPlugInsForImagesOption preferPlugInsForImagesOption) : HTMLPlugInElement(tagName, document) // m_needsWidgetUpdate(!createdByParser) allows HTMLObjectElement to delay @@ -47,6 +51,7 @@ HTMLPlugInImageElement::HTMLPlugInImageElement(const QualifiedName& tagName, Doc , m_needsWidgetUpdate(!createdByParser) , m_shouldPreferPlugInsForImages(preferPlugInsForImagesOption == ShouldPreferPlugInsForImages) , m_needsDocumentActivationCallbacks(false) + , m_simulatedMouseClickTimer(this, &HTMLPlugInImageElement::simulatedMouseClickTimerFired, simulatedMouseClickTimerDelay) { setHasCustomCallbacks(); @@ -257,4 +262,26 @@ void HTMLPlugInImageElement::updateSnapshot(PassRefPtr<Image> image) setDisplayState(DisplayingSnapshot); } +void HTMLPlugInImageElement::setPendingClickEvent(PassRefPtr<MouseEvent> event) +{ + m_pendingClickEventFromSnapshot = event; +} + +void HTMLPlugInImageElement::dispatchPendingMouseClick() +{ + ASSERT(!m_simulatedMouseClickTimer.isActive()); + m_simulatedMouseClickTimer.restart(); +} + +void HTMLPlugInImageElement::simulatedMouseClickTimerFired(DeferrableOneShotTimer<HTMLPlugInImageElement>*) +{ + ASSERT(displayState() == PlayingWithPendingMouseClick); + ASSERT(m_pendingClickEventFromSnapshot); + + dispatchSimulatedClick(m_pendingClickEventFromSnapshot.get(), SendMouseOverUpDownEvents, DoNotShowPressedLook); + + setDisplayState(Playing); + m_pendingClickEventFromSnapshot = nullptr; +} + } // namespace WebCore diff --git a/Source/WebCore/html/HTMLPlugInImageElement.h b/Source/WebCore/html/HTMLPlugInImageElement.h index 95fbd8a79..c5bf6fa1f 100644 --- a/Source/WebCore/html/HTMLPlugInImageElement.h +++ b/Source/WebCore/html/HTMLPlugInImageElement.h @@ -30,6 +30,7 @@ namespace WebCore { class HTMLImageLoader; class FrameLoader; +class MouseEvent; enum PluginCreationOption { CreateAnyWidgetType, @@ -58,6 +59,8 @@ public: bool needsWidgetUpdate() const { return m_needsWidgetUpdate; } void setNeedsWidgetUpdate(bool needsWidgetUpdate) { m_needsWidgetUpdate = needsWidgetUpdate; } + void setPendingClickEvent(PassRefPtr<MouseEvent>); + protected: HTMLPlugInImageElement(const QualifiedName& tagName, Document*, bool createdByParser, PreferPlugInsForImagesOption); @@ -91,11 +94,15 @@ private: virtual bool useFallbackContent() const { return false; } virtual void updateSnapshot(PassRefPtr<Image>) OVERRIDE; + virtual void dispatchPendingMouseClick() OVERRIDE; + void simulatedMouseClickTimerFired(DeferrableOneShotTimer<HTMLPlugInImageElement>*); bool m_needsWidgetUpdate; bool m_shouldPreferPlugInsForImages; bool m_needsDocumentActivationCallbacks; RefPtr<RenderStyle> m_customStyleForPageCache; + RefPtr<MouseEvent> m_pendingClickEventFromSnapshot; + DeferrableOneShotTimer<HTMLPlugInImageElement> m_simulatedMouseClickTimer; }; } // namespace WebCore diff --git a/Source/WebCore/html/HTMLTableRowsCollection.cpp b/Source/WebCore/html/HTMLTableRowsCollection.cpp index d94038e63..98459366e 100644 --- a/Source/WebCore/html/HTMLTableRowsCollection.cpp +++ b/Source/WebCore/html/HTMLTableRowsCollection.cpp @@ -151,13 +151,13 @@ HTMLTableRowElement* HTMLTableRowsCollection::lastRow(HTMLTableElement* table) // Must call get() on the table in case that argument is compiled before dereferencing the // table to get at the collection cache. Order of argument evaluation is undefined and can // differ between compilers. -HTMLTableRowsCollection::HTMLTableRowsCollection(Element* table) +HTMLTableRowsCollection::HTMLTableRowsCollection(Node* table) : HTMLCollection(table, TableRows, OverridesItemAfter) { ASSERT(table->hasTagName(tableTag)); } -PassRefPtr<HTMLTableRowsCollection> HTMLTableRowsCollection::create(Element* table, CollectionType) +PassRefPtr<HTMLTableRowsCollection> HTMLTableRowsCollection::create(Node* table, CollectionType) { return adoptRef(new HTMLTableRowsCollection(table)); } diff --git a/Source/WebCore/html/HTMLTableRowsCollection.h b/Source/WebCore/html/HTMLTableRowsCollection.h index c4312896f..1a54f0f1f 100644 --- a/Source/WebCore/html/HTMLTableRowsCollection.h +++ b/Source/WebCore/html/HTMLTableRowsCollection.h @@ -38,13 +38,13 @@ class HTMLTableRowElement; class HTMLTableRowsCollection : public HTMLCollection { public: - static PassRefPtr<HTMLTableRowsCollection> create(Element*, CollectionType); + static PassRefPtr<HTMLTableRowsCollection> create(Node*, CollectionType); static HTMLTableRowElement* rowAfter(HTMLTableElement*, HTMLTableRowElement*); static HTMLTableRowElement* lastRow(HTMLTableElement*); private: - HTMLTableRowsCollection(Element*); + HTMLTableRowsCollection(Node*); virtual Element* virtualItemAfter(unsigned& offsetInArray, Element*) const OVERRIDE; }; diff --git a/Source/WebCore/html/HTMLTextAreaElement.cpp b/Source/WebCore/html/HTMLTextAreaElement.cpp index 1632927dc..fa6da55c0 100644 --- a/Source/WebCore/html/HTMLTextAreaElement.cpp +++ b/Source/WebCore/html/HTMLTextAreaElement.cpp @@ -529,6 +529,16 @@ void HTMLTextAreaElement::attach() fixPlaceholderRenderer(m_placeholder, innerTextElement()); } +bool HTMLTextAreaElement::shouldMatchReadOnlySelector() const +{ + return readOnly(); +} + +bool HTMLTextAreaElement::shouldMatchReadWriteSelector() const +{ + return !readOnly(); +} + void HTMLTextAreaElement::updatePlaceholderText() { ExceptionCode ec = 0; diff --git a/Source/WebCore/html/HTMLTextAreaElement.h b/Source/WebCore/html/HTMLTextAreaElement.h index fcc19f8d4..3964ce2be 100644 --- a/Source/WebCore/html/HTMLTextAreaElement.h +++ b/Source/WebCore/html/HTMLTextAreaElement.h @@ -112,6 +112,8 @@ private: virtual bool shouldUseInputMethod(); virtual void attach() OVERRIDE; + virtual bool shouldMatchReadOnlySelector() const OVERRIDE; + virtual bool shouldMatchReadWriteSelector() const OVERRIDE; bool valueMissing(const String& value) const { return isRequiredFormControl() && !disabled() && !readOnly() && value.isEmpty(); } bool tooLong(const String&, NeedsToCheckDirtyFlag) const; diff --git a/Source/WebCore/html/InputType.cpp b/Source/WebCore/html/InputType.cpp index 4a437e029..b16fa3b18 100644 --- a/Source/WebCore/html/InputType.cpp +++ b/Source/WebCore/html/InputType.cpp @@ -258,6 +258,11 @@ bool InputType::valueMissing(const String&) const return false; } +bool InputType::hasBadInput() const +{ + return false; +} + bool InputType::patternMismatch(const String&) const { return false; @@ -346,6 +351,12 @@ bool InputType::stepMismatch(const String& value) const return createStepRange(RejectAny).stepMismatch(numericValue); } +String InputType::badInputText() const +{ + ASSERT_NOT_REACHED(); + return validationMessageTypeMismatchText(); +} + String InputType::typeMismatchText() const { return validationMessageTypeMismatchText(); @@ -368,6 +379,9 @@ String InputType::validationMessage() const if (typeMismatch()) return typeMismatchText(); + if (hasBadInput()) + return badInputText(); + if (patternMismatch(value)) return validationMessagePatternMismatchText(); @@ -689,11 +703,6 @@ String InputType::sanitizeValue(const String& proposedValue) const return proposedValue; } -bool InputType::hasUnacceptableValue() -{ - return false; -} - bool InputType::receiveDroppedFiles(const DragData*) { ASSERT_NOT_REACHED(); @@ -861,6 +870,11 @@ bool InputType::supportsPlaceholder() const return false; } +bool InputType::supportsReadOnly() const +{ + return false; +} + void InputType::updateInnerTextValue() { } diff --git a/Source/WebCore/html/InputType.h b/Source/WebCore/html/InputType.h index fe4a9e4d9..333a256a0 100644 --- a/Source/WebCore/html/InputType.h +++ b/Source/WebCore/html/InputType.h @@ -156,6 +156,7 @@ public: virtual bool typeMismatch() const; virtual bool supportsRequired() const; virtual bool valueMissing(const String&) const; + virtual bool hasBadInput() const; virtual bool patternMismatch(const String&) const; bool rangeUnderflow(const String&) const; bool rangeOverflow(const String&) const; @@ -170,6 +171,7 @@ public: virtual StepRange createStepRange(AnyStepHandling) const; virtual void stepUp(int, ExceptionCode&); virtual void stepUpFromRenderer(int); + virtual String badInputText() const; virtual String typeMismatchText() const; virtual String valueMissingText() const; virtual bool canSetStringValue() const; @@ -178,7 +180,6 @@ public: // Returing the null string means "use the default value." // This function must be called only by HTMLInputElement::sanitizeValue(). virtual String sanitizeValue(const String&) const; - virtual bool hasUnacceptableValue(); // Event handlers @@ -267,6 +268,7 @@ public: virtual bool isSteppable() const; virtual bool shouldRespectHeightAndWidthAttributes(); virtual bool supportsPlaceholder() const; + virtual bool supportsReadOnly() const; virtual void updateInnerTextValue(); virtual void updatePlaceholderText(); virtual void multipleAttributeChanged(); diff --git a/Source/WebCore/html/LabelsNodeList.h b/Source/WebCore/html/LabelsNodeList.h index 9052eedd6..0da4f3c7e 100644 --- a/Source/WebCore/html/LabelsNodeList.h +++ b/Source/WebCore/html/LabelsNodeList.h @@ -32,8 +32,9 @@ namespace WebCore { class LabelsNodeList : public LiveNodeList { public: - static PassRefPtr<LabelsNodeList> create(Node* forNode, const AtomicString&) + static PassRefPtr<LabelsNodeList> create(Node* forNode, CollectionType type, const AtomicString&) { + ASSERT_UNUSED(type, type == LabelsNodeListType); return adoptRef(new LabelsNodeList(forNode)); } ~LabelsNodeList(); diff --git a/Source/WebCore/html/NumberInputType.cpp b/Source/WebCore/html/NumberInputType.cpp index 7498cc991..440ee7b9b 100644 --- a/Source/WebCore/html/NumberInputType.cpp +++ b/Source/WebCore/html/NumberInputType.cpp @@ -39,6 +39,7 @@ #include "HTMLParserIdioms.h" #include "InputTypeNames.h" #include "KeyboardEvent.h" +#include "LocalizedStrings.h" #include "PlatformLocale.h" #include "RenderTextControl.h" #include <limits> @@ -213,16 +214,6 @@ String NumberInputType::serialize(const Decimal& value) const return serializeForNumberType(value); } -void NumberInputType::handleBlurEvent() -{ - // Reset the renderer value, which might be unmatched with the element value. - element()->setFormControlValueMatchesRenderer(false); - - // We need to reset the renderer value explicitly because an unacceptable - // renderer value should be purged before style calculation. - updateInnerTextValue(); -} - static bool isE(UChar ch) { return ch == 'e' || ch == 'E'; @@ -260,14 +251,17 @@ String NumberInputType::sanitizeValue(const String& proposedValue) const return isfinite(parseToDoubleForNumberType(proposedValue)) ? proposedValue : emptyString(); } -bool NumberInputType::hasUnacceptableValue() +bool NumberInputType::hasBadInput() const { - if (!element()->renderer()) - return false; String standardValue = convertFromVisibleValue(element()->innerTextValue()); return !standardValue.isEmpty() && !isfinite(parseToDoubleForNumberType(standardValue)); } +String NumberInputType::badInputText() const +{ + return validationMessageBadInputForNumberText(); +} + bool NumberInputType::shouldRespectSpeechAttribute() { return true; diff --git a/Source/WebCore/html/NumberInputType.h b/Source/WebCore/html/NumberInputType.h index 11cca557b..c77a9a78e 100644 --- a/Source/WebCore/html/NumberInputType.h +++ b/Source/WebCore/html/NumberInputType.h @@ -53,12 +53,12 @@ private: virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE; virtual Decimal parseToNumber(const String&, const Decimal&) const OVERRIDE; virtual String serialize(const Decimal&) const OVERRIDE; - virtual void handleBlurEvent() OVERRIDE; virtual String localizeValue(const String&) const OVERRIDE; virtual String visibleValue() const OVERRIDE; virtual String convertFromVisibleValue(const String&) const OVERRIDE; virtual String sanitizeValue(const String&) const OVERRIDE; - virtual bool hasUnacceptableValue() OVERRIDE; + virtual bool hasBadInput() const OVERRIDE; + virtual String badInputText() const OVERRIDE; virtual bool shouldRespectSpeechAttribute() OVERRIDE; virtual bool supportsPlaceholder() const OVERRIDE; virtual bool isNumberField() const OVERRIDE; diff --git a/Source/WebCore/html/RadioNodeList.h b/Source/WebCore/html/RadioNodeList.h index 23a527d35..57cad32d4 100644 --- a/Source/WebCore/html/RadioNodeList.h +++ b/Source/WebCore/html/RadioNodeList.h @@ -36,8 +36,9 @@ namespace WebCore { class RadioNodeList : public LiveNodeList { public: - static PassRefPtr<RadioNodeList> create(Node* rootNode, const AtomicString& name) + static PassRefPtr<RadioNodeList> create(Node* rootNode, CollectionType type, const AtomicString& name) { + ASSERT_UNUSED(type, type == RadioNodeListType); return adoptRef(new RadioNodeList(rootNode, name)); } diff --git a/Source/WebCore/html/RangeInputType.cpp b/Source/WebCore/html/RangeInputType.cpp index c37f6b770..ed2a8a118 100644 --- a/Source/WebCore/html/RangeInputType.cpp +++ b/Source/WebCore/html/RangeInputType.cpp @@ -260,7 +260,6 @@ void RangeInputType::createShadowSubtree() track->appendChild(SliderThumbElement::create(document), ec); RefPtr<HTMLElement> container = SliderContainerElement::create(document); container->appendChild(track.release(), ec); - container->appendChild(TrackLimiterElement::create(document), ec); element()->userAgentShadowRoot()->appendChild(container.release(), ec); } diff --git a/Source/WebCore/html/TextFieldInputType.cpp b/Source/WebCore/html/TextFieldInputType.cpp index a5edcb0b3..4a95b89c9 100644 --- a/Source/WebCore/html/TextFieldInputType.cpp +++ b/Source/WebCore/html/TextFieldInputType.cpp @@ -329,6 +329,11 @@ void TextFieldInputType::readonlyAttributeChanged() m_innerSpinButton->releaseCapture(); } +bool TextFieldInputType::supportsReadOnly() const +{ + return true; +} + bool TextFieldInputType::shouldUseInputMethod() const { return true; @@ -458,7 +463,7 @@ void TextFieldInputType::subtreeHasChanged() // sanitizeValue() is needed because IME input doesn't dispatch BeforeTextInsertedEvent. element()->setValueFromRenderer(sanitizeValue(convertFromVisibleValue(element()->innerTextValue()))); element()->updatePlaceholderVisibility(false); - // Recalc for :invalid and hasUnacceptableValue() change. + // Recalc for :invalid change. element()->setNeedsStyleRecalc(); didSetValueByUserEdit(wasChanged ? ValueChangeStateChanged : ValueChangeStateNone); diff --git a/Source/WebCore/html/TextFieldInputType.h b/Source/WebCore/html/TextFieldInputType.h index b32aeaa68..a79887138 100644 --- a/Source/WebCore/html/TextFieldInputType.h +++ b/Source/WebCore/html/TextFieldInputType.h @@ -64,6 +64,7 @@ protected: virtual void destroyShadowSubtree() OVERRIDE; virtual void disabledAttributeChanged() OVERRIDE; virtual void readonlyAttributeChanged() OVERRIDE; + virtual bool supportsReadOnly() const OVERRIDE; virtual void handleBlurEvent() OVERRIDE; virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE; virtual void updateInnerTextValue() OVERRIDE; diff --git a/Source/WebCore/html/ValidityState.cpp b/Source/WebCore/html/ValidityState.cpp index 649765df9..f04ea76ef 100644 --- a/Source/WebCore/html/ValidityState.cpp +++ b/Source/WebCore/html/ValidityState.cpp @@ -76,6 +76,11 @@ bool ValidityState::stepMismatch() const return m_control->stepMismatch(); } +bool ValidityState::badInput() const +{ + return m_control->hasBadInput(); +} + bool ValidityState::customError() const { return m_control->customError(); diff --git a/Source/WebCore/html/ValidityState.h b/Source/WebCore/html/ValidityState.h index 28f9ec640..452739a77 100644 --- a/Source/WebCore/html/ValidityState.h +++ b/Source/WebCore/html/ValidityState.h @@ -52,6 +52,7 @@ public: bool rangeUnderflow() const; bool rangeOverflow() const; bool stepMismatch() const; + bool badInput() const; bool customError() const; bool valid() const; diff --git a/Source/WebCore/html/ValidityState.idl b/Source/WebCore/html/ValidityState.idl index dae343b9a..170c45e69 100644 --- a/Source/WebCore/html/ValidityState.idl +++ b/Source/WebCore/html/ValidityState.idl @@ -30,6 +30,7 @@ readonly attribute boolean rangeUnderflow; readonly attribute boolean rangeOverflow; readonly attribute boolean stepMismatch; + readonly attribute boolean badInput; readonly attribute boolean customError; readonly attribute boolean valid; }; diff --git a/Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp b/Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp index ef754f597..3eb38a105 100644 --- a/Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp +++ b/Source/WebCore/html/canvas/CanvasRenderingContext2D.cpp @@ -2070,8 +2070,11 @@ void CanvasRenderingContext2D::setFont(const String& newFont) if (parsedStyle->isEmpty()) return; - RefPtr<CSSValue> fontValue = parsedStyle->getPropertyCSSValue(CSSPropertyFont); - if (fontValue && fontValue->isInheritedValue()) + String fontValue = parsedStyle->getPropertyValue(CSSPropertyFont); + + // According to http://lists.w3.org/Archives/Public/public-html/2009Jul/0947.html, + // the "inherit" and "initial" values must be ignored. + if (fontValue == "inherit" || fontValue == "initial") return; // The parse succeeded. @@ -2303,10 +2306,10 @@ void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, flo maskImageContext->translate(location.x() - maskRect.x(), location.y() - maskRect.y()); // We draw when fontWidth is 0 so compositing operations (eg, a "copy" op) still work. maskImageContext->scale(FloatSize((fontWidth > 0 ? (width / fontWidth) : 0), 1)); - maskImageContext->drawBidiText(font, textRun, FloatPoint(0, 0)); + maskImageContext->drawBidiText(font, textRun, FloatPoint(0, 0), Font::UseFallbackIfFontNotReady); } else { maskImageContext->translate(-maskRect.x(), -maskRect.y()); - maskImageContext->drawBidiText(font, textRun, location); + maskImageContext->drawBidiText(font, textRun, location, Font::UseFallbackIfFontNotReady); } GraphicsContextStateSaver stateSaver(*c); @@ -2330,9 +2333,9 @@ void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, flo c->translate(location.x(), location.y()); // We draw when fontWidth is 0 so compositing operations (eg, a "copy" op) still work. c->scale(FloatSize((fontWidth > 0 ? (width / fontWidth) : 0), 1)); - c->drawBidiText(font, textRun, FloatPoint(0, 0)); + c->drawBidiText(font, textRun, FloatPoint(0, 0), Font::UseFallbackIfFontNotReady); } else - c->drawBidiText(font, textRun, location); + c->drawBidiText(font, textRun, location, Font::UseFallbackIfFontNotReady); didDraw(textRect); diff --git a/Source/WebCore/html/parser/XSSAuditor.cpp b/Source/WebCore/html/parser/XSSAuditor.cpp index 19b6ca6e3..93becd993 100644 --- a/Source/WebCore/html/parser/XSSAuditor.cpp +++ b/Source/WebCore/html/parser/XSSAuditor.cpp @@ -542,13 +542,16 @@ String XSSAuditor::decodedSnippetForAttribute(const HTMLToken& token, const HTML // In HTTP URLs, characters following the first ?, #, or third slash may come from // the page itself and can be merely ignored by an attacker's server when a remote // script or script-like resource is requested. In DATA URLS, the payload starts at - // the first comma, and the the first /* or // may introduce a comment. Characters + // the first comma, and the the first /*, //, or <!-- may introduce a comment. Characters // following this may come from the page itself and may be ignored when the script is // executed. For simplicity, we don't differentiate based on URL scheme, and stop at - // the first # or ?, the third slash, or the first slash once a comma is seen. + // the first # or ?, the third slash, or the first slash or < once a comma is seen. for (size_t currentLength = 0; currentLength < decodedSnippet.length(); ++currentLength) { UChar currentChar = decodedSnippet[currentLength]; - if (currentChar == '?' || currentChar == '#' || ((currentChar == '/' || currentChar == '\\') && (commaSeen || ++slashCount > 2))) { + if (currentChar == '?' + || currentChar == '#' + || ((currentChar == '/' || currentChar == '\\') && (commaSeen || ++slashCount > 2)) + || (currentChar == '<' && commaSeen)) { decodedSnippet.truncate(currentLength); break; } diff --git a/Source/WebCore/html/shadow/ContentDistributor.cpp b/Source/WebCore/html/shadow/ContentDistributor.cpp index e3216839f..0c095e437 100644 --- a/Source/WebCore/html/shadow/ContentDistributor.cpp +++ b/Source/WebCore/html/shadow/ContentDistributor.cpp @@ -58,6 +58,40 @@ size_t ContentDistribution::find(const Node* node) const return it.get()->value; } +ShadowRootContentDistributionData::ShadowRootContentDistributionData() + : m_insertionPointAssignedTo(0) + , m_numberOfShadowElementChildren(0) + , m_numberOfContentElementChildren(0) + , m_numberOfElementShadowChildren(0) + , m_insertionPointListIsValid(false) +{ +} + +void ShadowRootContentDistributionData::invalidateInsertionPointList() +{ + m_insertionPointListIsValid = false; + m_insertionPointList.clear(); +} + +const Vector<InsertionPoint*>& ShadowRootContentDistributionData::ensureInsertionPointList(ShadowRoot* shadowRoot) +{ + if (m_insertionPointListIsValid) + return m_insertionPointList; + + m_insertionPointListIsValid = true; + ASSERT(m_insertionPointList.isEmpty()); + + if (!shadowRoot->hasInsertionPoint()) + return m_insertionPointList; + + for (Node* node = shadowRoot; node; node = node->traverseNextNode(shadowRoot)) { + if (node->isInsertionPoint()) + m_insertionPointList.append(toInsertionPoint(node)); + } + + return m_insertionPointList; +} + ContentDistributor::ContentDistributor() : m_validity(Undetermined) { @@ -107,17 +141,18 @@ void ContentDistributor::distribute(Element* host) for (ShadowRoot* root = host->youngestShadowRoot(); root; root = root->olderShadowRoot()) { HTMLShadowElement* firstActiveShadowInsertionPoint = 0; - for (Node* node = root; node; node = node->traverseNextNode(root)) { - if (!isActiveInsertionPoint(node)) + const Vector<InsertionPoint*>& insertionPoints = root->insertionPointList(); + for (size_t i = 0; i < insertionPoints.size(); ++i) { + InsertionPoint* point = insertionPoints[i]; + if (!point->isActive()) continue; - InsertionPoint* point = toInsertionPoint(node); - if (isHTMLShadowElement(node)) { + if (isHTMLShadowElement(point)) { if (!firstActiveShadowInsertionPoint) - firstActiveShadowInsertionPoint = toHTMLShadowElement(node); + firstActiveShadowInsertionPoint = toHTMLShadowElement(point); } else { distributeSelectionsTo(point, pool, distributed); - if (ElementShadow* shadow = node->parentNode()->isElementNode() ? toElement(node->parentNode())->shadow() : 0) + if (ElementShadow* shadow = point->parentNode()->isElementNode() ? toElement(point->parentNode())->shadow() : 0) shadow->invalidateDistribution(); } } @@ -148,13 +183,10 @@ bool ContentDistributor::invalidate(Element* host) for (ShadowRoot* root = host->youngestShadowRoot(); root; root = root->olderShadowRoot()) { root->setAssignedTo(0); - - for (Node* node = root; node; node = node->traverseNextNode(root)) { - if (!node->isInsertionPoint()) - continue; + const Vector<InsertionPoint*>& insertionPoints = root->insertionPointList(); + for (size_t i = 0; i < insertionPoints.size(); ++i) { needsReattach = needsReattach || true; - InsertionPoint* point = toInsertionPoint(node); - point->clearDistribution(); + insertionPoints[i]->clearDistribution(); } } diff --git a/Source/WebCore/html/shadow/ContentDistributor.h b/Source/WebCore/html/shadow/ContentDistributor.h index 97cffbcc7..cc2fc232e 100644 --- a/Source/WebCore/html/shadow/ContentDistributor.h +++ b/Source/WebCore/html/shadow/ContentDistributor.h @@ -68,6 +68,38 @@ private: HashMap<const Node*, size_t> m_indices; }; +class ShadowRootContentDistributionData { +public: + ShadowRootContentDistributionData(); + + InsertionPoint* insertionPointAssignedTo() const { return m_insertionPointAssignedTo; } + void setInsertionPointAssignedTo(InsertionPoint* insertionPoint) { m_insertionPointAssignedTo = insertionPoint; } + + void incrementNumberOfShadowElementChildren() { ++m_numberOfShadowElementChildren; invalidateInsertionPointList(); } + void decrementNumberOfShadowElementChildren() { ASSERT(m_numberOfShadowElementChildren > 0); --m_numberOfShadowElementChildren; invalidateInsertionPointList(); } + bool hasShadowElementChildren() const { return m_numberOfShadowElementChildren > 0; } + + void incrementNumberOfContentElementChildren() { ++m_numberOfContentElementChildren; invalidateInsertionPointList(); } + void decrementNumberOfContentElementChildren() { ASSERT(m_numberOfContentElementChildren > 0); --m_numberOfContentElementChildren; invalidateInsertionPointList(); } + bool hasContentElementChildren() const { return m_numberOfContentElementChildren > 0; } + + void incrementNumberOfElementShadowChildren() { ++m_numberOfElementShadowChildren; } + void decrementNumberOfElementShadowChildren() { ASSERT(m_numberOfElementShadowChildren > 0); --m_numberOfElementShadowChildren; } + unsigned numberOfElementShadowChildren() const { return m_numberOfElementShadowChildren; } + bool hasElementShadowChildren() const { return m_numberOfElementShadowChildren > 0; } + + void invalidateInsertionPointList(); + const Vector<InsertionPoint*>& ensureInsertionPointList(ShadowRoot*); + +private: + InsertionPoint* m_insertionPointAssignedTo; + unsigned m_numberOfShadowElementChildren; + unsigned m_numberOfContentElementChildren; + unsigned m_numberOfElementShadowChildren; + bool m_insertionPointListIsValid; + Vector<InsertionPoint*> m_insertionPointList; +}; + class ContentDistributor { WTF_MAKE_NONCOPYABLE(ContentDistributor); public: diff --git a/Source/WebCore/html/shadow/MediaControlElements.cpp b/Source/WebCore/html/shadow/MediaControlElements.cpp index 2128bc232..6ae55f3d9 100644 --- a/Source/WebCore/html/shadow/MediaControlElements.cpp +++ b/Source/WebCore/html/shadow/MediaControlElements.cpp @@ -36,6 +36,7 @@ #include "CSSValueKeywords.h" #include "DOMTokenList.h" #include "EventNames.h" +#include "EventTarget.h" #include "FloatConversion.h" #include "FloatPoint.h" #include "Frame.h" @@ -63,6 +64,7 @@ #include "StyleResolver.h" #include "Text.h" #if ENABLE(VIDEO_TRACK) +#include "TextTrack.h" #include "TextTrackList.h" #endif @@ -77,6 +79,11 @@ static const float cSkipTime = 0.2f; static const float cScanRepeatDelay = 1.5f; static const float cScanMaximumRate = 8; +#if ENABLE(VIDEO_TRACK) +static const char* textTracksOffAttrValue = "-1"; // This must match HTMLMediaElement::textTracksOffIndex() +static const int textTracksIndexNotFound = -2; +#endif + HTMLMediaElement* toParentMediaElement(Node* node) { if (!node) @@ -99,6 +106,26 @@ MediaControlElementType mediaControlElementType(Node* node) return static_cast<MediaControlElement*>(element)->displayType(); } +#if ENABLE(VIDEO_TRACK) +static const AtomicString& trackIndexAttributeName() +{ + DEFINE_STATIC_LOCAL(AtomicString, name, ("x-webkit-track-index", AtomicString::ConstructFromLiteral)); + return name; +} + +static int trackListIndexForElement(Element* element) +{ + const AtomicString trackIndexAttributeValue = element->getAttribute(trackIndexAttributeName()); + if (trackIndexAttributeValue.isNull() || trackIndexAttributeValue.isEmpty()) + return textTracksIndexNotFound; + bool ok; + int trackIndex = trackIndexAttributeValue.toInt(&ok); + if (!ok) + return textTracksIndexNotFound; + return trackIndex; +} +#endif + // ---------------------------- MediaControlElement::MediaControlElement(Document* document) @@ -884,8 +911,13 @@ const AtomicString& MediaControlClosedCaptionsContainerElement::shadowPseudoId() inline MediaControlToggleClosedCaptionsButtonElement::MediaControlToggleClosedCaptionsButtonElement(Document* document, MediaControls* controls) : MediaControlInputElement(document, MediaShowClosedCaptionsButton) +#if PLATFORM(MAC) , m_controls(controls) +#endif { +#if !PLATFORM(MAC) + UNUSED_PARAM(controls); +#endif } PassRefPtr<MediaControlToggleClosedCaptionsButtonElement> MediaControlToggleClosedCaptionsButtonElement::create(Document* document, MediaControls* controls) @@ -901,18 +933,25 @@ PassRefPtr<MediaControlToggleClosedCaptionsButtonElement> MediaControlToggleClos void MediaControlToggleClosedCaptionsButtonElement::updateDisplayType() { - setDisplayType(mediaController()->closedCaptionsVisible() ? MediaHideClosedCaptionsButton : MediaShowClosedCaptionsButton); + bool captionsVisible = mediaController()->closedCaptionsVisible(); + setDisplayType(captionsVisible ? MediaHideClosedCaptionsButton : MediaShowClosedCaptionsButton); + setChecked(captionsVisible); } void MediaControlToggleClosedCaptionsButtonElement::defaultEventHandler(Event* event) { if (event->type() == eventNames().clickEvent) { - // FIXME: This is now incorrectly doing two things at once: showing the list of captions and toggling display. - // https://bugs.webkit.org/show_bug.cgi?id=101670 + // FIXME: It's not great that the shared code is dictating behavior of platform-specific + // UI. Not all ports may want the closed captions button to toggle a list of tracks, so + // we have to use #if. + // https://bugs.webkit.org/show_bug.cgi?id=101877 +#if !PLATFORM(MAC) mediaController()->setClosedCaptionsVisible(!mediaController()->closedCaptionsVisible()); setChecked(mediaController()->closedCaptionsVisible()); - m_controls->toggleClosedCaptionTrackList(); updateDisplayType(); +#else + m_controls->toggleClosedCaptionTrackList(); +#endif event->setDefaultHandled(); } @@ -927,22 +966,52 @@ const AtomicString& MediaControlToggleClosedCaptionsButtonElement::shadowPseudoI // ---------------------------- -inline MediaControlClosedCaptionsTrackListElement::MediaControlClosedCaptionsTrackListElement(Document* document) +inline MediaControlClosedCaptionsTrackListElement::MediaControlClosedCaptionsTrackListElement(Document* document, MediaControls* controls) : MediaControlElement(document) + , m_controls(controls) { } -PassRefPtr<MediaControlClosedCaptionsTrackListElement> MediaControlClosedCaptionsTrackListElement::create(Document* document) +PassRefPtr<MediaControlClosedCaptionsTrackListElement> MediaControlClosedCaptionsTrackListElement::create(Document* document, MediaControls* controls) { - RefPtr<MediaControlClosedCaptionsTrackListElement> element = adoptRef(new MediaControlClosedCaptionsTrackListElement(document)); + ASSERT(controls); + RefPtr<MediaControlClosedCaptionsTrackListElement> element = adoptRef(new MediaControlClosedCaptionsTrackListElement(document, controls)); return element.release(); } void MediaControlClosedCaptionsTrackListElement::defaultEventHandler(Event* event) { - // FIXME: Hook this up to actual text tracks. - // https://bugs.webkit.org/show_bug.cgi?id=101670 - UNUSED_PARAM(event); +#if ENABLE(VIDEO_TRACK) + if (event->type() == eventNames().clickEvent) { + // FIXME: Add modifier key for exclusivity override. + // http://webkit.org/b/103361 + + Node* target = event->target()->toNode(); + if (!target || !target->isElementNode()) + return; + + // When we created the elements in the track list, we gave them a custom + // attribute representing the index in the HTMLMediaElement's list of tracks. + // Check if the event target has such a custom element and, if so, + // tell the HTMLMediaElement to enable that track. + + int trackIndex = trackListIndexForElement(toElement(target)); + if (trackIndex == textTracksIndexNotFound) + return; + + HTMLMediaElement* mediaElement = toParentMediaElement(this); + if (!mediaElement) + return; + + mediaElement->toggleTrackAtIndex(trackIndex); + + // We've selected a track to display, so we can now close the menu. + m_controls->toggleClosedCaptionTrackList(); + updateDisplay(); + } + + MediaControlElement::defaultEventHandler(event); +#endif } const AtomicString& MediaControlClosedCaptionsTrackListElement::shadowPseudoId() const @@ -954,8 +1023,50 @@ const AtomicString& MediaControlClosedCaptionsTrackListElement::shadowPseudoId() void MediaControlClosedCaptionsTrackListElement::updateDisplay() { #if ENABLE(VIDEO_TRACK) + DEFINE_STATIC_LOCAL(AtomicString, selectedClassValue, ("selected", AtomicString::ConstructFromLiteral)); + + if (!mediaController()->hasClosedCaptions()) + return; + + HTMLMediaElement* mediaElement = toParentMediaElement(this); + if (!mediaElement) + return; + + TextTrackList* trackList = mediaElement->textTracks(); + + if (!trackList || !trackList->length()) + return; + + bool captionsVisible = mediaElement->closedCaptionsVisible(); + for (unsigned i = 0, length = menuItems.size(); i < length; ++i) { + RefPtr<Element> trackItem = menuItems[i]; + int trackIndex = trackListIndexForElement(trackItem.get()); + if (trackIndex != textTracksIndexNotFound) { + if (trackIndex == HTMLMediaElement::textTracksOffIndex()) { + if (captionsVisible) + trackItem->classList()->remove(selectedClassValue, ASSERT_NO_EXCEPTION); + else + trackItem->classList()->add(selectedClassValue, ASSERT_NO_EXCEPTION); + } else { + TextTrack* track = trackList->item(trackIndex); + if (!track) + continue; + if (track->mode() == TextTrack::showingKeyword()) + trackItem->classList()->add(selectedClassValue, ASSERT_NO_EXCEPTION); + else + trackItem->classList()->remove(selectedClassValue, ASSERT_NO_EXCEPTION); + } + } + } +#endif +} + +void MediaControlClosedCaptionsTrackListElement::resetTrackListMenu() +{ +#if ENABLE(VIDEO_TRACK) // Remove any existing content. removeChildren(); + menuItems.clear(); if (!mediaController()->hasClosedCaptions()) return; @@ -987,15 +1098,15 @@ void MediaControlClosedCaptionsTrackListElement::updateDisplay() trackItem = doc->createElement(liTag, ASSERT_NO_EXCEPTION); trackItem->appendChild(doc->createTextNode("Off")); - // FIXME: These lists are not yet live. Mark the Off entry as the selected one for now. - trackItem->setAttribute(classAttr, "selected"); + trackItem->setAttribute(trackIndexAttributeName(), textTracksOffAttrValue, ASSERT_NO_EXCEPTION); captionsList->appendChild(trackItem); + menuItems.append(trackItem); trackItem = doc->createElement(liTag, ASSERT_NO_EXCEPTION); trackItem->appendChild(doc->createTextNode("Off")); - // FIXME: These lists are not yet live. Mark the Off entry as the selected one for now. - trackItem->setAttribute(classAttr, "selected"); + trackItem->setAttribute(trackIndexAttributeName(), textTracksOffAttrValue, ASSERT_NO_EXCEPTION); subtitlesList->appendChild(trackItem); + menuItems.append(trackItem); bool hasCaptions = false; bool hasSubtitles = false; @@ -1003,6 +1114,13 @@ void MediaControlClosedCaptionsTrackListElement::updateDisplay() for (unsigned i = 0, length = trackList->length(); i < length; ++i) { TextTrack* track = trackList->item(i); trackItem = doc->createElement(liTag, ASSERT_NO_EXCEPTION); + + // Add a custom attribute to the <li> element which will allow + // us to easily associate the user tapping here with the + // track. Since this list is rebuilt if the tracks change, we + // should always be in sync. + trackItem->setAttribute(trackIndexAttributeName(), String::number(i), ASSERT_NO_EXCEPTION); + AtomicString labelText = track->label(); if (labelText.isNull() || labelText.isEmpty()) labelText = displayNameForLanguageLocale(track->language()); @@ -1018,6 +1136,7 @@ void MediaControlClosedCaptionsTrackListElement::updateDisplay() subtitlesList->appendChild(trackItem); } trackItem->appendChild(doc->createTextNode(labelText)); + menuItems.append(trackItem); } captionsSection->appendChild(captionsList); @@ -1027,6 +1146,8 @@ void MediaControlClosedCaptionsTrackListElement::updateDisplay() appendChild(captionsSection); if (hasSubtitles) appendChild(subtitlesSection); + + updateDisplay(); #endif } diff --git a/Source/WebCore/html/shadow/MediaControlElements.h b/Source/WebCore/html/shadow/MediaControlElements.h index c3fbc8121..e05032854 100644 --- a/Source/WebCore/html/shadow/MediaControlElements.h +++ b/Source/WebCore/html/shadow/MediaControlElements.h @@ -393,7 +393,9 @@ private: MediaControlToggleClosedCaptionsButtonElement(Document*, MediaControls*); virtual const AtomicString& shadowPseudoId() const; +#if PLATFORM(MAC) MediaControls* m_controls; +#endif }; // ---------------------------- @@ -415,18 +417,23 @@ private: class MediaControlClosedCaptionsTrackListElement : public MediaControlElement { public: - static PassRefPtr<MediaControlClosedCaptionsTrackListElement> create(Document*); + static PassRefPtr<MediaControlClosedCaptionsTrackListElement> create(Document*, MediaControls*); virtual void defaultEventHandler(Event*); virtual bool willRespondToMouseClickEvents() OVERRIDE { return true; } void updateDisplay(); + void resetTrackListMenu(); private: - MediaControlClosedCaptionsTrackListElement(Document*); + MediaControlClosedCaptionsTrackListElement(Document*, MediaControls*); virtual MediaControlElementType displayType() const { return MediaClosedCaptionsTrackList; } virtual const AtomicString& shadowPseudoId() const; + + typedef Vector<RefPtr<Element> > TrackMenuItems; + TrackMenuItems menuItems; + MediaControls* m_controls; }; // ---------------------------- diff --git a/Source/WebCore/html/shadow/MediaControlsApple.cpp b/Source/WebCore/html/shadow/MediaControlsApple.cpp index 6cc1c7f7d..93733aeb8 100644 --- a/Source/WebCore/html/shadow/MediaControlsApple.cpp +++ b/Source/WebCore/html/shadow/MediaControlsApple.cpp @@ -149,7 +149,7 @@ PassRefPtr<MediaControlsApple> MediaControlsApple::createControls(Document* docu if (document->page()->theme()->supportsClosedCaptioning()) { RefPtr<MediaControlClosedCaptionsContainerElement> closedCaptionsContainer = MediaControlClosedCaptionsContainerElement::create(document); - RefPtr<MediaControlClosedCaptionsTrackListElement> closedCaptionsTrackList = MediaControlClosedCaptionsTrackListElement::create(document); + RefPtr<MediaControlClosedCaptionsTrackListElement> closedCaptionsTrackList = MediaControlClosedCaptionsTrackListElement::create(document, controls.get()); controls->m_closedCaptionsTrackList = closedCaptionsTrackList.get(); closedCaptionsContainer->appendChild(closedCaptionsTrackList.release(), ec, true); if (ec) @@ -289,6 +289,13 @@ void MediaControlsApple::makeTransparent() m_closedCaptionsContainer->hide(); } +void MediaControlsApple::changedClosedCaptionsVisibility() +{ + MediaControls::changedClosedCaptionsVisibility(); + if (m_closedCaptionsTrackList) + m_closedCaptionsTrackList->updateDisplay(); +} + void MediaControlsApple::reset() { Page* page = document()->page(); @@ -323,7 +330,7 @@ void MediaControlsApple::reset() if (m_mediaController->hasClosedCaptions()) { m_toggleClosedCaptionsButton->show(); if (m_closedCaptionsTrackList) - m_closedCaptionsTrackList->updateDisplay(); + m_closedCaptionsTrackList->resetTrackListMenu(); } else m_toggleClosedCaptionsButton->hide(); } diff --git a/Source/WebCore/html/shadow/MediaControlsApple.h b/Source/WebCore/html/shadow/MediaControlsApple.h index dc47306ec..a1ee8963c 100644 --- a/Source/WebCore/html/shadow/MediaControlsApple.h +++ b/Source/WebCore/html/shadow/MediaControlsApple.h @@ -58,6 +58,7 @@ public: virtual void updateCurrentTimeDisplay() OVERRIDE; virtual void updateStatusDisplay() OVERRIDE; + virtual void changedClosedCaptionsVisibility() OVERRIDE; void toggleClosedCaptionTrackList(); private: diff --git a/Source/WebCore/html/shadow/SliderThumbElement.cpp b/Source/WebCore/html/shadow/SliderThumbElement.cpp index e63954e41..d6c1a3111 100644 --- a/Source/WebCore/html/shadow/SliderThumbElement.cpp +++ b/Source/WebCore/html/shadow/SliderThumbElement.cpp @@ -194,10 +194,11 @@ void RenderSliderContainer::layout() double percentageOffset = sliderPosition(input).toDouble(); LayoutUnit availableExtent = isVertical ? track->contentHeight() : track->contentWidth(); + availableExtent -= isVertical ? thumb->height() : thumb->width(); LayoutUnit offset = percentageOffset * availableExtent; LayoutPoint thumbLocation = thumb->location(); if (isVertical) - thumbLocation.setY(thumbLocation.y() + track->contentHeight() - offset); + thumbLocation.setY(thumbLocation.y() + track->contentHeight() - thumb->height() - offset); else if (style()->isLeftToRightDirection()) thumbLocation.setX(thumbLocation.x() + offset); else @@ -271,16 +272,13 @@ void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point) IntRect trackBoundingBox = trackElement->renderer()->absoluteBoundingBoxRectIgnoringTransforms(); IntRect inputBoundingBox = input->renderer()->absoluteBoundingBoxRectIgnoringTransforms(); if (isVertical) { - trackSize = trackElement->renderBox()->contentHeight(); + trackSize = trackElement->renderBox()->contentHeight() - renderBox()->height(); position = offset.y() - renderBox()->height() / 2 - trackBoundingBox.y() + inputBoundingBox.y() - renderBox()->marginBottom(); currentPosition = absoluteThumbOrigin.y() - absoluteSliderContentOrigin.y(); } else { - trackSize = trackElement->renderBox()->contentWidth(); + trackSize = trackElement->renderBox()->contentWidth() - renderBox()->width(); position = offset.x() - renderBox()->width() / 2 - trackBoundingBox.x() + inputBoundingBox.x(); - if (isLeftToRightDirection) - position -= renderBox()->marginLeft(); - else - position += renderBox()->width() - renderBox()->marginRight(); + position -= isLeftToRightDirection ? renderBox()->marginLeft() : renderBox()->marginRight(); currentPosition = absoluteThumbOrigin.x() - absoluteSliderContentOrigin.x(); } position = max<LayoutUnit>(0, min(position, trackSize)); @@ -438,58 +436,6 @@ const AtomicString& SliderThumbElement::shadowPseudoId() const // -------------------------------- -inline TrackLimiterElement::TrackLimiterElement(Document* document) - : HTMLDivElement(HTMLNames::divTag, document) -{ -} - -PassRefPtr<TrackLimiterElement> TrackLimiterElement::create(Document* document) -{ - RefPtr<TrackLimiterElement> element = adoptRef(new TrackLimiterElement(document)); - - element->setInlineStyleProperty(CSSPropertyVisibility, CSSValueHidden); - element->setInlineStyleProperty(CSSPropertyPosition, CSSValueStatic); - - return element.release(); -} - -RenderObject* TrackLimiterElement::createRenderer(RenderArena* arena, RenderStyle*) -{ - return new (arena) RenderSliderThumb(this); -} - -const AtomicString& TrackLimiterElement::shadowPseudoId() const -{ - HTMLInputElement* input = shadowHost()->toInputElement(); - if (!input) - return sliderThumbShadowPseudoId(); - - RenderStyle* sliderStyle = input->renderer()->style(); - switch (sliderStyle->appearance()) { - case MediaSliderPart: - case MediaSliderThumbPart: - case MediaVolumeSliderPart: - case MediaVolumeSliderThumbPart: - case MediaFullScreenVolumeSliderPart: - case MediaFullScreenVolumeSliderThumbPart: - return mediaSliderThumbShadowPseudoId(); - default: - return sliderThumbShadowPseudoId(); - } -} - -TrackLimiterElement* trackLimiterElementOf(Node* node) -{ - ASSERT(node); - ShadowRoot* shadow = node->toInputElement()->userAgentShadowRoot(); - ASSERT(shadow); - Node* limiter = shadow->firstChild()->lastChild(); - ASSERT(limiter); - return static_cast<TrackLimiterElement*>(limiter); -} - -// -------------------------------- - inline SliderContainerElement::SliderContainerElement(Document* document) : HTMLDivElement(HTMLNames::divTag, document) { diff --git a/Source/WebCore/html/shadow/SliderThumbElement.h b/Source/WebCore/html/shadow/SliderThumbElement.h index f55ecef3d..869ad4b5d 100644 --- a/Source/WebCore/html/shadow/SliderThumbElement.h +++ b/Source/WebCore/html/shadow/SliderThumbElement.h @@ -115,22 +115,6 @@ private: // -------------------------------- -class TrackLimiterElement : public HTMLDivElement { -public: - static PassRefPtr<TrackLimiterElement> create(Document*); - -private: - TrackLimiterElement(Document*); - virtual RenderObject* createRenderer(RenderArena*, RenderStyle*); - virtual const AtomicString& shadowPseudoId() const; -}; - -// This always return a valid pointer. -// An assertion fails if the specified node is not a range input. -TrackLimiterElement* trackLimiterElementOf(Node*); - -// -------------------------------- - class SliderContainerElement : public HTMLDivElement { public: static PassRefPtr<SliderContainerElement> create(Document*); diff --git a/Source/WebCore/html/track/TextTrack.cpp b/Source/WebCore/html/track/TextTrack.cpp index 95ab19080..6a6e90be6 100644 --- a/Source/WebCore/html/track/TextTrack.cpp +++ b/Source/WebCore/html/track/TextTrack.cpp @@ -259,20 +259,18 @@ void TextTrack::removeCue(TextTrackCue* cue, ExceptionCode& ec) if (!cue) return; - // 4.8.10.12.4 Text track API + // 4.8.10.12.5 Text track API // The removeCue(cue) method of TextTrack objects, when invoked, must run the following steps: - // 1. If the given cue is not associated with the method's TextTrack - // object's text track, then throw an InvalidStateError exception. + // 1. If the given cue is not currently listed in the method's TextTrack + // object's text track's text track list of cues, then throw a NotFoundError exception. if (cue->track() != this) { - ec = INVALID_STATE_ERR; + ec = NOT_FOUND_ERR; return; } - - // 2. If the given cue is not currently listed in the method's TextTrack - // object's text track's text track list of cues, then throw a NotFoundError exception. - // 3. Remove cue from the method's TextTrack object's text track's text track list of cues. + + // 2. Remove cue from the method's TextTrack object's text track's text track list of cues. if (!m_cues || !m_cues->remove(cue)) { ec = INVALID_STATE_ERR; return; diff --git a/Source/WebCore/inspector/ConsoleMessage.cpp b/Source/WebCore/inspector/ConsoleMessage.cpp index 7039847df..d284ae26c 100644 --- a/Source/WebCore/inspector/ConsoleMessage.cpp +++ b/Source/WebCore/inspector/ConsoleMessage.cpp @@ -47,25 +47,24 @@ namespace WebCore { -ConsoleMessage::ConsoleMessage(MessageSource s, MessageType t, MessageLevel l, const String& m, const String& u, unsigned li, unsigned long requestIdentifier) - : m_source(s) - , m_type(t) - , m_level(l) - , m_message(m) - , m_url(u) - , m_line(li) +ConsoleMessage::ConsoleMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, const String& url, unsigned line, unsigned long requestIdentifier) + : m_source(source) + , m_type(type) + , m_level(level) + , m_message(message) + , m_url(url) + , m_line(line) , m_repeatCount(1) , m_requestId(IdentifiersFactory::requestId(requestIdentifier)) { } -ConsoleMessage::ConsoleMessage(MessageSource s, MessageType t, MessageLevel l, const String& m, PassRefPtr<ScriptArguments> arguments, PassRefPtr<ScriptCallStack> callStack, unsigned long requestIdentifier) - : m_source(s) - , m_type(t) - , m_level(l) - , m_message(m) +ConsoleMessage::ConsoleMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, PassRefPtr<ScriptArguments> arguments, PassRefPtr<ScriptCallStack> callStack, unsigned long requestIdentifier) + : m_source(source) + , m_type(type) + , m_level(level) + , m_message(message) , m_arguments(arguments) - , m_url() , m_line(0) , m_repeatCount(1) , m_requestId(IdentifiersFactory::requestId(requestIdentifier)) diff --git a/Source/WebCore/inspector/ConsoleMessage.h b/Source/WebCore/inspector/ConsoleMessage.h index 0068c9e51..157e6f35a 100644 --- a/Source/WebCore/inspector/ConsoleMessage.h +++ b/Source/WebCore/inspector/ConsoleMessage.h @@ -51,8 +51,8 @@ class ScriptValue; class ConsoleMessage { WTF_MAKE_NONCOPYABLE(ConsoleMessage); WTF_MAKE_FAST_ALLOCATED; public: - ConsoleMessage(MessageSource, MessageType, MessageLevel, const String& m, const String& u, unsigned li, unsigned long requestIdentifier = 0); - ConsoleMessage(MessageSource, MessageType, MessageLevel, const String& m, PassRefPtr<ScriptArguments>, PassRefPtr<ScriptCallStack>, unsigned long requestIdentifier = 0); + ConsoleMessage(MessageSource, MessageType, MessageLevel, const String& message, const String& url, unsigned line, unsigned long requestIdentifier = 0); + ConsoleMessage(MessageSource, MessageType, MessageLevel, const String& message, PassRefPtr<ScriptArguments>, PassRefPtr<ScriptCallStack>, unsigned long requestIdentifier = 0); ~ConsoleMessage(); void addToFrontend(InspectorFrontend::Console*, InjectedScriptManager*, bool generatePreview); diff --git a/Source/WebCore/inspector/InjectedScriptCanvasModuleSource.js b/Source/WebCore/inspector/InjectedScriptCanvasModuleSource.js index 20b7221cf..01dad7ddb 100644 --- a/Source/WebCore/inspector/InjectedScriptCanvasModuleSource.js +++ b/Source/WebCore/inspector/InjectedScriptCanvasModuleSource.js @@ -1189,9 +1189,10 @@ WebGLTextureResource.prototype = { }, /** + * Handles: texParameteri, texParameterf * @param {Call} call */ - pushCall_texParameterf: function(call) + pushCall_texParameter: function(call) { var args = call.args(); var pname = args[1]; @@ -1203,6 +1204,7 @@ WebGLTextureResource.prototype = { }, /** + * Handles: copyTexImage2D, copyTexSubImage2D * copyTexImage2D and copyTexSubImage2D define a texture image with pixels from the current framebuffer. * @param {Call} call */ @@ -1223,9 +1225,6 @@ WebGLTextureResource.prototype = { __proto__: WebGLBoundResource.prototype } -WebGLTextureResource.prototype.pushCall_texParameteri = WebGLTextureResource.prototype.pushCall_texParameterf; -WebGLTextureResource.prototype.pushCall_copyTexSubImage2D = WebGLTextureResource.prototype.pushCall_copyTexImage2D; - /** * @constructor * @extends {Resource} @@ -1456,6 +1455,8 @@ function WebGLRenderingContextResource(glContext, replayContextCallback) this._replayContextCallback = replayContextCallback; /** @type {Object.<number, boolean>} */ this._customErrors = null; + /** @type {!Object.<string, boolean>} */ + this._extensions = {}; } /** @@ -1633,6 +1634,14 @@ WebGLRenderingContextResource.prototype = { }, /** + * @param {string} name + */ + addExtension: function(name) + { + this._extensions[name] = true; + }, + + /** * @override * @param {Object} data * @param {Cache} cache @@ -1641,6 +1650,7 @@ WebGLRenderingContextResource.prototype = { { var gl = this.wrappedObject(); data.replayContextCallback = this._replayContextCallback; + data.extensions = TypeUtils.cloneObject(this._extensions); var originalErrors = this.getAllErrors(); @@ -1696,10 +1706,15 @@ WebGLRenderingContextResource.prototype = { { this._replayContextCallback = data.replayContextCallback; this._customErrors = null; + this._extensions = TypeUtils.cloneObject(data.extensions) || {}; var gl = /** @type {!WebGLRenderingContext} */ (Resource.wrappedObject(this._replayContextCallback())); this.setWrappedObject(gl); + // Enable corresponding WebGL extensions. + for (var name in this._extensions) + gl.getExtension(name); + var glState = data.glState; gl.bindFramebuffer(gl.FRAMEBUFFER, /** @type {WebGLFramebuffer} */ (ReplayableResource.replay(glState.FRAMEBUFFER_BINDING, cache))); gl.bindRenderbuffer(gl.RENDERBUFFER, /** @type {WebGLRenderbuffer} */ (ReplayableResource.replay(glState.RENDERBUFFER_BINDING, cache))); @@ -1853,45 +1868,54 @@ WebGLRenderingContextResource.prototype = { /** * @param {string} methodName + * @param {function(this:Resource, Call)=} pushCallFunc */ - function customWrapFunction(methodName) + function stateModifyingWrapFunction(methodName, pushCallFunc) { - var customPushCall = "pushCall_" + methodName; - /** - * @param {Object|number} target - * @this Resource.WrapFunction - */ - wrapFunctions[methodName] = function(target) - { - var resource = this._resource.currentBinding(target); - if (!resource) - return; - if (resource[customPushCall]) - resource[customPushCall].call(resource, this.call()); - else - resource.pushCall(this.call()); + if (pushCallFunc) { + /** + * @param {Object|number} target + * @this Resource.WrapFunction + */ + wrapFunctions[methodName] = function(target) + { + var resource = this._resource.currentBinding(target); + if (resource) + pushCallFunc.call(resource, this.call()); + } + } else { + /** + * @param {Object|number} target + * @this Resource.WrapFunction + */ + wrapFunctions[methodName] = function(target) + { + var resource = this._resource.currentBinding(target); + if (resource) + resource.pushCall(this.call()); + } } } - customWrapFunction("attachShader"); - customWrapFunction("bindAttribLocation"); - customWrapFunction("compileShader"); - customWrapFunction("detachShader"); - customWrapFunction("linkProgram"); - customWrapFunction("shaderSource"); - customWrapFunction("bufferData"); - customWrapFunction("bufferSubData"); - customWrapFunction("compressedTexImage2D"); - customWrapFunction("compressedTexSubImage2D"); - customWrapFunction("copyTexImage2D"); - customWrapFunction("copyTexSubImage2D"); - customWrapFunction("generateMipmap"); - customWrapFunction("texImage2D"); - customWrapFunction("texSubImage2D"); - customWrapFunction("texParameterf"); - customWrapFunction("texParameteri"); - customWrapFunction("framebufferRenderbuffer"); - customWrapFunction("framebufferTexture2D"); - customWrapFunction("renderbufferStorage"); + stateModifyingWrapFunction("attachShader"); + stateModifyingWrapFunction("bindAttribLocation"); + stateModifyingWrapFunction("compileShader"); + stateModifyingWrapFunction("detachShader"); + stateModifyingWrapFunction("linkProgram"); + stateModifyingWrapFunction("shaderSource"); + stateModifyingWrapFunction("bufferData"); + stateModifyingWrapFunction("bufferSubData"); + stateModifyingWrapFunction("compressedTexImage2D"); + stateModifyingWrapFunction("compressedTexSubImage2D"); + stateModifyingWrapFunction("copyTexImage2D", WebGLTextureResource.prototype.pushCall_copyTexImage2D); + stateModifyingWrapFunction("copyTexSubImage2D", WebGLTextureResource.prototype.pushCall_copyTexImage2D); + stateModifyingWrapFunction("generateMipmap"); + stateModifyingWrapFunction("texImage2D"); + stateModifyingWrapFunction("texSubImage2D"); + stateModifyingWrapFunction("texParameterf", WebGLTextureResource.prototype.pushCall_texParameter); + stateModifyingWrapFunction("texParameteri", WebGLTextureResource.prototype.pushCall_texParameter); + stateModifyingWrapFunction("framebufferRenderbuffer"); + stateModifyingWrapFunction("framebufferTexture2D"); + stateModifyingWrapFunction("renderbufferStorage"); /** @this Resource.WrapFunction */ wrapFunctions["getError"] = function() @@ -1907,6 +1931,15 @@ WebGLRenderingContextResource.prototype = { } } + /** + * @param {string} name + * @this Resource.WrapFunction + */ + wrapFunctions["getExtension"] = function(name) + { + this._resource.addExtension(name); + } + WebGLRenderingContextResource._wrapFunctions = wrapFunctions; } return wrapFunctions; @@ -2253,7 +2286,7 @@ CanvasRenderingContext2DResource.prototype = { /** * @param {string} methodName - * @param {Function=} func + * @param {function(this:Resource, Call)=} func */ function stateModifyingWrapFunction(methodName, func) { @@ -2273,9 +2306,9 @@ CanvasRenderingContext2DResource.prototype = { } for (var i = 0, methodName; methodName = CanvasRenderingContext2DResource.TransformationMatrixMethods[i]; ++i) - stateModifyingWrapFunction(methodName, methodName === "setTransform" ? this.pushCall_setTransform : null); + stateModifyingWrapFunction(methodName, methodName === "setTransform" ? this.pushCall_setTransform : undefined); for (var i = 0, methodName; methodName = CanvasRenderingContext2DResource.PathMethods[i]; ++i) - stateModifyingWrapFunction(methodName, methodName === "beginPath" ? this.pushCall_beginPath : null); + stateModifyingWrapFunction(methodName, methodName === "beginPath" ? this.pushCall_beginPath : undefined); stateModifyingWrapFunction("save", this.pushCall_save); stateModifyingWrapFunction("restore", this.pushCall_restore); diff --git a/Source/WebCore/inspector/InjectedScriptSource.js b/Source/WebCore/inspector/InjectedScriptSource.js index 333b14330..126fa68a4 100644 --- a/Source/WebCore/inspector/InjectedScriptSource.js +++ b/Source/WebCore/inspector/InjectedScriptSource.js @@ -723,7 +723,9 @@ InjectedScript.prototype = { var description = obj.nodeName.toLowerCase(); switch (obj.nodeType) { case 1 /* Node.ELEMENT_NODE */: - description = "<" + description + ">"; + description += obj.id ? "#" + obj.id : ""; + var className = obj.className; + description += className ? "." + className : ""; break; case 10 /*Node.DOCUMENT_TYPE_NODE */: description = "<!DOCTYPE " + description + ">"; @@ -820,22 +822,25 @@ InjectedScript.RemoteObject.prototype = { this.preview.properties = []; var isArray = this.subtype === "array"; - var elementsToDump = isArray ? 100 : 5; + var propertiesThreshold = { + properties: 5, + indexes: 100 + }; for (var o = object; injectedScript._isDefined(o); o = o.__proto__) - this._generateProtoPreview(o, elementsToDump); + this._generateProtoPreview(o, propertiesThreshold); }, /** * @param {Object} object - * @param {number} elementsToDump + * @param {Object} propertiesThreshold */ - _generateProtoPreview: function(object, elementsToDump) + _generateProtoPreview: function(object, propertiesThreshold) { var propertyNames = Object.keys(/** @type {!Object} */(object)); try { for (var i = 0; i < propertyNames.length; ++i) { - if (this.preview.properties.length >= elementsToDump) { + if (!propertiesThreshold.properties || !propertiesThreshold.indexes) { this.preview.overflow = true; this.preview.lossless = false; break; @@ -852,7 +857,7 @@ InjectedScript.RemoteObject.prototype = { var value = descriptor.value; if (value === null) { - this.preview.properties.push({ name: name, type: "object", value: "null" }); + this._appendPropertyPreview({ name: name, type: "object", value: "null" }, propertiesThreshold); continue; } @@ -867,7 +872,7 @@ InjectedScript.RemoteObject.prototype = { } value = "\"" + value.replace(/\n/g, "\u21B5") + "\""; } - this.preview.properties.push({ name: name, type: type, value: value + "" }); + this._appendPropertyPreview({ name: name, type: type, value: value + "" }, propertiesThreshold); continue; } @@ -881,13 +886,26 @@ InjectedScript.RemoteObject.prototype = { var property = { name: name, type: type, value: description }; if (subtype) property.subtype = subtype; - this.preview.properties.push(property); + this._appendPropertyPreview(property, propertiesThreshold); } } catch (e) { } }, /** + * @param {Object} property + * @param {Object} propertiesThreshold + */ + _appendPropertyPreview: function(property, propertiesThreshold) + { + if (isNaN(property.name)) + propertiesThreshold.properties--; + else + propertiesThreshold.indexes--; + this.preview.properties.push(property); + }, + + /** * @param {string} string * @param {number} maxLength * @param {boolean=} middle diff --git a/Source/WebCore/inspector/InspectorBaseAgent.cpp b/Source/WebCore/inspector/InspectorBaseAgent.cpp index ffa9555d4..e926494ef 100644 --- a/Source/WebCore/inspector/InspectorBaseAgent.cpp +++ b/Source/WebCore/inspector/InspectorBaseAgent.cpp @@ -57,6 +57,41 @@ void InspectorBaseAgentInterface::reportMemoryUsage(MemoryObjectInfo* memoryObje info.addWeakPointer(m_state); } +void InspectorAgentRegistry::append(PassOwnPtr<InspectorBaseAgentInterface> agent) +{ + m_agents.append(agent); +} + +void InspectorAgentRegistry::setFrontend(InspectorFrontend* frontend) +{ + for (size_t i = 0; i < m_agents.size(); i++) + m_agents[i]->setFrontend(frontend); +} + +void InspectorAgentRegistry::clearFrontend() +{ + for (size_t i = 0; i < m_agents.size(); i++) + m_agents[i]->clearFrontend(); +} + +void InspectorAgentRegistry::restore() +{ + for (size_t i = 0; i < m_agents.size(); i++) + m_agents[i]->restore(); +} + +void InspectorAgentRegistry::registerInDispatcher(InspectorBackendDispatcher* dispatcher) +{ + for (size_t i = 0; i < m_agents.size(); i++) + m_agents[i]->registerInDispatcher(dispatcher); +} + +void InspectorAgentRegistry::discardAgents() +{ + for (size_t i = 0; i < m_agents.size(); i++) + m_agents[i]->discardAgent(); +} + } // namespace WebCore #endif // ENABLE(INSPECTOR) diff --git a/Source/WebCore/inspector/InspectorBaseAgent.h b/Source/WebCore/inspector/InspectorBaseAgent.h index 849763fa5..48fa8e4c3 100644 --- a/Source/WebCore/inspector/InspectorBaseAgent.h +++ b/Source/WebCore/inspector/InspectorBaseAgent.h @@ -65,6 +65,20 @@ private: String m_name; }; +class InspectorAgentRegistry { +public: + void append(PassOwnPtr<InspectorBaseAgentInterface>); + + void setFrontend(InspectorFrontend*); + void clearFrontend(); + void restore(); + void registerInDispatcher(InspectorBackendDispatcher*); + void discardAgents(); + +private: + Vector<OwnPtr<InspectorBaseAgentInterface> > m_agents; +}; + template<typename T> class InspectorBaseAgent : public InspectorBaseAgentInterface { public: diff --git a/Source/WebCore/inspector/InspectorClient.h b/Source/WebCore/inspector/InspectorClient.h index 24bde511b..5961a3c65 100644 --- a/Source/WebCore/inspector/InspectorClient.h +++ b/Source/WebCore/inspector/InspectorClient.h @@ -72,6 +72,9 @@ public: // FIXME: Platforms may want to implement this (see https://bugs.webkit.org/show_bug.cgi?id=82886). } + virtual bool overridesShowPaintRects() { return false; } + virtual void setShowPaintRects(bool) { } + virtual bool canShowFPSCounter() { return false; } virtual void setShowFPSCounter(bool) { } diff --git a/Source/WebCore/inspector/InspectorController.cpp b/Source/WebCore/inspector/InspectorController.cpp index f55865bdf..ca92c4ae2 100644 --- a/Source/WebCore/inspector/InspectorController.cpp +++ b/Source/WebCore/inspector/InspectorController.cpp @@ -171,9 +171,7 @@ InspectorController::InspectorController(Page* page, InspectorClient* inspectorC InspectorController::~InspectorController() { - for (Agents::iterator it = m_agents.begin(); it != m_agents.end(); ++it) - (*it)->discardAgent(); - + m_agents.discardAgents(); ASSERT(!m_inspectorClient); } @@ -221,18 +219,14 @@ void InspectorController::connectFrontend(InspectorFrontendChannel* frontendChan // We can reconnect to existing front-end -> unmute state. m_state->unmute(); - InspectorFrontend* frontend = m_inspectorFrontend.get(); - for (Agents::iterator it = m_agents.begin(); it != m_agents.end(); ++it) - (*it)->setFrontend(frontend); + m_agents.setFrontend(m_inspectorFrontend.get()); InspectorInstrumentation::frontendCreated(); ASSERT(m_inspectorClient); m_inspectorBackendDispatcher = InspectorBackendDispatcher::create(frontendChannel); - InspectorBackendDispatcher* dispatcher = m_inspectorBackendDispatcher.get(); - for (Agents::iterator it = m_agents.begin(); it != m_agents.end(); ++it) - (*it)->registerInDispatcher(dispatcher); + m_agents.registerInDispatcher(m_inspectorBackendDispatcher.get()); } void InspectorController::disconnectFrontend() @@ -246,8 +240,7 @@ void InspectorController::disconnectFrontend() // Pre-disconnect state will be used to restore inspector agents. m_state->mute(); - for (Agents::iterator it = m_agents.begin(); it != m_agents.end(); ++it) - (*it)->clearFrontend(); + m_agents.clearFrontend(); m_inspectorFrontend.clear(); @@ -281,9 +274,7 @@ void InspectorController::reconnectFrontend(InspectorFrontendChannel* frontendCh ASSERT(!m_inspectorFrontend); connectFrontend(frontendChannel); m_state->loadFromCookie(inspectorStateCookie); - - for (Agents::iterator it = m_agents.begin(); it != m_agents.end(); ++it) - (*it)->restore(); + m_agents.restore(); } void InspectorController::setProcessId(long processId) diff --git a/Source/WebCore/inspector/InspectorController.h b/Source/WebCore/inspector/InspectorController.h index 2e89092e2..201d5b043 100644 --- a/Source/WebCore/inspector/InspectorController.h +++ b/Source/WebCore/inspector/InspectorController.h @@ -31,6 +31,9 @@ #ifndef InspectorController_h #define InspectorController_h +#if ENABLE(INSPECTOR) + +#include "InspectorBaseAgent.h" #include <wtf/Forward.h> #include <wtf/HashMap.h> #include <wtf/Noncopyable.h> @@ -141,10 +144,11 @@ private: OwnPtr<InspectorFrontend> m_inspectorFrontend; Page* m_page; InspectorClient* m_inspectorClient; - typedef Vector<OwnPtr<InspectorBaseAgentInterface> > Agents; - Agents m_agents; + InspectorAgentRegistry m_agents; }; } +#endif // ENABLE(INSPECTOR) + #endif // !defined(InspectorController_h) diff --git a/Source/WebCore/inspector/InspectorOverlayPage.html b/Source/WebCore/inspector/InspectorOverlayPage.html index 4c4f903b1..f98422688 100644 --- a/Source/WebCore/inspector/InspectorOverlayPage.html +++ b/Source/WebCore/inspector/InspectorOverlayPage.html @@ -83,13 +83,20 @@ body.platform-linux { } #tag-name { + /* Keep this in sync with view-source.css (.webkit-html-tag-name) */ color: rgb(136, 18, 128); } #node-id { + /* Keep this in sync with view-source.css (.webkit-html-attribute-value) */ color: rgb(26, 26, 166); } +#class-name { + /* Keep this in sync with view-source.css (.webkit-html-attribute-name) */ + color: rgb(153, 69, 0); +} + #right-gutter { display: none; right: 0; @@ -335,8 +342,11 @@ function _drawElementTitle(highlight) return; document.getElementById("tag-name").textContent = elementInfo.tagName; - document.getElementById("node-id").textContent = elementInfo.nodeId ? "#" + elementInfo.nodeId : ""; - document.getElementById("class-name").textContent = elementInfo.className || ""; + document.getElementById("node-id").textContent = elementInfo.idValue ? "#" + elementInfo.idValue : ""; + var className = elementInfo.className; + if (className && className.length > 50) + className = className.substring(0, 50) + "\u2026"; + document.getElementById("class-name").textContent = className || ""; document.getElementById("node-width").textContent = elementInfo.nodeWidth; document.getElementById("node-height").textContent = elementInfo.nodeHeight; var elementTitle = document.getElementById("element-title"); diff --git a/Source/WebCore/inspector/InspectorPageAgent.cpp b/Source/WebCore/inspector/InspectorPageAgent.cpp index 133de98a7..1a46e9a16 100644 --- a/Source/WebCore/inspector/InspectorPageAgent.cpp +++ b/Source/WebCore/inspector/InspectorPageAgent.cpp @@ -93,7 +93,7 @@ static const char pageAgentScreenHeightOverride[] = "pageAgentScreenHeightOverri static const char pageAgentFontScaleFactorOverride[] = "pageAgentFontScaleFactorOverride"; static const char pageAgentFitWindow[] = "pageAgentFitWindow"; static const char pageAgentShowFPSCounter[] = "pageAgentShowFPSCounter"; -static const char showPaintRects[] = "showPaintRects"; +static const char pageAgentShowPaintRects[] = "pageAgentShowPaintRects"; #if ENABLE(TOUCH_EVENTS) static const char touchEventEmulationEnabled[] = "touchEventEmulationEnabled"; #endif @@ -359,6 +359,8 @@ void InspectorPageAgent::restore() enable(&error); bool scriptExecutionDisabled = m_state->getBoolean(PageAgentState::pageAgentScriptExecutionDisabled); setScriptExecutionDisabled(0, scriptExecutionDisabled); + bool showPaintRects = m_state->getBoolean(PageAgentState::pageAgentShowPaintRects); + setShowPaintRects(0, showPaintRects); bool showFPSCounter = m_state->getBoolean(PageAgentState::pageAgentShowFPSCounter); setShowFPSCounter(0, showFPSCounter); @@ -393,6 +395,7 @@ void InspectorPageAgent::disable(ErrorString*) m_instrumentingAgents->setInspectorPageAgent(0); setScriptExecutionDisabled(0, false); + setShowPaintRects(0, false); setShowFPSCounter(0, false); // When disabling the agent, reset the override values. @@ -725,9 +728,11 @@ void InspectorPageAgent::setDeviceMetricsOverride(ErrorString* errorString, int void InspectorPageAgent::setShowPaintRects(ErrorString*, bool show) { - m_state->setBoolean(PageAgentState::showPaintRects, show); - if (!show) - m_page->mainFrame()->view()->invalidate(); + m_state->setBoolean(PageAgentState::pageAgentShowPaintRects, show); + m_client->setShowPaintRects(show); + + if (!show && mainFrame() && mainFrame()->view()) + mainFrame()->view()->invalidate(); } void InspectorPageAgent::canShowFPSCounter(ErrorString*, bool* outParam) @@ -909,7 +914,7 @@ void InspectorPageAgent::applyScreenHeightOverride(long* height) void InspectorPageAgent::didPaint(GraphicsContext* context, const LayoutRect& rect) { - if (!m_enabled || !m_state->getBoolean(PageAgentState::showPaintRects)) + if (!m_enabled || m_client->overridesShowPaintRects() || !m_state->getBoolean(PageAgentState::pageAgentShowPaintRects)) return; static int colorSelector = 0; diff --git a/Source/WebCore/inspector/WorkerInspectorController.cpp b/Source/WebCore/inspector/WorkerInspectorController.cpp index e04e7eeed..d9b390ff6 100644 --- a/Source/WebCore/inspector/WorkerInspectorController.cpp +++ b/Source/WebCore/inspector/WorkerInspectorController.cpp @@ -96,16 +96,23 @@ WorkerInspectorController::WorkerInspectorController(WorkerContext* workerContex , m_state(adoptPtr(new InspectorState(m_stateClient.get()))) , m_instrumentingAgents(adoptPtr(new InstrumentingAgents())) , m_injectedScriptManager(InjectedScriptManager::createForWorker()) + , m_runtimeAgent(0) { + OwnPtr<InspectorRuntimeAgent> runtimeAgent = WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), workerContext); + m_runtimeAgent = runtimeAgent.get(); + m_agents.append(runtimeAgent.release()); - m_runtimeAgent = WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), workerContext); - m_consoleAgent = WorkerConsoleAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()); - + OwnPtr<InspectorConsoleAgent> consoleAgent = WorkerConsoleAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()); #if ENABLE(JAVASCRIPT_DEBUGGER) - m_debuggerAgent = WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), workerContext, m_injectedScriptManager.get()); - m_profilerAgent = InspectorProfilerAgent::create(m_instrumentingAgents.get(), m_consoleAgent.get(), workerContext, m_state.get(), m_injectedScriptManager.get()); + OwnPtr<InspectorDebuggerAgent> debuggerAgent = WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), workerContext, m_injectedScriptManager.get()); + InspectorDebuggerAgent* debuggerAgentPtr = debuggerAgent.get(); + m_runtimeAgent->setScriptDebugServer(&debuggerAgent->scriptDebugServer()); + m_agents.append(debuggerAgent.release()); + + m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent.get(), workerContext, m_state.get(), m_injectedScriptManager.get())); #endif - m_timelineAgent = InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0); + m_agents.append(InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0)); + m_agents.append(consoleAgent.release()); m_injectedScriptManager->injectedScriptHost()->init(0 , 0 @@ -115,13 +122,9 @@ WorkerInspectorController::WorkerInspectorController(WorkerContext* workerContex , 0 , 0 #if ENABLE(JAVASCRIPT_DEBUGGER) - , m_debuggerAgent.get() + , debuggerAgentPtr #endif ); - -#if ENABLE(JAVASCRIPT_DEBUGGER) - m_runtimeAgent->setScriptDebugServer(&m_debuggerAgent->scriptDebugServer()); -#endif } WorkerInspectorController::~WorkerInspectorController() @@ -136,20 +139,8 @@ void WorkerInspectorController::connectFrontend() m_frontendChannel = adoptPtr(new PageInspectorProxy(m_workerContext)); m_frontend = adoptPtr(new InspectorFrontend(m_frontendChannel.get())); m_backendDispatcher = InspectorBackendDispatcher::create(m_frontendChannel.get()); - m_consoleAgent->registerInDispatcher(m_backendDispatcher.get()); - m_timelineAgent->registerInDispatcher(m_backendDispatcher.get()); -#if ENABLE(JAVASCRIPT_DEBUGGER) - m_debuggerAgent->registerInDispatcher(m_backendDispatcher.get()); - m_profilerAgent->registerInDispatcher(m_backendDispatcher.get()); -#endif - m_runtimeAgent->registerInDispatcher(m_backendDispatcher.get()); - -#if ENABLE(JAVASCRIPT_DEBUGGER) - m_debuggerAgent->setFrontend(m_frontend.get()); - m_profilerAgent->setFrontend(m_frontend.get()); -#endif - m_consoleAgent->setFrontend(m_frontend.get()); - m_timelineAgent->setFrontend(m_frontend.get()); + m_agents.registerInDispatcher(m_backendDispatcher.get()); + m_agents.setFrontend(m_frontend.get()); } void WorkerInspectorController::disconnectFrontend() @@ -161,13 +152,7 @@ void WorkerInspectorController::disconnectFrontend() // Destroying agents would change the state, but we don't want that. // Pre-disconnect state will be used to restore inspector agents. m_state->mute(); -#if ENABLE(JAVASCRIPT_DEBUGGER) - m_debuggerAgent->clearFrontend(); - m_profilerAgent->clearFrontend(); -#endif - m_consoleAgent->clearFrontend(); - m_timelineAgent->clearFrontend(); - + m_agents.clearFrontend(); m_frontend.clear(); m_frontendChannel.clear(); } @@ -178,12 +163,7 @@ void WorkerInspectorController::restoreInspectorStateFromCookie(const String& in connectFrontend(); m_state->loadFromCookie(inspectorCookie); -#if ENABLE(JAVASCRIPT_DEBUGGER) - m_debuggerAgent->restore(); - m_profilerAgent->restore(); -#endif - m_consoleAgent->restore(); - m_timelineAgent->restore(); + m_agents.restore(); } void WorkerInspectorController::dispatchMessageFromFrontend(const String& message) diff --git a/Source/WebCore/inspector/WorkerInspectorController.h b/Source/WebCore/inspector/WorkerInspectorController.h index 0e61e9b1c..21dc723fe 100644 --- a/Source/WebCore/inspector/WorkerInspectorController.h +++ b/Source/WebCore/inspector/WorkerInspectorController.h @@ -33,6 +33,7 @@ #if ENABLE(INSPECTOR) && ENABLE(WORKERS) +#include "InspectorBaseAgent.h" #include <wtf/FastAllocBase.h> #include <wtf/Forward.h> #include <wtf/Noncopyable.h> @@ -42,20 +43,13 @@ namespace WebCore { class InjectedScriptManager; -#if ENABLE(JAVASCRIPT_DEBUGGER) -class InspectorDebuggerAgent; -#endif class InspectorBackendDispatcher; -class InspectorConsoleAgent; class InspectorFrontend; class InspectorFrontendChannel; -class InspectorConsoleAgent; class InspectorInstrumentation; -class InspectorProfilerAgent; class InspectorRuntimeAgent; class InspectorState; class InspectorStateClient; -class InspectorTimelineAgent; class InstrumentingAgents; class WorkerContext; @@ -83,14 +77,8 @@ private: OwnPtr<InspectorState> m_state; OwnPtr<InstrumentingAgents> m_instrumentingAgents; OwnPtr<InjectedScriptManager> m_injectedScriptManager; -#if ENABLE(JAVASCRIPT_DEBUGGER) - OwnPtr<InspectorDebuggerAgent> m_debuggerAgent; - OwnPtr<InspectorProfilerAgent> m_profilerAgent; -#endif - OwnPtr<InspectorRuntimeAgent> m_runtimeAgent; - OwnPtr<InspectorConsoleAgent> m_consoleAgent; - OwnPtr<InspectorTimelineAgent> m_timelineAgent; - + InspectorRuntimeAgent* m_runtimeAgent; + InspectorAgentRegistry m_agents; OwnPtr<InspectorFrontendChannel> m_frontendChannel; OwnPtr<InspectorFrontend> m_frontend; RefPtr<InspectorBackendDispatcher> m_backendDispatcher; diff --git a/Source/WebCore/inspector/front-end/ConsoleMessage.js b/Source/WebCore/inspector/front-end/ConsoleMessage.js index 1920afb01..39e4f6b9c 100644 --- a/Source/WebCore/inspector/front-end/ConsoleMessage.js +++ b/Source/WebCore/inspector/front-end/ConsoleMessage.js @@ -322,17 +322,7 @@ WebInspector.ConsoleMessageImpl.prototype = { titleElement.createTextChild(": "); } - var span = titleElement.createChild("span", "console-formatted-" + property.type); - if (property.type === "object") { - if (property.subtype === "node") - span.addStyleClass("console-formatted-preview-node"); - else if (property.subtype === "regexp") - span.addStyleClass("console-formatted-string"); - span.textContent = property.value; - } else if (property.type === "function") - span.textContent = "function"; - else - span.textContent = property.value; + this._appendPropertyPreview(titleElement, property); } if (preview.overflow) titleElement.createChild("span").textContent = "\u2026"; @@ -340,6 +330,39 @@ WebInspector.ConsoleMessageImpl.prototype = { return preview.lossless; }, + /** + * @param {Element} titleElement + * @param {RuntimeAgent.PropertyPreview} property + */ + _appendPropertyPreview: function(titleElement, property) + { + var span = titleElement.createChild("span", "console-formatted-" + property.type); + + if (property.type === "function") { + span.textContent = "function"; + return; + } + + if (property.type === "object" && property.subtype === "regexp") { + span.addStyleClass("console-formatted-string"); + span.textContent = property.value; + return; + } + + if (property.type === "object" && property.subtype === "node") { + span.addStyleClass("console-formatted-preview-node"); + var match = property.value.match(/([^#.]+)(#[^.]+)?(\..*)?/); + span.createChild("span", "webkit-html-tag-name").textContent = match[1]; + if (match[2]) + span.createChild("span", "webkit-html-attribute-value").textContent = match[2]; + if (match[3]) + span.createChild("span", "webkit-html-attribute-name").textContent = match[3]; + return; + } + + span.textContent = property.value; + }, + _formatParameterAsNode: function(object, elem) { function printNode(nodeId) diff --git a/Source/WebCore/inspector/front-end/HeapSnapshotDataGrids.js b/Source/WebCore/inspector/front-end/HeapSnapshotDataGrids.js index 4757e09ba..8cd22d608 100644 --- a/Source/WebCore/inspector/front-end/HeapSnapshotDataGrids.js +++ b/Source/WebCore/inspector/front-end/HeapSnapshotDataGrids.js @@ -438,9 +438,8 @@ WebInspector.HeapSnapshotContainmentDataGrid = function(columns) } WebInspector.HeapSnapshotContainmentDataGrid.prototype = { - setDataSource: function(snapshotView, snapshot, nodeIndex) + setDataSource: function(snapshot, nodeIndex) { - this.snapshotView = snapshotView; this.snapshot = snapshot; var node = new WebInspector.HeapSnapshotNode(snapshot, nodeIndex || snapshot.rootNodeIndex); var fakeEdge = { node: node }; @@ -552,9 +551,8 @@ WebInspector.HeapSnapshotConstructorsDataGrid.prototype = { this.snapshot.nodeClassName(parseInt(id, 10), didGetClassName.bind(this)); }, - setDataSource: function(snapshotView, snapshot) + setDataSource: function(snapshot) { - this.snapshotView = snapshotView; this.snapshot = snapshot; if (this._profileIndex === -1) this._populateChildren(); @@ -645,9 +643,8 @@ WebInspector.HeapSnapshotDiffDataGrid.prototype = { }[sortColumn]; }, - setDataSource: function(snapshotView, snapshot) + setDataSource: function(snapshot) { - this.snapshotView = snapshotView; this.snapshot = snapshot; }, @@ -716,9 +713,8 @@ WebInspector.HeapSnapshotDominatorsDataGrid.prototype = { return 25; }, - setDataSource: function(snapshotView, snapshot) + setDataSource: function(snapshot) { - this.snapshotView = snapshotView; this.snapshot = snapshot; var fakeNode = { nodeIndex: this.snapshot.rootNodeIndex }; diff --git a/Source/WebCore/inspector/front-end/HeapSnapshotGridNodes.js b/Source/WebCore/inspector/front-end/HeapSnapshotGridNodes.js index 40e815400..02095da9f 100644 --- a/Source/WebCore/inspector/front-end/HeapSnapshotGridNodes.js +++ b/Source/WebCore/inspector/front-end/HeapSnapshotGridNodes.js @@ -444,7 +444,6 @@ WebInspector.HeapSnapshotGenericObjectNode.prototype = { valueStyle += " detached-dom-tree-node"; data["object"] = { valueStyle: valueStyle, value: value, nodeId: this.snapshotNodeId }; - var view = this.dataGrid.snapshotView; data["distanceToWindow"] = this._distanceToWindow; data["shallowSize"] = Number.withThousandsSeparator(this._shallowSize); data["retainedSize"] = Number.withThousandsSeparator(this._retainedSize); @@ -827,7 +826,6 @@ WebInspector.HeapSnapshotConstructorNode.prototype = { get data() { var data = { object: this._name }; - var view = this.dataGrid.snapshotView; data["count"] = Number.withThousandsSeparator(this._count); data["distanceToWindow"] = this._distanceToWindow; data["shallowSize"] = Number.withThousandsSeparator(this._shallowSize); diff --git a/Source/WebCore/inspector/front-end/HeapSnapshotView.js b/Source/WebCore/inspector/front-end/HeapSnapshotView.js index 46d3ef544..86566db77 100644 --- a/Source/WebCore/inspector/front-end/HeapSnapshotView.js +++ b/Source/WebCore/inspector/front-end/HeapSnapshotView.js @@ -153,7 +153,7 @@ WebInspector.HeapSnapshotView = function(parent, profile) this.baseSelectElement.selectedIndex = profileIndex - 1; else this.baseSelectElement.selectedIndex = profileIndex; - this.dataGrid.setDataSource(this, heapSnapshotProxy); + this.dataGrid.setDataSource(heapSnapshotProxy); } } @@ -463,7 +463,7 @@ WebInspector.HeapSnapshotView.prototype = { _setRetainmentDataGridSource: function(nodeItem) { if (nodeItem && nodeItem.snapshotNodeIndex) - this.retainmentDataGrid.setDataSource(this, nodeItem.isDeletedNode ? nodeItem.dataGrid.baseSnapshot : nodeItem.dataGrid.snapshot, nodeItem.snapshotNodeIndex); + this.retainmentDataGrid.setDataSource(nodeItem.isDeletedNode ? nodeItem.dataGrid.baseSnapshot : nodeItem.dataGrid.snapshot, nodeItem.snapshotNodeIndex); else this.retainmentDataGrid.reset(); }, @@ -509,7 +509,7 @@ WebInspector.HeapSnapshotView.prototype = { _updateDataSourceAndView: function() { var dataGrid = this.dataGrid; - if (dataGrid.snapshotView) + if (dataGrid.snapshot) return; this.profile.load(didLoadSnapshot.bind(this)); @@ -518,7 +518,7 @@ WebInspector.HeapSnapshotView.prototype = { if (this.dataGrid !== dataGrid) return; if (dataGrid.snapshot !== snapshotProxy) - dataGrid.setDataSource(this, snapshotProxy); + dataGrid.setDataSource(snapshotProxy); if (dataGrid === this.diffDataGrid) { if (!this._baseProfileUid) this._baseProfileUid = this._profiles()[this.baseSelectElement.selectedIndex].uid; diff --git a/Source/WebCore/inspector/front-end/Linkifier.js b/Source/WebCore/inspector/front-end/Linkifier.js index a4b5c9117..9f17d42b5 100644 --- a/Source/WebCore/inspector/front-end/Linkifier.js +++ b/Source/WebCore/inspector/front-end/Linkifier.js @@ -49,7 +49,7 @@ WebInspector.LinkifierFormatter.prototype = { */ WebInspector.Linkifier = function(formatter) { - this._formatter = formatter || new WebInspector.Linkifier.DefaultFormatter(); + this._formatter = formatter || new WebInspector.Linkifier.DefaultFormatter(WebInspector.Linkifier.MaxLengthForDisplayedURLs); this._liveLocations = []; } @@ -173,4 +173,11 @@ WebInspector.Linkifier.DefaultCSSFormatter.prototype = { anchor.textContent = ""; }, __proto__: WebInspector.Linkifier.DefaultFormatter.prototype -}
\ No newline at end of file +} + +/** + * The maximum number of characters to display in a URL. + * @const + * @type {number} + */ +WebInspector.Linkifier.MaxLengthForDisplayedURLs = 150; diff --git a/Source/WebCore/inspector/front-end/ResourceUtils.js b/Source/WebCore/inspector/front-end/ResourceUtils.js index 01b47f5d1..ce047a66a 100644 --- a/Source/WebCore/inspector/front-end/ResourceUtils.js +++ b/Source/WebCore/inspector/front-end/ResourceUtils.js @@ -85,7 +85,7 @@ WebInspector.displayNameForURL = function(url) WebInspector.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier) { var container = document.createDocumentFragment(); - var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|data:|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/; + var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|data:|www\.)[\w$\-_+*'=\|\/\\(){}[\]^%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({^%@&#~]/; var lineColumnRegEx = /:(\d+)(:(\d+))?$/; while (string) { @@ -181,7 +181,7 @@ WebInspector.linkifyURLAsNode = function(url, linkText, classes, isExternal, too a.title = url; else if (typeof tooltipText !== "string" || tooltipText.length) a.title = tooltipText; - a.textContent = linkText.trimMiddle(150); + a.textContent = linkText.trimMiddle(WebInspector.Linkifier.MaxLengthForDisplayedURLs); if (isExternal) a.setAttribute("target", "_blank"); diff --git a/Source/WebCore/inspector/front-end/SettingsScreen.js b/Source/WebCore/inspector/front-end/SettingsScreen.js index 9d06805fd..02ae22065 100644 --- a/Source/WebCore/inspector/front-end/SettingsScreen.js +++ b/Source/WebCore/inspector/front-end/SettingsScreen.js @@ -308,8 +308,10 @@ WebInspector.GenericSettingsTab = function() if (WebInspector.experimentsSettings.nativeMemorySnapshots.isEnabled()) p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show uninstrumented native memory"), WebInspector.settings.showNativeSnapshotUninstrumentedSize)); - p = this._appendSection(WebInspector.UIString("Timeline")); - p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show CPU activity on the ruler"), WebInspector.settings.showCpuOnTimelineRuler)); + if (Capabilities.timelineCanMonitorMainThread) { + p = this._appendSection(WebInspector.UIString("Timeline")); + p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show CPU activity on the ruler"), WebInspector.settings.showCpuOnTimelineRuler)); + } p = this._appendSection(WebInspector.UIString("Console")); p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Log XMLHttpRequests"), WebInspector.settings.monitoringXHREnabled)); diff --git a/Source/WebCore/inspector/front-end/TimelinePanel.js b/Source/WebCore/inspector/front-end/TimelinePanel.js index 7cf93b073..f616d4219 100644 --- a/Source/WebCore/inspector/front-end/TimelinePanel.js +++ b/Source/WebCore/inspector/front-end/TimelinePanel.js @@ -131,11 +131,12 @@ WebInspector.TimelinePanel = function() this._expandOffset = 15; this._headerLineCount = 1; + this._adjustHeaderHeight(); this._mainThreadTasks = /** @type {!Array.<{startTime: number, endTime: number}>} */ ([]); - this._mainThreadMonitoringEnabled = false; - if (WebInspector.settings.showCpuOnTimelineRuler.get() && Capabilities.timelineCanMonitorMainThread) - this._enableMainThreadMonitoring(); + this._cpuBarsElement = this._timelineGrid.gridHeaderElement.createChild("div", "timeline-cpu-bars"); + this._mainThreadMonitoringEnabled = Capabilities.timelineCanMonitorMainThread && WebInspector.settings.showCpuOnTimelineRuler.get(); + WebInspector.settings.showCpuOnTimelineRuler.addChangeListener(this._showCpuOnTimelineRulerChanged, this); this._createFileSelector(); @@ -155,6 +156,15 @@ WebInspector.TimelinePanel = function() WebInspector.TimelinePanel.rowHeight = 18; WebInspector.TimelinePanel.prototype = { + _showCpuOnTimelineRulerChanged: function() + { + var mainThreadMonitoringEnabled = WebInspector.settings.showCpuOnTimelineRuler.get(); + if (this._mainThreadMonitoringEnabled !== mainThreadMonitoringEnabled) { + this._mainThreadMonitoringEnabled = mainThreadMonitoringEnabled; + this._refreshMainThreadBars(); + } + }, + /** * @param {Event} event * @return {boolean} @@ -891,7 +901,7 @@ WebInspector.TimelinePanel.prototype = { var startTime = this._overviewPane.windowStartTime() - this._timelinePaddingLeft * scale; var endTime = startTime + width * scale; - var tasks = this._mainThreadTasks; + var tasks = this._mainThreadMonitoringEnabled ? this._mainThreadTasks : []; function compareEndTime(value, task) { @@ -948,11 +958,8 @@ WebInspector.TimelinePanel.prototype = { } }, - _enableMainThreadMonitoring: function() + _adjustHeaderHeight: function() { - var container = this._timelineGrid.gridHeaderElement; - this._cpuBarsElement = container.createChild("div", "timeline-cpu-bars"); - const headerBorderWidth = 1; const headerMargin = 2; @@ -960,8 +967,6 @@ WebInspector.TimelinePanel.prototype = { this.sidebarElement.firstChild.style.height = headerHeight + "px"; this._timelineGrid.dividersLabelBarElement.style.height = headerHeight + headerMargin + "px"; this._itemsGraphsElement.style.top = headerHeight + headerBorderWidth + "px"; - - this._mainThreadMonitoringEnabled = true; }, _adjustScrollPosition: function(totalHeight) diff --git a/Source/WebCore/inspector/front-end/inspector.css b/Source/WebCore/inspector/front-end/inspector.css index ed979b3ae..54bb4695b 100644 --- a/Source/WebCore/inspector/front-end/inspector.css +++ b/Source/WebCore/inspector/front-end/inspector.css @@ -1067,6 +1067,7 @@ ol.watch-expressions > li.hovered { .console-message-url { float: right; + text-align: right; max-width: 100%; margin-left: 4px; } diff --git a/Source/WebCore/loader/DocumentLoader.cpp b/Source/WebCore/loader/DocumentLoader.cpp index 218db822f..9f5f04861 100644 --- a/Source/WebCore/loader/DocumentLoader.cpp +++ b/Source/WebCore/loader/DocumentLoader.cpp @@ -49,6 +49,7 @@ #include "MainResourceLoader.h" #include "Page.h" #include "ResourceBuffer.h" +#include "SchemeRegistry.h" #include "Settings.h" #include "TextResourceDecoder.h" #include "WebCoreMemoryInstrumentation.h" @@ -97,6 +98,7 @@ DocumentLoader::DocumentLoader(const ResourceRequest& req, const SubstituteData& , m_isStopping(false) , m_gotFirstByte(false) , m_isClientRedirect(false) + , m_loadingEmptyDocument(false) , m_wasOnloadHandled(false) , m_stopRecordingResponses(false) , m_substituteResourceDeliveryTimer(this, &DocumentLoader::substituteResourceDeliveryTimerFired) @@ -114,7 +116,7 @@ FrameLoader* DocumentLoader::frameLoader() const DocumentLoader::~DocumentLoader() { - ASSERT(!m_frame || frameLoader()->activeDocumentLoader() != this || !frameLoader()->isLoading()); + ASSERT(!m_frame || frameLoader()->activeDocumentLoader() != this || !isLoading()); if (m_iconLoadDecisionCallback) m_iconLoadDecisionCallback->invalidate(); if (m_iconDataCallback) @@ -285,7 +287,7 @@ void DocumentLoader::commitIfReady() void DocumentLoader::finishedLoading() { commitIfReady(); - if (!frameLoader() || frameLoader()->stateMachine()->creatingInitialEmptyDocument()) + if (!frameLoader()) return; if (!maybeCreateArchive()) { @@ -300,7 +302,8 @@ void DocumentLoader::finishedLoading() if (!m_mainDocumentError.isNull()) return; clearMainResourceLoader(); - frameLoader()->checkLoadComplete(); + if (!frameLoader()->stateMachine()->creatingInitialEmptyDocument()) + frameLoader()->checkLoadComplete(); } void DocumentLoader::commitLoad(const char* data, int length) @@ -327,6 +330,9 @@ void DocumentLoader::commitData(const char* bytes, size_t length) m_gotFirstByte = true; m_writer.begin(documentURL(), false); m_writer.setDocumentWasLoadedAsPartOfNavigation(); + + if (frameLoader()->stateMachine()->creatingInitialEmptyDocument()) + return; #if ENABLE(MHTML) // The origin is the MHTML file, we need to set the base URL to the document encoded in the MHTML so @@ -449,6 +455,7 @@ void DocumentLoader::clearMainResourceLoader() m_mainResourceData = m_mainResourceLoader->resourceData(); m_mainResourceLoader = 0; } + m_loadingEmptyDocument = false; if (this == frameLoader()->activeDocumentLoader()) checkLoadComplete(); @@ -463,7 +470,7 @@ bool DocumentLoader::isLoadingInAPISense() const return true; Document* doc = m_frame->document(); - if ((m_mainResourceLoader || !m_frame->document()->loadEventFinished()) && isLoading()) + if ((isLoadingMainResource() || !m_frame->document()->loadEventFinished()) && isLoading()) return true; if (m_cachedResourceLoader->requestCount()) return true; @@ -769,8 +776,6 @@ KURL DocumentLoader::documentURL() const url = requestURL(); if (url.isEmpty()) url = responseURL(); - if (url.isEmpty()) - url = blankURL(); return url; } @@ -830,7 +835,7 @@ void DocumentLoader::removePlugInStreamLoader(ResourceLoader* loader) bool DocumentLoader::isLoadingMainResource() const { - return !!m_mainResourceLoader; + return !!m_mainResourceLoader || m_loadingEmptyDocument; } bool DocumentLoader::isLoadingMultipartContent() const @@ -843,17 +848,41 @@ bool DocumentLoader::isMultipartReplacingLoad() const return isLoadingMultipartContent() && frameLoader()->isReplacing(); } +bool DocumentLoader::maybeLoadEmpty() +{ + bool shouldLoadEmpty = !m_substituteData.isValid() && (m_request.url().isEmpty() || SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(m_request.url().protocol())); + if (!shouldLoadEmpty && !frameLoader()->client()->representationExistsForURLScheme(m_request.url().protocol())) + return false; + + m_loadingEmptyDocument = true; + if (m_request.url().isEmpty() && !frameLoader()->stateMachine()->creatingInitialEmptyDocument()) + m_request.setURL(blankURL()); + String mimeType = shouldLoadEmpty ? "text/html" : frameLoader()->client()->generatedMIMETypeForURLScheme(m_request.url().protocol()); + setResponse(ResourceResponse(m_request.url(), mimeType, 0, String(), String())); + finishedLoading(); + return true; +} + void DocumentLoader::startLoadingMainResource() { m_mainDocumentError = ResourceError(); timing()->markNavigationStart(); ASSERT(!m_mainResourceLoader); + + if (maybeLoadEmpty()) + return; + m_mainResourceLoader = MainResourceLoader::create(m_frame); // FIXME: Is there any way the extra fields could have not been added by now? // If not, it would be great to remove this line of code. frameLoader()->addExtraFieldsToMainResourceRequest(m_request); m_mainResourceLoader->load(m_request, m_substituteData); + + if (m_request.isNull()) { + m_mainResourceLoader = 0; + maybeLoadEmpty(); + } } void DocumentLoader::cancelMainResourceLoad(const ResourceError& error) diff --git a/Source/WebCore/loader/DocumentLoader.h b/Source/WebCore/loader/DocumentLoader.h index e5acf4c82..7ef0477ad 100644 --- a/Source/WebCore/loader/DocumentLoader.h +++ b/Source/WebCore/loader/DocumentLoader.h @@ -185,7 +185,7 @@ namespace WebCore { String clientRedirectDestinationForHistory() const { return urlForHistory(); } void setClientRedirectSourceForHistory(const String& clientRedirectSourceForHistory) { m_clientRedirectSourceForHistory = clientRedirectSourceForHistory; } - String serverRedirectSourceForHistory() const { return urlForHistory() == url() ? String() : urlForHistory().string(); } // null if no server redirect occurred. + String serverRedirectSourceForHistory() const { return (urlForHistory() == url() || url() == blankURL()) ? String() : urlForHistory().string(); } // null if no server redirect occurred. String serverRedirectDestinationForHistory() const { return url(); } bool didCreateGlobalHistoryEntry() const { return m_didCreateGlobalHistoryEntry; } @@ -265,6 +265,8 @@ namespace WebCore { void clearArchiveResources(); #endif + bool maybeLoadEmpty(); + bool isMultipartReplacingLoad() const; void deliverSubstituteResourcesAfterDelay(); @@ -307,6 +309,7 @@ namespace WebCore { bool m_isStopping; bool m_gotFirstByte; bool m_isClientRedirect; + bool m_loadingEmptyDocument; // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadHandled are roughly the same // and should be merged. diff --git a/Source/WebCore/loader/FrameLoadRequest.cpp b/Source/WebCore/loader/FrameLoadRequest.cpp new file mode 100644 index 000000000..014678823 --- /dev/null +++ b/Source/WebCore/loader/FrameLoadRequest.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "FrameLoadRequest.h" + +#include "Document.h" +#include "Frame.h" + +namespace WebCore { + +FrameLoadRequest::FrameLoadRequest(Frame* frame, const ResourceRequest& resourceRequest, const SubstituteData& substituteData) + : m_requester(frame->document()->securityOrigin()) + , m_resourceRequest(resourceRequest) + , m_lockHistory(false) + , m_shouldCheckNewWindowPolicy(false) + , m_substituteData(substituteData) +{ +} + +} // namespace WebCore diff --git a/Source/WebCore/loader/FrameLoadRequest.h b/Source/WebCore/loader/FrameLoadRequest.h index d65a9b5fa..1b7789986 100644 --- a/Source/WebCore/loader/FrameLoadRequest.h +++ b/Source/WebCore/loader/FrameLoadRequest.h @@ -28,19 +28,25 @@ #include "ResourceRequest.h" #include "SecurityOrigin.h" +#include "SubstituteData.h" namespace WebCore { +class Frame; struct FrameLoadRequest { public: explicit FrameLoadRequest(SecurityOrigin* requester) : m_requester(requester) + , m_lockHistory(false) + , m_shouldCheckNewWindowPolicy(false) { } FrameLoadRequest(SecurityOrigin* requester, const ResourceRequest& resourceRequest) : m_requester(requester) , m_resourceRequest(resourceRequest) + , m_lockHistory(false) + , m_shouldCheckNewWindowPolicy(false) { } @@ -48,9 +54,13 @@ public: : m_requester(requester) , m_resourceRequest(resourceRequest) , m_frameName(frameName) + , m_lockHistory(false) + , m_shouldCheckNewWindowPolicy(false) { } + FrameLoadRequest(Frame*, const ResourceRequest&, const SubstituteData& = SubstituteData()); + bool isEmpty() const { return m_resourceRequest.isEmpty(); } const SecurityOrigin* requester() const { return m_requester.get(); } @@ -61,10 +71,23 @@ public: const String& frameName() const { return m_frameName; } void setFrameName(const String& frameName) { m_frameName = frameName; } + void setLockHistory(bool lockHistory) { m_lockHistory = lockHistory; } + bool lockHistory() const { return m_lockHistory; } + + void setShouldCheckNewWindowPolicy(bool checkPolicy) { m_shouldCheckNewWindowPolicy = checkPolicy; } + bool shouldCheckNewWindowPolicy() const { return m_shouldCheckNewWindowPolicy; } + + const SubstituteData& substituteData() const { return m_substituteData; } + void setSubstituteData(const SubstituteData& data) { m_substituteData = data; } + bool hasSubstituteData() { return m_substituteData.isValid(); } + private: RefPtr<SecurityOrigin> m_requester; ResourceRequest m_resourceRequest; String m_frameName; + bool m_lockHistory; + bool m_shouldCheckNewWindowPolicy; + SubstituteData m_substituteData; }; } diff --git a/Source/WebCore/loader/FrameLoader.cpp b/Source/WebCore/loader/FrameLoader.cpp index 437a1f616..0352b1d8c 100644 --- a/Source/WebCore/loader/FrameLoader.cpp +++ b/Source/WebCore/loader/FrameLoader.cpp @@ -214,14 +214,14 @@ FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client) , m_subframeLoader(frame) , m_icon(frame) , m_mixedContentChecker(frame) - , m_state(FrameStateCommittedPage) + , m_state(FrameStateProvisional) , m_loadType(FrameLoadTypeStandard) , m_delegateIsHandlingProvisionalLoadError(false) , m_quickRedirectComing(false) , m_sentRedirectNotification(false) , m_inStopAllLoaders(false) , m_isExecutingJavaScriptFormAction(false) - , m_didCallImplicitClose(false) + , m_didCallImplicitClose(true) , m_wasUnloadEventEmitted(false) , m_pageDismissalEventBeingDispatched(NoDismissal) , m_isComplete(false) @@ -254,19 +254,11 @@ FrameLoader::~FrameLoader() void FrameLoader::init() { // This somewhat odd set of steps gives the frame an initial empty document. - // It would be better if this could be done with even fewer steps. - m_stateMachine.advanceTo(FrameLoaderStateMachine::CreatingInitialEmptyDocument); setPolicyDocumentLoader(m_client->createDocumentLoader(ResourceRequest(KURL(ParsedURLString, emptyString())), SubstituteData()).get()); setProvisionalDocumentLoader(m_policyDocumentLoader.get()); - setState(FrameStateProvisional); - m_provisionalDocumentLoader->setResponse(ResourceResponse(KURL(), "text/html", 0, String(), String())); - m_provisionalDocumentLoader->finishedLoading(); - ASSERT(!m_frame->document()); - m_documentLoader->writer()->begin(KURL(), false); - m_documentLoader->writer()->end(); + m_provisionalDocumentLoader->startLoadingMainResource(); m_frame->document()->cancelParsing(); m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument); - m_didCallImplicitClose = true; m_networkingContext = m_client->createNetworkingContext(); m_progressTracker = FrameProgressTracker::create(m_frame); @@ -1252,36 +1244,36 @@ SubstituteData FrameLoader::defaultSubstituteDataForURL(const KURL& url) return SubstituteData(SharedBuffer::create(encodedSrcdoc.data(), encodedSrcdoc.length()), "text/html", "UTF-8", KURL()); } -void FrameLoader::load(const ResourceRequest& request, bool lockHistory) +void FrameLoader::load(const FrameLoadRequest& passedRequest) { - load(request, defaultSubstituteDataForURL(request.url()), lockHistory); -} + FrameLoadRequest request(passedRequest); -void FrameLoader::load(const ResourceRequest& request, const SubstituteData& substituteData, bool lockHistory) -{ if (m_inStopAllLoaders) return; - - RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request, substituteData); - if (lockHistory && m_documentLoader) - loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory()); - load(loader.get()); -} -void FrameLoader::load(const ResourceRequest& request, const String& frameName, bool lockHistory) -{ - if (frameName.isEmpty()) { - load(request, lockHistory); - return; + if (!request.frameName().isEmpty()) { + Frame* frame = findFrameForNavigation(request.frameName()); + if (frame) { + request.setShouldCheckNewWindowPolicy(false); + if (frame->loader() != this) { + frame->loader()->load(request); + return; + } + } } - Frame* frame = findFrameForNavigation(frameName); - if (frame) { - frame->loader()->load(request, lockHistory); + if (request.shouldCheckNewWindowPolicy()) { + policyChecker()->checkNewWindowPolicy(NavigationAction(request.resourceRequest(), NavigationTypeOther), FrameLoader::callContinueLoadAfterNewWindowPolicy, request.resourceRequest(), 0, request.frameName(), this); return; } - policyChecker()->checkNewWindowPolicy(NavigationAction(request, NavigationTypeOther), FrameLoader::callContinueLoadAfterNewWindowPolicy, request, 0, frameName, this); + if (!request.hasSubstituteData()) + request.setSubstituteData(defaultSubstituteDataForURL(request.resourceRequest().url())); + + RefPtr<DocumentLoader> loader = m_client->createDocumentLoader(request.resourceRequest(), request.substituteData()); + if (request.lockHistory() && m_documentLoader) + loader->setClientRedirectSourceForHistory(m_documentLoader->didCreateGlobalHistoryEntry() ? m_documentLoader->urlForHistory().string() : m_documentLoader->clientRedirectSourceForHistory()); + load(loader.get()); } void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, bool lockHistory, FrameLoadType type, PassRefPtr<FormState> formState) diff --git a/Source/WebCore/loader/FrameLoader.h b/Source/WebCore/loader/FrameLoader.h index 516369a86..8a435c895 100644 --- a/Source/WebCore/loader/FrameLoader.h +++ b/Source/WebCore/loader/FrameLoader.h @@ -104,9 +104,8 @@ public: void loadFrameRequest(const FrameLoadRequest&, bool lockHistory, bool lockBackForwardList, // Called by submitForm, calls loadPostRequest and loadURL. PassRefPtr<Event>, PassRefPtr<FormState>, ShouldSendReferrer); - void load(const ResourceRequest&, bool lockHistory); // Called by WebFrame, calls load(ResourceRequest, SubstituteData). - void load(const ResourceRequest&, const SubstituteData&, bool lockHistory); // Called both by WebFrame and internally, calls load(DocumentLoader*). - void load(const ResourceRequest&, const String& frameName, bool lockHistory); // Called by WebPluginController. + void load(const FrameLoadRequest&); + #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML) void loadArchive(PassRefPtr<Archive>); #endif diff --git a/Source/WebCore/loader/FrameLoaderClient.h b/Source/WebCore/loader/FrameLoaderClient.h index 85e4eecf1..a6fdbabae 100644 --- a/Source/WebCore/loader/FrameLoaderClient.h +++ b/Source/WebCore/loader/FrameLoaderClient.h @@ -63,6 +63,7 @@ namespace WebCore { class AuthenticationChallenge; class CachedFrame; + class CachedResourceRequest; class Color; class DOMWindowExtension; class DOMWrapperWorld; @@ -179,6 +180,8 @@ namespace WebCore { virtual void dispatchUnableToImplementPolicy(const ResourceError&) = 0; + virtual void dispatchWillRequestResource(CachedResourceRequest*) { } + virtual void dispatchWillSendSubmitEvent(PassRefPtr<FormState>) = 0; virtual void dispatchWillSubmitForm(FramePolicyFunction, PassRefPtr<FormState>) = 0; diff --git a/Source/WebCore/loader/FrameLoaderStateMachine.cpp b/Source/WebCore/loader/FrameLoaderStateMachine.cpp index 790b14408..5400abd11 100644 --- a/Source/WebCore/loader/FrameLoaderStateMachine.cpp +++ b/Source/WebCore/loader/FrameLoaderStateMachine.cpp @@ -35,7 +35,7 @@ namespace WebCore { FrameLoaderStateMachine::FrameLoaderStateMachine() - : m_state(Uninitialized) + : m_state(CreatingInitialEmptyDocument) { } diff --git a/Source/WebCore/loader/FrameLoaderStateMachine.h b/Source/WebCore/loader/FrameLoaderStateMachine.h index fe37ece9c..8bce923e8 100644 --- a/Source/WebCore/loader/FrameLoaderStateMachine.h +++ b/Source/WebCore/loader/FrameLoaderStateMachine.h @@ -44,7 +44,6 @@ public: // alternate between CommittedFirstRealLoad and FirstLayoutDone. // Otherwise, the states only go down the list. enum State { - Uninitialized, CreatingInitialEmptyDocument, DisplayingInitialEmptyDocument, DisplayingInitialEmptyDocumentPostCommit, diff --git a/Source/WebCore/loader/MainResourceLoader.cpp b/Source/WebCore/loader/MainResourceLoader.cpp index 1b113a0d3..3ff68d8bb 100644 --- a/Source/WebCore/loader/MainResourceLoader.cpp +++ b/Source/WebCore/loader/MainResourceLoader.cpp @@ -67,11 +67,6 @@ namespace WebCore { -static bool shouldLoadAsEmptyDocument(const KURL& url) -{ - return url.isEmpty() || SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(url.protocol()); -} - MainResourceLoader::MainResourceLoader(Frame* frame) : ResourceLoader(frame, ResourceLoaderOptions(SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck)) , m_dataLoadTimer(this, &MainResourceLoader::handleSubstituteDataLoadNow) @@ -338,13 +333,10 @@ void MainResourceLoader::continueAfterContentPolicy(PolicyAction contentPolicy, if (!reachedTerminalState()) ResourceLoader::didReceiveResponse(r); - if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping()) { - if (m_substituteData.isValid()) { - if (m_substituteData.content()->size()) - didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true); - if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping()) - didFinishLoading(0); - } else if (shouldLoadAsEmptyDocument(url) || frameLoader()->client()->representationExistsForURLScheme(url.protocol())) + if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping() && m_substituteData.isValid()) { + if (m_substituteData.content()->size()) + didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true); + if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping()) didFinishLoading(0); } } @@ -385,7 +377,7 @@ void MainResourceLoader::didReceiveResponse(const ResourceResponse& r) // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred. // See <rdar://problem/6304600> for more details. #if !USE(CF) - ASSERT(shouldLoadAsEmptyDocument(r.url()) || !defersLoading()); + ASSERT(!defersLoading()); #endif if (m_loadingMultipartContent) { @@ -500,7 +492,7 @@ void MainResourceLoader::didFinishLoading(double finishTime) // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred. // See <rdar://problem/6304600> for more details. #if !USE(CF) - ASSERT(shouldLoadAsEmptyDocument(frameLoader()->activeDocumentLoader()->url()) || !defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame.get())); + ASSERT(!defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame.get())); #endif // The additional processing can do anything including possibly removing the last @@ -561,18 +553,6 @@ void MainResourceLoader::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) c info.addMember(m_dataLoadTimer); } -void MainResourceLoader::handleEmptyLoad(const KURL& url, bool forURLScheme) -{ - String mimeType; - if (forURLScheme) - mimeType = frameLoader()->client()->generatedMIMETypeForURLScheme(url.protocol()); - else - mimeType = "text/html"; - - ResourceResponse response(url, mimeType, 0, String(), String()); - didReceiveResponse(response); -} - void MainResourceLoader::handleSubstituteDataLoadNow(MainResourceLoaderTimer*) { RefPtr<MainResourceLoader> protect(this); @@ -609,29 +589,10 @@ void MainResourceLoader::handleSubstituteDataLoadSoon(const ResourceRequest& r) handleSubstituteDataLoadNow(0); } -bool MainResourceLoader::loadNow(ResourceRequest& r) +void MainResourceLoader::loadNow(ResourceRequest& r) { - bool shouldLoadEmptyBeforeRedirect = shouldLoadAsEmptyDocument(r.url()); - ASSERT(!m_handle); - ASSERT(shouldLoadEmptyBeforeRedirect || !defersLoading()); - - // Send this synthetic delegate callback since clients expect it, and - // we no longer send the callback from within NSURLConnection for - // initial requests. - willSendRequest(r, ResourceResponse()); - ASSERT(!deletionHasBegun()); - - // <rdar://problem/4801066> - // willSendRequest() is liable to make the call to frameLoader() return NULL, so we need to check that here - if (!frameLoader()) - return false; - - const KURL& url = r.url(); - bool shouldLoadEmpty = shouldLoadAsEmptyDocument(url) && !m_substituteData.isValid(); - - if (shouldLoadEmptyBeforeRedirect && !shouldLoadEmpty && defersLoading()) - return true; + ASSERT(!defersLoading()); #if USE(PLATFORM_STRATEGIES) platformStrategies()->loaderStrategy()->resourceLoadScheduler()->addMainResourceLoad(this); @@ -641,12 +602,10 @@ bool MainResourceLoader::loadNow(ResourceRequest& r) if (m_substituteData.isValid()) handleSubstituteDataLoadSoon(r); - else if (shouldLoadEmpty || frameLoader()->client()->representationExistsForURLScheme(url.protocol())) - handleEmptyLoad(url, !shouldLoadEmpty); else m_handle = ResourceHandle::create(m_frame->loader()->networkingContext(), r, this, false, true); - return false; + return; } void MainResourceLoader::load(const ResourceRequest& r, const SubstituteData& substituteData) @@ -664,23 +623,26 @@ void MainResourceLoader::load(const ResourceRequest& r, const SubstituteData& su documentLoader()->timing()->markFetchStart(); ResourceRequest request(r); - documentLoader()->applicationCacheHost()->maybeLoadMainResource(request, m_substituteData); + // Send this synthetic delegate callback since clients expect it, and + // we no longer send the callback from within NSURLConnection for + // initial requests. + willSendRequest(request, ResourceResponse()); + ASSERT(!deletionHasBegun()); - bool defer = defersLoading(); - if (defer) { - bool shouldLoadEmpty = shouldLoadAsEmptyDocument(request.url()); - if (shouldLoadEmpty) - defer = false; - } - if (!defer) { - if (loadNow(request)) { - // Started as an empty document, but was redirected to something non-empty. - ASSERT(defersLoading()); - defer = true; - } + // <rdar://problem/4801066> + // willSendRequest() is liable to make the call to frameLoader() return null, so we need to check that here + if (!frameLoader() || request.isNull()) { + if (!reachedTerminalState()) + releaseResources(); + return; } - if (defer) + + documentLoader()->applicationCacheHost()->maybeLoadMainResource(request, m_substituteData); + + if (defersLoading()) m_initialRequest = request; + else + loadNow(request); } void MainResourceLoader::setDefersLoading(bool defers) diff --git a/Source/WebCore/loader/MainResourceLoader.h b/Source/WebCore/loader/MainResourceLoader.h index 09406e8e2..350cecd65 100644 --- a/Source/WebCore/loader/MainResourceLoader.h +++ b/Source/WebCore/loader/MainResourceLoader.h @@ -81,9 +81,8 @@ private: virtual void willCancel(const ResourceError&) OVERRIDE; virtual void didCancel(const ResourceError&) OVERRIDE; - bool loadNow(ResourceRequest&); + void loadNow(ResourceRequest&); - void handleEmptyLoad(const KURL&, bool forURLScheme); void handleSubstituteDataLoadSoon(const ResourceRequest&); void handleSubstituteDataLoadNow(MainResourceLoaderTimer*); diff --git a/Source/WebCore/loader/ResourceBuffer.cpp b/Source/WebCore/loader/ResourceBuffer.cpp index 0e30ec323..57ae9ac5b 100644 --- a/Source/WebCore/loader/ResourceBuffer.cpp +++ b/Source/WebCore/loader/ResourceBuffer.cpp @@ -71,6 +71,14 @@ void ResourceBuffer::append(const char* data, unsigned size) m_sharedBuffer->append(data, size); } +#if USE(NETWORK_CFDATA_ARRAY_CALLBACK) +void ResourceBuffer::append(CFDataRef data) +{ + ASSERT(m_sharedBuffer); + m_sharedBuffer->append(data); +} +#endif + void ResourceBuffer::clear() { m_sharedBuffer->clear(); diff --git a/Source/WebCore/loader/ResourceBuffer.h b/Source/WebCore/loader/ResourceBuffer.h index 83642ffd3..2fdd8f367 100644 --- a/Source/WebCore/loader/ResourceBuffer.h +++ b/Source/WebCore/loader/ResourceBuffer.h @@ -55,6 +55,9 @@ public: virtual bool isEmpty() const; void append(const char*, unsigned); +#if USE(NETWORK_CFDATA_ARRAY_CALLBACK) + void append(CFDataRef); +#endif void clear(); unsigned getSomeData(const char*& data, unsigned position = 0) const; diff --git a/Source/WebCore/loader/blackberry/CookieJarBlackBerry.cpp b/Source/WebCore/loader/blackberry/CookieJarBlackBerry.cpp index 781202280..0679666a5 100644 --- a/Source/WebCore/loader/blackberry/CookieJarBlackBerry.cpp +++ b/Source/WebCore/loader/blackberry/CookieJarBlackBerry.cpp @@ -39,38 +39,18 @@ namespace WebCore { String cookies(Document const* document, KURL const& url) { - Frame* frame = document->frame(); - Page* page = frame ? frame->page() : 0; - - if (!page) - return String(); - - if (!(frame && frame->loader() && frame->loader()->client())) + if (!document->settings()->cookieEnabled()) return String(); - if (!static_cast<FrameLoaderClientBlackBerry*>(frame->loader()->client())->cookiesEnabled()) - return String(); - - ASSERT(document && url == document->cookieURL()); // 'HttpOnly' cookies should no be accessible from scripts, so we filter them out here return cookieManager().getCookie(url, NoHttpOnlyCookie); } void setCookies(Document* document, KURL const& url, String const& value) { - Frame* frame = document->frame(); - Page* page = frame ? frame->page() : 0; - - if (!page) + if (!document->settings()->cookieEnabled()) return; - if (!(frame && frame->loader() && frame->loader()->client())) - return; - - if (!static_cast<FrameLoaderClientBlackBerry*>(frame->loader()->client())->cookiesEnabled()) - return; - - ASSERT(document && url == document->cookieURL()); cookieManager().setCookies(url, value, NoHttpOnlyCookie); } @@ -98,12 +78,7 @@ void deleteCookie(const Document* document, const KURL& url, const String& cooki String cookieRequestHeaderFieldValue(const Document* document, const KURL &url) { - ASSERT(document); - - if (!(document->frame() && document->frame()->loader() && document->frame()->loader()->client())) - return String(); - - if (!static_cast<FrameLoaderClientBlackBerry*>(document->frame()->loader()->client())->cookiesEnabled()) + if (!document->settings()->cookieEnabled()) return String(); return cookieManager().getCookie(url, WithHttpOnlyCookies); diff --git a/Source/WebCore/loader/cache/CachedResourceLoader.cpp b/Source/WebCore/loader/cache/CachedResourceLoader.cpp index 83a5a1ce6..b946fe4ec 100644 --- a/Source/WebCore/loader/cache/CachedResourceLoader.cpp +++ b/Source/WebCore/loader/cache/CachedResourceLoader.cpp @@ -423,6 +423,9 @@ CachedResourceHandle<CachedResource> CachedResourceLoader::requestResource(Cache if (!canRequest(type, url, request.forPreload())) return 0; + if (Frame* f = frame()) + f->loader()->client()->dispatchWillRequestResource(&request); + if (memoryCache()->disabled()) { DocumentResourceMap::iterator it = m_documentResources.find(url.string()); if (it != m_documentResources.end()) { diff --git a/Source/WebCore/loader/mac/ResourceLoaderMac.mm b/Source/WebCore/loader/mac/ResourceLoaderMac.mm index ad4d60a16..8e7ce9fe5 100644 --- a/Source/WebCore/loader/mac/ResourceLoaderMac.mm +++ b/Source/WebCore/loader/mac/ResourceLoaderMac.mm @@ -35,6 +35,7 @@ #if USE(NETWORK_CFDATA_ARRAY_CALLBACK) #include "InspectorInstrumentation.h" +#include "ResourceBuffer.h" #endif #if USE(CFNETWORK) diff --git a/Source/WebCore/page/ContextMenuController.cpp b/Source/WebCore/page/ContextMenuController.cpp index 5640dc769..adf0a797a 100644 --- a/Source/WebCore/page/ContextMenuController.cpp +++ b/Source/WebCore/page/ContextMenuController.cpp @@ -702,9 +702,8 @@ static bool selectionContainsPossibleWord(Frame* frame) // Current algorithm: look for a character that's not just a separator. for (TextIterator it(frame->selection()->toNormalizedRange().get()); !it.atEnd(); it.advance()) { int length = it.length(); - const UChar* characters = it.characters(); for (int i = 0; i < length; ++i) - if (!(category(characters[i]) & (Separator_Space | Separator_Line | Separator_Paragraph))) + if (!(category(it.characterAt(i)) & (Separator_Space | Separator_Line | Separator_Paragraph))) return true; } return false; diff --git a/Source/WebCore/page/DOMWindow.idl b/Source/WebCore/page/DOMWindow.idl index db7c09d78..4a3a5f4de 100644 --- a/Source/WebCore/page/DOMWindow.idl +++ b/Source/WebCore/page/DOMWindow.idl @@ -341,6 +341,10 @@ attribute CSSValueListConstructor CSSValueList; attribute WebKitCSSTransformValueConstructor WebKitCSSTransformValue; +#if defined(ENABLE_CSS_SHADERS) && ENABLE_CSS_SHADERS + attribute WebKitCSSMixFunctionValueConstructor WebKitCSSMixFunctionValue; +#endif + #if defined(ENABLE_CSS_FILTERS) && ENABLE_CSS_FILTERS attribute WebKitCSSFilterValueConstructor WebKitCSSFilterValue; #endif diff --git a/Source/WebCore/page/DragController.cpp b/Source/WebCore/page/DragController.cpp index 81ea3f95d..3a0dd16d2 100644 --- a/Source/WebCore/page/DragController.cpp +++ b/Source/WebCore/page/DragController.cpp @@ -42,6 +42,7 @@ #include "EventHandler.h" #include "FloatRect.h" #include "Frame.h" +#include "FrameLoadRequest.h" #include "FrameLoader.h" #include "FrameSelection.h" #include "FrameView.h" @@ -237,7 +238,7 @@ bool DragController::performDrag(DragData* dragData) return false; m_client->willPerformDragDestinationAction(DragDestinationActionLoad, dragData); - m_page->mainFrame()->loader()->load(ResourceRequest(dragData->asURL(m_page->mainFrame())), false); + m_page->mainFrame()->loader()->load(FrameLoadRequest(m_page->mainFrame(), ResourceRequest(dragData->asURL(m_page->mainFrame())))); return true; } diff --git a/Source/WebCore/page/EventHandler.cpp b/Source/WebCore/page/EventHandler.cpp index 8705af623..da7d2238c 100644 --- a/Source/WebCore/page/EventHandler.cpp +++ b/Source/WebCore/page/EventHandler.cpp @@ -279,6 +279,18 @@ static inline bool scrollNode(float delta, ScrollGranularity granularity, Scroll return enclosingBox->scroll(delta < 0 ? negativeDirection : positiveDirection, granularity, absDelta, stopNode); } +static Node* closestScrollableNodeInDocumentIfPossible(Node* node) +{ + for (Node* scrollableNode = node; scrollableNode; scrollableNode = scrollableNode->parentNode()) { + if (scrollableNode->isDocumentNode()) + break; + RenderObject* renderer = scrollableNode->renderer(); + if (renderer && renderer->isBox() && toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()) + return scrollableNode; + } + return node; +} + #if ENABLE(GESTURE_EVENTS) static inline bool shouldGesturesTriggerActive() { @@ -348,6 +360,8 @@ EventHandler::EventHandler(Frame* frame) #endif , m_mouseMovedDurationRunningAverage(0) , m_baseEventType(PlatformEvent::NoType) + , m_didStartDrag(false) + , m_didLongPressInvokeContextMenu(false) { } @@ -401,6 +415,8 @@ void EventHandler::clear() #endif m_mouseMovedDurationRunningAverage = 0; m_baseEventType = PlatformEvent::NoType; + m_didStartDrag = false; + m_didLongPressInvokeContextMenu = false; } void EventHandler::nodeWillBeRemoved(Node* nodeToBeRemoved) @@ -711,7 +727,7 @@ static bool canAutoscroll(RenderObject* renderer) #if ENABLE(DRAG_SUPPORT) bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& event) { - if (handleDrag(event)) + if (handleDrag(event, ShouldCheckDragHysteresis)) return true; if (!m_mousePressed) @@ -1602,8 +1618,8 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent) m_mousePressNode = mev.targetNode(); - Frame* subframe = subframeForHitTestResult(mev); - if (subframe && passMousePressEventToSubframe(mev, subframe)) { + RefPtr<Frame> subframe = subframeForHitTestResult(mev); + if (subframe && passMousePressEventToSubframe(mev, subframe.get())) { // Start capturing future events for this frame. We only do this if we didn't clear // the m_mousePressed flag, which may happen if an AppKit widget entered a modal event loop. m_capturesDragging = subframe->eventHandler()->capturesDragging(); @@ -2429,7 +2445,7 @@ bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e) if (useLatchedWheelEventNode) { if (!m_latchedWheelEventNode) { - m_latchedWheelEventNode = result.innerNode(); + m_latchedWheelEventNode = closestScrollableNodeInDocumentIfPossible(result.innerNode()); m_widgetIsLatched = result.isOverWidget(); } @@ -2596,6 +2612,8 @@ bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent) return handleGestureTapDown(); case PlatformEvent::GestureLongPress: return handleGestureLongPress(gestureEvent); + case PlatformEvent::GestureLongTap: + return handleGestureLongTap(gestureEvent); case PlatformEvent::GestureTwoFingerTap: return handleGestureTwoFingerTap(gestureEvent); case PlatformEvent::GestureScrollEnd: @@ -2647,9 +2665,35 @@ bool EventHandler::handleGestureTap(const PlatformGestureEvent& gestureEvent) bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEvent) { +#if ENABLE(DRAG_SUPPORT) + if (m_frame->settings() && m_frame->settings()->touchDragDropEnabled()) { + IntPoint adjustedPoint = gestureEvent.position(); +#if ENABLE(TOUCH_ADJUSTMENT) + adjustGesturePosition(gestureEvent, adjustedPoint); +#endif + PlatformMouseEvent mouseDownEvent(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 0, false, false, false, false, WTF::currentTime()); + handleMousePressEvent(mouseDownEvent); + PlatformMouseEvent mouseDragEvent(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WTF::currentTime()); + HitTestRequest request(HitTestRequest::ReadOnly); + MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseDragEvent); + m_didStartDrag = false; + handleDrag(mev, DontCheckDragHysteresis); + if (m_didStartDrag) + return true; + } +#endif return handleGestureForTextSelectionOrContextMenu(gestureEvent); } +bool EventHandler::handleGestureLongTap(const PlatformGestureEvent& gestureEvent) +{ +#if ENABLE(CONTEXT_MENUS) && !OS(ANDROID) + if (!m_didLongPressInvokeContextMenu) + return sendContextMenuEventForGesture(gestureEvent); +#endif + return false; +} + bool EventHandler::handleGestureForTextSelectionOrContextMenu(const PlatformGestureEvent& gestureEvent) { #if OS(ANDROID) @@ -2663,6 +2707,7 @@ bool EventHandler::handleGestureForTextSelectionOrContextMenu(const PlatformGest } #endif #if ENABLE(CONTEXT_MENUS) + m_didLongPressInvokeContextMenu = (gestureEvent.type() == PlatformEvent::GestureLongPress); return sendContextMenuEventForGesture(gestureEvent); #else return false; @@ -2760,6 +2805,7 @@ bool EventHandler::adjustGesturePosition(const PlatformGestureEvent& gestureEven bestClickableNodeForTouchPoint(gestureEvent.position(), IntSize(gestureEvent.area().width() / 2, gestureEvent.area().height() / 2), adjustedPoint, targetNode); break; case PlatformEvent::GestureLongPress: + case PlatformEvent::GestureLongTap: case PlatformEvent::GestureTwoFingerTap: bestContextMenuNodeForTouchPoint(gestureEvent.position(), IntSize(gestureEvent.area().width() / 2, gestureEvent.area().height() / 2), adjustedPoint, targetNode); break; @@ -3330,7 +3376,7 @@ static bool ExactlyOneBitSet(DragSourceAction n) return n && !(n & (n - 1)); } -bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event) +bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDragHysteresis checkDragHysteresis) { if (event.event().button() != LeftButton || event.event().type() != PlatformEvent::MouseMoved) { // If we allowed the other side of the bridge to handle a drag @@ -3409,7 +3455,7 @@ bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event) view->setCursor(pointerCursor()); } - if (!dragHysteresisExceeded(event.event().position())) + if (checkDragHysteresis == ShouldCheckDragHysteresis && !dragHysteresisExceeded(event.event().position())) return true; // Once we're past the hysteresis point, we don't want to treat this gesture as a click @@ -3460,11 +3506,11 @@ bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event) if (m_mouseDownMayStartDrag) { Page* page = m_frame->page(); DragController* dragController = page ? page->dragController() : 0; - bool startedDrag = dragController && dragController->startDrag(m_frame, dragState(), srcOp, event.event(), m_mouseDownPos); + m_didStartDrag = dragController && dragController->startDrag(m_frame, dragState(), srcOp, event.event(), m_mouseDownPos); // In WebKit2 we could reenter this code and start another drag. // On OS X this causes problems with the ownership of the pasteboard // and the promised types. - if (startedDrag) { + if (m_didStartDrag) { m_mouseDownMayStartDrag = false; return true; } diff --git a/Source/WebCore/page/EventHandler.h b/Source/WebCore/page/EventHandler.h index fcbcd616b..c15898a02 100644 --- a/Source/WebCore/page/EventHandler.h +++ b/Source/WebCore/page/EventHandler.h @@ -91,6 +91,7 @@ extern const int GeneralDragHysteresis; enum HitTestScrollbars { ShouldHitTestScrollbars, DontHitTestScrollbars }; enum AppendTrailingWhitespace { ShouldAppendTrailingWhitespace, DontAppendTrailingWhitespace }; +enum CheckDragHysteresis { ShouldCheckDragHysteresis, DontCheckDragHysteresis }; class EventHandler { WTF_MAKE_NONCOPYABLE(EventHandler); @@ -170,6 +171,7 @@ public: bool handleGestureEvent(const PlatformGestureEvent&); bool handleGestureTap(const PlatformGestureEvent&); bool handleGestureLongPress(const PlatformGestureEvent&); + bool handleGestureLongTap(const PlatformGestureEvent&); bool handleGestureTwoFingerTap(const PlatformGestureEvent&); bool handleGestureScrollUpdate(const PlatformGestureEvent&); bool isScrollbarHandlingGestures() const; @@ -307,7 +309,7 @@ private: void freeClipboard(); - bool handleDrag(const MouseEventWithHitTestResults&); + bool handleDrag(const MouseEventWithHitTestResults&, CheckDragHysteresis); #endif bool handleMouseUp(const MouseEventWithHitTestResults&); #if ENABLE(DRAG_SUPPORT) @@ -468,6 +470,8 @@ private: double m_mouseMovedDurationRunningAverage; PlatformEvent::Type m_baseEventType; + bool m_didStartDrag; + bool m_didLongPressInvokeContextMenu; }; } // namespace WebCore diff --git a/Source/WebCore/page/Frame.cpp b/Source/WebCore/page/Frame.cpp index d16cf9480..ac794691d 100644 --- a/Source/WebCore/page/Frame.cpp +++ b/Source/WebCore/page/Frame.cpp @@ -657,8 +657,13 @@ void Frame::dispatchVisibilityStateChangeEvent() { if (m_doc) m_doc->dispatchVisibilityStateChangeEvent(); + + Vector<RefPtr<Frame> > childFrames; for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling()) - child->dispatchVisibilityStateChangeEvent(); + childFrames.append(child); + + for (size_t i = 0; i < childFrames.size(); ++i) + childFrames[i]->dispatchVisibilityStateChangeEvent(); } #endif diff --git a/Source/WebCore/page/FrameView.cpp b/Source/WebCore/page/FrameView.cpp index 93ce91bf0..dcdae213e 100644 --- a/Source/WebCore/page/FrameView.cpp +++ b/Source/WebCore/page/FrameView.cpp @@ -1822,7 +1822,7 @@ void FrameView::repaintFixedElementsAfterScrolling() if (!m_nestedLayoutCount && hasViewportConstrainedObjects()) { if (RenderView* root = rootRenderer(this)) { root->updateWidgetPositions(); - root->layer()->updateLayerPositionsAfterScroll(); + root->layer()->updateLayerPositionsAfterDocumentScroll(); } } } diff --git a/Source/WebCore/page/Settings.in b/Source/WebCore/page/Settings.in index 88d51c416..126630c33 100644 --- a/Source/WebCore/page/Settings.in +++ b/Source/WebCore/page/Settings.in @@ -164,3 +164,7 @@ frameFlatteningEnabled initial=false allowCustomScrollbarInMainFrame initial=true webSecurityEnabled initial=true spatialNavigationEnabled initial=false + +# This setting adds a means to enable/disable touch initiated drag & drop. If +# enabled, the user can initiate drag using long press. +touchDragDropEnabled initial=false diff --git a/Source/WebCore/page/TouchAdjustment.cpp b/Source/WebCore/page/TouchAdjustment.cpp index 3a956956e..1de02203c 100644 --- a/Source/WebCore/page/TouchAdjustment.cpp +++ b/Source/WebCore/page/TouchAdjustment.cpp @@ -75,9 +75,14 @@ bool nodeRespondsToTapGesture(Node* node) return true; if (node->willRespondToMouseClickEvents() || node->willRespondToMouseMoveEvents()) return true; - if (node->renderStyle()) { - // Accept nodes that has a CSS effect when touched. - if (node->renderStyle()->affectedByActiveRules() || node->renderStyle()->affectedByHoverRules()) + // Accept nodes that has a CSS effect when touched. + if (node->isElementNode()) { + Element* element = toElement(node); + if (element->childrenAffectedByActive() || element->childrenAffectedByHover()) + return true; + } + if (RenderStyle* renderStyle = node->renderStyle()) { + if (renderStyle->affectedByActive() || renderStyle->affectedByHover()) return true; } return false; diff --git a/Source/WebCore/page/mac/EventHandlerMac.mm b/Source/WebCore/page/mac/EventHandlerMac.mm index f8a0f17e2..45150e4f5 100644 --- a/Source/WebCore/page/mac/EventHandlerMac.mm +++ b/Source/WebCore/page/mac/EventHandlerMac.mm @@ -48,7 +48,6 @@ #include "Scrollbar.h" #include "Settings.h" #include "WebCoreSystemInterface.h" -#include <objc/objc-runtime.h> #include <wtf/MainThread.h> #include <wtf/ObjcRuntimeExtras.h> #include <wtf/StdLibExtras.h> diff --git a/Source/WebCore/platform/ActivePlatformGestureAnimation.cpp b/Source/WebCore/platform/ActivePlatformGestureAnimation.cpp deleted file mode 100644 index 5a9332686..000000000 --- a/Source/WebCore/platform/ActivePlatformGestureAnimation.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "ActivePlatformGestureAnimation.h" - -#include "PlatformGestureCurve.h" -#include "PlatformGestureCurveTarget.h" - -#if PLATFORM(CHROMIUM) -#include "TraceEvent.h" -#endif - -namespace WebCore { - -PassOwnPtr<ActivePlatformGestureAnimation> ActivePlatformGestureAnimation::create(PassOwnPtr<PlatformGestureCurve> curve, PlatformGestureCurveTarget* target) -{ - return adoptPtr(new ActivePlatformGestureAnimation(curve, target)); -} - -PassOwnPtr<ActivePlatformGestureAnimation> ActivePlatformGestureAnimation::create(PassOwnPtr<PlatformGestureCurve> curve, PlatformGestureCurveTarget* target, double startTime) -{ - return adoptPtr(new ActivePlatformGestureAnimation(curve, target, startTime)); -} - -ActivePlatformGestureAnimation::~ActivePlatformGestureAnimation() -{ -#if PLATFORM(CHROMIUM) - TRACE_EVENT_ASYNC_END0("input", "GestureAnimation", this); -#endif -} - -ActivePlatformGestureAnimation::ActivePlatformGestureAnimation(PassOwnPtr<PlatformGestureCurve> curve, PlatformGestureCurveTarget* target) - : m_startTime(0) - , m_waitingForFirstTick(true) - , m_curve(curve) - , m_target(target) -{ -#if PLATFORM(CHROMIUM) - TRACE_EVENT_ASYNC_BEGIN1("input", "GestureAnimation", this, "curve", m_curve->debugName()); -#endif -} - -ActivePlatformGestureAnimation::ActivePlatformGestureAnimation(PassOwnPtr<PlatformGestureCurve> curve, PlatformGestureCurveTarget* target, double startTime) - : m_startTime(startTime) - , m_waitingForFirstTick(false) - , m_curve(curve) - , m_target(target) -{ -#if PLATFORM(CHROMIUM) - TRACE_EVENT_ASYNC_BEGIN1("input", "GestureAnimation", this, "curve", m_curve->debugName()); -#endif -} - -bool ActivePlatformGestureAnimation::animate(double time) -{ - if (m_waitingForFirstTick) { - m_startTime = time; - m_waitingForFirstTick = false; - } - // All PlatformGestureCurves assume zero-based time, so we subtract - // the animation start time before passing to the curve. - return m_curve->apply(time - m_startTime, m_target); -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/ActivePlatformGestureAnimation.h b/Source/WebCore/platform/ActivePlatformGestureAnimation.h deleted file mode 100644 index 21f199c07..000000000 --- a/Source/WebCore/platform/ActivePlatformGestureAnimation.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ActivePlatformGestureAnimation_h -#define ActivePlatformGestureAnimation_h - -#include <wtf/Noncopyable.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class PlatformGestureCurve; -class PlatformGestureCurveTarget; - -// Implements a gesture animation (fling scroll, etc.) using a curve with a generic interface -// to define the animation parameters as a function of time, and applies the animation -// to a target, again via a generic interface. It is assumed that animate() is called -// on a more-or-less regular basis by the owner. -class ActivePlatformGestureAnimation { - WTF_MAKE_NONCOPYABLE(ActivePlatformGestureAnimation); -public: - static PassOwnPtr<ActivePlatformGestureAnimation> create(PassOwnPtr<PlatformGestureCurve>, PlatformGestureCurveTarget*); - static PassOwnPtr<ActivePlatformGestureAnimation> create(PassOwnPtr<PlatformGestureCurve>, PlatformGestureCurveTarget*, double startTime); - ~ActivePlatformGestureAnimation(); - - bool animate(double time); - -private: - // Assumes a valid PlatformGestureCurveTarget that outlives the animation. - ActivePlatformGestureAnimation(PassOwnPtr<PlatformGestureCurve>, PlatformGestureCurveTarget*); - ActivePlatformGestureAnimation(PassOwnPtr<PlatformGestureCurve>, PlatformGestureCurveTarget*, double startTime); - - double m_startTime; - bool m_waitingForFirstTick; - OwnPtr<PlatformGestureCurve> m_curve; - PlatformGestureCurveTarget* m_target; -}; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/LocalizedStrings.cpp b/Source/WebCore/platform/LocalizedStrings.cpp index 02772235f..bdacdb88d 100644 --- a/Source/WebCore/platform/LocalizedStrings.cpp +++ b/Source/WebCore/platform/LocalizedStrings.cpp @@ -992,4 +992,15 @@ String validationMessageStepMismatchText(const String&, const String&) return WEB_UI_STRING("step mismatch", "Validation message for input form controls with value not respecting the step attribute"); } +String validationMessageBadInputForNumberText() +{ + notImplemented(); + return validationMessageTypeMismatchText(); +} + +String clickToExitFullScreenText() +{ + return WEB_UI_STRING("Click to exit full screen mode", "Message to display in browser window when in webkit full screen mode."); +} + } // namespace WebCore diff --git a/Source/WebCore/platform/LocalizedStrings.h b/Source/WebCore/platform/LocalizedStrings.h index 6732748b1..bb219db14 100644 --- a/Source/WebCore/platform/LocalizedStrings.h +++ b/Source/WebCore/platform/LocalizedStrings.h @@ -252,10 +252,16 @@ namespace WebCore { String validationMessageRangeUnderflowText(const String& minimum); String validationMessageRangeOverflowText(const String& maximum); String validationMessageStepMismatchText(const String& base, const String& step); + String validationMessageBadInputForNumberText(); +#if ENABLE(INPUT_MULTIPLE_FIELDS_UI) + String validationMessageBadInputForDateTimeText(); +#endif #if USE(SOUP) String unacceptableTLSCertificate(); #endif + String clickToExitFullScreenText(); + #if !PLATFORM(CHROMIUM) #define WEB_UI_STRING(string, description) WebCore::localizedString(string) #define WEB_UI_STRING_KEY(string, key, description) WebCore::localizedString(key) diff --git a/Source/WebCore/platform/RunLoop.h b/Source/WebCore/platform/RunLoop.h index ce9845e2a..fbfb837f1 100644 --- a/Source/WebCore/platform/RunLoop.h +++ b/Source/WebCore/platform/RunLoop.h @@ -167,7 +167,10 @@ private: Vector<GRefPtr<GMainLoop> > m_runLoopMainLoops; #elif PLATFORM(EFL) bool m_initEfl; + + Mutex m_pipeLock; OwnPtr<Ecore_Pipe> m_pipe; + static void wakeUpEvent(void* data, void*, unsigned int); #endif }; diff --git a/Source/WebCore/platform/ScrollAnimatorNone.cpp b/Source/WebCore/platform/ScrollAnimatorNone.cpp index 60bac8464..128a52c24 100644 --- a/Source/WebCore/platform/ScrollAnimatorNone.cpp +++ b/Source/WebCore/platform/ScrollAnimatorNone.cpp @@ -590,12 +590,6 @@ void ScrollAnimatorNone::stopAnimationTimerIfNeeded() #endif } -void ScrollAnimatorNone::scrollBy(const IntPoint& location) -{ - m_currentPosX += location.x(); - m_currentPosY += location.y(); -} - } // namespace WebCore #endif // ENABLE(SMOOTH_SCROLLING) diff --git a/Source/WebCore/platform/ScrollAnimatorNone.h b/Source/WebCore/platform/ScrollAnimatorNone.h index 30fa1c7fa..b38da16a8 100644 --- a/Source/WebCore/platform/ScrollAnimatorNone.h +++ b/Source/WebCore/platform/ScrollAnimatorNone.h @@ -96,9 +96,6 @@ public: double m_maximumCoastTime; }; - // PlatformGestureCurveTarget implementation. - virtual void scrollBy(const IntPoint&); - protected: virtual void animationWillStart() { } virtual void animationDidFinish() { } diff --git a/Source/WebCore/platform/TouchFlingPlatformGestureCurve.cpp b/Source/WebCore/platform/TouchFlingPlatformGestureCurve.cpp deleted file mode 100644 index ed37cf1d9..000000000 --- a/Source/WebCore/platform/TouchFlingPlatformGestureCurve.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "TouchFlingPlatformGestureCurve.h" - -#include "PlatformGestureCurveTarget.h" -#include <math.h> - -namespace WebCore { - -using namespace std; - -// This curve implementation is based on the notion of a single, absolute curve, which starts at -// a large velocity and smoothly decreases to zero. For a given input velocity, we find where on -// the curve this velocity occurs, and start the animation at this point---denoted by (m_timeOffset, -// m_positionOffset). -// -// This has the effect of automatically determining an animation duration that scales with input -// velocity, as faster initial velocities start earlier on the curve and thus take longer to reach the end. -// No complicated time scaling is required. -// -// Since the starting velocity is implicitly determined by our starting point, we only store the -// relative magnitude and direction of both initial x- and y-velocities, and use this to scale the -// computed displacement at any point in time. This guarantees that fling trajectories are straight -// lines when viewed in x-y space. Initial velocities that lie outside the max velocity are constrained -// to start at zero (and thus are implicitly scaled). -// -// The curve is modelled as a 4th order polynomial, starting at t = 0, and ending at t = m_curveDuration. -// Attempts to generate position/velocity estimates outside this range are undefined. - -static const int cMaxSearchIterations = 20; - -PassOwnPtr<PlatformGestureCurve> TouchFlingPlatformGestureCurve::createForTouchPad(const FloatPoint& velocity, IntPoint cumulativeScroll) -{ - // The default parameters listed below are a matched set, and should not be changed independently of one another. - return create(velocity, -5.70762e+03, 1.72e+02, 3.7e+00, 1.3, cumulativeScroll); -} - -PassOwnPtr<PlatformGestureCurve> TouchFlingPlatformGestureCurve::createForTouchScreen(const FloatPoint& velocity, IntPoint cumulativeScroll) -{ - // The touchscreen-specific parameters listed below are a matched set, and should not be changed independently of one another. - return create(velocity, -5.70762e+03, 1.72e+02, 3.7e+00, 1.3, cumulativeScroll); -} - -PassOwnPtr<PlatformGestureCurve> TouchFlingPlatformGestureCurve::create(const FloatPoint& velocity, float p0, float p1, float p2, float curveDuration, IntPoint cumulativeScroll) -{ - return adoptPtr(new TouchFlingPlatformGestureCurve(velocity, p0, p1, p2, curveDuration, cumulativeScroll)); -} - -inline double position(double t, float* p) -{ - return p[0] * exp(-p[2] * t) - p[1] * t - p[0]; -} - -inline double velocity(double t, float* p) -{ - return -p[0] * p[2] * exp(-p[2] * t) - p[1]; -} - -TouchFlingPlatformGestureCurve::TouchFlingPlatformGestureCurve(const FloatPoint& initialVelocity, float p0, float p1, float p2, float curveDuration, const IntPoint& cumulativeScroll) - : m_cumulativeScroll(cumulativeScroll) - , m_curveDuration(curveDuration) -{ - ASSERT(initialVelocity != FloatPoint::zero()); - - m_coefficients[0] = p0; // alpha - m_coefficients[1] = p1; // beta - m_coefficients[2] = p2; // gamma - - float maxInitialVelocity = max(fabs(initialVelocity.x()), fabs(initialVelocity.y())); - - // Force maxInitialVelocity to lie in the range v(0) to v(curveDuration), and assume that - // the curve parameters define a monotonically decreasing velocity, or else bisection search may - // fail. - if (maxInitialVelocity > velocity(0, m_coefficients)) - maxInitialVelocity = velocity(0, m_coefficients); - - if (maxInitialVelocity < velocity(m_curveDuration, m_coefficients)) - maxInitialVelocity = velocity(m_curveDuration, m_coefficients); - - // We keep track of relative magnitudes and directions of the velocity/displacement components here. - m_displacementRatio = FloatPoint(initialVelocity.x() / maxInitialVelocity, initialVelocity.y() / maxInitialVelocity); - - // Use basic bisection to estimate where we should start on the curve. - // FIXME: Would Newton's method be better? - const double epsilon = 1; // It is probably good enough to get the start point to within 1 pixel/sec. - double t0 = 0; - double t1 = curveDuration; - int numIterations = 0; - while (t0 < t1 && numIterations < cMaxSearchIterations) { - numIterations++; - m_timeOffset = (t0 + t1) * 0.5; - double vOffset = velocity(m_timeOffset, m_coefficients); - if (fabs(maxInitialVelocity - vOffset) < epsilon) - break; - - if (vOffset > maxInitialVelocity) - t0 = m_timeOffset; - else - t1 = m_timeOffset; - } - - // Compute curve position at offset time - m_positionOffset = position(m_timeOffset, m_coefficients); -} - -TouchFlingPlatformGestureCurve::~TouchFlingPlatformGestureCurve() -{ -} - -const char* TouchFlingPlatformGestureCurve::debugName() const -{ - return "TouchpadFling"; -} - -bool TouchFlingPlatformGestureCurve::apply(double time, PlatformGestureCurveTarget* target) -{ - float displacement; - if (time < 0) - displacement = 0; - else if (time + m_timeOffset < m_curveDuration) - displacement = position(time + m_timeOffset, m_coefficients) - m_positionOffset; - else - displacement = position(m_curveDuration, m_coefficients) - m_positionOffset; - - // Keep track of integer portion of scroll thus far, and prepare increment. - IntPoint scroll(displacement * m_displacementRatio.x(), displacement * m_displacementRatio.y()); - IntPoint scrollIncrement(scroll - m_cumulativeScroll); - m_cumulativeScroll = scroll; - - if (time + m_timeOffset < m_curveDuration || scrollIncrement != IntPoint::zero()) { - target->scrollBy(scrollIncrement); - return true; - } - - return false; -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/TouchFlingPlatformGestureCurve.h b/Source/WebCore/platform/TouchFlingPlatformGestureCurve.h deleted file mode 100644 index f238a717d..000000000 --- a/Source/WebCore/platform/TouchFlingPlatformGestureCurve.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef TouchFlingPlatformGestureCurve_h -#define TouchFlingPlatformGestureCurve_h - -#include "FloatPoint.h" -#include "PlatformGestureCurve.h" -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class PlatformGestureCurveTarget; - -// Implementation of PlatformGestureCurve suitable for touch pad/screen-based -// fling scroll. Starts with a flat velocity profile based on 'velocity', which -// tails off to zero. Time is scaled to that duration of the fling is proportional -// the initial velocity. -class TouchFlingPlatformGestureCurve : public PlatformGestureCurve { -public: - static PassOwnPtr<PlatformGestureCurve> createForTouchPad(const FloatPoint& velocity, IntPoint cumulativeScroll = IntPoint()); - static PassOwnPtr<PlatformGestureCurve> createForTouchScreen(const FloatPoint& velocity, IntPoint cumulativeScroll = IntPoint()); - static PassOwnPtr<PlatformGestureCurve> create(const FloatPoint& velocity, float p0, float p1, float p2, float curveDuration, IntPoint cumulativeScroll = IntPoint()); - virtual ~TouchFlingPlatformGestureCurve(); - - virtual const char* debugName() const OVERRIDE; - virtual bool apply(double monotonicTime, PlatformGestureCurveTarget*) OVERRIDE; - -private: - TouchFlingPlatformGestureCurve(const FloatPoint& velocity, float p0, float p1, float p2, float curveDuration, const IntPoint& cumulativeScroll); - - FloatPoint m_displacementRatio; - IntPoint m_cumulativeScroll; - float m_coefficients[3]; - float m_timeOffset; - float m_curveDuration; - float m_positionOffset; -}; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/WheelFlingPlatformGestureCurve.cpp b/Source/WebCore/platform/WheelFlingPlatformGestureCurve.cpp deleted file mode 100644 index 73ffc381d..000000000 --- a/Source/WebCore/platform/WheelFlingPlatformGestureCurve.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "WheelFlingPlatformGestureCurve.h" - -#include "PlatformGestureCurveTarget.h" -#include <math.h> - -namespace WebCore { - -PassOwnPtr<PlatformGestureCurve> WheelFlingPlatformGestureCurve::create(const FloatPoint& velocity) -{ - return adoptPtr(new WheelFlingPlatformGestureCurve(velocity)); -} - -WheelFlingPlatformGestureCurve::WheelFlingPlatformGestureCurve(const FloatPoint& velocity) - : m_velocity(velocity) -{ - ASSERT(velocity != FloatPoint::zero()); -} - -WheelFlingPlatformGestureCurve::~WheelFlingPlatformGestureCurve() -{ -} - -const char* WheelFlingPlatformGestureCurve::debugName() const -{ - return "WheelFling"; -} - -bool WheelFlingPlatformGestureCurve::apply(double time, PlatformGestureCurveTarget* target) -{ - // Use a Rayleigh distribution for the curve. This simulates a velocity profile - // that starts at 0, increases to a maximum, then decreases again smoothly. By - // using the cumulative distribution function (CDF) instead of the point-mass function, - // we can isolate timing jitter by remembering the CDF value at the last tick. Since - // the CDF maxes out at 1, scale it by the input velocity. - // - // CDF -> F(x; sigma) = 1 - exp{-x^2/2\sigma^2} - // ref: http://en.wikipedia.org/wiki/Rayleigh_distribution - // FIXME: consider making the value of sigma settable in the constructor. - static double twoSigmaSquaredInverse = 16; // sigma = 0.25 - float cdf = 1 - exp(-time * time * twoSigmaSquaredInverse); - IntPoint scroll(cdf * m_velocity.x(), cdf * m_velocity.y()); - IntPoint scrollIncrement(scroll - m_cumulativeScroll); - m_cumulativeScroll = scroll; - - if (cdf < 0.5 || scrollIncrement != IntPoint::zero()) { - target->scrollBy(scrollIncrement); - return true; - } - - return false; -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/WheelFlingPlatformGestureCurve.h b/Source/WebCore/platform/WheelFlingPlatformGestureCurve.h deleted file mode 100644 index 96cfaca1a..000000000 --- a/Source/WebCore/platform/WheelFlingPlatformGestureCurve.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WheelFlingPlatformGestureCurve_h -#define WheelFlingPlatformGestureCurve_h - -#include "FloatPoint.h" -#include "PlatformGestureCurve.h" -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class PlatformGestureCurveTarget; - -// Implementation of PlatformGestureCurve suitable for mouse wheel-based fling -// scroll. A Rayleigh distribtution curve is used to define the velocity profile, -// so velocity starts at zero, accelerates to a maximum proportional to 'velocity', -// then gently tails off to zero again. -class WheelFlingPlatformGestureCurve : public PlatformGestureCurve { -public: - static PassOwnPtr<PlatformGestureCurve> create(const FloatPoint& velocity); - virtual ~WheelFlingPlatformGestureCurve(); - - virtual const char* debugName() const OVERRIDE; - virtual bool apply(double time, PlatformGestureCurveTarget*) OVERRIDE; - -private: - explicit WheelFlingPlatformGestureCurve(const FloatPoint& velocity); - - FloatPoint m_velocity; - IntPoint m_cumulativeScroll; -}; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/audio/AudioDestinationConsumer.h b/Source/WebCore/platform/audio/AudioDestinationConsumer.h new file mode 100644 index 000000000..ecba08ffc --- /dev/null +++ b/Source/WebCore/platform/audio/AudioDestinationConsumer.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name of Google Inc. nor the names of its contributors + * may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef AudioDestinationConsumer_h +#define AudioDestinationConsumer_h + +#include <wtf/RefCounted.h> + +namespace WebCore { + +class AudioBus; + +class AudioDestinationConsumer : public RefCounted<AudioDestinationConsumer> { +public: + virtual ~AudioDestinationConsumer() { } + + virtual void consumeAudio(AudioBus*, size_t numberOfFrames) = 0; +}; + +} // WebCore + +#endif // AudioDestinationConsumer_h diff --git a/Source/WebCore/platform/audio/gstreamer/WebKitWebAudioSourceGStreamer.cpp b/Source/WebCore/platform/audio/gstreamer/WebKitWebAudioSourceGStreamer.cpp index 20b02b0ed..583c13a00 100644 --- a/Source/WebCore/platform/audio/gstreamer/WebKitWebAudioSourceGStreamer.cpp +++ b/Source/WebCore/platform/audio/gstreamer/WebKitWebAudioSourceGStreamer.cpp @@ -26,6 +26,7 @@ #include "AudioIOCallback.h" #include <wtf/gobject/GOwnPtr.h> #include "GRefPtrGStreamer.h" +#include "GStreamerVersioning.h" #include <gst/audio/multichannel.h> #include <gst/pbutils/pbutils.h> @@ -178,8 +179,7 @@ static void webkit_web_audio_src_init(WebKitWebAudioSrc* src) src->priv = priv; new (priv) WebKitWebAudioSourcePrivate(); - GRefPtr<GstPadTemplate> padTemplate = adoptGRef(gst_static_pad_template_get(&srcTemplate)); - priv->sourcePad = gst_ghost_pad_new_no_target_from_template("src", padTemplate.get()); + priv->sourcePad = webkitGstGhostPadFromStaticTemplate(&srcTemplate, "src", 0); gst_element_add_pad(GST_ELEMENT(src), priv->sourcePad); priv->provider = 0; diff --git a/Source/WebCore/platform/blackberry/EventLoopBlackBerry.cpp b/Source/WebCore/platform/blackberry/EventLoopBlackBerry.cpp index 18528bcc7..aaebe6cef 100644 --- a/Source/WebCore/platform/blackberry/EventLoopBlackBerry.cpp +++ b/Source/WebCore/platform/blackberry/EventLoopBlackBerry.cpp @@ -28,6 +28,7 @@ void EventLoop::cycle() { ASSERT(BlackBerry::Platform::webKitThreadMessageClient()); BlackBerry::Platform::webKitThreadMessageClient()->processNextMessage(); + m_ended = !BlackBerry::Platform::webKitThreadMessageClient()->isRunning(); } } // namespace WebCore diff --git a/Source/WebCore/platform/blackberry/LocalizedStringsBlackBerry.cpp b/Source/WebCore/platform/blackberry/LocalizedStringsBlackBerry.cpp index 7bd71a5fe..14de8202c 100644 --- a/Source/WebCore/platform/blackberry/LocalizedStringsBlackBerry.cpp +++ b/Source/WebCore/platform/blackberry/LocalizedStringsBlackBerry.cpp @@ -524,6 +524,12 @@ String validationMessageValueMissingForSelectText() return validationMessageValueMissingText(); } +String validationMessageBadInputForNumberText() +{ + notImplemented(); + return validationMessageTypeMismatchText(); +} + String localizedMediaControlElementString(const String&) { notImplemented(); diff --git a/Source/WebCore/platform/chromium/PlatformSupport.h b/Source/WebCore/platform/chromium/PlatformSupport.h index d0a4db3c4..7686a3b2a 100644 --- a/Source/WebCore/platform/chromium/PlatformSupport.h +++ b/Source/WebCore/platform/chromium/PlatformSupport.h @@ -49,10 +49,6 @@ typedef struct NPObject NPObject; typedef struct _NPP NPP_t; typedef NPP_t* NPP; -#if OS(WINDOWS) -typedef struct HFONT__* HFONT; -#endif - namespace WebCore { class Color; @@ -77,17 +73,11 @@ struct FontRenderStyle; class PlatformSupport { public: - // Font --------------------------------------------------------------- -#if OS(WINDOWS) - static bool ensureFontLoaded(HFONT); -#endif - // IndexedDB ---------------------------------------------------------- static PassRefPtr<IDBFactoryBackendInterface> idbFactory(); // Plugin ------------------------------------------------------------- static bool plugins(bool refresh, Vector<PluginInfo>*); - static NPObject* pluginScriptableObject(Widget*); // Theming ------------------------------------------------------------ #if OS(WINDOWS) && !ENABLE(DEFAULT_RENDER_THEME) diff --git a/Source/WebCore/platform/chromium/support/PlatformGestureCurveFactory.cpp b/Source/WebCore/platform/chromium/support/PlatformGestureCurveFactory.cpp deleted file mode 100644 index 203f39ce9..000000000 --- a/Source/WebCore/platform/chromium/support/PlatformGestureCurveFactory.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "PlatformGestureCurveFactory.h" - -#include "FloatPoint.h" -#include "IntRect.h" -#include "TouchFlingPlatformGestureCurve.h" -#include "WebFlingAnimatorToGestureCurveAdapter.h" -#include "WebInputEvent.h" - -namespace WebKit { - -PlatformGestureCurveFactory* PlatformGestureCurveFactory::get() -{ - DEFINE_STATIC_LOCAL(PlatformGestureCurveFactory, factory, ()); - return &factory; -} - -PassOwnPtr<WebCore::PlatformGestureCurve> PlatformGestureCurveFactory::createCurve(int deviceSource, const WebCore::FloatPoint& point, WebCore::IntPoint cumulativeScroll) -{ - OwnPtr<WebFlingAnimator> flingAnimator = m_mockFlingAnimator.release(); - if (!flingAnimator) - flingAnimator = adoptPtr(Platform::current()->createFlingAnimator()); - - if (flingAnimator) - return WebFlingAnimatorToGestureCurveAdapter::create(point, WebCore::IntRect(), flingAnimator.release()); - - if (deviceSource == WebGestureEvent::Touchscreen) - return WebCore::TouchFlingPlatformGestureCurve::createForTouchScreen(point, cumulativeScroll); - - return WebCore::TouchFlingPlatformGestureCurve::createForTouchPad(point, cumulativeScroll); -} - -void PlatformGestureCurveFactory::setWebFlingAnimatorForTest(PassOwnPtr<WebFlingAnimator> mockFlingAnimator) -{ - m_mockFlingAnimator = mockFlingAnimator; -} - -} // namespace WebKit diff --git a/Source/WebCore/platform/chromium/support/PlatformGestureCurveFactory.h b/Source/WebCore/platform/chromium/support/PlatformGestureCurveFactory.h deleted file mode 100644 index 1ab3bf441..000000000 --- a/Source/WebCore/platform/chromium/support/PlatformGestureCurveFactory.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PlatformGestureCurveFactory_h -#define PlatformGestureCurveFactory_h - -#include "PlatformGestureCurve.h" -#include <public/WebFlingAnimator.h> -#include <wtf/PassOwnPtr.h> - -namespace WebKit { - -class PlatformGestureCurveFactory { -public: - static PlatformGestureCurveFactory* get(); - - PassOwnPtr<WebCore::PlatformGestureCurve> createCurve(int deviceSource, const WebCore::FloatPoint&, WebCore::IntPoint cumulativeScroll = WebCore::IntPoint()); - void setWebFlingAnimatorForTest(PassOwnPtr<WebFlingAnimator>); - -private: - ~PlatformGestureCurveFactory(); - - OwnPtr<WebFlingAnimator> m_mockFlingAnimator; -}; - -} // namespace WebKit - -#endif // PlatformGestureCurveFactory_h diff --git a/Source/WebCore/platform/chromium/support/WebFlingAnimatorToGestureCurveAdapter.h b/Source/WebCore/platform/chromium/support/WebFlingAnimatorToGestureCurveAdapter.h deleted file mode 100644 index 56f83bd2a..000000000 --- a/Source/WebCore/platform/chromium/support/WebFlingAnimatorToGestureCurveAdapter.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebFlingAnimatorToGestureCurveAdapter_h -#define WebFlingAnimatorToGestureCurveAdapter_h - -#include "FloatPoint.h" -#include "IntPoint.h" -#include "IntRect.h" -#include "PlatformGestureCurve.h" -#include "PlatformGestureCurveTarget.h" -#include <public/Platform.h> -#include <public/WebFlingAnimator.h> - -namespace WebKit { - -class WebFlingAnimatorToGestureCurveAdapter : public WebCore::PlatformGestureCurve { -public: - static PassOwnPtr<PlatformGestureCurve> create(const WebCore::FloatPoint& velocity, const WebCore::IntRect& range, PassOwnPtr<WebFlingAnimator> animator) - { - return adoptPtr(new WebFlingAnimatorToGestureCurveAdapter(velocity, range, animator)); - } - - // WebCore::PlatformGestureCurve implementation: - virtual const char* debugName() const OVERRIDE { return "WebFlingAnimatorToGestureCurveAdapter"; } - virtual bool apply(double time, WebCore::PlatformGestureCurveTarget* target) OVERRIDE - { - if (!m_animator->updatePosition()) - return false; - - WebCore::IntPoint currentPosition = m_animator->getCurrentPosition(); - target->scrollBy(WebCore::IntPoint(currentPosition - m_lastPosition)); - m_lastPosition = currentPosition; - return true; - } - -private: - WebFlingAnimatorToGestureCurveAdapter(const WebCore::FloatPoint& velocity, const WebCore::IntRect& range, PassOwnPtr<WebFlingAnimator> animator) - : m_animator(animator) - { - m_animator->startFling(velocity, range); - } - - OwnPtr<WebFlingAnimator> m_animator; - WebCore::IntPoint m_lastPosition; -}; - -} - -#endif // WebFlingAnimatorToGestureCurveAdapter_h diff --git a/Source/WebCore/platform/chromium/support/WebMediaStreamSource.cpp b/Source/WebCore/platform/chromium/support/WebMediaStreamSource.cpp index a51693610..05ce7d068 100644 --- a/Source/WebCore/platform/chromium/support/WebMediaStreamSource.cpp +++ b/Source/WebCore/platform/chromium/support/WebMediaStreamSource.cpp @@ -34,8 +34,11 @@ #include <public/WebMediaStreamSource.h> +#include "AudioBus.h" #include "MediaStreamSource.h" +#include <public/WebAudioDestinationConsumer.h> #include <public/WebString.h> +#include <wtf/MainThread.h> #include <wtf/PassOwnPtr.h> #include <wtf/Vector.h> @@ -121,6 +124,7 @@ private: WebMediaStreamSource::ExtraData* WebMediaStreamSource::extraData() const { + ASSERT(!m_private.isNull()); RefPtr<MediaStreamSource::ExtraData> data = m_private->extraData(); if (!data) return 0; @@ -129,9 +133,72 @@ WebMediaStreamSource::ExtraData* WebMediaStreamSource::extraData() const void WebMediaStreamSource::setExtraData(ExtraData* extraData) { + ASSERT(!m_private.isNull()); m_private->setExtraData(adoptRef(new ExtraDataContainer(extraData))); } +bool WebMediaStreamSource::requiresAudioConsumer() const +{ + ASSERT(!m_private.isNull()); + return m_private->requiresAudioConsumer(); +} + +class ConsumerWrapper : public WebCore::AudioDestinationConsumer { +public: + static PassRefPtr<ConsumerWrapper> create(WebAudioDestinationConsumer* consumer) + { + return adoptRef(new ConsumerWrapper(consumer)); + } + + virtual void consumeAudio(AudioBus*, size_t numberOfFrames) OVERRIDE; + + WebAudioDestinationConsumer* consumer() { return m_consumer; } + +private: + explicit ConsumerWrapper(WebAudioDestinationConsumer* consumer) : m_consumer(consumer) { } + + // m_consumer is not owned by this class. + WebAudioDestinationConsumer* m_consumer; +}; + +void ConsumerWrapper::consumeAudio(AudioBus* bus, size_t numberOfFrames) +{ + if (!bus) + return; + + // Wrap AudioBus. + size_t numberOfChannels = bus->numberOfChannels(); + WebKit::WebVector<const float*> busVector(numberOfChannels); + for (size_t i = 0; i < numberOfChannels; ++i) + busVector[i] = bus->channel(i)->data(); + + m_consumer->consumeAudio(busVector, numberOfFrames); +} + +void WebMediaStreamSource::addAudioConsumer(WebAudioDestinationConsumer* consumer) +{ + ASSERT(isMainThread()); + ASSERT(!m_private.isNull() && consumer); + + m_private->addAudioConsumer(ConsumerWrapper::create(consumer)); +} + +bool WebMediaStreamSource::removeAudioConsumer(WebAudioDestinationConsumer* consumer) +{ + ASSERT(isMainThread()); + ASSERT(!m_private.isNull() && consumer); + + const Vector<RefPtr<AudioDestinationConsumer> >& consumers = m_private->audioConsumers(); + for (Vector<RefPtr<AudioDestinationConsumer> >::const_iterator it = consumers.begin(); it != consumers.end(); ++it) { + ConsumerWrapper* wrapper = static_cast<ConsumerWrapper*>((*it).get()); + if (wrapper->consumer() == consumer) { + m_private->removeAudioConsumer(wrapper); + return true; + } + } + return false; +} + } // namespace WebKit #endif // ENABLE(MEDIA_STREAM) diff --git a/Source/WebCore/platform/efl/LocalizedStringsEfl.cpp b/Source/WebCore/platform/efl/LocalizedStringsEfl.cpp index 5fdd3b283..87b956c37 100644 --- a/Source/WebCore/platform/efl/LocalizedStringsEfl.cpp +++ b/Source/WebCore/platform/efl/LocalizedStringsEfl.cpp @@ -535,6 +535,12 @@ String validationMessageValueMissingForSelectText() return validationMessageValueMissingText(); } +String validationMessageBadInputForNumberText() +{ + notImplemented(); + return validationMessageTypeMismatchText(); +} + String missingPluginText() { return String::fromUTF8("missing plugin"); diff --git a/Source/WebCore/platform/efl/RenderThemeEfl.cpp b/Source/WebCore/platform/efl/RenderThemeEfl.cpp index 67d848312..936f983c6 100644 --- a/Source/WebCore/platform/efl/RenderThemeEfl.cpp +++ b/Source/WebCore/platform/efl/RenderThemeEfl.cpp @@ -406,14 +406,14 @@ static void applyColorCallback(void* data, Evas_Object*, const char* /* signal * that->platformColorsDidChange(); // Triggers relayout. } -static void fillColorsFromEdjeClass(Evas_Object* o, const char* colorClass, Color* color1, Color* color2 = 0, Color* color3 = 0) +static bool fillColorsFromEdjeClass(Evas_Object* o, const char* colorClass, Color* color1, Color* color2 = 0, Color* color3 = 0) { int r1, g1, b1, a1; int r2, g2, b2, a2; int r3, g3, b3, a3; - bool ok = edje_object_color_class_get(o, colorClass, &r1, &g1, &b1, &a1, &r2, &g2, &b2, &a2, &r3, &g3, &b3, &a3); - _ASSERT_ON_RELEASE_RETURN(ok, "Could not get color class '%s'\n", colorClass); + if (!edje_object_color_class_get(o, colorClass, &r1, &g1, &b1, &a1, &r2, &g2, &b2, &a2, &r3, &g3, &b3, &a3)) + return false; if (color1) color1->setRGB(makeRGBA(r1, g1, b1, a1)); @@ -421,18 +421,22 @@ static void fillColorsFromEdjeClass(Evas_Object* o, const char* colorClass, Colo color2->setRGB(makeRGBA(r2, g2, b2, a2)); if (color3) color3->setRGB(makeRGBA(r3, g3, b3, a3)); + + return true; } void RenderThemeEfl::setColorFromThemeClass(const char* colorClass) { ASSERT(edje()); - if (!strcmp("webkit/selection/active", colorClass)) - fillColorsFromEdjeClass(edje(), colorClass, &m_activeSelectionForegroundColor, &m_activeSelectionBackgroundColor); - else if (!strcmp("webkit/selection/inactive", colorClass)) - fillColorsFromEdjeClass(edje(), colorClass, &m_inactiveSelectionForegroundColor, &m_inactiveSelectionBackgroundColor); + if (!strcmp("webkit/selection/foreground", colorClass)) + m_supportsSelectionForegroundColor = fillColorsFromEdjeClass(edje(), colorClass, &m_activeSelectionForegroundColor, &m_inactiveSelectionForegroundColor); + else if (!strcmp("webkit/selection/background", colorClass)) + fillColorsFromEdjeClass(edje(), colorClass, &m_activeSelectionBackgroundColor, &m_inactiveSelectionBackgroundColor); else if (!strcmp("webkit/focus_ring", colorClass)) { - fillColorsFromEdjeClass(edje(), colorClass, &m_focusRingColor); + if (!fillColorsFromEdjeClass(edje(), colorClass, &m_focusRingColor)) + return; + // platformFocusRingColor() is only used for the default theme (without page) // The following is ugly, but no other way to do it unless we change it to use page themes as much as possible. RenderTheme::setCustomFocusRingColor(m_focusRingColor); @@ -493,14 +497,14 @@ bool RenderThemeEfl::loadTheme() // Set new loaded theme, and apply it. m_edje = o; - edje_object_signal_callback_add(edje(), "color_class,set", "webkit/selection/active", applyColorCallback, this); - edje_object_signal_callback_add(edje(), "color_class,set", "webkit/selection/inactive", applyColorCallback, this); + edje_object_signal_callback_add(edje(), "color_class,set", "webkit/selection/foreground", applyColorCallback, this); + edje_object_signal_callback_add(edje(), "color_class,set", "webkit/selection/background", applyColorCallback, this); edje_object_signal_callback_add(edje(), "color_class,set", "webkit/focus_ring", applyColorCallback, this); applyPartDescriptionsFrom(m_themePath); - setColorFromThemeClass("webkit/selection/active"); - setColorFromThemeClass("webkit/selection/inactive"); + setColorFromThemeClass("webkit/selection/foreground"); + setColorFromThemeClass("webkit/selection/background"); setColorFromThemeClass("webkit/focus_ring"); platformColorsDidChange(); // Schedules a relayout, do last. @@ -598,6 +602,7 @@ RenderThemeEfl::RenderThemeEfl(Page* page) , m_mediaPanelColor(220, 220, 195) // light tannish color. , m_mediaSliderColor(Color::white) #endif + , m_supportsSelectionForegroundColor(false) , m_partCache(0) { } @@ -678,6 +683,12 @@ Color RenderThemeEfl::platformFocusRingColor() const return m_focusRingColor; } +bool RenderThemeEfl::supportsSelectionForegroundColors() const +{ + loadThemeIfNeeded(); + return m_supportsSelectionForegroundColor; +} + bool RenderThemeEfl::paintSliderTrack(RenderObject* object, const PaintInfo& info, const IntRect& rect) { if (object->style()->appearance() == SliderHorizontalPart) diff --git a/Source/WebCore/platform/efl/RenderThemeEfl.h b/Source/WebCore/platform/efl/RenderThemeEfl.h index 34999f190..622213c5e 100644 --- a/Source/WebCore/platform/efl/RenderThemeEfl.h +++ b/Source/WebCore/platform/efl/RenderThemeEfl.h @@ -96,6 +96,9 @@ public: // A general method asking if any control tinting is supported at all. virtual bool supportsControlTints() const { return true; } + // A general method asking if foreground colors of selection are supported. + virtual bool supportsSelectionForegroundColors() const; + // A method to obtain the baseline position for a "leaf" control. This will only be used if a baseline // position cannot be determined by examining child content. Checkboxes and radio buttons are examples of // controls that need to do this. @@ -255,6 +258,8 @@ private: OwnPtr<Ecore_Evas> m_canvas; RefPtr<Evas_Object> m_edje; + bool m_supportsSelectionForegroundColor; + struct ThemePartDesc { FormType type; LengthSize min; diff --git a/Source/WebCore/platform/efl/RunLoopEfl.cpp b/Source/WebCore/platform/efl/RunLoopEfl.cpp index f299d8ecf..88685e0e9 100644 --- a/Source/WebCore/platform/efl/RunLoopEfl.cpp +++ b/Source/WebCore/platform/efl/RunLoopEfl.cpp @@ -102,6 +102,7 @@ void RunLoop::wakeUpEvent(void* data, void*, unsigned int) void RunLoop::wakeUp() { + MutexLocker locker(m_pipeLock); ecore_pipe_write(m_pipe.get(), wakupEcorePipeMessage, ecorePipeMessageSize); } diff --git a/Source/WebCore/platform/graphics/BitmapImage.h b/Source/WebCore/platform/graphics/BitmapImage.h index 7043d9be8..a9f649a60 100644 --- a/Source/WebCore/platform/graphics/BitmapImage.h +++ b/Source/WebCore/platform/graphics/BitmapImage.h @@ -218,7 +218,7 @@ protected: #endif size_t currentFrame() const { return m_currentFrame; } - size_t frameCount(); + virtual size_t frameCount(); NativeImagePtr frameAtIndex(size_t); bool frameIsCompleteAtIndex(size_t); float frameDurationAtIndex(size_t); diff --git a/Source/WebCore/platform/graphics/Font.cpp b/Source/WebCore/platform/graphics/Font.cpp index 0f32e4902..f55725e67 100644 --- a/Source/WebCore/platform/graphics/Font.cpp +++ b/Source/WebCore/platform/graphics/Font.cpp @@ -156,10 +156,12 @@ void Font::update(PassRefPtr<FontSelector> fontSelector) const m_typesettingFeatures = computeTypesettingFeatures(); } -void Font::drawText(GraphicsContext* context, const TextRun& run, const FloatPoint& point, int from, int to) const +void Font::drawText(GraphicsContext* context, const TextRun& run, const FloatPoint& point, int from, int to, CustomFontNotReadyAction customFontNotReadyAction) const { - // Don't draw anything while we are using custom fonts that are in the process of loading. - if (loadingCustomFonts()) + // Don't draw anything while we are using custom fonts that are in the process of loading, + // except if the 'force' argument is set to true (in which case it will use a fallback + // font). + if (loadingCustomFonts() && customFontNotReadyAction == DoNotPaintIfFontNotReady) return; to = (to == -1 ? run.length() : to); diff --git a/Source/WebCore/platform/graphics/Font.h b/Source/WebCore/platform/graphics/Font.h index b60d9dd3d..e36f9947c 100644 --- a/Source/WebCore/platform/graphics/Font.h +++ b/Source/WebCore/platform/graphics/Font.h @@ -42,6 +42,12 @@ class QTextLayout; QT_END_NAMESPACE #endif +// "X11/X.h" defines Complex to 0 and conflicts +// with Complex value in CodePath enum. +#ifdef Complex +#undef Complex +#endif + namespace WebCore { class FloatPoint; @@ -97,7 +103,8 @@ public: void update(PassRefPtr<FontSelector>) const; - void drawText(GraphicsContext*, const TextRun&, const FloatPoint&, int from = 0, int to = -1) const; + enum CustomFontNotReadyAction { DoNotPaintIfFontNotReady, UseFallbackIfFontNotReady }; + void drawText(GraphicsContext*, const TextRun&, const FloatPoint&, int from = 0, int to = -1, CustomFontNotReadyAction = DoNotPaintIfFontNotReady) const; void drawEmphasisMarks(GraphicsContext*, const TextRun&, const AtomicString& mark, const FloatPoint&, int from = 0, int to = -1) const; float width(const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const; diff --git a/Source/WebCore/platform/graphics/GraphicsContext.cpp b/Source/WebCore/platform/graphics/GraphicsContext.cpp index 55f31f415..c21173ae2 100644 --- a/Source/WebCore/platform/graphics/GraphicsContext.cpp +++ b/Source/WebCore/platform/graphics/GraphicsContext.cpp @@ -28,7 +28,6 @@ #include "BidiResolver.h" #include "BitmapImage.h" -#include "Font.h" #include "Generator.h" #include "ImageBuffer.h" #include "IntRect.h" @@ -404,7 +403,7 @@ void GraphicsContext::drawEmphasisMarks(const Font& font, const TextRun& run, co font.drawEmphasisMarks(this, run, mark, point, from, to); } -void GraphicsContext::drawBidiText(const Font& font, const TextRun& run, const FloatPoint& point) +void GraphicsContext::drawBidiText(const Font& font, const TextRun& run, const FloatPoint& point, Font::CustomFontNotReadyAction customFontNotReadyAction) { if (paintingDisabled()) return; @@ -428,7 +427,7 @@ void GraphicsContext::drawBidiText(const Font& font, const TextRun& run, const F subrun.setDirection(isRTL ? RTL : LTR); subrun.setDirectionalOverride(bidiRun->dirOverride(false)); - font.drawText(this, subrun, currPoint); + font.drawText(this, subrun, currPoint, 0, -1, customFontNotReadyAction); bidiRun = bidiRun->next(); // FIXME: Have Font::drawText return the width of what it drew so that we don't have to re-measure here. diff --git a/Source/WebCore/platform/graphics/GraphicsContext.h b/Source/WebCore/platform/graphics/GraphicsContext.h index 85cff9961..71b3a0bbd 100644 --- a/Source/WebCore/platform/graphics/GraphicsContext.h +++ b/Source/WebCore/platform/graphics/GraphicsContext.h @@ -30,6 +30,7 @@ #include "ColorSpace.h" #include "DashArray.h" #include "FloatRect.h" +#include "Font.h" #include "Gradient.h" #include "Image.h" #include "ImageOrientation.h" @@ -114,7 +115,6 @@ namespace WebCore { class AffineTransform; class DrawingBuffer; - class Font; class Generator; #if !USE(SKIA) class GraphicsContextPlatformPrivate; @@ -355,7 +355,7 @@ namespace WebCore { void drawText(const Font&, const TextRun&, const FloatPoint&, int from = 0, int to = -1); void drawEmphasisMarks(const Font&, const TextRun& , const AtomicString& mark, const FloatPoint&, int from = 0, int to = -1); - void drawBidiText(const Font&, const TextRun&, const FloatPoint&); + void drawBidiText(const Font&, const TextRun&, const FloatPoint&, Font::CustomFontNotReadyAction = Font::DoNotPaintIfFontNotReady); void drawHighlightForText(const Font&, const TextRun&, const FloatPoint&, int h, const Color& backgroundColor, ColorSpace, int from = 0, int to = -1); enum RoundingMode { diff --git a/Source/WebCore/platform/graphics/Icon.h b/Source/WebCore/platform/graphics/Icon.h index b703c7141..781a08cb2 100644 --- a/Source/WebCore/platform/graphics/Icon.h +++ b/Source/WebCore/platform/graphics/Icon.h @@ -32,7 +32,7 @@ OBJC_CLASS NSImage; #elif PLATFORM(WIN) typedef struct HICON__* HICON; #elif PLATFORM(QT) -#include <QImage> +#include <QIcon> #elif PLATFORM(GTK) typedef struct _GdkPixbuf GdkPixbuf; #elif PLATFORM(EFL) @@ -70,7 +70,7 @@ private: HICON m_hIcon; #elif PLATFORM(QT) Icon(); - QImage m_image; + QIcon m_icon; #elif PLATFORM(GTK) Icon(); GdkPixbuf* m_icon; diff --git a/Source/WebCore/platform/graphics/WidthIterator.cpp b/Source/WebCore/platform/graphics/WidthIterator.cpp index 15ca61773..96600c732 100644 --- a/Source/WebCore/platform/graphics/WidthIterator.cpp +++ b/Source/WebCore/platform/graphics/WidthIterator.cpp @@ -241,7 +241,7 @@ inline unsigned WidthIterator::advanceInternal(TextIterator& textIterator, Glyph // Account for word spacing. // We apply additional space between "words" by adding width to the space character. - if (treatAsSpace && (character != '\t' || !m_run.allowTabs()) && textIterator.currentCharacter() && m_font->wordSpacing()) + if (treatAsSpace && (character != '\t' || !m_run.allowTabs()) && (textIterator.currentCharacter() || character == noBreakSpace) && m_font->wordSpacing()) width += m_font->wordSpacing(); } else m_isAfterExpansion = false; diff --git a/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm b/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm index 96443f45c..80a3c6959 100644 --- a/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm +++ b/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm @@ -43,7 +43,7 @@ #import "UUID.h" #import "WebCoreAVFResourceLoader.h" #import "WebCoreSystemInterface.h" -#import <objc/objc-runtime.h> +#import <objc/runtime.h> #import <wtf/UnusedParam.h> #import <wtf/Uint8Array.h> #import <wtf/Uint16Array.h> diff --git a/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm b/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm index 3aa47e73a..5b9b883c2 100644 --- a/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm +++ b/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm @@ -38,7 +38,7 @@ #import "SoftLinking.h" #import "UTIUtilities.h" #import <AVFoundation/AVAssetResourceLoader.h> -#import <objc/objc-runtime.h> +#import <objc/runtime.h> #import <wtf/text/CString.h> namespace WebCore { diff --git a/Source/WebCore/platform/graphics/ca/PlatformCALayer.h b/Source/WebCore/platform/graphics/ca/PlatformCALayer.h index 6b0591032..f63705176 100644 --- a/Source/WebCore/platform/graphics/ca/PlatformCALayer.h +++ b/Source/WebCore/platform/graphics/ca/PlatformCALayer.h @@ -80,7 +80,11 @@ public: PlatformLayer* platformLayer() const; +#if PLATFORM(WIN) + bool usesTileCacheLayer() const { return false; } +#else bool usesTileCacheLayer() const { return m_layerType == LayerTypePageTileCacheLayer || m_layerType == LayerTypeTileCacheLayer; } +#endif PlatformCALayer* rootLayer() const; diff --git a/Source/WebCore/platform/graphics/ca/mac/PlatformCALayerMac.mm b/Source/WebCore/platform/graphics/ca/mac/PlatformCALayerMac.mm index 408766404..0f4eceb79 100644 --- a/Source/WebCore/platform/graphics/ca/mac/PlatformCALayerMac.mm +++ b/Source/WebCore/platform/graphics/ca/mac/PlatformCALayerMac.mm @@ -40,7 +40,7 @@ #import "WebTiledLayer.h" #import "WebTileCacheLayer.h" #import <objc/objc-auto.h> -#import <objc/objc-runtime.h> +#import <objc/runtime.h> #import <QuartzCore/QuartzCore.h> #import <wtf/CurrentTime.h> #import <wtf/MathExtras.h> diff --git a/Source/WebCore/platform/graphics/cairo/GraphicsContextCairo.cpp b/Source/WebCore/platform/graphics/cairo/GraphicsContextCairo.cpp index e5adf4110..b87af4ac6 100644 --- a/Source/WebCore/platform/graphics/cairo/GraphicsContextCairo.cpp +++ b/Source/WebCore/platform/graphics/cairo/GraphicsContextCairo.cpp @@ -70,7 +70,7 @@ namespace WebCore { // A helper which quickly fills a rectangle with a simple color fill. static inline void fillRectWithColor(cairo_t* cr, const FloatRect& rect, const Color& color) { - if (!color.alpha()) + if (!color.alpha() && cairo_get_operator(cr) == CAIRO_OPERATOR_OVER) return; setSourceRGBAFromColor(cr, color); cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height()); diff --git a/Source/WebCore/platform/graphics/chromium/DeferredImageDecoder.cpp b/Source/WebCore/platform/graphics/chromium/DeferredImageDecoder.cpp index 14de694e8..ff8bf308b 100644 --- a/Source/WebCore/platform/graphics/chromium/DeferredImageDecoder.cpp +++ b/Source/WebCore/platform/graphics/chromium/DeferredImageDecoder.cpp @@ -40,6 +40,8 @@ const char labelLazyDecoded[] = "lazy"; } // namespace +bool DeferredImageDecoder::s_enabled = false; + DeferredImageDecoder::DeferredImageDecoder(ImageDecoder* actualDecoder) : m_allDataReceived(false) , m_actualDecoder(adoptPtr(actualDecoder)) @@ -49,8 +51,6 @@ DeferredImageDecoder::DeferredImageDecoder(ImageDecoder* actualDecoder) DeferredImageDecoder::~DeferredImageDecoder() { - // FIXME: Remove the corresponding entry in ImageDecodingStore if image - // is defer-decoded. } DeferredImageDecoder* DeferredImageDecoder::create(const SharedBuffer& data, ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorOption) @@ -80,6 +80,10 @@ SkBitmap DeferredImageDecoder::createResizedLazyDecodingBitmap(const SkBitmap& b SkBitmap resizedBitmap; resizedBitmap.setConfig(SkBitmap::kARGB_8888_Config, scaledSubset.width(), scaledSubset.height(), rowBytes); + + // FIXME: This code has the potential problem that multiple + // LazyDecodingPixelRefs are created even though they share the same + // scaled size and ImageFrameGenerator. resizedBitmap.setPixelRef(new LazyDecodingPixelRef(pixelRef->frameGenerator(), scaledSize, scaledSubset))->unref(); // See comments in createLazyDecodingBitmap(). @@ -87,6 +91,11 @@ SkBitmap DeferredImageDecoder::createResizedLazyDecodingBitmap(const SkBitmap& b return resizedBitmap; } +void DeferredImageDecoder::setEnabled(bool enabled) +{ + s_enabled = enabled; +} + String DeferredImageDecoder::filenameExtension() const { return m_actualDecoder ? m_actualDecoder->filenameExtension() : m_filenameExtension; @@ -98,7 +107,7 @@ ImageFrame* DeferredImageDecoder::frameBufferAtIndex(size_t index) // because a multiframe is usually animated GIF. Animation is handled by // BitmapImage which uses some metadata functions that do synchronous image // decoding. - if (ImageDecodingStore::instanceOnMainThread() + if (s_enabled && m_actualDecoder && m_actualDecoder->repetitionCount() == cAnimationNone && m_actualDecoder->isSizeAvailable()) { @@ -200,7 +209,7 @@ SkBitmap DeferredImageDecoder::createLazyDecodingBitmap() SkBitmap bitmap; bitmap.setConfig(SkBitmap::kARGB_8888_Config, fullSize.width(), fullSize.height()); - m_frameGenerator = ImageFrameGenerator::create(m_data.release(), m_allDataReceived); + m_frameGenerator = ImageFrameGenerator::create(fullSize, m_data.release(), m_allDataReceived); m_actualDecoder.clear(); bitmap.setPixelRef(new LazyDecodingPixelRef(m_frameGenerator, fullSize, fullRect))->unref(); diff --git a/Source/WebCore/platform/graphics/chromium/DeferredImageDecoder.h b/Source/WebCore/platform/graphics/chromium/DeferredImageDecoder.h index b795049f0..5df92354b 100644 --- a/Source/WebCore/platform/graphics/chromium/DeferredImageDecoder.h +++ b/Source/WebCore/platform/graphics/chromium/DeferredImageDecoder.h @@ -47,6 +47,8 @@ public: static SkBitmap createResizedLazyDecodingBitmap(const SkBitmap&, const SkISize& scaledSize, const SkIRect& scaledSubset); + static void setEnabled(bool); + String filenameExtension() const; ImageFrame* frameBufferAtIndex(size_t index); @@ -79,6 +81,8 @@ private: ImageFrame m_lazyDecodedFrame; RefPtr<ImageFrameGenerator> m_frameGenerator; + + static bool s_enabled; }; } // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/FontCacheChromiumWin.cpp b/Source/WebCore/platform/graphics/chromium/FontCacheChromiumWin.cpp index 18e304388..d41fd14a8 100644 --- a/Source/WebCore/platform/graphics/chromium/FontCacheChromiumWin.cpp +++ b/Source/WebCore/platform/graphics/chromium/FontCacheChromiumWin.cpp @@ -33,10 +33,10 @@ #include "FontCache.h" #include "Font.h" +#include "FontPlatformDataChromiumWin.h" #include "FontUtilsChromiumWin.h" #include "HWndDC.h" #include "LayoutTestSupport.h" -#include "PlatformSupport.h" #include "SimpleFontData.h" #include <unicode/uniset.h> #include <wtf/HashMap.h> @@ -283,7 +283,7 @@ static bool fontContainsCharacter(const FontPlatformData* fontData, HWndDC hdc(0); HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(hdc, hfont)); int count = GetFontUnicodeRanges(hdc, 0); - if (!count && PlatformSupport::ensureFontLoaded(hfont)) + if (!count && FontPlatformData::ensureFontLoaded(hfont)) count = GetFontUnicodeRanges(hdc, 0); if (!count) { LOG_ERROR("Unable to get the font unicode range after second attempt"); diff --git a/Source/WebCore/platform/graphics/chromium/FontChromiumWin.cpp b/Source/WebCore/platform/graphics/chromium/FontChromiumWin.cpp index 2efc2a4df..c5903eadf 100644 --- a/Source/WebCore/platform/graphics/chromium/FontChromiumWin.cpp +++ b/Source/WebCore/platform/graphics/chromium/FontChromiumWin.cpp @@ -33,9 +33,9 @@ #include "Font.h" #include "FontFallbackList.h" +#include "FontPlatformDataChromiumWin.h" #include "GlyphBuffer.h" #include "NotImplemented.h" -#include "PlatformSupport.h" #include "PlatformContextSkia.h" #include "SimpleFontData.h" #include "SkiaFontWin.h" @@ -527,7 +527,7 @@ static void drawGlyphsWin(GraphicsContext* graphicsContext, success = painter.drawGlyphs(curLen, &glyphs[0], &advances[0], horizontalOffset - point.x() - currentWidth); if (!success && !executions) { // Ask the browser to load the font for us and retry. - PlatformSupport::ensureFontLoaded(font->platformData().hfont()); + FontPlatformData::ensureFontLoaded(font->platformData().hfont()); continue; } break; diff --git a/Source/WebCore/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp b/Source/WebCore/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp index dbb8d297f..f912027b4 100644 --- a/Source/WebCore/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp +++ b/Source/WebCore/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp @@ -34,13 +34,13 @@ #include "FontCache.h" #include "HWndDC.h" -#include "PlatformSupport.h" #include "SharedBuffer.h" #include "SkTypeface_win.h" #include "SkiaFontWin.h" - #include <mlang.h> #include <objidl.h> +#include <public/Platform.h> +#include <public/win/WebSandboxSupport.h> #include <windows.h> #include <wtf/StdLibExtras.h> @@ -175,7 +175,7 @@ SCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties); if (S_OK != hr) { - if (PlatformSupport::ensureFontLoaded(hfont())) { + if (FontPlatformData::ensureFontLoaded(hfont())) { // FIXME: Handle gracefully the error if this call also fails. hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties); @@ -223,4 +223,12 @@ String FontPlatformData::description() const } #endif +bool FontPlatformData::ensureFontLoaded(HFONT font) +{ + WebKit::WebSandboxSupport* sandboxSupport = WebKit::Platform::current()->sandboxSupport(); + // if there is no sandbox, then we can assume the font + // was able to be loaded successfully already + return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true; +} + } diff --git a/Source/WebCore/platform/graphics/chromium/FontPlatformDataChromiumWin.h b/Source/WebCore/platform/graphics/chromium/FontPlatformDataChromiumWin.h index 0cd005c3c..b3ea594b9 100644 --- a/Source/WebCore/platform/graphics/chromium/FontPlatformDataChromiumWin.h +++ b/Source/WebCore/platform/graphics/chromium/FontPlatformDataChromiumWin.h @@ -106,6 +106,8 @@ public: SCRIPT_FONTPROPERTIES* scriptFontProperties() const; SCRIPT_CACHE* scriptCache() const { return &m_scriptCache; } + static bool ensureFontLoaded(HFONT); + private: // We refcount the internal HFONT so that FontPlatformData can be // efficiently copied. WebKit depends on being able to copy it, and we diff --git a/Source/WebCore/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp b/Source/WebCore/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp index f5425b9df..f1bd65f38 100644 --- a/Source/WebCore/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp +++ b/Source/WebCore/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp @@ -33,9 +33,9 @@ #include <vector> #include "Font.h" +#include "FontPlatformDataChromiumWin.h" #include "GlyphPageTreeNode.h" #include "HWndDC.h" -#include "PlatformSupport.h" #include "SimpleFontData.h" #include "SystemInfo.h" #include "UniscribeHelperTextRun.h" @@ -56,7 +56,7 @@ static bool getGlyphIndices(HFONT font, HDC dc, const UChar* characters, unsigne { if (GetGlyphIndices(dc, characters, charactersLength, glyphBuffer, flag) != GDI_ERROR) return true; - if (PlatformSupport::ensureFontLoaded(font)) { + if (FontPlatformData::ensureFontLoaded(font)) { if (GetGlyphIndices(dc, characters, charactersLength, glyphBuffer, flag) != GDI_ERROR) return true; // FIXME: Handle gracefully the error if this call also fails. @@ -88,7 +88,7 @@ static bool fillBMPGlyphs(unsigned offset, TEXTMETRIC tm = {0}; if (!GetTextMetrics(dc, &tm)) { - if (PlatformSupport::ensureFontLoaded(fontData->platformData().hfont())) { + if (FontPlatformData::ensureFontLoaded(fontData->platformData().hfont())) { if (!GetTextMetrics(dc, &tm)) { // FIXME: Handle gracefully the error if this call also fails. // See http://crbug.com/6401 diff --git a/Source/WebCore/platform/graphics/chromium/ImageDecodingStore.cpp b/Source/WebCore/platform/graphics/chromium/ImageDecodingStore.cpp index 449e45254..489fddc42 100644 --- a/Source/WebCore/platform/graphics/chromium/ImageDecodingStore.cpp +++ b/Source/WebCore/platform/graphics/chromium/ImageDecodingStore.cpp @@ -26,21 +26,22 @@ #include "config.h" #include "ImageDecodingStore.h" +#include "ImageFrameGenerator.h" #include "ScaledImageFragment.h" - -#include <wtf/MainThread.h> +#include "SharedBuffer.h" namespace WebCore { namespace { -ImageDecodingStore* s_instanceOnMainThread = 0; +ImageDecodingStore* s_instance = 0; -static void setInstanceOnMainThread(ImageDecodingStore* imageDecodingStore) +static void setInstance(ImageDecodingStore* imageDecodingStore) { - delete s_instanceOnMainThread; - s_instanceOnMainThread = imageDecodingStore; + delete s_instance; + s_instance = imageDecodingStore; } + } // namespace ImageDecodingStore::ImageDecodingStore() @@ -51,46 +52,98 @@ ImageDecodingStore::~ImageDecodingStore() { } -ImageDecodingStore* ImageDecodingStore::instanceOnMainThread() +ImageDecodingStore* ImageDecodingStore::instance() { - ASSERT(isMainThread()); - return s_instanceOnMainThread; + return s_instance; } -void ImageDecodingStore::initializeOnMainThread() +void ImageDecodingStore::initializeOnce() { - ASSERT(isMainThread()); - setInstanceOnMainThread(ImageDecodingStore::create().leakPtr()); + setInstance(ImageDecodingStore::create().leakPtr()); } void ImageDecodingStore::shutdown() { - ASSERT(isMainThread()); - setInstanceOnMainThread(0); + setInstance(0); } -bool ImageDecodingStore::calledOnValidThread() const +const ScaledImageFragment* ImageDecodingStore::lockCompleteCache(const ImageFrameGenerator* generator, const SkISize& scaledSize) { - return this == instanceOnMainThread() && isMainThread(); + CacheEntry* cacheEntry = 0; + { + MutexLocker lock(m_mutex); + CacheMap::iterator iter = m_cacheMap.find(std::make_pair(generator, scaledSize)); + if (iter == m_cacheMap.end()) + return 0; + cacheEntry = iter->value; + if (!cacheEntry->cachedImage->isComplete()) + return 0; + + // Increment use count such that it doesn't get evicted. + ++cacheEntry->useCount; + } + cacheEntry->cachedImage->bitmap().lockPixels(); + return cacheEntry->cachedImage.get(); } -ScaledImageFragment* ImageDecodingStore::lookupFrameCache(int imageId, const SkISize& scaledSize) const +const ScaledImageFragment* ImageDecodingStore::lockIncompleteCache(const ImageFrameGenerator* generator, const SkISize& scaledSize) { - for (size_t i = 0; i < m_frameCache.size(); ++i) { - if (m_frameCache[i]->isEqual(imageId, scaledSize)) - return m_frameCache[i].get(); - } + // TODO: Implement. return 0; } -void ImageDecodingStore::deleteFrameCache(int imageId) +void ImageDecodingStore::unlockCache(const ImageFrameGenerator* generator, const ScaledImageFragment* cachedImage) +{ + cachedImage->bitmap().unlockPixels(); + if (!cachedImage->isComplete()) { + // Delete the image if it is incomplete. It was never stored in cache. + delete cachedImage; + return; + } + + MutexLocker lock(m_mutex); + CacheMap::iterator iter = m_cacheMap.find(std::make_pair(generator, cachedImage->scaledSize())); + ASSERT(iter != m_cacheMap.end()); + + CacheEntry* cacheEntry = iter->value; + --cacheEntry->useCount; + ASSERT(cacheEntry->useCount >= 0); +} + +const ScaledImageFragment* ImageDecodingStore::insertAndLockCache(const ImageFrameGenerator* generator, PassOwnPtr<ScaledImageFragment> image) { - for (size_t i = 0; i < m_frameCache.size(); ++i) { - if (m_frameCache[i]->isEqual(imageId)) { - m_frameCache.remove(i); - return; - } + // Prune old cache entries to give space for the new one. + prune(); + + // Lock the underlying SkBitmap to prevent it from being purged. + image->bitmap().lockPixels(); + + if (!image->isComplete()) { + // Incomplete image is not stored in the cache and deleted after use. + // See unlockCache(). + // TODO: We should allow incomplete images to be stored together with + // the corresponding ImageDecoder. + return image.leakPtr(); } + + ScaledImageFragment* cachedImage = image.get(); + OwnPtr<CacheEntry> newCacheEntry = CacheEntry::createAndUse(image); + + CacheIdentifier key = std::make_pair(generator, cachedImage->scaledSize()); + MutexLocker lock(m_mutex); + ASSERT(!m_cacheMap.contains(key)); + + // m_cacheMap is used for indexing and quick lookup of a cached image. + // m_cacheEntries is used to support LRU operations to reorder cache + // entries quickly. It also owns cached images. + m_cacheMap.add(key, newCacheEntry.get()); + m_cacheEntries.append(newCacheEntry.release()); + return cachedImage; +} + +void ImageDecodingStore::prune() +{ + // TODO: Implement. } } // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/ImageDecodingStore.h b/Source/WebCore/platform/graphics/chromium/ImageDecodingStore.h index a6fa56194..0aea2e969 100644 --- a/Source/WebCore/platform/graphics/chromium/ImageDecodingStore.h +++ b/Source/WebCore/platform/graphics/chromium/ImageDecodingStore.h @@ -26,40 +26,73 @@ #ifndef ImageDecodingStore_h #define ImageDecodingStore_h +#include "ScaledImageFragment.h" #include "SkTypes.h" #include "SkSize.h" +#include "SkSizeHash.h" #include <wtf/OwnPtr.h> #include <wtf/PassOwnPtr.h> +#include <wtf/ThreadingPrimitives.h> #include <wtf/Vector.h> namespace WebCore { class ImageDecoder; class ImageFrameGenerator; -class ScaledImageFragment; class SharedBuffer; -// This class can only be instantiated on main thread. There will be an -// instance on impl thread in the future but that part of implementation -// is incomplete. See bug: https://bugs.webkit.org/show_bug.cgi?id=94240 -// for details. class ImageDecodingStore { public: static PassOwnPtr<ImageDecodingStore> create() { return adoptPtr(new ImageDecodingStore); } ~ImageDecodingStore(); - static ImageDecodingStore* instanceOnMainThread(); - static void initializeOnMainThread(); + static ImageDecodingStore* instance(); + static void initializeOnce(); static void shutdown(); + const ScaledImageFragment* lockCompleteCache(const ImageFrameGenerator*, const SkISize& scaledSize); + const ScaledImageFragment* lockIncompleteCache(const ImageFrameGenerator*, const SkISize& scaledSize); + void unlockCache(const ImageFrameGenerator*, const ScaledImageFragment*); + const ScaledImageFragment* insertAndLockCache(const ImageFrameGenerator*, PassOwnPtr<ScaledImageFragment>); + private: + struct CacheEntry { + static PassOwnPtr<CacheEntry> create() { return adoptPtr(new CacheEntry()); } + static PassOwnPtr<CacheEntry> createAndUse(PassOwnPtr<ScaledImageFragment> image) { return adoptPtr(new CacheEntry(image, 1)); } + + CacheEntry() + : useCount(0) + { + } + + CacheEntry(PassOwnPtr<ScaledImageFragment> image, int count) + : cachedImage(image) + , useCount(count) + { + } + + ~CacheEntry() + { + ASSERT(!useCount); + } + + OwnPtr<ScaledImageFragment> cachedImage; + int useCount; + }; + ImageDecodingStore(); - bool calledOnValidThread() const; - ScaledImageFragment* lookupFrameCache(int imageId, const SkISize& scaledSize) const; - void deleteFrameCache(int imageId); + void prune(); + + Vector<OwnPtr<CacheEntry> > m_cacheEntries; + + typedef std::pair<const ImageFrameGenerator*, SkISize> CacheIdentifier; + typedef HashMap<CacheIdentifier, CacheEntry*> CacheMap; + CacheMap m_cacheMap; - Vector<OwnPtr<ScaledImageFragment> > m_frameCache; + // Protect concurrent access to all instances of CacheEntry stored in m_cacheEntries and + // m_cacheMap as well as the containers. + Mutex m_mutex; }; } // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/ImageFrameGenerator.cpp b/Source/WebCore/platform/graphics/chromium/ImageFrameGenerator.cpp index fe4e4bfbe..220a57d45 100644 --- a/Source/WebCore/platform/graphics/chromium/ImageFrameGenerator.cpp +++ b/Source/WebCore/platform/graphics/chromium/ImageFrameGenerator.cpp @@ -28,20 +28,34 @@ #include "ImageFrameGenerator.h" #include "ImageDecoder.h" +#include "ImageDecodingStore.h" +#include "ScaledImageFragment.h" #include "SharedBuffer.h" #include "skia/ext/image_operations.h" namespace WebCore { -ImageFrameGenerator::ImageFrameGenerator(PassRefPtr<SharedBuffer> data, bool allDataReceived) - : m_allDataReceived(false) +namespace { + +skia::ImageOperations::ResizeMethod resizeMethod() +{ + return skia::ImageOperations::RESIZE_LANCZOS3; +} + +} // namespace + +ImageFrameGenerator::ImageFrameGenerator(const SkISize& fullSize, PassRefPtr<SharedBuffer> data, bool allDataReceived) + : m_fullSize(fullSize) + , m_allDataReceived(false) { setData(data, allDataReceived); } ImageFrameGenerator::~ImageFrameGenerator() { + // TODO: Call ImageDecodingStore to remove all cache entries indexed + // by this object. } void ImageFrameGenerator::setData(PassRefPtr<SharedBuffer> data, bool allDataReceived) @@ -49,17 +63,64 @@ void ImageFrameGenerator::setData(PassRefPtr<SharedBuffer> data, bool allDataRec // FIXME: Doing a full copy is expensive, instead copy only new data. RefPtr<SharedBuffer> dataCopy = data->copy(); - MutexLocker lock(m_mutex); + MutexLocker lock(m_dataMutex); m_data = dataCopy; m_allDataReceived = allDataReceived; } -SkBitmap ImageFrameGenerator::decodeAndScale(const SkISize& scaledSize, const SkIRect& scaledSubset) +const ScaledImageFragment* ImageFrameGenerator::decodeAndScale(const SkISize& scaledSize) +{ + // Prevents concurrent decode or scale operations on the same image data. + // Multiple LazyDecodingPixelRefs can call this method at the same time. + MutexLocker lock(m_decodeMutex); + const ScaledImageFragment* cachedImage = 0; + + cachedImage = tryToLockCache(scaledSize); + if (cachedImage) + return cachedImage; + + cachedImage = tryToScale(0, scaledSize); + if (cachedImage) + return cachedImage; + + cachedImage = tryToDecodeAndScale(scaledSize); + if (cachedImage) + return cachedImage; + return 0; +} + +const ScaledImageFragment* ImageFrameGenerator::tryToLockCache(const SkISize& scaledSize) +{ + return ImageDecodingStore::instance()->lockCompleteCache(this, scaledSize); +} + +const ScaledImageFragment* ImageFrameGenerator::tryToScale(const ScaledImageFragment* fullSizeImage, const SkISize& scaledSize) +{ + // If the requested scaled size is the same as the full size then exit + // early. This saves a cache lookup. + if (scaledSize == m_fullSize) + return 0; + + if (!fullSizeImage) + fullSizeImage = ImageDecodingStore::instance()->lockCompleteCache(this, m_fullSize); + + if (!fullSizeImage) + return 0; + + SkBitmap scaledBitmap = skia::ImageOperations::Resize( + fullSizeImage->bitmap(), resizeMethod(), scaledSize.width(), scaledSize.height()); + OwnPtr<ScaledImageFragment> scaledImage = ScaledImageFragment::create(scaledSize, scaledBitmap, fullSizeImage->isComplete()); + + ImageDecodingStore::instance()->unlockCache(this, fullSizeImage); + return ImageDecodingStore::instance()->insertAndLockCache(this, scaledImage.release()); +} + +const ScaledImageFragment* ImageFrameGenerator::tryToDecodeAndScale(const SkISize& scaledSize) { RefPtr<SharedBuffer> data; bool allDataReceived = false; { - MutexLocker lock(m_mutex); + MutexLocker lock(m_dataMutex); // FIXME: We should do a shallow copy instead. Now we're restricted by the API of SharedBuffer. data = m_data->copy(); @@ -67,22 +128,26 @@ SkBitmap ImageFrameGenerator::decodeAndScale(const SkISize& scaledSize, const Sk } OwnPtr<ImageDecoder> decoder(adoptPtr(ImageDecoder::create(*data.get(), ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileApplied))); + if (!decoder && m_imageDecoderFactory) + decoder = m_imageDecoderFactory->create(); if (!decoder) - return SkBitmap(); + return 0; decoder->setData(data.get(), allDataReceived); ImageFrame* frame = decoder->frameBufferAtIndex(0); - if (!frame) - return SkBitmap(); + if (!frame || frame->status() == ImageFrame::FrameEmpty) + return 0; + + bool isComplete = frame->status() == ImageFrame::FrameComplete; + SkBitmap fullSizeBitmap = frame->getSkBitmap(); + ASSERT(fullSizeBitmap.width() == m_fullSize.width() && fullSizeBitmap.height() == m_fullSize.height()); - SkBitmap bitmap = frame->getSkBitmap(); - SkISize bitmapSize = SkISize::Make(bitmap.width(), bitmap.height()); - if (bitmapSize != scaledSize) - bitmap = skia::ImageOperations::Resize(bitmap, skia::ImageOperations::RESIZE_LANCZOS3, scaledSize.width(), scaledSize.height()); + const ScaledImageFragment* fullSizeImage = ImageDecodingStore::instance()->insertAndLockCache( + this, ScaledImageFragment::create(m_fullSize, fullSizeBitmap, isComplete)); - SkBitmap bitmapSubset; - bitmap.extractSubset(&bitmapSubset, scaledSubset); - return bitmapSubset; + if (m_fullSize == scaledSize) + return fullSizeImage; + return tryToScale(fullSizeImage, scaledSize); } } // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/ImageFrameGenerator.h b/Source/WebCore/platform/graphics/chromium/ImageFrameGenerator.h index 6df5b23ce..0831c4498 100644 --- a/Source/WebCore/platform/graphics/chromium/ImageFrameGenerator.h +++ b/Source/WebCore/platform/graphics/chromium/ImageFrameGenerator.h @@ -38,26 +38,49 @@ namespace WebCore { +class ImageDecoder; +class ScaledImageFragment; class SharedBuffer; +class ImageDecoderFactory { +public: + virtual ~ImageDecoderFactory() { } + virtual PassOwnPtr<ImageDecoder> create() = 0; +}; + class ImageFrameGenerator : public ThreadSafeRefCounted<ImageFrameGenerator> { public: - static PassRefPtr<ImageFrameGenerator> create(PassRefPtr<SharedBuffer> data, bool allDataReceived) + static PassRefPtr<ImageFrameGenerator> create(const SkISize& fullSize, PassRefPtr<SharedBuffer> data, bool allDataReceived) { - return adoptRef(new ImageFrameGenerator(data, allDataReceived)); + return adoptRef(new ImageFrameGenerator(fullSize, data, allDataReceived)); } - ImageFrameGenerator(PassRefPtr<SharedBuffer>, bool allDataReceived); + ImageFrameGenerator(const SkISize& fullSize, PassRefPtr<SharedBuffer>, bool allDataReceived); ~ImageFrameGenerator(); - SkBitmap decodeAndScale(const SkISize& scaledSize, const SkIRect& scaledSubset); + const ScaledImageFragment* decodeAndScale(const SkISize& scaledSize); void setData(PassRefPtr<SharedBuffer>, bool allDataReceived); + void setImageDecoderFactoryForTesting(PassOwnPtr<ImageDecoderFactory> factory) { m_imageDecoderFactory = factory; } + private: + // These methods are called while m_decodeMutex is locked. + const ScaledImageFragment* tryToLockCache(const SkISize& scaledSize); + const ScaledImageFragment* tryToScale(const ScaledImageFragment* fullSizeImage, const SkISize& scaledSize); + const ScaledImageFragment* tryToDecodeAndScale(const SkISize& scaledSize); + + SkISize m_fullSize; RefPtr<SharedBuffer> m_data; bool m_allDataReceived; - Mutex m_mutex; + + OwnPtr<ImageDecoderFactory> m_imageDecoderFactory; + + // Prevents multiple decode operations on the same data. + Mutex m_decodeMutex; + + // Prevents concurrent access to m_data. + Mutex m_dataMutex; }; } // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/LazyDecodingPixelRef.cpp b/Source/WebCore/platform/graphics/chromium/LazyDecodingPixelRef.cpp index 0a5d5a38a..555266362 100644 --- a/Source/WebCore/platform/graphics/chromium/LazyDecodingPixelRef.cpp +++ b/Source/WebCore/platform/graphics/chromium/LazyDecodingPixelRef.cpp @@ -38,6 +38,7 @@ LazyDecodingPixelRef::LazyDecodingPixelRef(PassRefPtr<ImageFrameGenerator> frame , m_frameGenerator(frameGenerator) , m_scaledSize(scaledSize) , m_scaledSubset(scaledSubset) + , m_lockedCachedImage(0) { } @@ -58,18 +59,29 @@ bool LazyDecodingPixelRef::isClipped() const void* LazyDecodingPixelRef::onLockPixels(SkColorTable**) { m_mutex.lock(); - ASSERT(m_lockedBitmap.isNull()); - m_lockedBitmap = m_frameGenerator->decodeAndScale(m_scaledSize, m_scaledSubset); - if (m_lockedBitmap.isNull()) + ASSERT(!m_lockedCachedImage); + + m_lockedCachedImage = ImageDecodingStore::instance()->lockCompleteCache(m_frameGenerator.get(), m_scaledSize); + + // Use ImageFrameGenerator to generate the image. It will lock the cache + // entry for us. + if (!m_lockedCachedImage) + m_lockedCachedImage = m_frameGenerator->decodeAndScale(m_scaledSize); + + if (!m_lockedCachedImage) return 0; - m_lockedBitmap.lockPixels(); - return m_lockedBitmap.getAddr(0, 0); + + ASSERT(!m_lockedCachedImage->bitmap().isNull()); + ASSERT(m_lockedCachedImage->scaledSize() == m_scaledSize); + return m_lockedCachedImage->bitmap().getAddr(m_scaledSubset.x(), m_scaledSubset.y()); } void LazyDecodingPixelRef::onUnlockPixels() { - m_lockedBitmap.unlockPixels(); - m_lockedBitmap.reset(); + if (m_lockedCachedImage) { + ImageDecodingStore::instance()->unlockCache(m_frameGenerator.get(), m_lockedCachedImage); + m_lockedCachedImage = 0; + } m_mutex.unlock(); } diff --git a/Source/WebCore/platform/graphics/chromium/LazyDecodingPixelRef.h b/Source/WebCore/platform/graphics/chromium/LazyDecodingPixelRef.h index 80314cf21..9b2a46d4e 100644 --- a/Source/WebCore/platform/graphics/chromium/LazyDecodingPixelRef.h +++ b/Source/WebCore/platform/graphics/chromium/LazyDecodingPixelRef.h @@ -38,6 +38,7 @@ namespace WebCore { class ImageFrameGenerator; +class ScaledImageFragment; class LazyDecodingPixelRef : public SkPixelRef { public: @@ -61,7 +62,7 @@ private: SkISize m_scaledSize; SkIRect m_scaledSubset; - SkBitmap m_lockedBitmap; + const ScaledImageFragment* m_lockedCachedImage; Mutex m_mutex; }; diff --git a/Source/WebCore/platform/graphics/chromium/ScaledImageFragment.cpp b/Source/WebCore/platform/graphics/chromium/ScaledImageFragment.cpp index 974e6ff84..71bb620ae 100644 --- a/Source/WebCore/platform/graphics/chromium/ScaledImageFragment.cpp +++ b/Source/WebCore/platform/graphics/chromium/ScaledImageFragment.cpp @@ -33,22 +33,11 @@ ScaledImageFragment::~ScaledImageFragment() { } -ScaledImageFragment::ScaledImageFragment(int imageId, const SkISize& scaledSize, const SkBitmap& bitmap, const bool isComplete) - : m_imageId(imageId) - , m_scaledSize(scaledSize) +ScaledImageFragment::ScaledImageFragment(const SkISize& scaledSize, const SkBitmap& bitmap, const bool isComplete) + : m_scaledSize(scaledSize) , m_bitmap(bitmap) , m_isComplete(isComplete) { } -bool ScaledImageFragment::isEqual(int imageId, const SkISize& scaledSize) const -{ - return imageId == m_imageId && scaledSize == m_scaledSize; -} - -bool ScaledImageFragment::isEqual(int imageId) const -{ - return imageId == m_imageId; -} - } // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/ScaledImageFragment.h b/Source/WebCore/platform/graphics/chromium/ScaledImageFragment.h index 5b7ffc960..f0707b3ce 100644 --- a/Source/WebCore/platform/graphics/chromium/ScaledImageFragment.h +++ b/Source/WebCore/platform/graphics/chromium/ScaledImageFragment.h @@ -34,29 +34,23 @@ namespace WebCore { -// ScaledImageFragment is a scaled version of a image. It is identified -// by two things: -// 1. Image ID. The original image that this fragment comes from. -// 2. Scaled image size. +// ScaledImageFragment is a scaled version of an image. class ScaledImageFragment { public: - static PassOwnPtr<ScaledImageFragment> create(int imageId, const SkISize& scaledSize, const SkBitmap& bitmap, bool isComplete) + static PassOwnPtr<ScaledImageFragment> create(const SkISize& scaledSize, const SkBitmap& bitmap, bool isComplete) { - return adoptPtr(new ScaledImageFragment(imageId, scaledSize, bitmap, isComplete)); + return adoptPtr(new ScaledImageFragment(scaledSize, bitmap, isComplete)); } - ScaledImageFragment(int imageId, const SkISize&, const SkBitmap&, bool isComplete); + ScaledImageFragment(const SkISize&, const SkBitmap&, bool isComplete); ~ScaledImageFragment(); + const SkISize& scaledSize() const { return m_scaledSize; } const SkBitmap& bitmap() const { return m_bitmap; } SkBitmap& bitmap() { return m_bitmap; } - - bool isEqual(int imageId, const SkISize& scaledSize) const; - bool isEqual(int imageId) const; bool isComplete() const { return m_isComplete; } private: - int m_imageId; SkISize m_scaledSize; SkBitmap m_bitmap; bool m_isComplete; diff --git a/Source/WebCore/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp b/Source/WebCore/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp index a7aed729c..289c1cd65 100644 --- a/Source/WebCore/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp +++ b/Source/WebCore/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp @@ -36,14 +36,13 @@ #include "Font.h" #include "FontCache.h" #include "FontDescription.h" +#include "FontPlatformDataChromiumWin.h" #include "HWndDC.h" -#include "PlatformSupport.h" -#include <wtf/MathExtras.h> - +#include <mlang.h> +#include <objidl.h> #include <unicode/uchar.h> #include <unicode/unorm.h> -#include <objidl.h> -#include <mlang.h> +#include <wtf/MathExtras.h> namespace WebCore { @@ -61,7 +60,7 @@ void SimpleFontData::platformInit() TEXTMETRIC textMetric = {0}; if (!GetTextMetrics(dc, &textMetric)) { - if (PlatformSupport::ensureFontLoaded(m_platformData.hfont())) { + if (FontPlatformData::ensureFontLoaded(m_platformData.hfont())) { // Retry GetTextMetrics. // FIXME: Handle gracefully the error if this call also fails. // See http://crbug.com/6401. @@ -136,7 +135,7 @@ void SimpleFontData::determinePitch() // is *not* fixed pitch. Unbelievable but true. TEXTMETRIC textMetric = {0}; if (!GetTextMetrics(dc, &textMetric)) { - if (PlatformSupport::ensureFontLoaded(m_platformData.hfont())) { + if (FontPlatformData::ensureFontLoaded(m_platformData.hfont())) { // Retry GetTextMetrics. // FIXME: Handle gracefully the error if this call also fails. // See http://crbug.com/6401. @@ -159,7 +158,7 @@ FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const GLYPHMETRICS gdiMetrics; static const MAT2 identity = { 0, 1, 0, 0, 0, 0, 0, 1 }; if (GetGlyphOutline(hdc, glyph, GGO_METRICS | GGO_GLYPH_INDEX, &gdiMetrics, 0, 0, &identity) == -1) { - if (PlatformSupport::ensureFontLoaded(m_platformData.hfont())) { + if (FontPlatformData::ensureFontLoaded(m_platformData.hfont())) { // Retry GetTextMetrics. // FIXME: Handle gracefully the error if this call also fails. // See http://crbug.com/6401. @@ -185,7 +184,7 @@ float SimpleFontData::platformWidthForGlyph(Glyph glyph) const int width = 0; if (!GetCharWidthI(dc, glyph, 1, 0, &width)) { // Ask the browser to preload the font and retry. - if (PlatformSupport::ensureFontLoaded(m_platformData.hfont())) { + if (FontPlatformData::ensureFontLoaded(m_platformData.hfont())) { // FIXME: Handle gracefully the error if this call also fails. // See http://crbug.com/6401. if (!GetCharWidthI(dc, glyph, 1, 0, &width)) diff --git a/Source/WebCore/platform/graphics/chromium/SkSizeHash.h b/Source/WebCore/platform/graphics/chromium/SkSizeHash.h new file mode 100644 index 000000000..6f297cfdf --- /dev/null +++ b/Source/WebCore/platform/graphics/chromium/SkSizeHash.h @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef SkSizeHash_h +#define SkSizeHash_h + +#include "SkScalar.h" +#include "SkSize.h" + +#include <wtf/HashMap.h> + +namespace WTF { + +template<> struct IntHash<SkSize> { + static unsigned hash(const SkSize& key) { return pairIntHash(key.width(), key.height()); } + static bool equal(const SkSize& a, const SkSize& b) { return a == b; } + static const bool safeToCompareToEmptyOrDeleted = true; +}; + +template<> struct DefaultHash<SkSize> { + typedef IntHash<SkSize> Hash; +}; + +template<> struct HashTraits<SkSize> : GenericHashTraits<SkSize> { + static const bool emptyValueIsZero = true; + static const bool needsDestruction = false; + static SkSize emptyValue() { return SkSize::Make(0, 0); } + static void constructDeletedValue(SkSize& slot) + { + slot = SkSize::Make(-1, -1); + } + static bool isDeletedValue(const SkSize& value) + { + return value.width() == -1 && value.height() == -1; + } +}; + +template<> struct IntHash<SkISize> { + static unsigned hash(const SkISize& key) { return pairIntHash(key.width(), key.height()); } + static bool equal(const SkISize& a, const SkISize& b) { return a == b; } + static const bool safeToCompareToEmptyOrDeleted = true; +}; + +template<> struct DefaultHash<SkISize> { + typedef IntHash<SkISize> Hash; +}; + +template<> struct HashTraits<SkISize> : GenericHashTraits<SkISize> { + static const bool emptyValueIsZero = true; + static const bool needsDestruction = false; + static SkISize emptyValue() { return SkISize::Make(0, 0); } + static void constructDeletedValue(SkISize& slot) + { + slot = SkISize::Make(-1, -1); + } + static bool isDeletedValue(const SkISize& value) + { + return value.width() == -1 && value.height() == -1; + } +}; + +} // namespace WTF + +#endif // SkSizeHash_h diff --git a/Source/WebCore/platform/graphics/chromium/UniscribeHelperTextRun.cpp b/Source/WebCore/platform/graphics/chromium/UniscribeHelperTextRun.cpp index f7701c2a3..ab4331b2b 100644 --- a/Source/WebCore/platform/graphics/chromium/UniscribeHelperTextRun.cpp +++ b/Source/WebCore/platform/graphics/chromium/UniscribeHelperTextRun.cpp @@ -32,7 +32,7 @@ #include "UniscribeHelperTextRun.h" #include "Font.h" -#include "PlatformSupport.h" +#include "FontPlatformDataChromiumWin.h" #include "SimpleFontData.h" #include "TextRun.h" @@ -82,7 +82,7 @@ void UniscribeHelperTextRun::tryToPreloadFont(HFONT font) // Ask the browser to get the font metrics for this font. // That will preload the font and it should now be accessible // from the renderer. - PlatformSupport::ensureFontLoaded(font); + FontPlatformData::ensureFontLoaded(font); } bool UniscribeHelperTextRun::nextWinFontData( diff --git a/Source/WebCore/platform/graphics/filters/FETurbulence.h b/Source/WebCore/platform/graphics/filters/FETurbulence.h index 47c8bee79..84ff11261 100644 --- a/Source/WebCore/platform/graphics/filters/FETurbulence.h +++ b/Source/WebCore/platform/graphics/filters/FETurbulence.h @@ -61,6 +61,9 @@ public: static void fillRegionWorker(void*); virtual void platformApplySoftware(); +#if ENABLE(OPENCL) + virtual bool platformApplyOpenCL(); +#endif virtual void dump(); virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); } diff --git a/Source/WebCore/platform/graphics/filters/FilterEffect.cpp b/Source/WebCore/platform/graphics/filters/FilterEffect.cpp index a2bb54d31..0a0f82278 100644 --- a/Source/WebCore/platform/graphics/filters/FilterEffect.cpp +++ b/Source/WebCore/platform/graphics/filters/FilterEffect.cpp @@ -2,6 +2,7 @@ * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com> * Copyright (C) 2009 Dirk Schulze <krit@webkit.org> * Copyright (C) Research In Motion Limited 2010. All rights reserved. + * Copyright (C) 2012 University of Szeged * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -123,6 +124,10 @@ void FilterEffect::apply() } // Add platform specific apply functions here and return earlier. +#if ENABLE(OPENCL) + if (platformApplyOpenCL()) + return; +#endif #if USE(SKIA) if (platformApplySkia()) return; @@ -130,6 +135,31 @@ void FilterEffect::apply() platformApplySoftware(); } +#if ENABLE(OPENCL) +// This function will be changed to abstract virtual when all filters are landed. +bool FilterEffect::platformApplyOpenCL() +{ + if (!FilterContextOpenCL::context()) + return false; + + unsigned size = m_inputEffects.size(); + for (unsigned i = 0; i < size; ++i) { + FilterEffect* in = m_inputEffects.at(i).get(); + // Software code path expects that at least one of the following fileds is valid. + if (!in->m_imageBufferResult && !in->m_unmultipliedImageResult && !in->m_premultipliedImageResult) + in->asImageBuffer(); + } + + platformApplySoftware(); + ImageBuffer* sourceImage = asImageBuffer(); + if (sourceImage) { + RefPtr<Uint8ClampedArray> sourceImageData = sourceImage->getUnmultipliedImageData(IntRect(IntPoint(), sourceImage->internalSize())); + createOpenCLImageResult(sourceImageData->data()); + } + return true; +} +#endif + void FilterEffect::forceValidPreMultipliedPixels() { // Must operate on pre-multiplied results; other formats cannot have invalid pixels. @@ -187,6 +217,10 @@ void FilterEffect::clearResult() m_unmultipliedImageResult.clear(); if (m_premultipliedImageResult) m_premultipliedImageResult.clear(); +#if ENABLE(OPENCL) + if (m_openCLImageResult) + m_openCLImageResult.clear(); +#endif } ImageBuffer* FilterEffect::asImageBuffer() @@ -195,6 +229,10 @@ ImageBuffer* FilterEffect::asImageBuffer() return 0; if (m_imageBufferResult) return m_imageBufferResult.get(); +#if ENABLE(OPENCL) + if (m_openCLImageResult) + return openCLImageToImageBuffer(); +#endif m_imageBufferResult = ImageBuffer::create(m_absolutePaintRect.size(), 1, m_resultColorSpace, m_filter->renderingMode()); IntRect destinationRect(IntPoint(), m_absolutePaintRect.size()); if (m_premultipliedImageResult) @@ -204,6 +242,28 @@ ImageBuffer* FilterEffect::asImageBuffer() return m_imageBufferResult.get(); } +#if ENABLE(OPENCL) +ImageBuffer* FilterEffect::openCLImageToImageBuffer() +{ + FilterContextOpenCL* context = FilterContextOpenCL::context(); + ASSERT(context); + + size_t origin[3] = { 0, 0, 0 }; + size_t region[3] = { m_absolutePaintRect.width(), m_absolutePaintRect.height(), 1 }; + + RefPtr<Uint8ClampedArray> destinationPixelArray = Uint8ClampedArray::create(m_absolutePaintRect.width() * m_absolutePaintRect.height() * 4); + + clFinish(context->commandQueue()); + clEnqueueReadImage(context->commandQueue(), m_openCLImageResult, CL_TRUE, origin, region, 0, 0, destinationPixelArray->data(), 0, 0, 0); + + m_imageBufferResult = ImageBuffer::create(m_absolutePaintRect.size()); + IntRect destinationRect(IntPoint(), m_absolutePaintRect.size()); + m_imageBufferResult->putByteArray(Unmultiplied, destinationPixelArray.get(), destinationRect.size(), destinationRect, IntPoint()); + + return m_imageBufferResult.get(); +} +#endif + PassRefPtr<Uint8ClampedArray> FilterEffect::asUnmultipliedImage(const IntRect& rect) { ASSERT(isFilterSizeValid(rect)); @@ -363,6 +423,22 @@ Uint8ClampedArray* FilterEffect::createPremultipliedImageResult() return m_premultipliedImageResult.get(); } +#if ENABLE(OPENCL) +OpenCLHandle FilterEffect::createOpenCLImageResult(uint8_t* source) +{ + ASSERT(!hasResult()); + cl_image_format clImageFormat; + clImageFormat.image_channel_order = CL_RGBA; + clImageFormat.image_channel_data_type = CL_UNORM_INT8; + + FilterContextOpenCL* context = FilterContextOpenCL::context(); + ASSERT(context); + m_openCLImageResult = clCreateImage2D(context->deviceContext(), CL_MEM_READ_WRITE | (source ? CL_MEM_COPY_HOST_PTR : 0), + &clImageFormat, m_absolutePaintRect.width(), m_absolutePaintRect.height(), 0, source, 0); + return m_openCLImageResult; +} +#endif + void FilterEffect::transformResultColorSpace(ColorSpace dstColorSpace) { #if USE(CG) @@ -374,12 +450,27 @@ void FilterEffect::transformResultColorSpace(ColorSpace dstColorSpace) // FIXME: We can avoid this potentially unnecessary ImageBuffer conversion by adding // color space transform support for the {pre,un}multiplied arrays. +#if ENABLE(OPENCL) + if (openCLImage()) { + FilterContextOpenCL* context = FilterContextOpenCL::context(); + ASSERT(context); + context->openCLTransformColorSpace(m_openCLImageResult, absolutePaintRect(), m_resultColorSpace, dstColorSpace); + if (m_imageBufferResult) + m_imageBufferResult.clear(); + goto skipSoftwareCodePath; + } +#endif if (!m_imageBufferResult) { asImageBuffer(); ASSERT(m_imageBufferResult); } m_imageBufferResult->transformColorSpace(m_resultColorSpace, dstColorSpace); + +#if ENABLE(OPENCL) +skipSoftwareCodePath: +#endif + m_resultColorSpace = dstColorSpace; if (m_unmultipliedImageResult) diff --git a/Source/WebCore/platform/graphics/filters/FilterEffect.h b/Source/WebCore/platform/graphics/filters/FilterEffect.h index 069ede3ee..b9f219326 100644 --- a/Source/WebCore/platform/graphics/filters/FilterEffect.h +++ b/Source/WebCore/platform/graphics/filters/FilterEffect.h @@ -33,6 +33,10 @@ #include <wtf/Uint8ClampedArray.h> #include <wtf/Vector.h> +#if ENABLE(OPENCL) +#include "FilterContextOpenCL.h" +#endif + static const float kMaxFilterSize = 5000.0f; #if USE(SKIA) @@ -70,6 +74,12 @@ public: void copyUnmultipliedImage(Uint8ClampedArray* destination, const IntRect&); void copyPremultipliedImage(Uint8ClampedArray* destination, const IntRect&); +#if ENABLE(OPENCL) + OpenCLHandle openCLImage() { return m_openCLImageResult; } + void setOpenCLImage(OpenCLHandle openCLImage) { m_openCLImageResult = openCLImage; } + ImageBuffer* openCLImageToImageBuffer(); +#endif + FilterEffectVector& inputEffects() { return m_inputEffects; } FilterEffect* inputEffect(unsigned) const; unsigned numberOfEffectInputs() const { return m_inputEffects.size(); } @@ -77,7 +87,12 @@ public: inline bool hasResult() const { // This function needs platform specific checks, if the memory managment is not done by FilterEffect. - return m_imageBufferResult || m_unmultipliedImageResult || m_premultipliedImageResult; + return m_imageBufferResult +#if ENABLE(OPENCL) + || m_openCLImageResult +#endif + || m_unmultipliedImageResult + || m_premultipliedImageResult; } IntRect drawingRegionOfInputImage(const IntRect&) const; @@ -101,6 +116,9 @@ public: virtual void correctFilterResultIfNeeded() { } virtual void platformApplySoftware() = 0; +#if ENABLE(OPENCL) + virtual bool platformApplyOpenCL(); +#endif #if USE(SKIA) virtual bool platformApplySkia() { return false; } virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*) { return 0; } @@ -149,6 +167,9 @@ protected: ImageBuffer* createImageBufferResult(); Uint8ClampedArray* createUnmultipliedImageResult(); Uint8ClampedArray* createPremultipliedImageResult(); +#if ENABLE(OPENCL) + OpenCLHandle createOpenCLImageResult(uint8_t* = 0); +#endif // Return true if the filter will only operate correctly on valid RGBA values, with // alpha in [0,255] and each color component in [0, alpha]. @@ -162,6 +183,9 @@ private: RefPtr<Uint8ClampedArray> m_unmultipliedImageResult; RefPtr<Uint8ClampedArray> m_premultipliedImageResult; FilterEffectVector m_inputEffects; +#if ENABLE(OPENCL) + OpenCLHandle m_openCLImageResult; +#endif bool m_alphaImage; diff --git a/Source/WebCore/platform/graphics/filters/SourceAlpha.h b/Source/WebCore/platform/graphics/filters/SourceAlpha.h index 96916e9f2..b0220ce9e 100644 --- a/Source/WebCore/platform/graphics/filters/SourceAlpha.h +++ b/Source/WebCore/platform/graphics/filters/SourceAlpha.h @@ -33,6 +33,9 @@ public: static const AtomicString& effectName(); virtual void platformApplySoftware(); +#if ENABLE(OPENCL) + virtual bool platformApplyOpenCL(); +#endif virtual void dump(); virtual void determineAbsolutePaintRect(); diff --git a/Source/WebCore/platform/graphics/filters/SourceGraphic.h b/Source/WebCore/platform/graphics/filters/SourceGraphic.h index c7e833e35..185e564bf 100644 --- a/Source/WebCore/platform/graphics/filters/SourceGraphic.h +++ b/Source/WebCore/platform/graphics/filters/SourceGraphic.h @@ -34,6 +34,9 @@ public: static const AtomicString& effectName(); virtual void platformApplySoftware(); +#if ENABLE(OPENCL) + virtual bool platformApplyOpenCL(); +#endif virtual void dump(); virtual void determineAbsolutePaintRect(); diff --git a/Source/WebCore/platform/graphics/glx/GLContextGLX.h b/Source/WebCore/platform/graphics/glx/GLContextGLX.h index 00f56e791..888146b11 100644 --- a/Source/WebCore/platform/graphics/glx/GLContextGLX.h +++ b/Source/WebCore/platform/graphics/glx/GLContextGLX.h @@ -25,7 +25,6 @@ #include "GLContext.h" typedef struct __GLXcontextRec* GLXContext; -typedef struct __GLXcontextRec *GLXContext; typedef unsigned long GLXPbuffer; typedef unsigned long GLXPixmap; typedef unsigned char GLubyte; diff --git a/Source/WebCore/platform/graphics/gpu/SharedGraphicsContext3D.cpp b/Source/WebCore/platform/graphics/gpu/SharedGraphicsContext3D.cpp index c063fe4bb..58a16b4ac 100644 --- a/Source/WebCore/platform/graphics/gpu/SharedGraphicsContext3D.cpp +++ b/Source/WebCore/platform/graphics/gpu/SharedGraphicsContext3D.cpp @@ -42,12 +42,19 @@ public: if (m_context && (!m_context->makeContextCurrent() || (m_context->getExtensions()->getGraphicsResetStatusARB() != GraphicsContext3D::NO_ERROR))) m_context.clear(); - if (!m_context) + bool wasCreated = false; + + if (!m_context) { createContext(); + wasCreated = true; + } if (m_context && !m_context->makeContextCurrent()) m_context.clear(); + if (m_context && wasCreated) + m_context->getExtensions()->pushGroupMarkerEXT("SharedGraphicsContext"); + return m_context; } diff --git a/Source/WebCore/platform/graphics/gpu/opencl/FilterContextOpenCL.cpp b/Source/WebCore/platform/graphics/gpu/opencl/FilterContextOpenCL.cpp new file mode 100644 index 000000000..9dcafe762 --- /dev/null +++ b/Source/WebCore/platform/graphics/gpu/opencl/FilterContextOpenCL.cpp @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2012 University of Szeged + * Copyright (C) 2012 Tamas Czene <tczene@inf.u-szeged.hu> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(OPENCL) +#include "FilterContextOpenCL.h" + +namespace WebCore { + +FilterContextOpenCL* FilterContextOpenCL::m_context = 0; +int FilterContextOpenCL::m_alreadyInitialized = 0; + +FilterContextOpenCL* FilterContextOpenCL::context() +{ + if (m_context) + return m_context; + if (m_alreadyInitialized) + return 0; + + m_alreadyInitialized = true; + FilterContextOpenCL* localContext = new FilterContextOpenCL(); + + // Initializing the context. + cl_int errorNumber; + cl_device_id* devices; + cl_platform_id firstPlatformId; + size_t deviceBufferSize = 0; + + errorNumber = clGetPlatformIDs(1, &firstPlatformId, 0); + cl_context_properties contextProperties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)firstPlatformId, 0}; + localContext->m_deviceContext = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU, 0, 0, &errorNumber); + if (errorNumber != CL_SUCCESS) { + localContext->m_deviceContext = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_CPU, 0, 0, &errorNumber); + if (errorNumber != CL_SUCCESS) + return 0; + } + + errorNumber = clGetContextInfo(localContext->m_deviceContext, CL_CONTEXT_DEVICES, 0, 0, &deviceBufferSize); + if (errorNumber != CL_SUCCESS) + return 0; + + if (!deviceBufferSize) + return 0; + + devices = reinterpret_cast<cl_device_id*>(fastMalloc(deviceBufferSize)); + errorNumber = clGetContextInfo(localContext->m_deviceContext, CL_CONTEXT_DEVICES, deviceBufferSize, devices, 0); + if (errorNumber != CL_SUCCESS) + return 0; + + localContext->m_commandQueue = clCreateCommandQueue(localContext->m_deviceContext, devices[0], 0, 0); + if (!localContext->m_commandQueue) + return 0; + + localContext->m_deviceId = devices[0]; + fastFree(devices); + + cl_bool imageSupport = CL_FALSE; + clGetDeviceInfo(localContext->m_deviceId, CL_DEVICE_IMAGE_SUPPORT, sizeof(cl_bool), &imageSupport, 0); + if (imageSupport != CL_TRUE) + return 0; + + m_context = localContext; + return m_context; +} + +OpenCLHandle FilterContextOpenCL::createOpenCLImage(IntSize paintSize) +{ + FilterContextOpenCL* context = FilterContextOpenCL::context(); + + cl_image_format clImageFormat; + clImageFormat.image_channel_order = CL_RGBA; + clImageFormat.image_channel_data_type = CL_UNORM_INT8; + + OpenCLHandle image = clCreateImage2D(context->deviceContext(), CL_MEM_READ_WRITE, &clImageFormat, + paintSize.width(), paintSize.height(), 0, 0, 0); + return image; +} + +static const char* transformColorSpaceKernelProgram = +PROGRAM_STR( +const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST; + +__kernel void transformColorSpace(__read_only image2d_t source, __write_only image2d_t destination, __constant float *clLookUpTable) +{ + int2 sourceCoord = (int2) (get_global_id(0), get_global_id(1)); + float4 pixel = read_imagef(source, sampler, sourceCoord); + + pixel = (float4)(clLookUpTable[(int)(round(pixel.x * 255))], clLookUpTable[(int)(round(pixel.y * 255))], + clLookUpTable[(int)(round(pixel.z * 255))], pixel.w); + + write_imagef(destination, sourceCoord, pixel); +} +); + +void FilterContextOpenCL::openCLTransformColorSpace(OpenCLHandle& source, IntRect sourceSize, ColorSpace srcColorSpace, ColorSpace dstColorSpace) +{ + DEFINE_STATIC_LOCAL(OpenCLHandle, deviceRgbLUT, ()); + DEFINE_STATIC_LOCAL(OpenCLHandle, linearRgbLUT, ()); + + if (srcColorSpace == dstColorSpace) + return; + + if ((srcColorSpace != ColorSpaceLinearRGB && srcColorSpace != ColorSpaceDeviceRGB) + || (dstColorSpace != ColorSpaceLinearRGB && dstColorSpace != ColorSpaceDeviceRGB)) + return; + + FilterContextOpenCL* context = FilterContextOpenCL::context(); + ASSERT(context); + + OpenCLHandle destination = context->createOpenCLImage(sourceSize.size()); + + if (!m_transformColorSpaceProgram) { + m_transformColorSpaceProgram = compileProgram(transformColorSpaceKernelProgram); + ASSERT(m_transformColorSpaceProgram); + m_transformColorSpaceKernel = kernelByName(m_transformColorSpaceProgram, "transformColorSpace"); + ASSERT(m_transformColorSpaceKernel); + } + + RunKernel kernel(context, m_transformColorSpaceKernel, sourceSize.width(), sourceSize.height()); + kernel.addArgument(source); + kernel.addArgument(destination); + + if (dstColorSpace == ColorSpaceLinearRGB) { + if (!linearRgbLUT) { + Vector<float> lookUpTable; + for (unsigned i = 0; i < 256; i++) { + float color = i / 255.0f; + color = (color <= 0.04045f ? color / 12.92f : pow((color + 0.055f) / 1.055f, 2.4f)); + color = std::max(0.0f, color); + color = std::min(1.0f, color); + lookUpTable.append((round(color * 255)) / 255); + } + linearRgbLUT = kernel.addArgument(lookUpTable.data(), sizeof(float) * 256); + } else + kernel.addArgument(linearRgbLUT); + } else if (dstColorSpace == ColorSpaceDeviceRGB) { + if (!deviceRgbLUT) { + Vector<float> lookUpTable; + for (unsigned i = 0; i < 256; i++) { + float color = i / 255.0f; + color = (powf(color, 1.0f / 2.4f) * 1.055f) - 0.055f; + color = std::max(0.0f, color); + color = std::min(1.0f, color); + lookUpTable.append((round(color * 255)) / 255); + } + deviceRgbLUT = kernel.addArgument(lookUpTable.data(), sizeof(float) * 256); + } else + kernel.addArgument(deviceRgbLUT); + } + + kernel.run(); + source.clear(); + source = destination; +} + +cl_program FilterContextOpenCL::compileProgram(const char* source) +{ + cl_program program; + cl_int errorNumber; + + FilterContextOpenCL* context = FilterContextOpenCL::context(); + ASSERT(context); + + program = clCreateProgramWithSource(context->m_deviceContext, 1, (const char**) &source, 0, 0); + errorNumber = clBuildProgram(program, 0, 0, 0, 0, 0); + if (errorNumber) + return 0; + + return program; +} +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/graphics/gpu/opencl/FilterContextOpenCL.h b/Source/WebCore/platform/graphics/gpu/opencl/FilterContextOpenCL.h new file mode 100644 index 000000000..d4fbf3a47 --- /dev/null +++ b/Source/WebCore/platform/graphics/gpu/opencl/FilterContextOpenCL.h @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2012 University of Szeged + * Copyright (C) 2012 Tamas Czene <tczene@inf.u-szeged.hu> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef FilterContextOpenCL_h +#define FilterContextOpenCL_h + +#if ENABLE(OPENCL) +#include "CL/cl.h" +#include "Color.h" +#include "ColorSpace.h" +#include "IntRect.h" +#include "IntSize.h" +#include "OpenCLHandle.h" + +#define PROGRAM_STR(...) #__VA_ARGS__ +#define PROGRAM(...) PROGRAM_STR(__VA_ARGS__) + +namespace WebCore { + +class FilterContextOpenCL { +public: + FilterContextOpenCL() + : m_deviceId(0) + , m_deviceContext(0) + , m_commandQueue(0) + , m_transformColorSpaceProgram(0) + , m_transformColorSpaceKernel(0) + , m_turbulenceCompileStatus(openclNotCompiledYet) + , m_turbulenceProgram(0) + , m_turbulenceOperation(0) + { + } + + // Returns 0 if initialization failed. + static FilterContextOpenCL* context(); + + cl_device_id deviceId() { return m_deviceId; } + cl_context deviceContext() { return m_deviceContext; } + cl_command_queue commandQueue() { return m_commandQueue; } + + OpenCLHandle createOpenCLImage(IntSize); + void openCLTransformColorSpace(OpenCLHandle&, IntRect, ColorSpace, ColorSpace); + + inline bool compileFETurbulence(); + + inline void applyFETurbulence(OpenCLHandle, IntSize, int, void*, void*, void*, void*, void*, + void*, int, int, int, int, float, float, bool, int, int); + +private: + + class RunKernel { + public: + RunKernel(FilterContextOpenCL* context, cl_kernel kernel, size_t width, size_t height) + : m_context(context) + , m_kernel(kernel) + , index(0) + { + m_globalSize[0] = width; + m_globalSize[1] = height; + } + + void addArgument(OpenCLHandle handle) + { + clSetKernelArg(m_kernel, index++, sizeof(OpenCLHandle), handle.handleAddress()); + } + + void addArgument(cl_int value) + { + clSetKernelArg(m_kernel, index++, sizeof(cl_int), reinterpret_cast<void*>(&value)); + } + + void addArgument(cl_float value) + { + clSetKernelArg(m_kernel, index++, sizeof(cl_float), reinterpret_cast<void*>(&value)); + } + + void addArgument(cl_sampler handle) + { + clSetKernelArg(m_kernel, index++, sizeof(cl_sampler), reinterpret_cast<void*>(&handle)); + } + + OpenCLHandle addArgument(void* buffer, int size) + { + OpenCLHandle handle(clCreateBuffer(m_context->deviceContext(), CL_MEM_READ_ONLY, size, 0, 0)); + clEnqueueWriteBuffer(m_context->commandQueue(), handle, CL_TRUE, 0, size, buffer, 0, 0, 0); + clSetKernelArg(m_kernel, index++, sizeof(OpenCLHandle), handle.handleAddress()); + return handle; + } + + void run() + { + clFinish(m_context->m_commandQueue); + clEnqueueNDRangeKernel(m_context->m_commandQueue, m_kernel, 2, 0, m_globalSize, 0, 0, 0, 0); + } + + FilterContextOpenCL* m_context; + cl_kernel m_kernel; + size_t m_globalSize[2]; + int index; + }; + + enum OpenCLCompileStatus { + openclNotCompiledYet, + openclCompileFailed, + openclCompileSuccessful + }; + + static cl_program compileProgram(const char*); + static inline cl_kernel kernelByName(cl_program program, const char* name) { return clCreateKernel(program, name, 0); } + + static FilterContextOpenCL* m_context; + static int m_alreadyInitialized; + + cl_device_id m_deviceId; + cl_context m_deviceContext; + cl_command_queue m_commandQueue; + + cl_program m_transformColorSpaceProgram; + cl_kernel m_transformColorSpaceKernel; + + OpenCLCompileStatus m_turbulenceCompileStatus; + cl_program m_turbulenceProgram; + cl_kernel m_turbulenceOperation; +}; + +} // namespace WebCore + +#endif // ENABLE(OPENCL) + +#endif diff --git a/Source/WebCore/platform/graphics/gpu/opencl/OpenCLFESourceAlpha.cpp b/Source/WebCore/platform/graphics/gpu/opencl/OpenCLFESourceAlpha.cpp new file mode 100644 index 000000000..ab93d072f --- /dev/null +++ b/Source/WebCore/platform/graphics/gpu/opencl/OpenCLFESourceAlpha.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2012 University of Szeged + * Copyright (C) 2012 Tamas Czene <tczene@inf.u-szeged.hu> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(FILTERS) && ENABLE(OPENCL) +#include "SourceAlpha.h" + +#include "Filter.h" +#include "FilterContextOpenCL.h" +#include "ImageBuffer.h" + +namespace WebCore { + +bool SourceAlpha::platformApplyOpenCL() +{ + FilterContextOpenCL* context = FilterContextOpenCL::context(); + + if (!context) + return false; + + platformApplySoftware(); + ImageBuffer* sourceImage = asImageBuffer(); + if (!sourceImage) + return false; + + RefPtr<Uint8ClampedArray> sourceImageData = sourceImage->getUnmultipliedImageData(IntRect(IntPoint(), sourceImage->internalSize())); + createOpenCLImageResult(sourceImageData->data()); + return true; +} + +} // namespace WebCore + +#endif // ENABLE(FILTERS) && ENABLE(OPENCL) diff --git a/Source/WebCore/platform/graphics/gpu/opencl/OpenCLFESourceGraphic.cpp b/Source/WebCore/platform/graphics/gpu/opencl/OpenCLFESourceGraphic.cpp new file mode 100644 index 000000000..b2e9ef792 --- /dev/null +++ b/Source/WebCore/platform/graphics/gpu/opencl/OpenCLFESourceGraphic.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2012 University of Szeged + * Copyright (C) 2012 Tamas Czene <tczene@inf.u-szeged.hu> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(FILTERS) && ENABLE(OPENCL) +#include "SourceGraphic.h" + +#include "Filter.h" +#include "FilterContextOpenCL.h" +#include "ImageBuffer.h" + +namespace WebCore { + +bool SourceGraphic::platformApplyOpenCL() +{ + FilterContextOpenCL* context = FilterContextOpenCL::context(); + + if (!context) + return false; + + platformApplySoftware(); + ImageBuffer* sourceImage = asImageBuffer(); + if (!sourceImage) + return false; + + RefPtr<Uint8ClampedArray> sourceImageData = sourceImage->getUnmultipliedImageData(IntRect(IntPoint(), sourceImage->internalSize())); + createOpenCLImageResult(sourceImageData->data()); + return true; +} + +} // namespace WebCore + +#endif // ENABLE(FILTERS) && ENABLE(OPENCL) diff --git a/Source/WebCore/platform/graphics/gpu/opencl/OpenCLFETurbulence.cpp b/Source/WebCore/platform/graphics/gpu/opencl/OpenCLFETurbulence.cpp new file mode 100644 index 000000000..7ebc6074d --- /dev/null +++ b/Source/WebCore/platform/graphics/gpu/opencl/OpenCLFETurbulence.cpp @@ -0,0 +1,248 @@ +/* + * Copyright (C) 2012 University of Szeged + * Copyright (C) 2012 Tamas Czene <tczene@inf.u-szeged.hu> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "config.h" + +#if ENABLE(FILTERS) && ENABLE(OPENCL) +#include "FETurbulence.h" + +#include "FETurbulence.cpp" +#include "FilterContextOpenCL.h" +#include "SVGFilter.h" + +namespace WebCore { + +static const char* turbulenceKernelProgram = +PROGRAM_STR( +__constant int s_perlinNoise = 4096; +__constant int s_blockSize = 256; +__constant int s_blockMask = 255; + +typedef struct { + int noisePositionIntegerValue; + float noisePositionFractionValue; +} Noise; + +typedef struct { + int width; + int wrapX; + int height; + int wrapY; +} StitchData; + +float linearInterpolation(float t, float a, float b) +{ + return mad(b - a, t, a); +} + +float noise2D(__constant float *component, __constant int *latticeSelector, StitchData stitchData, float noiseVectorX, float noiseVectorY, int stitchTiles) +{ + Noise noiseX; + noiseX.noisePositionIntegerValue = (int)(noiseVectorX + s_perlinNoise); + noiseX.noisePositionFractionValue = (noiseVectorX + s_perlinNoise) - noiseX.noisePositionIntegerValue; + Noise noiseY; + noiseY.noisePositionIntegerValue = (int)(noiseVectorY + s_perlinNoise); + noiseY.noisePositionFractionValue = (noiseVectorY + s_perlinNoise) - noiseY.noisePositionIntegerValue; + + // If stitching, adjust lattice points accordingly. + if (stitchTiles) { + if (noiseX.noisePositionIntegerValue >= stitchData.wrapX) + noiseX.noisePositionIntegerValue -= stitchData.width; + if (noiseX.noisePositionIntegerValue >= stitchData.wrapX - 1) + noiseX.noisePositionIntegerValue -= stitchData.width - 1; + if (noiseY.noisePositionIntegerValue >= stitchData.wrapY) + noiseY.noisePositionIntegerValue -= stitchData.height; + if (noiseY.noisePositionIntegerValue >= stitchData.wrapY - 1) + noiseY.noisePositionIntegerValue -= stitchData.height - 1; + } + + noiseX.noisePositionIntegerValue &= s_blockMask; + noiseY.noisePositionIntegerValue &= s_blockMask; + int latticeIndex = latticeSelector[noiseX.noisePositionIntegerValue]; + int nextLatticeIndex = latticeSelector[(noiseX.noisePositionIntegerValue + 1) & s_blockMask]; + + float sx = noiseX.noisePositionFractionValue * noiseX.noisePositionFractionValue * (3 - 2 * noiseX.noisePositionFractionValue); + float sy = noiseY.noisePositionFractionValue * noiseY.noisePositionFractionValue * (3 - 2 * noiseY.noisePositionFractionValue); + + // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement. + int temp = latticeSelector[latticeIndex + noiseY.noisePositionIntegerValue]; + float u = noiseX.noisePositionFractionValue * component[temp * 2] + noiseY.noisePositionFractionValue * component[temp * 2 + 1]; + temp = latticeSelector[nextLatticeIndex + noiseY.noisePositionIntegerValue]; + float v = (noiseX.noisePositionFractionValue - 1) * component[temp * 2] + noiseY.noisePositionFractionValue * component[temp * 2 + 1]; + float a = linearInterpolation(sx, u, v); + temp = latticeSelector[latticeIndex + noiseY.noisePositionIntegerValue + 1]; + u = noiseX.noisePositionFractionValue * component[temp * 2] + (noiseY.noisePositionFractionValue - 1) * component[temp * 2 + 1]; + temp = latticeSelector[nextLatticeIndex + noiseY.noisePositionIntegerValue + 1]; + v = (noiseX.noisePositionFractionValue - 1) * component[temp * 2] + (noiseY.noisePositionFractionValue - 1) * component[temp * 2 + 1]; + float b = linearInterpolation(sx, u, v); + return linearInterpolation(sy, a, b); +} + +__kernel void Turbulence(__write_only image2d_t destination, __constant float *transform, __constant float *redComponent, + __constant float *greenComponent, __constant float *blueComponent, __constant float *alphaComponent, + __constant int *latticeSelector, __private int offsetX, __private int offsetY, __private int tileWidth, + __private int tileHeight, __private float baseFrequencyX, __private float baseFrequencyY, __private int stitchTiles, + __private int numOctaves, __private int type, __private int filter_height) +{ + StitchData stitchData = { 0, 0, 0, 0 }; + // Adjust the base frequencies if necessary for stitching. + if (stitchTiles) { + // When stitching tiled turbulence, the frequencies must be adjusted + // so that the tile borders will be continuous. + if (baseFrequencyX) { + float lowFrequency = floor(tileWidth * baseFrequencyX) / tileWidth; + float highFrequency = ceil(tileWidth * baseFrequencyX) / tileWidth; + // BaseFrequency should be non-negative according to the standard. + baseFrequencyX = (baseFrequencyX / lowFrequency < highFrequency / baseFrequencyX) ? lowFrequency : highFrequency; + } + if (baseFrequencyY) { + float lowFrequency = floor(tileHeight * baseFrequencyY) / tileHeight; + float highFrequency = ceil(tileHeight * baseFrequencyY) / tileHeight; + baseFrequencyY = (baseFrequencyY / lowFrequency < highFrequency / baseFrequencyY) ? lowFrequency : highFrequency; + } + // Set up TurbulenceInitial stitch values. + stitchData.width = round(tileWidth * baseFrequencyX); + stitchData.wrapX = s_perlinNoise + stitchData.width; + stitchData.height = round(tileHeight * baseFrequencyY); + stitchData.wrapY = s_perlinNoise + stitchData.height; + } + float4 turbulenceFunctionResult = (float4)(0, 0, 0, 0); + float x = (get_global_id(0) + offsetX) * baseFrequencyX; + float y = (get_global_id(1) + offsetY) * baseFrequencyY; + + float noiseVectorX = transform[0] * x + transform[2] * y + transform[4]; + float noiseVectorY = transform[1] * x + transform[3] * y + transform[5]; + + float ratio = 1; + for (int octave = 0; octave < numOctaves; ++octave) { + float4 noise2DResult = (float4)( noise2D(redComponent, latticeSelector, stitchData, noiseVectorX, noiseVectorY, stitchTiles) / ratio, + noise2D(greenComponent, latticeSelector, stitchData, noiseVectorX, noiseVectorY, stitchTiles) / ratio, + noise2D(blueComponent, latticeSelector, stitchData, noiseVectorX, noiseVectorY, stitchTiles) / ratio, + noise2D(alphaComponent, latticeSelector, stitchData, noiseVectorX, noiseVectorY, stitchTiles) / ratio); + + turbulenceFunctionResult += (type == 1) ? noise2DResult : fabs(noise2DResult); + + noiseVectorX *= 2; + noiseVectorY *= 2; + ratio *= 2; + if (stitchTiles) { + // Update stitch values. Subtracting s_perlinNoiseoise before the multiplication and + // adding it afterward simplifies to subtracting it once. + stitchData.width *= 2; + stitchData.wrapX = 2 * stitchData.wrapX - s_perlinNoise; + stitchData.height *= 2; + stitchData.wrapY = 2 * stitchData.wrapY - s_perlinNoise; + } + } + + if (type == 1) + turbulenceFunctionResult = mad(0.5f, turbulenceFunctionResult, 0.5f); + // Clamp result. + turbulenceFunctionResult = clamp(turbulenceFunctionResult, 0.0f, 1.0f); + + write_imagef(destination, (int2)(get_global_id(0), get_global_id(1)), turbulenceFunctionResult); +} +); + +inline bool FilterContextOpenCL::compileFETurbulence() +{ + if (m_turbulenceCompileStatus != openclNotCompiledYet) + return m_turbulenceCompileStatus == openclCompileSuccessful; + + m_turbulenceCompileStatus = openclCompileFailed; + m_turbulenceProgram = compileProgram(turbulenceKernelProgram); + if (!m_turbulenceProgram) + return false; + m_turbulenceOperation = kernelByName(m_turbulenceProgram, "Turbulence"); + if (!m_turbulenceOperation) + return false; + + m_turbulenceCompileStatus = openclCompileSuccessful; + return openclCompileFailed; +} + +inline void FilterContextOpenCL::applyFETurbulence(OpenCLHandle destination, + IntSize destinationSize, int blockSize, + void* transform, void* redComponent, void* greenComponent, + void* blueComponent, void* alphaComponent, + void* latticeSelector, int offsetX, int offsetY, int tileWidth, int tileHeight, + float baseFrequencyX, float baseFrequencyY, bool stitchTiles, int numOctaves, int type) +{ + RunKernel kernel(this, m_turbulenceOperation, destinationSize.width(), destinationSize.height()); + + kernel.addArgument(destination); + OpenCLHandle transformHandle(kernel.addArgument(transform, sizeof(float) * 6)); + OpenCLHandle redComponentHandle(kernel.addArgument(redComponent, sizeof(float) * (2 * blockSize + 2) * 2)); + OpenCLHandle greenComponentHandle(kernel.addArgument(greenComponent, sizeof(float) * (2 * blockSize + 2) * 2)); + OpenCLHandle blueComponentHandle(kernel.addArgument(blueComponent, sizeof(float) * (2 * blockSize + 2) * 2)); + OpenCLHandle alphaComponentHandle(kernel.addArgument(alphaComponent, sizeof(float) * (2 * blockSize + 2) * 2)); + OpenCLHandle latticeSelectorHandle(kernel.addArgument(latticeSelector, sizeof(int) * (2 * blockSize + 2))); + kernel.addArgument(offsetX); + kernel.addArgument(offsetY); + kernel.addArgument(tileWidth); + kernel.addArgument(tileHeight); + kernel.addArgument(baseFrequencyX); + kernel.addArgument(baseFrequencyY); + kernel.addArgument(stitchTiles); + kernel.addArgument(numOctaves); + kernel.addArgument(type); + kernel.addArgument(destinationSize.height()); + + kernel.run(); + + transformHandle.clear(); + redComponentHandle.clear(); + greenComponentHandle.clear(); + blueComponentHandle.clear(); + alphaComponentHandle.clear(); + latticeSelectorHandle.clear(); +} + +bool FETurbulence::platformApplyOpenCL() +{ + FilterContextOpenCL* context = FilterContextOpenCL::context(); + if (!context || !context->compileFETurbulence()) + return false; + + OpenCLHandle destination = createOpenCLImageResult(); + + PaintingData paintingData(m_seed, roundedIntSize(filterPrimitiveSubregion().size())); + initPaint(paintingData); + + AffineTransform invertedTransform = reinterpret_cast<SVGFilter*>(filter())->absoluteTransform().inverse(); + float transformComponents[6] = { invertedTransform.a(), invertedTransform.b(), invertedTransform.c(), invertedTransform.d(), invertedTransform.e(), invertedTransform.f() }; + + context->applyFETurbulence(destination, absolutePaintRect().size(), s_blockSize, transformComponents, paintingData.gradient, + paintingData.gradient + 1, paintingData.gradient + 2, paintingData.gradient + 3, paintingData.latticeSelector, + absolutePaintRect().x(), absolutePaintRect().y(), paintingData.filterSize.width(), paintingData.filterSize.height(), + m_baseFrequencyX, m_baseFrequencyY, m_stitchTiles, m_numOctaves, m_type); + + return true; +} + +} // namespace WebCore + +#endif // ENABLE(FILTERS) && ENABLE(OPENCL) diff --git a/Source/WebCore/platform/graphics/gpu/opencl/OpenCLHandle.h b/Source/WebCore/platform/graphics/gpu/opencl/OpenCLHandle.h new file mode 100644 index 000000000..9f585dcf9 --- /dev/null +++ b/Source/WebCore/platform/graphics/gpu/opencl/OpenCLHandle.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2012 Tamas Czene <tczene@inf.u-szeged.hu> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ +#if ENABLE(OPENCL) + +#ifndef OpenCLHandle_h +#define OpenCLHandle_h + +#include "CL/cl.h" + +namespace WebCore { + +class OpenCLHandle { +public: + OpenCLHandle() : m_openCLMemory(0) { } + OpenCLHandle(cl_mem openCLMemory) : m_openCLMemory(openCLMemory) { } + + operator cl_mem() { return m_openCLMemory; } + + void operator=(OpenCLHandle openCLMemory) { m_openCLMemory = openCLMemory; } + + // This conversion operator allows implicit conversion to bool but not to other integer types. + typedef cl_mem (OpenCLHandle::*UnspecifiedBoolType); + operator UnspecifiedBoolType() const { return m_openCLMemory ? &OpenCLHandle::m_openCLMemory : 0; } + + void* handleAddress() { return reinterpret_cast<void*>(&m_openCLMemory); } + + void clear() + { + if (m_openCLMemory) + clReleaseMemObject(m_openCLMemory); + m_openCLMemory = 0; + } + +private: + cl_mem m_openCLMemory; +}; + +} + +#endif +#endif // ENABLE(OPENCL) diff --git a/Source/WebCore/platform/graphics/gstreamer/GStreamerUtilities.cpp b/Source/WebCore/platform/graphics/gstreamer/GStreamerUtilities.cpp index ac363a75d..1b5741e55 100644 --- a/Source/WebCore/platform/graphics/gstreamer/GStreamerUtilities.cpp +++ b/Source/WebCore/platform/graphics/gstreamer/GStreamerUtilities.cpp @@ -29,6 +29,11 @@ namespace WebCore { bool initializeGStreamer() { +#if GST_CHECK_VERSION(0, 10, 31) + if (gst_is_initialized()) + return true; +#endif + GOwnPtr<GError> error; // FIXME: We should probably pass the arguments from the command line. bool gstInitialized = gst_init_check(0, 0, &error.outPtr()); diff --git a/Source/WebCore/platform/graphics/gstreamer/GStreamerVersioning.cpp b/Source/WebCore/platform/graphics/gstreamer/GStreamerVersioning.cpp index 7158caf62..30f5d99ca 100644 --- a/Source/WebCore/platform/graphics/gstreamer/GStreamerVersioning.cpp +++ b/Source/WebCore/platform/graphics/gstreamer/GStreamerVersioning.cpp @@ -34,6 +34,23 @@ void webkitGstObjectRefSink(GstObject* gstObject) #endif } +GstPad* webkitGstGhostPadFromStaticTemplate(GstStaticPadTemplate* staticPadTemplate, const gchar* name, GstPad* target) +{ + GstPad* pad; + GstPadTemplate* padTemplate = gst_static_pad_template_get(staticPadTemplate); + + if (target) + pad = gst_ghost_pad_new_from_template(name, target, padTemplate); + else + pad = gst_ghost_pad_new_no_target_from_template(name, padTemplate); + +#ifdef GST_API_VERSION_1 + gst_object_unref(padTemplate); +#endif + + return pad; +} + GRefPtr<GstCaps> webkitGstGetPadCaps(GstPad* pad) { if (!pad) diff --git a/Source/WebCore/platform/graphics/gstreamer/GStreamerVersioning.h b/Source/WebCore/platform/graphics/gstreamer/GStreamerVersioning.h index 2ecf08cef..e5d8065ce 100644 --- a/Source/WebCore/platform/graphics/gstreamer/GStreamerVersioning.h +++ b/Source/WebCore/platform/graphics/gstreamer/GStreamerVersioning.h @@ -29,6 +29,7 @@ class IntSize; }; void webkitGstObjectRefSink(GstObject*); +GstPad* webkitGstGhostPadFromStaticTemplate(GstStaticPadTemplate*, const gchar* name, GstPad* target); GRefPtr<GstCaps> webkitGstGetPadCaps(GstPad*); bool getVideoSizeAndFormatFromCaps(GstCaps*, WebCore::IntSize&, GstVideoFormat&, int& pixelAspectRatioNumerator, int& pixelAspectRatioDenominator, int& stride); GstBuffer* createGstBuffer(GstBuffer*); diff --git a/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp b/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp index aebb3a732..f804d1f7e 100644 --- a/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp +++ b/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp @@ -217,7 +217,6 @@ static void webkit_web_src_class_init(WebKitWebSrcClass* klass) static void webkit_web_src_init(WebKitWebSrc* src) { - GRefPtr<GstPadTemplate> padTemplate = adoptGRef(gst_static_pad_template_get(&srcTemplate)); WebKitWebSrcPrivate* priv = WEBKIT_WEB_SRC_GET_PRIVATE(src); src->priv = priv; @@ -237,7 +236,7 @@ static void webkit_web_src_init(WebKitWebSrc* src) GRefPtr<GstPad> targetPad = adoptGRef(gst_element_get_static_pad(GST_ELEMENT(priv->appsrc), "src")); - priv->srcpad = gst_ghost_pad_new_from_template("src", targetPad.get(), padTemplate.get()); + priv->srcpad = webkitGstGhostPadFromStaticTemplate(&srcTemplate, "src", targetPad.get()); gst_element_add_pad(GST_ELEMENT(src), priv->srcpad); diff --git a/Source/WebCore/platform/graphics/mac/MediaPlayerPrivateQTKit.mm b/Source/WebCore/platform/graphics/mac/MediaPlayerPrivateQTKit.mm index c03eda9e4..4281b7eb6 100644 --- a/Source/WebCore/platform/graphics/mac/MediaPlayerPrivateQTKit.mm +++ b/Source/WebCore/platform/graphics/mac/MediaPlayerPrivateQTKit.mm @@ -43,7 +43,7 @@ #import "TimeRanges.h" #import "WebCoreSystemInterface.h" #import <QTKit/QTKit.h> -#import <objc/objc-runtime.h> +#import <objc/runtime.h> #import <wtf/UnusedParam.h> #if USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/mac/WebLayer.mm b/Source/WebCore/platform/graphics/mac/WebLayer.mm index ca4393d85..d868135ed 100644 --- a/Source/WebCore/platform/graphics/mac/WebLayer.mm +++ b/Source/WebCore/platform/graphics/mac/WebLayer.mm @@ -33,7 +33,7 @@ #import "GraphicsLayerCA.h" #import "PlatformCALayer.h" #import "ThemeMac.h" -#import <objc/objc-runtime.h> +#import <objc/runtime.h> #import <QuartzCore/QuartzCore.h> #import <wtf/UnusedParam.h> #import "WebCoreSystemInterface.h" diff --git a/Source/WebCore/platform/graphics/qt/GraphicsContext3DQt.cpp b/Source/WebCore/platform/graphics/qt/GraphicsContext3DQt.cpp index 1ead15d18..f2063cebc 100644 --- a/Source/WebCore/platform/graphics/qt/GraphicsContext3DQt.cpp +++ b/Source/WebCore/platform/graphics/qt/GraphicsContext3DQt.cpp @@ -108,17 +108,6 @@ GraphicsContext3DPrivate::GraphicsContext3DPrivate(GraphicsContext3D* context, H , m_platformContext(0) , m_surfaceOwner(0) { - if (m_hostWindow && m_hostWindow->platformPageClient()) { - // This is the WebKit1 code path. - QWebPageClient* webPageClient = m_hostWindow->platformPageClient(); - webPageClient->createPlatformGraphicsContext3D(&m_platformContext, &m_surface, &m_surfaceOwner); - if (!m_surface) - return; - - makeCurrentIfNeeded(); - return; - } - if (renderStyle == GraphicsContext3D::RenderToCurrentGLContext) { m_platformContext = QOpenGLContext::currentContext(); m_surface = m_platformContext->surface(); @@ -144,9 +133,8 @@ GraphicsContext3DPrivate::GraphicsContext3DPrivate(GraphicsContext3D* context, H m_surfaceFlags = GraphicsSurface::SupportsTextureTarget | GraphicsSurface::SupportsSharing; - if (!surfaceSize.isEmpty()) { + if (!surfaceSize.isEmpty()) m_graphicsSurface = GraphicsSurface::create(surfaceSize, m_surfaceFlags, m_platformContext); - } #endif } @@ -225,10 +213,24 @@ void GraphicsContext3DPrivate::paintToTextureMapper(TextureMapper* textureMapper blitMultisampleFramebufferAndRestoreContext(); if (textureMapper->accelerationMode() == TextureMapper::OpenGLMode) { +#if USE(GRAPHICS_SURFACE) + // CGL only provides us the context, but not the view the context is currently bound to. + // To make sure the context is bound the the right surface we have to do a makeCurrent through QOpenGL again. + // FIXME: Remove this code as soon as GraphicsSurfaceMac makes use of NSOpenGL. + QOpenGLContext* currentContext = QOpenGLContext::currentContext(); + QSurface* currentSurface = currentContext->surface(); + makeCurrentIfNeeded(); + + m_graphicsSurface->copyFromTexture(m_context->m_texture, IntRect(0, 0, m_context->m_currentWidth, m_context->m_currentHeight)); + + // CGL only provides us the context, but not the view the context is currently bound to. + // To make sure the context is bound the the right surface we have to do a makeCurrent through QOpenGL again. + // FIXME: Remove this code as soon as GraphicsSurfaceMac makes use of NSOpenGL. + currentContext->makeCurrent(currentSurface); + TextureMapperGL* texmapGL = static_cast<TextureMapperGL*>(textureMapper); - TextureMapperGL::Flags flags = TextureMapperGL::ShouldFlipTexture | (m_context->m_attrs.alpha ? TextureMapperGL::SupportsBlending : 0); - IntSize textureSize(m_context->m_currentWidth, m_context->m_currentHeight); - texmapGL->drawTexture(m_context->m_texture, flags, textureSize, targetRect, matrix, opacity, mask); + m_graphicsSurface->paintToTextureMapper(texmapGL, targetRect, matrix, opacity, mask); +#endif return; } @@ -289,10 +291,8 @@ uint32_t GraphicsContext3DPrivate::copyToGraphicsSurface() return 0; blitMultisampleFramebufferAndRestoreContext(); - makeCurrentIfNeeded(); m_graphicsSurface->copyFromTexture(m_context->m_texture, IntRect(0, 0, m_context->m_currentWidth, m_context->m_currentHeight)); - uint32_t frontBuffer = m_graphicsSurface->swapBuffers(); - return frontBuffer; + return m_graphicsSurface->frontBuffer(); } GraphicsSurfaceToken GraphicsContext3DPrivate::graphicsSurfaceToken() const diff --git a/Source/WebCore/platform/graphics/qt/IconQt.cpp b/Source/WebCore/platform/graphics/qt/IconQt.cpp index adc3bdbdd..b6cc6126d 100644 --- a/Source/WebCore/platform/graphics/qt/IconQt.cpp +++ b/Source/WebCore/platform/graphics/qt/IconQt.cpp @@ -24,6 +24,7 @@ #include "GraphicsContext.h" #include "IntRect.h" #include "NotImplemented.h" +#include <QMimeDatabase> #include <wtf/text/WTFString.h> namespace WebCore { @@ -37,16 +38,49 @@ Icon::~Icon() } // FIXME: Move the code to ChromeClient::iconForFiles(). -PassRefPtr<Icon> Icon::createIconForFiles(const Vector<String>&) +PassRefPtr<Icon> Icon::createIconForFiles(const Vector<String>& filenames) { - // FIXME: Should use QMimeType in Qt 5. - notImplemented(); - return 0; + if (filenames.isEmpty()) + return 0; + + QMimeType mimeType = QMimeDatabase().mimeTypeForFile(filenames[0], QMimeDatabase::MatchExtension); + + QString iconName = mimeType.iconName(); + QString genericIconName = mimeType.genericIconName(); + + // We try to match one of three cases: + // 1. All the files have the same type. + // 2. All the files are of the same generic type. + // 3. The files are not even of the same generic type. + const int count = filenames.size(); + for (int i = 1; i < count; ++i) { + mimeType = QMimeDatabase().mimeTypeForFile(filenames[i], QMimeDatabase::MatchExtension); + if (iconName != mimeType.iconName()) + iconName.clear(); + if (genericIconName != mimeType.genericIconName()) { + genericIconName.clear(); + break; + } + } + + // FIXME: By default, only X11 will support themed icons. + RefPtr<Icon> icon = adoptRef(new Icon); + if (!iconName.isEmpty()) + icon->m_icon = QIcon::fromTheme(iconName, QIcon::fromTheme(genericIconName)); + else if (!genericIconName.isEmpty()) + icon->m_icon = QIcon::fromTheme(genericIconName); + + if (icon->m_icon.isNull()) + return 0; + return icon.release(); } -void Icon::paint(GraphicsContext*, const IntRect&) +void Icon::paint(GraphicsContext* context, const IntRect& rect) { - notImplemented(); + if (m_icon.isNull()) + return; + + m_icon.paint(context->platformContext(), rect); } } diff --git a/Source/WebCore/platform/graphics/skia/ImageBufferSkia.cpp b/Source/WebCore/platform/graphics/skia/ImageBufferSkia.cpp index 17e91db7e..8b788650d 100644 --- a/Source/WebCore/platform/graphics/skia/ImageBufferSkia.cpp +++ b/Source/WebCore/platform/graphics/skia/ImageBufferSkia.cpp @@ -79,7 +79,6 @@ static SkCanvas* createAcceleratedCanvas(const IntSize& size, ImageBufferData* d GrContext* gr = context3D->grContext(); if (!gr) return 0; - context3D->getExtensions()->pushGroupMarkerEXT("AcceleratedCanvasContext"); gr->resetContext(); GrTextureDesc desc; desc.fFlags = kRenderTarget_GrTextureFlagBit; diff --git a/Source/WebCore/platform/graphics/skia/SkiaFontWin.cpp b/Source/WebCore/platform/graphics/skia/SkiaFontWin.cpp index b8a0550ad..104d82457 100644 --- a/Source/WebCore/platform/graphics/skia/SkiaFontWin.cpp +++ b/Source/WebCore/platform/graphics/skia/SkiaFontWin.cpp @@ -32,10 +32,10 @@ #include "SkiaFontWin.h" #include "AffineTransform.h" +#include "FontPlatformDataChromiumWin.h" #include "Gradient.h" #include "Pattern.h" #include "PlatformContextSkia.h" -#include "PlatformSupport.h" #include "SimpleFontData.h" #include "SkCanvas.h" #include "SkDevice.h" @@ -221,7 +221,7 @@ static void paintSkiaText(GraphicsContext* context, HFONT hfont, TextDrawingModeFlags textMode = platformContext->getTextDrawingMode(); // Ensure font load for printing, because PDF device needs it. if (platformContext->isVector()) - PlatformSupport::ensureFontLoaded(hfont); + FontPlatformData::ensureFontLoaded(hfont); // Filling (if necessary). This is the common case. SkPaint paint; diff --git a/Source/WebCore/platform/graphics/surfaces/GraphicsSurface.cpp b/Source/WebCore/platform/graphics/surfaces/GraphicsSurface.cpp index d966dc516..0a115f02c 100644 --- a/Source/WebCore/platform/graphics/surfaces/GraphicsSurface.cpp +++ b/Source/WebCore/platform/graphics/surfaces/GraphicsSurface.cpp @@ -78,9 +78,13 @@ uint32_t GraphicsSurface::swapBuffers() return platformSwapBuffers(); } +IntSize GraphicsSurface::size() const +{ + return platformSize(); +} + GraphicsSurface::GraphicsSurface(const IntSize& size, Flags flags) : m_flags(flags) - , m_size(size) , m_platformSurface(0) , m_texture(0) , m_fbo(0) diff --git a/Source/WebCore/platform/graphics/surfaces/GraphicsSurface.h b/Source/WebCore/platform/graphics/surfaces/GraphicsSurface.h index 5602cf521..549e804c4 100644 --- a/Source/WebCore/platform/graphics/surfaces/GraphicsSurface.h +++ b/Source/WebCore/platform/graphics/surfaces/GraphicsSurface.h @@ -74,7 +74,7 @@ public: Flags flags() const { return m_flags; } PlatformGraphicsSurface platformSurface() const { return m_platformSurface; } - IntSize size() const { return m_size; } + IntSize size() const; static PassRefPtr<GraphicsSurface> create(const IntSize&, Flags, const PlatformGraphicsContext3D shareContext = 0); static PassRefPtr<GraphicsSurface> create(const IntSize&, Flags, const GraphicsSurfaceToken&); @@ -103,6 +103,7 @@ protected: void platformPaintToTextureMapper(TextureMapper*, const FloatRect& targetRect, const TransformationMatrix&, float opacity, BitmapTexture* mask); uint32_t platformFrontBuffer() const; uint32_t platformSwapBuffers(); + IntSize platformSize() const; PassOwnPtr<GraphicsContext> platformBeginPaint(const IntSize&, char* bits, int stride); @@ -118,7 +119,6 @@ private: #endif private: - IntSize m_size; PlatformGraphicsSurface m_platformSurface; uint32_t m_texture; uint32_t m_fbo; diff --git a/Source/WebCore/platform/graphics/surfaces/mac/GraphicsSurfaceMac.cpp b/Source/WebCore/platform/graphics/surfaces/mac/GraphicsSurfaceMac.cpp index 8597eb4e2..5dfc8c55f 100644 --- a/Source/WebCore/platform/graphics/surfaces/mac/GraphicsSurfaceMac.cpp +++ b/Source/WebCore/platform/graphics/surfaces/mac/GraphicsSurfaceMac.cpp @@ -72,11 +72,14 @@ static uint32_t createTexture(IOSurfaceRef handle) struct GraphicsSurfacePrivate { public: - GraphicsSurfacePrivate(const GraphicsSurfaceToken& token) + GraphicsSurfacePrivate(const GraphicsSurfaceToken& token, const IntSize& size) : m_context(0) + , m_size(size) , m_token(token) , m_frontBufferTexture(0) + , m_frontBufferReadTexture(0) , m_backBufferTexture(0) + , m_backBufferReadTexture(0) , m_readFbo(0) , m_drawFbo(0) { @@ -86,8 +89,11 @@ public: GraphicsSurfacePrivate(const PlatformGraphicsContext3D shareContext, const IntSize& size, GraphicsSurface::Flags flags) : m_context(0) + , m_size(size) , m_frontBufferTexture(0) + , m_frontBufferReadTexture(0) , m_backBufferTexture(0) + , m_backBufferReadTexture(0) , m_readFbo(0) , m_drawFbo(0) { @@ -106,8 +112,8 @@ public: unsigned pixelFormat = 'BGRA'; unsigned bytesPerElement = 4; - int width = size.width(); - int height = size.height(); + int width = m_size.width(); + int height = m_size.height(); unsigned long bytesPerRow = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, width * bytesPerElement); if (!bytesPerRow) @@ -150,9 +156,15 @@ public: if (m_frontBufferTexture) glDeleteTextures(1, &m_frontBufferTexture); + if (m_frontBufferReadTexture) + glDeleteTextures(1, &m_frontBufferReadTexture); + if (m_backBufferTexture) glDeleteTextures(1, &m_backBufferTexture); + if (m_backBufferReadTexture) + glDeleteTextures(1, &m_backBufferReadTexture); + if (m_frontBuffer) CFRelease(IOSurfaceRef(m_frontBuffer)); @@ -179,6 +191,7 @@ public: { std::swap(m_frontBuffer, m_backBuffer); std::swap(m_frontBufferTexture, m_backBufferTexture); + std::swap(m_frontBufferReadTexture, m_backBufferReadTexture); return IOSurfaceGetID(m_frontBuffer); } @@ -235,6 +248,7 @@ public: // Flushing the gl command buffer is necessary to ensure the texture has correctly been bound to the IOSurface. glFlush(); + swapBuffers(); doneCurrent(); } @@ -245,10 +259,10 @@ public: uint32_t frontBufferTextureID() { - if (!m_frontBufferTexture) - m_frontBufferTexture = createTexture(m_frontBuffer); + if (!m_frontBufferReadTexture) + m_frontBufferReadTexture = createTexture(m_frontBuffer); - return m_frontBufferTexture; + return m_frontBufferReadTexture; } uint32_t backBufferTextureID() @@ -269,13 +283,21 @@ public: return m_backBuffer; } + IntSize size() const + { + return m_size; + } + private: CGLContextObj m_context; + IntSize m_size; CGLContextObj m_detachedContext; PlatformGraphicsSurface m_frontBuffer; PlatformGraphicsSurface m_backBuffer; uint32_t m_frontBufferTexture; + uint32_t m_frontBufferReadTexture; uint32_t m_backBufferTexture; + uint32_t m_backBufferReadTexture; uint32_t m_readFbo; uint32_t m_drawFbo; GraphicsSurfaceToken m_token; @@ -322,8 +344,8 @@ void GraphicsSurface::platformCopyFromTexture(uint32_t texture, const IntRect& s void GraphicsSurface::platformPaintToTextureMapper(TextureMapper* textureMapper, const FloatRect& targetRect, const TransformationMatrix& transform, float opacity, BitmapTexture* mask) { TransformationMatrix adjustedTransform = transform; - adjustedTransform.multiply(TransformationMatrix::rectToRect(FloatRect(FloatPoint::zero(), m_size), targetRect)); - static_cast<TextureMapperGL*>(textureMapper)->drawTextureRectangleARB(m_private->frontBufferTextureID(), 0, m_size, targetRect, adjustedTransform, opacity, mask); + adjustedTransform.multiply(TransformationMatrix::rectToRect(FloatRect(FloatPoint::zero(), m_private->size()), targetRect)); + static_cast<TextureMapperGL*>(textureMapper)->drawTextureRectangleARB(m_private->frontBufferTextureID(), 0, m_private->size(), targetRect, adjustedTransform, opacity, mask); } uint32_t GraphicsSurface::platformFrontBuffer() const @@ -336,6 +358,11 @@ uint32_t GraphicsSurface::platformSwapBuffers() return m_private->swapBuffers(); } +IntSize GraphicsSurface::platformSize() const +{ + return m_private->size(); +} + PassRefPtr<GraphicsSurface> GraphicsSurface::platformCreate(const IntSize& size, Flags flags, const PlatformGraphicsContext3D shareContext) { // We currently disable support for CopyToTexture on Mac, because this is used for single buffered Tiles. @@ -362,7 +389,7 @@ PassRefPtr<GraphicsSurface> GraphicsSurface::platformImport(const IntSize& size, return PassRefPtr<GraphicsSurface>(); RefPtr<GraphicsSurface> surface = adoptRef(new GraphicsSurface(size, flags)); - surface->m_private = new GraphicsSurfacePrivate(token); + surface->m_private = new GraphicsSurfacePrivate(token, size); if (!surface->m_private->frontBuffer() || !surface->m_private->backBuffer()) return PassRefPtr<GraphicsSurface>(); diff --git a/Source/WebCore/platform/graphics/surfaces/qt/GraphicsSurfaceGLX.cpp b/Source/WebCore/platform/graphics/surfaces/qt/GraphicsSurfaceGLX.cpp index b96f08d51..01b72fbe0 100644 --- a/Source/WebCore/platform/graphics/surfaces/qt/GraphicsSurfaceGLX.cpp +++ b/Source/WebCore/platform/graphics/surfaces/qt/GraphicsSurfaceGLX.cpp @@ -138,7 +138,7 @@ static const int glxAttributes[] = { struct GraphicsSurfacePrivate { GraphicsSurfacePrivate(const PlatformGraphicsContext3D shareContext = 0) - : m_display(0) + : m_display(m_offScreenWindow.display()) , m_xPixmap(0) , m_glxPixmap(0) , m_surface(0) @@ -149,9 +149,9 @@ struct GraphicsSurfacePrivate { , m_fbConfig(0) , m_textureIsYInverted(false) , m_hasAlpha(false) + , m_isReceiver(false) { GLXContext shareContextObject = 0; - m_display = m_offScreenWindow.display(); #if PLATFORM(QT) if (shareContext) { @@ -199,6 +199,21 @@ struct GraphicsSurfacePrivate { m_glContext = glXCreateNewContext(m_display, m_fbConfig, GLX_RGBA_TYPE, shareContextObject, true); } + GraphicsSurfacePrivate(uint32_t winId) + : m_display(m_offScreenWindow.display()) + , m_xPixmap(0) + , m_glxPixmap(0) + , m_surface(winId) + , m_glxSurface(0) + , m_glContext(0) + , m_detachedContext(0) + , m_detachedSurface(0) + , m_fbConfig(0) + , m_textureIsYInverted(false) + , m_hasAlpha(false) + , m_isReceiver(true) + { } + ~GraphicsSurfacePrivate() { if (m_glxPixmap) @@ -249,7 +264,6 @@ struct GraphicsSurfacePrivate { XRenderPictFormat* format = XRenderFindVisualFormat(m_display, attr.visual); m_hasAlpha = (format->type == PictTypeDirect && format->direct.alphaMask); - m_size = IntSize(attr.width, attr.height); int numberOfConfigs; GLXFBConfig* configs = glXChooseFBConfig(m_display, XDefaultScreen(m_display), glxSpec, &numberOfConfigs); @@ -286,10 +300,9 @@ struct GraphicsSurfacePrivate { void swapBuffers() { - // If there is a xpixmap, we are on the reading side and do not want to swap any buffers. // The buffers are being switched on the writing side, the reading side just reads // whatever texture the XWindow contains. - if (m_xPixmap) + if (m_isReceiver) return; GLXContext glContext = glXGetCurrentContext(); @@ -330,14 +343,29 @@ struct GraphicsSurfacePrivate { pGlDeleteFramebuffers(1, &originFBO); glPopAttrib(); + + swapBuffers(); doneCurrent(); } Display* display() const { return m_display; } - GLXPixmap glxPixmap() const { return m_glxPixmap; } + GLXPixmap glxPixmap() const + { + if (!m_glxPixmap && m_surface) + const_cast<GraphicsSurfacePrivate*>(this)->createPixmap(m_surface); + return m_glxPixmap; + } - IntSize size() const { return m_size; } + IntSize size() const + { + if (m_size.isEmpty()) { + XWindowAttributes attr; + XGetWindowAttributes(m_display, m_surface, &attr); + const_cast<GraphicsSurfacePrivate*>(this)->m_size = IntSize(attr.width, attr.height); + } + return m_size; + } private: OffScreenRootWindow m_offScreenWindow; @@ -353,6 +381,7 @@ private: GLXFBConfig m_fbConfig; bool m_textureIsYInverted; bool m_hasAlpha; + bool m_isReceiver; }; static bool resolveGLMethods(GraphicsSurfacePrivate*) @@ -408,10 +437,10 @@ void GraphicsSurface::platformPaintToTextureMapper(TextureMapper* textureMapper, { TextureMapperGL* texMapGL = static_cast<TextureMapperGL*>(textureMapper); TransformationMatrix adjustedTransform = transform; - adjustedTransform.multiply(TransformationMatrix::rectToRect(FloatRect(FloatPoint::zero(), m_size), targetRect)); + adjustedTransform.multiply(TransformationMatrix::rectToRect(FloatRect(FloatPoint::zero(), m_private->size()), targetRect)); TextureMapperGL::Flags flags = m_private->textureIsYInverted() ? TextureMapperGL::ShouldFlipTexture : 0; flags |= TextureMapperGL::SupportsBlending; - texMapGL->drawTexture(platformGetTextureID(), flags, m_size, targetRect, adjustedTransform, opacity, mask); + texMapGL->drawTexture(platformGetTextureID(), flags, m_private->size(), targetRect, adjustedTransform, opacity, mask); } uint32_t GraphicsSurface::platformFrontBuffer() const @@ -425,6 +454,11 @@ uint32_t GraphicsSurface::platformSwapBuffers() return 0; } +IntSize GraphicsSurface::platformSize() const +{ + return m_private->size(); +} + PassRefPtr<GraphicsSurface> GraphicsSurface::platformCreate(const IntSize& size, Flags flags, const PlatformGraphicsContext3D shareContext) { // X11 does not support CopyToTexture, so we do not create a GraphicsSurface if this is requested. @@ -453,16 +487,12 @@ PassRefPtr<GraphicsSurface> GraphicsSurface::platformImport(const IntSize& size, return PassRefPtr<GraphicsSurface>(); RefPtr<GraphicsSurface> surface = adoptRef(new GraphicsSurface(size, flags)); + surface->m_platformSurface = token.frontBufferHandle; - surface->m_private = new GraphicsSurfacePrivate(); + surface->m_private = new GraphicsSurfacePrivate(surface->m_platformSurface); if (!resolveGLMethods(surface->m_private)) return PassRefPtr<GraphicsSurface>(); - surface->m_platformSurface = token.frontBufferHandle; - - surface->m_private->createPixmap(surface->m_platformSurface); - surface->m_size = surface->m_private->size(); - return surface; } diff --git a/Source/WebCore/platform/graphics/surfaces/win/GraphicsSurfaceWin.cpp b/Source/WebCore/platform/graphics/surfaces/win/GraphicsSurfaceWin.cpp index 19bebd2ff..b8586ac18 100644 --- a/Source/WebCore/platform/graphics/surfaces/win/GraphicsSurfaceWin.cpp +++ b/Source/WebCore/platform/graphics/surfaces/win/GraphicsSurfaceWin.cpp @@ -246,6 +246,10 @@ public: m_eglFrontBufferSurface = 0; } + IntSize size() const + { + return m_size; + } protected: void initializeShaderProgram() @@ -422,8 +426,8 @@ void GraphicsSurface::platformPaintToTextureMapper(TextureMapper* textureMapper, GLuint frontBufferTexture = platformGetTextureID(); TransformationMatrix adjustedTransform = transform; - adjustedTransform.multiply(TransformationMatrix::rectToRect(FloatRect(FloatPoint::zero(), m_size), targetRect)); - static_cast<TextureMapperGL*>(textureMapper)->drawTexture(frontBufferTexture, 0, m_size, targetRect, adjustedTransform, opacity, mask); + adjustedTransform.multiply(TransformationMatrix::rectToRect(FloatRect(FloatPoint::zero(), m_private->size()), targetRect)); + static_cast<TextureMapperGL*>(textureMapper)->drawTexture(frontBufferTexture, 0, m_private->size(), targetRect, adjustedTransform, opacity, mask); } uint32_t GraphicsSurface::platformFrontBuffer() const @@ -441,6 +445,11 @@ uint32_t GraphicsSurface::platformSwapBuffers() return platformFrontBuffer(); } +IntSize GraphicsSurface::platformSize() const +{ + return m_private->size(); +} + PassRefPtr<GraphicsSurface> GraphicsSurface::platformCreate(const IntSize& size, Flags flags, const PlatformGraphicsContext3D shareContext) { // Single buffered GraphicsSurface is currently not supported. diff --git a/Source/WebCore/platform/graphics/texmap/GraphicsLayerTextureMapper.cpp b/Source/WebCore/platform/graphics/texmap/GraphicsLayerTextureMapper.cpp index b47d08e7d..b1e9cb10d 100644 --- a/Source/WebCore/platform/graphics/texmap/GraphicsLayerTextureMapper.cpp +++ b/Source/WebCore/platform/graphics/texmap/GraphicsLayerTextureMapper.cpp @@ -90,6 +90,9 @@ void GraphicsLayerTextureMapper::willBeDestroyed() */ void GraphicsLayerTextureMapper::setNeedsDisplay() { + if (!m_hasOwnBackingStore) + return; + m_needsDisplay = true; notifyChange(TextureMapperLayer::DisplayChange); addRepaintRect(FloatRect(FloatPoint(), m_size)); @@ -107,6 +110,9 @@ void GraphicsLayerTextureMapper::setContentsNeedsDisplay() */ void GraphicsLayerTextureMapper::setNeedsDisplayInRect(const FloatRect& rect) { + if (!m_hasOwnBackingStore) + return; + if (m_needsDisplay) return; m_needsDisplayRect.unite(rect); @@ -191,6 +197,11 @@ void GraphicsLayerTextureMapper::setMaskLayer(GraphicsLayer* value) return; GraphicsLayer::setMaskLayer(value); notifyChange(TextureMapperLayer::MaskLayerChange); + + if (!value) + return; + value->setSize(size()); + value->setContentsVisible(contentsAreVisible()); } @@ -232,6 +243,8 @@ void GraphicsLayerTextureMapper::setSize(const FloatSize& value) return; GraphicsLayer::setSize(value); + if (maskLayer()) + maskLayer()->setSize(value); notifyChange(TextureMapperLayer::SizeChange); } @@ -294,6 +307,8 @@ void GraphicsLayerTextureMapper::setContentsVisible(bool value) return; notifyChange(TextureMapperLayer::ContentsVisibleChange); GraphicsLayer::setContentsVisible(value); + if (maskLayer()) + maskLayer()->setContentsVisible(value); } /* \reimp (GraphicsLayer.h) @@ -395,8 +410,6 @@ void GraphicsLayerTextureMapper::didFlushCompositingState() { updateBackingStore(); m_changeMask = 0; - m_needsDisplay = false; - m_needsDisplayRect = IntRect(); } void GraphicsLayerTextureMapper::didFlushCompositingStateRecursive() @@ -421,6 +434,10 @@ void GraphicsLayerTextureMapper::updateBackingStore() void GraphicsLayerTextureMapper::prepareBackingStore() { + TextureMapper* textureMapper = m_layer->textureMapper(); + if (!textureMapper) + return; + if (!shouldHaveBackingStore()) { m_backingStore.clear(); return; @@ -432,9 +449,6 @@ void GraphicsLayerTextureMapper::prepareBackingStore() if (dirtyRect.isEmpty()) return; - TextureMapper* textureMapper = m_layer->textureMapper(); - ASSERT(textureMapper); - if (!m_backingStore) m_backingStore = TextureMapperTiledBackingStore::create(); diff --git a/Source/WebCore/platform/graphics/texmap/TextureMapperGL.cpp b/Source/WebCore/platform/graphics/texmap/TextureMapperGL.cpp index 9a0f8fec4..cefc2b5fc 100644 --- a/Source/WebCore/platform/graphics/texmap/TextureMapperGL.cpp +++ b/Source/WebCore/platform/graphics/texmap/TextureMapperGL.cpp @@ -360,7 +360,6 @@ void TextureMapperGL::drawRepaintCounter(int value, int pointSize, const FloatPo cairo_surface_t* surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); cairo_t* cr = cairo_create(surface); - cairo_surface_destroy(surface); cairo_set_source_rgb(cr, 0, 0, 1); // Since we won't swap R+B for speed, this will paint red. cairo_rectangle(cr, 0, 0, width, height); @@ -382,6 +381,7 @@ void TextureMapperGL::drawRepaintCounter(int value, int pointSize, const FloatPo static_cast<BitmapTextureGL*>(texture.get())->updateContentsNoSwizzle(bits, sourceRect, IntPoint::zero(), stride); drawTexture(*texture, targetRect, modelViewMatrix, 1.0f, 0, AllEdges); + cairo_surface_destroy(surface); cairo_destroy(cr); #else @@ -691,21 +691,22 @@ void BitmapTextureGL::didReset() void BitmapTextureGL::updateContentsNoSwizzle(const void* srcData, const IntRect& targetRect, const IntPoint& sourceOffset, int bytesPerLine, unsigned bytesPerPixel, Platform3DObject glFormat) { - if (!driverSupportsSubImage() // For ES drivers that don't support sub-images. - || (bytesPerLine == static_cast<int>(targetRect.width() * bytesPerPixel) && sourceOffset == IntPoint::zero())) { - m_context3D->texSubImage2D(GraphicsContext3D::TEXTURE_2D, 0, targetRect.x(), targetRect.y(), targetRect.width(), targetRect.height(), glFormat, DEFAULT_TEXTURE_PIXEL_TRANSFER_TYPE, srcData); - return; - } - + m_context3D->bindTexture(GraphicsContext3D::TEXTURE_2D, m_id); #if !defined(TEXMAP_OPENGL_ES_2) - // Use the OpenGL sub-image extension, now that we know it's available. - m_context3D->pixelStorei(GL_UNPACK_ROW_LENGTH, bytesPerLine / bytesPerPixel); - m_context3D->pixelStorei(GL_UNPACK_SKIP_ROWS, sourceOffset.y()); - m_context3D->pixelStorei(GL_UNPACK_SKIP_PIXELS, sourceOffset.x()); + if (driverSupportsSubImage()) { // For ES drivers that don't support sub-images. + // Use the OpenGL sub-image extension, now that we know it's available. + m_context3D->pixelStorei(GL_UNPACK_ROW_LENGTH, bytesPerLine / bytesPerPixel); + m_context3D->pixelStorei(GL_UNPACK_SKIP_ROWS, sourceOffset.y()); + m_context3D->pixelStorei(GL_UNPACK_SKIP_PIXELS, sourceOffset.x()); + } +#endif m_context3D->texSubImage2D(GraphicsContext3D::TEXTURE_2D, 0, targetRect.x(), targetRect.y(), targetRect.width(), targetRect.height(), glFormat, DEFAULT_TEXTURE_PIXEL_TRANSFER_TYPE, srcData); - m_context3D->pixelStorei(GL_UNPACK_ROW_LENGTH, 0); - m_context3D->pixelStorei(GL_UNPACK_SKIP_ROWS, 0); - m_context3D->pixelStorei(GL_UNPACK_SKIP_PIXELS, 0); +#if !defined(TEXMAP_OPENGL_ES_2) + if (driverSupportsSubImage()) { // For ES drivers that don't support sub-images. + m_context3D->pixelStorei(GL_UNPACK_ROW_LENGTH, 0); + m_context3D->pixelStorei(GL_UNPACK_SKIP_ROWS, 0); + m_context3D->pixelStorei(GL_UNPACK_SKIP_PIXELS, 0); + } #endif } diff --git a/Source/WebCore/platform/graphics/texmap/TextureMapperLayer.cpp b/Source/WebCore/platform/graphics/texmap/TextureMapperLayer.cpp index 50b32b360..d2a10aa66 100644 --- a/Source/WebCore/platform/graphics/texmap/TextureMapperLayer.cpp +++ b/Source/WebCore/platform/graphics/texmap/TextureMapperLayer.cpp @@ -418,7 +418,6 @@ void TextureMapperLayer::flushCompositingStateSelf(GraphicsLayerTextureMapper* g m_state.pos = graphicsLayer->position(); m_state.anchorPoint = graphicsLayer->anchorPoint(); m_state.size = graphicsLayer->size(); - m_state.contentsRect = graphicsLayer->contentsRect(); m_state.transform = graphicsLayer->transform(); m_state.contentsRect = graphicsLayer->contentsRect(); m_state.preserves3D = graphicsLayer->preserves3D(); @@ -485,14 +484,9 @@ void TextureMapperLayer::flushCompositingState(GraphicsLayerTextureMapper* graph if (graphicsLayer && !(options & ComputationsOnly)) flushCompositingStateSelf(graphicsLayer, textureMapper); - if (graphicsLayer && m_state.maskLayer) { + if (graphicsLayer && m_state.maskLayer) m_state.maskLayer->flushCompositingState(toGraphicsLayerTextureMapper(graphicsLayer->maskLayer()), textureMapper); - // A mask layer has its parent's size by default, in case it's not set specifically. - if (m_state.maskLayer->m_size.isEmpty()) - m_state.maskLayer->m_size = m_size; - } - if (m_state.replicaLayer) m_state.replicaLayer->flushCompositingState(toGraphicsLayerTextureMapper(graphicsLayer->replicaLayer()), textureMapper); diff --git a/Source/WebCore/platform/graphics/win/ImageCairoWin.cpp b/Source/WebCore/platform/graphics/win/ImageCairoWin.cpp index d48dcbf88..c60d2a564 100644 --- a/Source/WebCore/platform/graphics/win/ImageCairoWin.cpp +++ b/Source/WebCore/platform/graphics/win/ImageCairoWin.cpp @@ -62,7 +62,7 @@ bool BitmapImage::getHBITMAPOfSize(HBITMAP bmp, LPSIZE size) GetObject(bmp, sizeof(BITMAP), &bmpInfo); // If this is a 32bpp bitmap, which it always should be, we'll clear it so alpha-wise it will be visible - if (bmpInfo.bmBitsPixel == 32) { + if (bmpInfo.bmBitsPixel == 32 && bmpInfo.bmBits) { int bufferSize = bmpInfo.bmWidthBytes * bmpInfo.bmHeight; memset(bmpInfo.bmBits, 255, bufferSize); } @@ -95,7 +95,10 @@ void BitmapImage::drawFrameMatchingSourceSize(GraphicsContext* ctxt, const Float { size_t frames = frameCount(); for (size_t i = 0; i < frames; ++i) { - cairo_surface_t* image = frameAtIndex(i)->surface(); + NativeImageCairo* nativeImage = frameAtIndex(i); + if (!nativeImage) + continue; + cairo_surface_t* image = nativeImage->surface(); if (!image) continue; diff --git a/Source/WebCore/platform/graphics/win/SimpleFontDataWin.cpp b/Source/WebCore/platform/graphics/win/SimpleFontDataWin.cpp index 2de224766..537b0e374 100644 --- a/Source/WebCore/platform/graphics/win/SimpleFontDataWin.cpp +++ b/Source/WebCore/platform/graphics/win/SimpleFontDataWin.cpp @@ -80,32 +80,32 @@ void SimpleFontData::initGDIFont() return; } - HWndDC hdc(0); - HGDIOBJ oldFont = SelectObject(hdc, m_platformData.hfont()); - OUTLINETEXTMETRIC metrics; - GetOutlineTextMetrics(hdc, sizeof(metrics), &metrics); - TEXTMETRIC& textMetrics = metrics.otmTextMetrics; - float ascent = textMetrics.tmAscent; - float descent = textMetrics.tmDescent; - float lineGap = textMetrics.tmExternalLeading; - m_fontMetrics.setAscent(ascent); - m_fontMetrics.setDescent(descent); - m_fontMetrics.setLineGap(lineGap); - m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap)); - m_avgCharWidth = textMetrics.tmAveCharWidth; - m_maxCharWidth = textMetrics.tmMaxCharWidth; - float xHeight = ascent * 0.56f; // Best guess for xHeight if no x glyph is present. + HWndDC hdc(0); + HGDIOBJ oldFont = SelectObject(hdc, m_platformData.hfont()); + OUTLINETEXTMETRIC metrics; + GetOutlineTextMetrics(hdc, sizeof(metrics), &metrics); + TEXTMETRIC& textMetrics = metrics.otmTextMetrics; + float ascent = textMetrics.tmAscent; + float descent = textMetrics.tmDescent; + float lineGap = textMetrics.tmExternalLeading; + m_fontMetrics.setAscent(ascent); + m_fontMetrics.setDescent(descent); + m_fontMetrics.setLineGap(lineGap); + m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap)); + m_avgCharWidth = textMetrics.tmAveCharWidth; + m_maxCharWidth = textMetrics.tmMaxCharWidth; + float xHeight = ascent * 0.56f; // Best guess for xHeight if no x glyph is present. #if !OS(WINCE) - GLYPHMETRICS gm; - MAT2 mat = { 1, 0, 0, 1 }; - DWORD len = GetGlyphOutline(hdc, 'x', GGO_METRICS, &gm, 0, 0, &mat); - if (len != GDI_ERROR && gm.gmptGlyphOrigin.y > 0) - xHeight = gm.gmptGlyphOrigin.y; + GLYPHMETRICS gm; + static const MAT2 identity = { 0, 1, 0, 0, 0, 0, 0, 1 }; + DWORD len = GetGlyphOutline(hdc, 'x', GGO_METRICS, &gm, 0, 0, &identity); + if (len != GDI_ERROR && gm.gmptGlyphOrigin.y > 0) + xHeight = gm.gmptGlyphOrigin.y; #endif - m_fontMetrics.setXHeight(xHeight); - m_fontMetrics.setUnitsPerEm(metrics.otmEMSquare); + m_fontMetrics.setXHeight(xHeight); + m_fontMetrics.setUnitsPerEm(metrics.otmEMSquare); - SelectObject(hdc, oldFont); + SelectObject(hdc, oldFont); } void SimpleFontData::platformCharWidthInit() diff --git a/Source/WebCore/platform/gtk/LocalizedStringsGtk.cpp b/Source/WebCore/platform/gtk/LocalizedStringsGtk.cpp index aae044089..25bc38916 100644 --- a/Source/WebCore/platform/gtk/LocalizedStringsGtk.cpp +++ b/Source/WebCore/platform/gtk/LocalizedStringsGtk.cpp @@ -741,4 +741,10 @@ String localizedString(const char* key) return String::fromUTF8(key, strlen(key)); } +String validationMessageBadInputForNumberText() +{ + notImplemented(); + return validationMessageTypeMismatchText(); +} + } diff --git a/Source/WebCore/platform/image-decoders/ImageDecoder.cpp b/Source/WebCore/platform/image-decoders/ImageDecoder.cpp index 4f652757f..d7086b08a 100644 --- a/Source/WebCore/platform/image-decoders/ImageDecoder.cpp +++ b/Source/WebCore/platform/image-decoders/ImageDecoder.cpp @@ -226,16 +226,6 @@ void ImageFrame::setStatus(FrameStatus status) m_status = status; } -int ImageFrame::width() const -{ - return m_size.width(); -} - -int ImageFrame::height() const -{ - return m_size.height(); -} - void ImageFrame::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const { MemoryClassInfo info(memoryObjectInfo, this, PlatformMemoryTypes::Image); diff --git a/Source/WebCore/platform/image-decoders/ImageDecoder.h b/Source/WebCore/platform/image-decoders/ImageDecoder.h index 2b5c9836a..3ed025faa 100644 --- a/Source/WebCore/platform/image-decoders/ImageDecoder.h +++ b/Source/WebCore/platform/image-decoders/ImageDecoder.h @@ -123,6 +123,7 @@ namespace WebCore { unsigned duration() const { return m_duration; } FrameDisposalMethod disposalMethod() const { return m_disposalMethod; } bool premultiplyAlpha() const { return m_premultiplyAlpha; } + void reportMemoryUsage(MemoryObjectInfo*) const; void setHasAlpha(bool alpha); void setColorProfile(const ColorProfile&); @@ -146,8 +147,6 @@ namespace WebCore { #endif } - void reportMemoryUsage(MemoryObjectInfo*) const; - #if PLATFORM(CHROMIUM) void setSkBitmap(const SkBitmap& bitmap) { @@ -160,30 +159,45 @@ namespace WebCore { } #endif - private: - int width() const; - int height() const; - inline void setRGBA(PixelData* dest, unsigned r, unsigned g, unsigned b, unsigned a) { - if (m_premultiplyAlpha && !a) - *dest = 0; - else { - if (m_premultiplyAlpha && a < 255) { - float alphaPercent = a / 255.0f; - r = static_cast<unsigned>(r * alphaPercent); - g = static_cast<unsigned>(g * alphaPercent); - b = static_cast<unsigned>(b * alphaPercent); + if (m_premultiplyAlpha && a < 255) { + if (!a) { + *dest = 0; + return; } + + float alphaPercent = a / 255.0f; + r = static_cast<unsigned>(r * alphaPercent); + g = static_cast<unsigned>(g * alphaPercent); + b = static_cast<unsigned>(b * alphaPercent); + } #if USE(SKIA) - // we are sure to call the NoCheck version, since we may - // deliberately pass non-premultiplied values, and we don't want - // an assert. - *dest = SkPackARGB32NoCheck(a, r, g, b); + // Call the "NoCheck" version since we may deliberately pass non-premultiplied + // values, and we don't want an assert. + *dest = SkPackARGB32NoCheck(a, r, g, b); #else - *dest = (a << 24 | r << 16 | g << 8 | b); + *dest = (a << 24 | r << 16 | g << 8 | b); +#endif + } + + private: + int width() const + { +#if USE(SKIA) + return m_bitmap.bitmap().width(); +#else + return m_size.width(); +#endif + } + + int height() const + { +#if USE(SKIA) + return m_bitmap.bitmap().height(); +#else + return m_size.height(); #endif - } } #if USE(SKIA) diff --git a/Source/WebCore/platform/image-decoders/gif/GIFImageDecoder.cpp b/Source/WebCore/platform/image-decoders/gif/GIFImageDecoder.cpp index 40e131e7c..8fc4a9a53 100644 --- a/Source/WebCore/platform/image-decoders/gif/GIFImageDecoder.cpp +++ b/Source/WebCore/platform/image-decoders/gif/GIFImageDecoder.cpp @@ -230,12 +230,13 @@ bool GIFImageDecoder::haveDecodedRow(unsigned frameIndex, unsigned char* rowBuff if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex)) return false; + ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin); // Write one row's worth of data into the frame. for (int x = xBegin; x < xEnd; ++x) { const unsigned char sourceValue = *(rowBuffer + (m_scaled ? m_scaledColumns[x] : x) - frameReader->x_offset); if ((!frameReader->is_transparent || (sourceValue != frameReader->tpixel)) && (sourceValue < colorMapSize)) { const size_t colorIndex = static_cast<size_t>(sourceValue) * 3; - buffer.setRGBA(x, yBegin, colorMap[colorIndex], colorMap[colorIndex + 1], colorMap[colorIndex + 2], 255); + buffer.setRGBA(currentAddress, colorMap[colorIndex], colorMap[colorIndex + 1], colorMap[colorIndex + 2], 255); } else { m_currentBufferSawAlpha = true; // We may or may not need to write transparent pixels to the buffer. @@ -246,8 +247,9 @@ bool GIFImageDecoder::haveDecodedRow(unsigned frameIndex, unsigned char* rowBuff // beyond the first, or the initial passes will "show through" the // later ones. if (writeTransparentPixels) - buffer.setRGBA(x, yBegin, 0, 0, 0, 0); + buffer.setRGBA(currentAddress, 0, 0, 0, 0); } + ++currentAddress; } // Tell the frame to copy the row data if need be. diff --git a/Source/WebCore/platform/image-decoders/png/PNGImageDecoder.cpp b/Source/WebCore/platform/image-decoders/png/PNGImageDecoder.cpp index b0c2adc9f..7984c9ae8 100644 --- a/Source/WebCore/platform/image-decoders/png/PNGImageDecoder.cpp +++ b/Source/WebCore/platform/image-decoders/png/PNGImageDecoder.cpp @@ -499,6 +499,7 @@ void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, unsigned rowIndex, #endif // Write the decoded row pixels to the frame buffer. + ImageFrame::PixelData* address = buffer.getAddr(0, y); int width = scaledSize().width(); bool nonTrivialAlpha = false; @@ -506,7 +507,7 @@ void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, unsigned rowIndex, for (int x = 0; x < width; ++x) { png_bytep pixel = row + (m_scaled ? m_scaledColumns[x] : x) * colorChannels; unsigned alpha = hasAlpha ? pixel[3] : 255; - buffer.setRGBA(x, y, pixel[0], pixel[1], pixel[2], alpha); + buffer.setRGBA(address++, pixel[0], pixel[1], pixel[2], alpha); nonTrivialAlpha |= alpha < 255; } #else @@ -514,7 +515,7 @@ void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, unsigned rowIndex, png_bytep pixel = row; for (int x = 0; x < width; ++x, pixel += colorChannels) { unsigned alpha = hasAlpha ? pixel[3] : 255; - buffer.setRGBA(x, y, pixel[0], pixel[1], pixel[2], alpha); + buffer.setRGBA(address++, pixel[0], pixel[1], pixel[2], alpha); nonTrivialAlpha |= alpha < 255; } #endif diff --git a/Source/WebCore/platform/image-decoders/skia/ImageDecoderSkia.cpp b/Source/WebCore/platform/image-decoders/skia/ImageDecoderSkia.cpp index c7f1578ea..b238216bf 100644 --- a/Source/WebCore/platform/image-decoders/skia/ImageDecoderSkia.cpp +++ b/Source/WebCore/platform/image-decoders/skia/ImageDecoderSkia.cpp @@ -138,16 +138,6 @@ void ImageFrame::setStatus(FrameStatus status) } } -int ImageFrame::width() const -{ - return m_bitmap.bitmap().width(); -} - -int ImageFrame::height() const -{ - return m_bitmap.bitmap().height(); -} - void ImageFrame::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const { MemoryClassInfo info(memoryObjectInfo, this, PlatformMemoryTypes::Image); diff --git a/Source/WebCore/platform/mac/HTMLConverter.mm b/Source/WebCore/platform/mac/HTMLConverter.mm index 6516a2d2c..2193b0d26 100644 --- a/Source/WebCore/platform/mac/HTMLConverter.mm +++ b/Source/WebCore/platform/mac/HTMLConverter.mm @@ -1667,6 +1667,7 @@ static NSInteger _colCompare(id block1, id block2, void *) // This function uses TextIterator, which makes offsets in its result compatible with HTML editing. + (NSAttributedString *)editingAttributedStringFromRange:(Range*)range { + NSFontManager *fontManager = [NSFontManager sharedFontManager]; NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init]; NSUInteger stringLength = 0; RetainPtr<NSMutableDictionary> attrs(AdoptNS, [[NSMutableDictionary alloc] init]); @@ -1702,6 +1703,8 @@ static NSInteger _colCompare(id block1, id block2, void *) [attrs.get() setObject:[NSNumber numberWithInteger:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName]; if (NSFont *font = style->font().primaryFont()->getNSFont()) [attrs.get() setObject:font forKey:NSFontAttributeName]; + else + [attrs.get() setObject:[fontManager convertFont:WebDefaultFont() toSize:style->font().primaryFont()->platformData().size()] forKey:NSFontAttributeName]; if (style->visitedDependentColor(CSSPropertyColor).alpha()) [attrs.get() setObject:nsColor(style->visitedDependentColor(CSSPropertyColor)) forKey:NSForegroundColorAttributeName]; else diff --git a/Source/WebCore/platform/mac/WebCoreFullScreenPlaceholderView.h b/Source/WebCore/platform/mac/WebCoreFullScreenPlaceholderView.h new file mode 100644 index 000000000..7b243b0a2 --- /dev/null +++ b/Source/WebCore/platform/mac/WebCoreFullScreenPlaceholderView.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WebCoreFullScreenPlaceholderView_h +#define WebCoreFullScreenPlaceholderView_h + +#import <wtf/RetainPtr.h> + +@interface WebCoreFullScreenPlaceholderView : NSView { + RetainPtr<NSView> _exitWarning; + NSObject* _target; + SEL _action; +} +@property(retain) id contents; +@property(assign) NSObject* target; +@property(assign) SEL action; +- (void)setExitWarningVisible:(BOOL)visible; +@end + +#endif // WebCoreFullScreenPlaceholderView_h diff --git a/Source/WebCore/platform/mac/WebCoreFullScreenPlaceholderView.mm b/Source/WebCore/platform/mac/WebCoreFullScreenPlaceholderView.mm new file mode 100644 index 000000000..4bbcdd923 --- /dev/null +++ b/Source/WebCore/platform/mac/WebCoreFullScreenPlaceholderView.mm @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebCoreFullScreenPlaceholderView.h" + +#include "LocalizedStrings.h" +#include "WebCoreFullScreenWarningView.h" +#include <wtf/UnusedParam.h> +#include <wtf/text/WTFString.h> + +@interface CAFilter : NSObject ++ (CAFilter *)filterWithType:(NSString *)type; +@end + +using namespace WebCore; + +@implementation WebCoreFullScreenPlaceholderView +- (id)initWithFrame:(NSRect)frameRect +{ + self = [super initWithFrame:frameRect]; + if (!self) + return nil; + + [self setLayer:[CALayer layer]]; + [self setLayerContentsRedrawPolicy:NSViewLayerContentsRedrawNever]; + [self setWantsLayer:YES]; + + _exitWarning = adoptNS([[WebCoreFullScreenWarningView alloc] initWithTitle:clickToExitFullScreenText()]); + NSRect warningFrame = [_exitWarning.get() frame]; + warningFrame.origin = NSMakePoint((frameRect.size.width - warningFrame.size.width) / 2, (frameRect.size.height - warningFrame.size.height) / 2); + [_exitWarning.get() setFrame:warningFrame]; + [_exitWarning.get() setHidden:YES]; + [self addSubview:_exitWarning.get()]; + + return self; +} + +@synthesize target = _target; +@synthesize action = _action; + +@dynamic contents; +- (void)setContents:(id)contents +{ + [[self layer] setContents:contents]; +} + +- (id)contents +{ + return [[self layer] contents]; +} + +- (void)setExitWarningVisible:(BOOL)visible +{ + [_exitWarning.get() setHidden:!visible]; + if (visible) { + CAFilter* filter = [CAFilter filterWithType:@"colorMonochrome"]; + [filter setValue:[NSNumber numberWithFloat:-0.2] forKey:@"inputBias"]; + [filter setValue:[NSNumber numberWithFloat:1] forKey:@"inputAmount"]; + [[self layer] setFilters:[NSArray arrayWithObject:filter]]; + } else + [[self layer] setFilters:nil]; +} + +- (void)mouseDown:(NSEvent *)theEvent +{ + UNUSED_PARAM(theEvent); + + if (!_target || !_action) + return; + [_target performSelector:_action]; +} + +@end diff --git a/Source/WebCore/platform/mac/WebCoreFullScreenWarningView.h b/Source/WebCore/platform/mac/WebCoreFullScreenWarningView.h new file mode 100644 index 000000000..f6ea9ad78 --- /dev/null +++ b/Source/WebCore/platform/mac/WebCoreFullScreenWarningView.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WebCoreFullScreenWarningView_h +#define WebCoreFullScreenWarningView_h + +#if ENABLE(FULLSCREEN_API) + +#include <wtf/RetainPtr.h> + +@interface WebCoreFullScreenWarningView : NSBox { + RetainPtr<NSTextField> _textField; +} +- (id)initWithTitle:(NSString*)title; +@end + +#endif + +#endif // WebCoreFullScreenWarningView_h diff --git a/Source/WebCore/platform/mac/WebCoreFullScreenWarningView.mm b/Source/WebCore/platform/mac/WebCoreFullScreenWarningView.mm new file mode 100644 index 000000000..1ba388237 --- /dev/null +++ b/Source/WebCore/platform/mac/WebCoreFullScreenWarningView.mm @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebCoreFullScreenWarningView.h" + +#include "LocalizedStrings.h" +#include <wtf/text/WTFString.h> + +static const CGFloat WarningViewTextWhite = 0.9; +static const CGFloat WarningViewTextAlpha = 1; +static const CGFloat WarningViewTextSize = 48; +static const CGFloat WarningViewPadding = 20; +static const CGFloat WarningViewCornerRadius = 10; +static const CGFloat WarningViewBorderWhite = 0.9; +static const CGFloat WarningViewBorderAlpha = 0.2; +static const CGFloat WarningViewBackgroundWhite = 0.1; +static const CGFloat WarningViewBackgroundAlpha = 0.9; +static const CGFloat WarningViewShadowWhite = 0.1; +static const CGFloat WarningViewShadowAlpha = 1; +static const float WarningViewShadowOpacity = 0.25; +static const NSSize WarningViewShadowOffset = {0, -2}; +static const CGFloat WarningViewShadowRadius = 5; +static const NSTimeInterval WarningViewHideDelay = 3; +static const NSTimeInterval WarningViewFadeDuration = 0.5; + +@implementation WebCoreFullScreenWarningView + +- (id)initWithTitle:(NSString*)title +{ + self = [super initWithFrame:NSZeroRect]; + if (!self) + return nil; + + [self setAutoresizingMask:(NSViewMinXMargin | NSViewMaxXMargin | NSViewMinYMargin | NSViewMaxYMargin)]; + [self setBoxType:NSBoxCustom]; + [self setTitlePosition:NSNoTitle]; + + _textField = adoptNS([[NSTextField alloc] initWithFrame:NSZeroRect]); + [_textField.get() setEditable:NO]; + [_textField.get() setSelectable:NO]; + [_textField.get() setBordered:NO]; + [_textField.get() setDrawsBackground:NO]; + + NSFont* textFont = [NSFont boldSystemFontOfSize:WarningViewTextSize]; + NSColor* textColor = [NSColor colorWithCalibratedWhite:WarningViewTextWhite alpha:WarningViewTextAlpha]; + RetainPtr<NSDictionary> attributes = adoptNS([[NSDictionary alloc] initWithObjectsAndKeys: + textFont, NSFontAttributeName, + textColor, NSForegroundColorAttributeName, + nil]); + RetainPtr<NSAttributedString> text = adoptNS([[NSAttributedString alloc] initWithString:title attributes:attributes.get()]); + [_textField.get() setAttributedStringValue:text.get()]; + [_textField.get() sizeToFit]; + NSRect textFieldFrame = [_textField.get() frame]; + NSSize frameSize = textFieldFrame.size; + frameSize.width += WarningViewPadding * 2; + frameSize.height += WarningViewPadding * 2; + [self setFrameSize:frameSize]; + + textFieldFrame.origin = NSMakePoint( + (frameSize.width - textFieldFrame.size.width) / 2, + (frameSize.height - textFieldFrame.size.height) / 2); + + // Offset the origin by the font's descender, to center the text field about the baseline: + textFieldFrame.origin.y += [[_textField.get() font] descender]; + + [_textField.get() setFrame:NSIntegralRect(textFieldFrame)]; + [self addSubview:_textField.get()]; + + NSColor* backgroundColor = [NSColor colorWithCalibratedWhite:WarningViewBackgroundWhite alpha:WarningViewBackgroundAlpha]; + [self setFillColor:backgroundColor]; + [self setCornerRadius:WarningViewCornerRadius]; + + NSColor* borderColor = [NSColor colorWithCalibratedWhite:WarningViewBorderWhite alpha:WarningViewBorderAlpha]; + [self setBorderColor:borderColor]; + + RetainPtr<NSShadow> shadow = adoptNS([[NSShadow alloc] init]); + RetainPtr<NSColor> shadowColor = [NSColor colorWithCalibratedWhite:WarningViewShadowWhite alpha:WarningViewShadowAlpha]; + [shadow.get() setShadowColor:shadowColor.get()]; + [shadow.get() setShadowOffset:WarningViewShadowOffset]; + [shadow.get() setShadowBlurRadius:WarningViewShadowRadius]; + [self setShadow:shadow.get()]; + + return self; +} +@end diff --git a/Source/WebCore/platform/mac/WebCoreObjCExtras.mm b/Source/WebCore/platform/mac/WebCoreObjCExtras.mm index d357f9800..f413b40dd 100644 --- a/Source/WebCore/platform/mac/WebCoreObjCExtras.mm +++ b/Source/WebCore/platform/mac/WebCoreObjCExtras.mm @@ -35,7 +35,6 @@ #include "WebCoreObjCExtras.h" #include <objc/objc-auto.h> -#include <objc/objc-runtime.h> #include <utility> #include <wtf/Assertions.h> #include <wtf/MainThread.h> diff --git a/Source/WebCore/platform/mac/WebVideoFullscreenController.mm b/Source/WebCore/platform/mac/WebVideoFullscreenController.mm index ce35fb1d8..3edc36145 100644 --- a/Source/WebCore/platform/mac/WebVideoFullscreenController.mm +++ b/Source/WebCore/platform/mac/WebVideoFullscreenController.mm @@ -36,7 +36,7 @@ #import <WebCore/DisplaySleepDisabler.h> #import <WebCore/HTMLMediaElement.h> #import <WebCore/SoftLinking.h> -#import <objc/objc-runtime.h> +#import <objc/runtime.h> #import <wtf/UnusedParam.h> #if USE(GSTREAMER) diff --git a/Source/WebCore/platform/mediastream/MediaStreamSource.cpp b/Source/WebCore/platform/mediastream/MediaStreamSource.cpp index 1720487dc..f23405c07 100644 --- a/Source/WebCore/platform/mediastream/MediaStreamSource.cpp +++ b/Source/WebCore/platform/mediastream/MediaStreamSource.cpp @@ -33,19 +33,21 @@ #if ENABLE(MEDIA_STREAM) #include "MediaStreamSource.h" +#include <wtf/PassOwnPtr.h> namespace WebCore { -PassRefPtr<MediaStreamSource> MediaStreamSource::create(const String& id, Type type, const String& name, ReadyState readyState) +PassRefPtr<MediaStreamSource> MediaStreamSource::create(const String& id, Type type, const String& name, ReadyState readyState, bool requiresConsumer) { - return adoptRef(new MediaStreamSource(id, type, name, readyState)); + return adoptRef(new MediaStreamSource(id, type, name, readyState, requiresConsumer)); } -MediaStreamSource::MediaStreamSource(const String& id, Type type, const String& name, ReadyState readyState) +MediaStreamSource::MediaStreamSource(const String& id, Type type, const String& name, ReadyState readyState, bool requiresConsumer) : m_id(id) , m_type(type) , m_name(name) , m_readyState(readyState) + , m_requiresConsumer(requiresConsumer) { } @@ -71,6 +73,33 @@ void MediaStreamSource::removeObserver(MediaStreamSource::Observer* observer) m_observers.remove(pos); } +void MediaStreamSource::addAudioConsumer(PassRefPtr<AudioDestinationConsumer> consumer) +{ + ASSERT(m_requiresConsumer); + MutexLocker locker(m_audioConsumersLock); + m_audioConsumers.append(consumer); +} + +bool MediaStreamSource::removeAudioConsumer(AudioDestinationConsumer* consumer) +{ + ASSERT(m_requiresConsumer); + MutexLocker locker(m_audioConsumersLock); + size_t pos = m_audioConsumers.find(consumer); + if (pos != notFound) { + m_audioConsumers.remove(pos); + return true; + } + return false; +} + +void MediaStreamSource::consumeAudio(AudioBus* bus, size_t numberOfFrames) +{ + ASSERT(m_requiresConsumer); + MutexLocker locker(m_audioConsumersLock); + for (Vector<RefPtr<AudioDestinationConsumer> >::iterator it = m_audioConsumers.begin(); it != m_audioConsumers.end(); ++it) + (*it)->consumeAudio(bus, numberOfFrames); +} + } // namespace WebCore #endif // ENABLE(MEDIA_STREAM) diff --git a/Source/WebCore/platform/mediastream/MediaStreamSource.h b/Source/WebCore/platform/mediastream/MediaStreamSource.h index bf7110edc..762870a9c 100644 --- a/Source/WebCore/platform/mediastream/MediaStreamSource.h +++ b/Source/WebCore/platform/mediastream/MediaStreamSource.h @@ -34,6 +34,7 @@ #if ENABLE(MEDIA_STREAM) +#include "AudioDestinationConsumer.h" #include <wtf/RefCounted.h> #include <wtf/Vector.h> #include <wtf/text/WTFString.h> @@ -64,7 +65,7 @@ public: ReadyStateEnded = 2 }; - static PassRefPtr<MediaStreamSource> create(const String& id, Type, const String& name, ReadyState = ReadyStateLive); + static PassRefPtr<MediaStreamSource> create(const String& id, Type, const String& name, ReadyState = ReadyStateLive, bool requiresConsumer = false); const String& id() const { return m_id; } Type type() const { return m_type; } @@ -79,14 +80,24 @@ public: PassRefPtr<ExtraData> extraData() const { return m_extraData; } void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; } + void consumeAudio(AudioBus*, size_t numberOfFrames); + + bool requiresAudioConsumer() const { return m_requiresConsumer; } + void addAudioConsumer(PassRefPtr<AudioDestinationConsumer>); + bool removeAudioConsumer(AudioDestinationConsumer*); + const Vector<RefPtr<AudioDestinationConsumer> >& audioConsumers() { return m_audioConsumers; } + private: - MediaStreamSource(const String& id, Type, const String& name, ReadyState); + MediaStreamSource(const String& id, Type, const String& name, ReadyState, bool requiresConsumer); String m_id; Type m_type; String m_name; ReadyState m_readyState; + bool m_requiresConsumer; Vector<Observer*> m_observers; + Mutex m_audioConsumersLock; + Vector<RefPtr<AudioDestinationConsumer> > m_audioConsumers; RefPtr<ExtraData> m_extraData; }; diff --git a/Source/WebCore/platform/network/blackberry/NetworkJob.cpp b/Source/WebCore/platform/network/blackberry/NetworkJob.cpp index 6c186f7b8..731384687 100644 --- a/Source/WebCore/platform/network/blackberry/NetworkJob.cpp +++ b/Source/WebCore/platform/network/blackberry/NetworkJob.cpp @@ -215,7 +215,7 @@ void NetworkJob::handleNotifyStatusReceived(int status, const String& message) purgeCredentials(); } -void NetworkJob::notifyHeadersReceived(BlackBerry::Platform::NetworkRequest::HeaderList& headers) +void NetworkJob::notifyHeadersReceived(const BlackBerry::Platform::NetworkRequest::HeaderList& headers) { BlackBerry::Platform::NetworkRequest::HeaderList::const_iterator endIt = headers.end(); for (BlackBerry::Platform::NetworkRequest::HeaderList::const_iterator it = headers.begin(); it != endIt; ++it) { diff --git a/Source/WebCore/platform/network/blackberry/NetworkJob.h b/Source/WebCore/platform/network/blackberry/NetworkJob.h index eb5c94420..cda091828 100644 --- a/Source/WebCore/platform/network/blackberry/NetworkJob.h +++ b/Source/WebCore/platform/network/blackberry/NetworkJob.h @@ -71,7 +71,7 @@ public: void updateDeferLoadingCount(int delta); virtual void notifyStatusReceived(int status, const BlackBerry::Platform::String& message); void handleNotifyStatusReceived(int status, const String& message); - virtual void notifyHeadersReceived(BlackBerry::Platform::NetworkRequest::HeaderList& headers); + virtual void notifyHeadersReceived(const BlackBerry::Platform::NetworkRequest::HeaderList& headers); virtual void notifyMultipartHeaderReceived(const char* key, const char* value); virtual void notifyAuthReceived(BlackBerry::Platform::NetworkRequest::AuthType, const char* realm, bool success, bool requireCredentials); // notifyStringHeaderReceived exists only to resolve ambiguity between char* and String parameters diff --git a/Source/WebCore/platform/network/blackberry/rss/RSSFilterStream.cpp b/Source/WebCore/platform/network/blackberry/rss/RSSFilterStream.cpp index 25daca258..ebdcc44f5 100644 --- a/Source/WebCore/platform/network/blackberry/rss/RSSFilterStream.cpp +++ b/Source/WebCore/platform/network/blackberry/rss/RSSFilterStream.cpp @@ -449,7 +449,7 @@ void RSSFilterStream::notifyStatusReceived(int status, const char* message) FilterStream::notifyStatusReceived(status, message); } -void RSSFilterStream::notifyHeadersReceived(NetworkRequest::HeaderList& headers) +void RSSFilterStream::notifyHeadersReceived(const NetworkRequest::HeaderList& headers) { if (!isRSSContent(m_resourceType)) { NetworkRequest::HeaderList::const_iterator end = headers.end(); diff --git a/Source/WebCore/platform/network/blackberry/rss/RSSFilterStream.h b/Source/WebCore/platform/network/blackberry/rss/RSSFilterStream.h index 6c3e848e4..69cbd8e1c 100644 --- a/Source/WebCore/platform/network/blackberry/rss/RSSFilterStream.h +++ b/Source/WebCore/platform/network/blackberry/rss/RSSFilterStream.h @@ -39,7 +39,7 @@ public: RSSFilterStream(); virtual void notifyStatusReceived(int status, const char* message); - virtual void notifyHeadersReceived(BlackBerry::Platform::NetworkRequest::HeaderList&); + virtual void notifyHeadersReceived(const BlackBerry::Platform::NetworkRequest::HeaderList&); virtual void notifyDataReceived(BlackBerry::Platform::NetworkBuffer*); virtual void notifyClose(int status); diff --git a/Source/WebCore/platform/qt/LocalizedStringsQt.cpp b/Source/WebCore/platform/qt/LocalizedStringsQt.cpp index 7dfff1fe9..d62e985f8 100644 --- a/Source/WebCore/platform/qt/LocalizedStringsQt.cpp +++ b/Source/WebCore/platform/qt/LocalizedStringsQt.cpp @@ -711,6 +711,12 @@ String validationMessageStepMismatchText(const String& base, const String& step) return String(); } +String validationMessageBadInputForNumberText() +{ + notImplemented(); + return validationMessageTypeMismatchText(); +} + String localizedString(const char* key) { return String::fromUTF8(key, strlen(key)); diff --git a/Source/WebCore/platform/qt/ScreenQt.cpp b/Source/WebCore/platform/qt/ScreenQt.cpp deleted file mode 100644 index d648c5315..000000000 --- a/Source/WebCore/platform/qt/ScreenQt.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2006 Dirk Mueller <mueller@kde.org> - * (C) 2006 Nikolas Zimmermann <zimmermann@kde.org> - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "Screen.h" - -#include "FloatRect.h" -#include "Frame.h" -#include "FrameView.h" -#include "IntRect.h" -#include "Page.h" -#include "Widget.h" - -#include <QApplication> -#include <QDesktopWidget> - -namespace WebCore { - -static QWidget* qwidgetForPage(const Page* page) -{ - Frame* frame = (page ? page->mainFrame() : 0); - FrameView* frameView = (frame ? frame->view() : 0); - - if (!frameView) - return 0; - - return frameView->qwidget(); -} - -FloatRect screenRect(const Page* page) -{ - QWidget* qw = qwidgetForPage(page); - if (!qw) - return FloatRect(); - - // Taken from KGlobalSettings::desktopGeometry - QDesktopWidget* dw = QApplication::desktop(); - if (!dw) - return FloatRect(); - - return IntRect(dw->screenGeometry(qw)); -} - -int screenDepth(const Page* page) -{ - QWidget* qw = qwidgetForPage(page); - if (!qw) - return 32; - - return qw->depth(); -} - -FloatRect usableScreenRect(const Page* page) -{ - QWidget* qw = qwidgetForPage(page); - if (!qw) - return FloatRect(); - - // Taken from KGlobalSettings::desktopGeometry - QDesktopWidget* dw = QApplication::desktop(); - if (!dw) - return FloatRect(); - - return IntRect(dw->availableGeometry(qw)); -} - -float scaleFactor(const Page*) -{ - return 1.0f; -} - -} - -// vim: ts=4 sw=4 et diff --git a/Source/WebCore/platform/text/TextBreakIterator.cpp b/Source/WebCore/platform/text/TextBreakIterator.cpp index edb73ef76..a4466d171 100644 --- a/Source/WebCore/platform/text/TextBreakIterator.cpp +++ b/Source/WebCore/platform/text/TextBreakIterator.cpp @@ -26,9 +26,18 @@ namespace WebCore { unsigned numGraphemeClusters(const String& s) { - NonSharedCharacterBreakIterator it(s.characters(), s.length()); + unsigned stringLength = s.length(); + + if (!stringLength) + return 0; + + // The only Latin-1 Extended Grapheme Cluster is CR LF + if (s.is8Bit() && !s.contains('\r')) + return stringLength; + + NonSharedCharacterBreakIterator it(s.characters(), stringLength); if (!it) - return s.length(); + return stringLength; unsigned num = 0; while (textBreakNext(it) != TextBreakDone) @@ -38,13 +47,22 @@ unsigned numGraphemeClusters(const String& s) unsigned numCharactersInGraphemeClusters(const String& s, unsigned numGraphemeClusters) { - NonSharedCharacterBreakIterator it(s.characters(), s.length()); + unsigned stringLength = s.length(); + + if (!stringLength) + return 0; + + // The only Latin-1 Extended Grapheme Cluster is CR LF + if (s.is8Bit() && !s.contains('\r')) + return std::min(stringLength, numGraphemeClusters); + + NonSharedCharacterBreakIterator it(s.characters(), stringLength); if (!it) - return std::min(s.length(), numGraphemeClusters); + return std::min(stringLength, numGraphemeClusters); for (unsigned i = 0; i < numGraphemeClusters; ++i) { if (textBreakNext(it) == TextBreakDone) - return s.length(); + return stringLength; } return textBreakCurrent(it); } diff --git a/Source/WebCore/platform/win/ClipboardUtilitiesWin.cpp b/Source/WebCore/platform/win/ClipboardUtilitiesWin.cpp index f33550e94..f0d1ef796 100644 --- a/Source/WebCore/platform/win/ClipboardUtilitiesWin.cpp +++ b/Source/WebCore/platform/win/ClipboardUtilitiesWin.cpp @@ -433,7 +433,7 @@ void setFileDescriptorData(IDataObject* dataObject, int size, const String& pass fgd->fgd[0].dwFlags = FD_FILESIZE; fgd->fgd[0].nFileSizeLow = size; - int maxSize = std::min(pathname.length(), WTF_ARRAY_LENGTH(fgd->fgd[0].cFileName)); + int maxSize = std::min<int>(pathname.length(), WTF_ARRAY_LENGTH(fgd->fgd[0].cFileName)); CopyMemory(fgd->fgd[0].cFileName, pathname.charactersWithNullTermination(), maxSize * sizeof(UChar)); GlobalUnlock(medium.hGlobal); diff --git a/Source/WebCore/plugins/PluginView.cpp b/Source/WebCore/plugins/PluginView.cpp index 0466846d4..5d32c938f 100644 --- a/Source/WebCore/plugins/PluginView.cpp +++ b/Source/WebCore/plugins/PluginView.cpp @@ -440,7 +440,10 @@ void PluginView::performRequest(PluginRequest* request) // PluginView, so we protect it. <rdar://problem/6991251> RefPtr<PluginView> protect(this); - m_parentFrame->loader()->load(request->frameLoadRequest().resourceRequest(), targetFrameName, false); + FrameLoadRequest frameRequest(m_parentFrame.get(), request->frameLoadRequest().resourceRequest()); + frameRequest.setFrameName(targetFrameName); + frameRequest.setShouldCheckNewWindowPolicy(true); + m_parentFrame->loader()->load(frameRequest); // FIXME: <rdar://problem/4807469> This should be sent when the document has finished loading if (request->sendNotification()) { diff --git a/Source/WebCore/plugins/PluginViewBase.h b/Source/WebCore/plugins/PluginViewBase.h index e4a0c4943..f71306a32 100644 --- a/Source/WebCore/plugins/PluginViewBase.h +++ b/Source/WebCore/plugins/PluginViewBase.h @@ -30,11 +30,16 @@ #include "Widget.h" #include <wtf/text/WTFString.h> +#if USE(V8) +struct NPObject; +#endif +#if USE(JSC) namespace JSC { class ExecState; class JSGlobalObject; class JSObject; } +#endif namespace WebCore { @@ -48,7 +53,12 @@ public: virtual PlatformLayer* platformLayer() const { return 0; } #endif +#if USE(V8) + virtual NPObject* scriptableObject() { return 0; } +#endif +#if USE(JSC) virtual JSC::JSObject* scriptObject(JSC::JSGlobalObject*) { return 0; } +#endif virtual void storageBlockingStateChanged() { } virtual void privateBrowsingStateChanged(bool) { } virtual bool getFormValue(String&) { return false; } diff --git a/Source/WebCore/plugins/blackberry/PluginViewBlackBerry.cpp b/Source/WebCore/plugins/blackberry/PluginViewBlackBerry.cpp index f5478f08c..9acaa4ccc 100644 --- a/Source/WebCore/plugins/blackberry/PluginViewBlackBerry.cpp +++ b/Source/WebCore/plugins/blackberry/PluginViewBlackBerry.cpp @@ -490,22 +490,15 @@ void PluginView::handleTouchEvent(TouchEvent* event) npTouchEvent.type = TOUCH_EVENT_DOUBLETAP; else if (event->isTouchHold()) npTouchEvent.type = TOUCH_EVENT_TOUCHHOLD; - else if (event->type() == eventNames().touchstartEvent) - npTouchEvent.type = TOUCH_EVENT_START; - else if (event->type() == eventNames().touchendEvent) - npTouchEvent.type = TOUCH_EVENT_END; - else if (event->type() == eventNames().touchmoveEvent) - npTouchEvent.type = TOUCH_EVENT_MOVE; else if (event->type() == eventNames().touchcancelEvent) npTouchEvent.type = TOUCH_EVENT_CANCEL; - else { - ASSERT_NOT_REACHED(); + else return; - } TouchList* touchList; - // The touches list is empty if in a touch end event. Use changedTouches instead. - if (npTouchEvent.type == TOUCH_EVENT_DOUBLETAP || npTouchEvent.type == TOUCH_EVENT_END) + // The touches list is empty if in a touch end event. + // Since DoubleTap is ususally a TouchEnd Use changedTouches instead. + if (npTouchEvent.type == TOUCH_EVENT_DOUBLETAP) touchList = event->changedTouches(); else touchList = event->touches(); @@ -536,13 +529,6 @@ void PluginView::handleTouchEvent(TouchEvent* event) if (dispatchNPEvent(npEvent)) event->setDefaultHandled(); - else if (npTouchEvent.type == TOUCH_EVENT_DOUBLETAP) { - // Send Touch Up if double tap not consumed - npTouchEvent.type = TOUCH_EVENT_END; - npEvent.data = &npTouchEvent; - if (dispatchNPEvent(npEvent)) - event->setDefaultHandled(); - } } void PluginView::handleMouseEvent(MouseEvent* event) @@ -559,19 +545,17 @@ void PluginView::handleMouseEvent(MouseEvent* event) mouseEvent.x = event->offsetX(); mouseEvent.y = event->offsetY(); - if (event->type() == eventNames().mousedownEvent) { + if (event->type() == eventNames().mousedownEvent) mouseEvent.type = MOUSE_BUTTON_DOWN; - parentFrame()->eventHandler()->setCapturingMouseEventsNode(node()); - } else if (event->type() == eventNames().mousemoveEvent) + else if (event->type() == eventNames().mousemoveEvent) mouseEvent.type = MOUSE_MOTION; else if (event->type() == eventNames().mouseoutEvent) mouseEvent.type = MOUSE_OUTBOUND; else if (event->type() == eventNames().mouseoverEvent) mouseEvent.type = MOUSE_OVER; - else if (event->type() == eventNames().mouseupEvent) { + else if (event->type() == eventNames().mouseupEvent) mouseEvent.type = MOUSE_BUTTON_UP; - parentFrame()->eventHandler()->setCapturingMouseEventsNode(0); - } else + else return; mouseEvent.button = event->button(); diff --git a/Source/WebCore/plugins/gtk/PluginViewGtk.cpp b/Source/WebCore/plugins/gtk/PluginViewGtk.cpp index 4006040d8..2e67bc67e 100644 --- a/Source/WebCore/plugins/gtk/PluginViewGtk.cpp +++ b/Source/WebCore/plugins/gtk/PluginViewGtk.cpp @@ -883,6 +883,13 @@ void PluginView::platformDestroy() XFreePixmap(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), m_drawable); m_drawable = 0; } + + GtkWidget* widget = platformWidget(); + if (widget) { + GtkWidget* parent = gtk_widget_get_parent(widget); + ASSERT(parent); + gtk_container_remove(GTK_CONTAINER(parent), widget); + } } } // namespace WebCore diff --git a/Source/WebCore/plugins/win/PluginDatabaseWin.cpp b/Source/WebCore/plugins/win/PluginDatabaseWin.cpp index 20b8af3cf..2460934b4 100644 --- a/Source/WebCore/plugins/win/PluginDatabaseWin.cpp +++ b/Source/WebCore/plugins/win/PluginDatabaseWin.cpp @@ -407,6 +407,16 @@ static inline void addMacromediaPluginDirectories(Vector<String>& directories) #endif } +#if PLATFORM(QT) +static inline void addQtWebKitPluginPath(Vector<String>& directories) +{ + Vector<String> qtPaths; + String qtPath(qgetenv("QTWEBKIT_PLUGIN_PATH").constData()); + qtPath.split(UChar(';'), false, qtPaths); + directories.append(qtPaths); +} +#endif + Vector<String> PluginDatabase::defaultPluginDirectories() { Vector<String> directories; @@ -421,6 +431,7 @@ Vector<String> PluginDatabase::defaultPluginDirectories() addMacromediaPluginDirectories(directories); #if PLATFORM(QT) addJavaPluginDirectory(directories); + addQtWebKitPluginPath(directories); #endif return directories; diff --git a/Source/WebCore/rendering/HitTestResult.cpp b/Source/WebCore/rendering/HitTestResult.cpp index 8553d6f5d..38f1f679f 100644 --- a/Source/WebCore/rendering/HitTestResult.cpp +++ b/Source/WebCore/rendering/HitTestResult.cpp @@ -104,7 +104,7 @@ HitTestLocation::HitTestLocation(const HitTestLocation& other, const LayoutSize& , m_boundingBox(other.m_boundingBox) , m_transformedPoint(other.m_transformedPoint) , m_transformedRect(other.m_transformedRect) - , m_region(region) + , m_region(region ? region : other.m_region) , m_isRectBased(other.m_isRectBased) , m_isRectilinear(other.m_isRectilinear) { @@ -192,34 +192,34 @@ IntRect HitTestLocation::rectForPoint(const LayoutPoint& point, unsigned topPadd return IntRect(actualPoint, actualPadding); } -HitTestResult::HitTestResult() : HitTestLocation() - , m_isOverWidget(false) +HitTestResult::HitTestResult() + : m_isOverWidget(false) { } HitTestResult::HitTestResult(const LayoutPoint& point) - : HitTestLocation(point) + : m_hitTestLocation(point) , m_pointInMainFrame(point) , m_isOverWidget(false) { } HitTestResult::HitTestResult(const LayoutPoint& centerPoint, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding) - : HitTestLocation(centerPoint, topPadding, rightPadding, bottomPadding, leftPadding) + : m_hitTestLocation(centerPoint, topPadding, rightPadding, bottomPadding, leftPadding) , m_pointInMainFrame(centerPoint) , m_isOverWidget(false) { } HitTestResult::HitTestResult(const HitTestLocation& other) - : HitTestLocation(other) - , m_pointInMainFrame(point()) + : m_hitTestLocation(other) + , m_pointInMainFrame(m_hitTestLocation.point()) , m_isOverWidget(false) { } HitTestResult::HitTestResult(const HitTestResult& other) - : HitTestLocation(other) + : m_hitTestLocation(other.m_hitTestLocation) , m_innerNode(other.innerNode()) , m_innerNonSharedNode(other.innerNonSharedNode()) , m_pointInMainFrame(other.m_pointInMainFrame) @@ -238,7 +238,7 @@ HitTestResult::~HitTestResult() HitTestResult& HitTestResult::operator=(const HitTestResult& other) { - HitTestLocation::operator=(other); + m_hitTestLocation = other.m_hitTestLocation; m_innerNode = other.innerNode(); m_innerNonSharedNode = other.innerNonSharedNode(); m_pointInMainFrame = other.m_pointInMainFrame; @@ -315,7 +315,7 @@ bool HitTestResult::isSelected() const if (!frame) return false; - return frame->selection()->contains(point()); + return frame->selection()->contains(m_hitTestLocation.point()); } String HitTestResult::spellingToolTip(TextDirection& dir) const @@ -326,7 +326,7 @@ String HitTestResult::spellingToolTip(TextDirection& dir) const if (!m_innerNonSharedNode) return String(); - DocumentMarker* marker = m_innerNonSharedNode->document()->markers()->markerContainingPoint(point(), DocumentMarker::Grammar); + DocumentMarker* marker = m_innerNonSharedNode->document()->markers()->markerContainingPoint(m_hitTestLocation.point(), DocumentMarker::Grammar); if (!marker) return String(); @@ -342,7 +342,7 @@ String HitTestResult::replacedString() const if (!m_innerNonSharedNode) return String(); - DocumentMarker* marker = m_innerNonSharedNode->document()->markers()->markerContainingPoint(point(), DocumentMarker::Replacement); + DocumentMarker* marker = m_innerNonSharedNode->document()->markers()->markerContainingPoint(m_hitTestLocation.point(), DocumentMarker::Replacement); if (!marker) return String(); @@ -700,21 +700,6 @@ bool HitTestResult::addNodeToRectBasedTestResult(Node* node, const HitTestReques mutableRectBasedTestResult().add(node); bool regionFilled = rect.contains(locationInContainer.boundingBox()); - // FIXME: This code (incorrectly) attempts to correct for culled inline nodes. See https://bugs.webkit.org/show_bug.cgi?id=85849. - if (node->renderer()->isInline() && !regionFilled) { - for (RenderObject* curr = node->renderer()->parent(); curr; curr = curr->parent()) { - if (!curr->isRenderInline()) - break; - - // We need to make sure the nodes for culled inlines get included. - RenderInline* currInline = toRenderInline(curr); - if (currInline->alwaysCreateLineBoxes()) - break; - - if (currInline->visibleToHitTesting() && currInline->node()) - mutableRectBasedTestResult().add(currInline->node()->shadowAncestorNode()); - } - } return !regionFilled; } @@ -735,21 +720,6 @@ bool HitTestResult::addNodeToRectBasedTestResult(Node* node, const HitTestReques mutableRectBasedTestResult().add(node); bool regionFilled = rect.contains(locationInContainer.boundingBox()); - // FIXME: This code (incorrectly) attempts to correct for culled inline nodes. See https://bugs.webkit.org/show_bug.cgi?id=85849. - if (node->renderer()->isInline() && !regionFilled) { - for (RenderObject* curr = node->renderer()->parent(); curr; curr = curr->parent()) { - if (!curr->isRenderInline()) - break; - - // We need to make sure the nodes for culled inlines get included. - RenderInline* currInline = toRenderInline(curr); - if (currInline->alwaysCreateLineBoxes()) - break; - - if (currInline->visibleToHitTesting() && currInline->node()) - mutableRectBasedTestResult().add(currInline->node()->shadowAncestorNode()); - } - } return !regionFilled; } diff --git a/Source/WebCore/rendering/HitTestResult.h b/Source/WebCore/rendering/HitTestResult.h index b219a97dc..57a41dab5 100644 --- a/Source/WebCore/rendering/HitTestResult.h +++ b/Source/WebCore/rendering/HitTestResult.h @@ -45,6 +45,7 @@ class Node; class RenderRegion; class Scrollbar; +// FIXME: HitTestLocation should be moved to a separate file. class HitTestLocation { public: @@ -55,7 +56,7 @@ public: // Pass non-zero padding values to perform a rect-based hit test. HitTestLocation(const LayoutPoint& centerPoint, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding); // Make a copy the HitTestLocation in a new region by applying given offset to internal point and area. - HitTestLocation(const HitTestLocation&, const LayoutSize& offset, RenderRegion*); + HitTestLocation(const HitTestLocation&, const LayoutSize& offset, RenderRegion* = 0); HitTestLocation(const HitTestLocation&); ~HitTestLocation(); HitTestLocation& operator=(const HitTestLocation&); @@ -100,8 +101,7 @@ private: bool m_isRectilinear; }; -// FIXME: HitTestResult should not be a HitTestLocation, but instead have a HitTestLocation. See https://bugs.webkit.org/show_bug.cgi?id=101590 -class HitTestResult : protected HitTestLocation { +class HitTestResult { public: typedef ListHashSet<RefPtr<Node> > NodeSet; @@ -121,7 +121,7 @@ public: bool isOverWidget() const { return m_isOverWidget; } // Forwarded from HitTestLocation - bool isRectBasedTest() const { return HitTestLocation::isRectBasedTest(); } + bool isRectBasedTest() const { return m_hitTestLocation.isRectBasedTest(); } // The hit-tested point in the coordinates of the main frame. const LayoutPoint& pointInMainFrame() const { return m_pointInMainFrame; } @@ -129,7 +129,7 @@ public: void setPointInMainFrame(const LayoutPoint& p) { m_pointInMainFrame = p; } // The hit-tested point in the coordinates of the innerNode frame, the frame containing innerNode. - const LayoutPoint& pointInInnerNodeFrame() const { return HitTestLocation::point(); } + const LayoutPoint& pointInInnerNodeFrame() const { return m_hitTestLocation.point(); } IntPoint roundedPointInInnerNodeFrame() const { return roundedIntPoint(pointInInnerNodeFrame()); } Frame* innerNodeFrame() const; @@ -139,7 +139,7 @@ public: void setToNonShadowAncestor(); - const HitTestLocation& hitTestLocation() const { return *this; } + const HitTestLocation& hitTestLocation() const { return m_hitTestLocation; } void setInnerNode(Node*); void setInnerNonSharedNode(Node*); @@ -198,6 +198,7 @@ private: #if ENABLE(VIDEO) HTMLMediaElement* mediaElement() const; #endif + HitTestLocation m_hitTestLocation; RefPtr<Node> m_innerNode; RefPtr<Node> m_innerNonSharedNode; diff --git a/Source/WebCore/rendering/InlineFlowBox.cpp b/Source/WebCore/rendering/InlineFlowBox.cpp index 36aaf95ec..f2eed4b95 100644 --- a/Source/WebCore/rendering/InlineFlowBox.cpp +++ b/Source/WebCore/rendering/InlineFlowBox.cpp @@ -48,7 +48,7 @@ namespace WebCore { struct SameSizeAsInlineFlowBox : public InlineBox { void* pointers[5]; - uint32_t bitfields : 24; + uint32_t bitfields : 23; }; COMPILE_ASSERT(sizeof(InlineFlowBox) == sizeof(SameSizeAsInlineFlowBox), InlineFlowBox_should_stay_small); @@ -981,12 +981,41 @@ bool InlineFlowBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& re return false; // Check children first. + // We need to account for culled inline parents of the hit-tested nodes, so that they may also get included in area-based hit-tests. + RenderObject* culledParent = 0; for (InlineBox* curr = lastChild(); curr; curr = curr->prevOnLine()) { - if ((curr->renderer()->isText() || !curr->boxModelObject()->hasSelfPaintingLayer()) && curr->nodeAtPoint(request, result, locationInContainer, accumulatedOffset, lineTop, lineBottom)) { - renderer()->updateHitTestResult(result, locationInContainer.point() - toLayoutSize(accumulatedOffset)); - return true; + if (curr->renderer()->isText() || !curr->boxModelObject()->hasSelfPaintingLayer()) { + RenderObject* newParent = 0; + // Culled parents are only relevant for area-based hit-tests, so ignore it in point-based ones. + if (locationInContainer.isRectBasedTest()) { + newParent = curr->renderer()->parent(); + if (newParent == renderer()) + newParent = 0; + } + // Check the culled parent after all its children have been checked, to do this we wait until + // we are about to test an element with a different parent. + if (newParent != culledParent) { + if (!newParent || !newParent->isDescendantOf(culledParent)) { + while (culledParent && culledParent != renderer() && culledParent != newParent) { + if (culledParent->isRenderInline() && toRenderInline(culledParent)->hitTestCulledInline(request, result, locationInContainer, accumulatedOffset)) + return true; + culledParent = culledParent->parent(); + } + } + culledParent = newParent; + } + if (curr->nodeAtPoint(request, result, locationInContainer, accumulatedOffset, lineTop, lineBottom)) { + renderer()->updateHitTestResult(result, locationInContainer.point() - toLayoutSize(accumulatedOffset)); + return true; + } } } + // Check any culled ancestor of the final children tested. + while (culledParent && culledParent != renderer()) { + if (culledParent->isRenderInline() && toRenderInline(culledParent)->hitTestCulledInline(request, result, locationInContainer, accumulatedOffset)) + return true; + culledParent = culledParent->parent(); + } // Now check ourselves. Pixel snap hit testing. LayoutRect frameRect = roundedFrameRect(); diff --git a/Source/WebCore/rendering/InlineFlowBox.h b/Source/WebCore/rendering/InlineFlowBox.h index 48b720c75..36d48dc87 100644 --- a/Source/WebCore/rendering/InlineFlowBox.h +++ b/Source/WebCore/rendering/InlineFlowBox.h @@ -52,7 +52,6 @@ public: , m_baselineType(AlphabeticBaseline) , m_hasAnnotationsBefore(false) , m_hasAnnotationsAfter(false) - , m_isFirstAfterPageBreak(false) #ifndef NDEBUG , m_hasBadChildList(false) #endif @@ -325,7 +324,6 @@ protected: // If the line contains any ruby runs, then this will be true. unsigned m_hasAnnotationsBefore : 1; unsigned m_hasAnnotationsAfter : 1; - unsigned m_isFirstAfterPageBreak : 1; unsigned m_lineBreakBidiStatusEor : 5; // WTF::Unicode::Direction unsigned m_lineBreakBidiStatusLastStrong : 5; // WTF::Unicode::Direction diff --git a/Source/WebCore/rendering/RenderBlock.cpp b/Source/WebCore/rendering/RenderBlock.cpp index d53cd5637..8c6249765 100644 --- a/Source/WebCore/rendering/RenderBlock.cpp +++ b/Source/WebCore/rendering/RenderBlock.cpp @@ -675,6 +675,7 @@ void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox, // We can reuse this block and make it the preBlock of the next continuation. pre = block; pre->removePositionedObjects(0); + pre->removeFloatingObjects(); block = toRenderBlock(block->parent()); } else { // No anonymous block available for use. Make one. @@ -3761,6 +3762,15 @@ void RenderBlock::removePositionedObjects(RenderBlock* o, ContainingBlockState c removePositionedObject(deadObjects.at(i)); } +void RenderBlock::removeFloatingObjects() +{ + if (!m_floatingObjects) + return; + + deleteAllValues(m_floatingObjects->set()); + m_floatingObjects->clear(); +} + RenderBlock::FloatingObject* RenderBlock::insertFloatingObject(RenderBox* o) { ASSERT(o->isFloating()); @@ -7245,7 +7255,14 @@ bool RenderBlock::lineWidthForPaginatedLineChanged(RootInlineBox* rootBox, Layou if (!inRenderFlowThread()) return false; - return rootBox->paginatedLineWidth() != availableLogicalWidthForContent(rootBox->lineTopWithLeading() + lineDelta); + RenderRegion* currentRegion = regionAtBlockOffset(rootBox->lineTopWithLeading() + lineDelta); + // Just bail if we still don't have a region. + if (!rootBox->hasContainingRegion() && !currentRegion) + return false; + // Just bail if the region didn't change. + if (rootBox->hasContainingRegion() && rootBox->containingRegion() == currentRegion) + return false; + return rootBox->paginatedLineWidth() != availableLogicalWidthForContent(currentRegion, offsetFromLogicalTopOfFirstPage()); } LayoutUnit RenderBlock::offsetFromLogicalTopOfFirstPage() const diff --git a/Source/WebCore/rendering/RenderBlock.h b/Source/WebCore/rendering/RenderBlock.h index 89c816c9b..9f008477b 100644 --- a/Source/WebCore/rendering/RenderBlock.h +++ b/Source/WebCore/rendering/RenderBlock.h @@ -117,6 +117,8 @@ public: static void removePositionedObject(RenderBox*); void removePositionedObjects(RenderBlock*, ContainingBlockState = SameContainingBlock); + void removeFloatingObjects(); + TrackedRendererListHashSet* positionedObjects() const; bool hasPositionedObjects() const { diff --git a/Source/WebCore/rendering/RenderBlockLineLayout.cpp b/Source/WebCore/rendering/RenderBlockLineLayout.cpp index eb6b4b5dd..970fbc346 100644 --- a/Source/WebCore/rendering/RenderBlockLineLayout.cpp +++ b/Source/WebCore/rendering/RenderBlockLineLayout.cpp @@ -1508,6 +1508,9 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin setLogicalHeight(lineBox->lineBottomWithLeading()); } + + if (inRenderFlowThread()) + lineBox->setContainingRegion(regionAtBlockOffset(lineBox->lineTopWithLeading())); } } @@ -1562,6 +1565,8 @@ void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState) layoutState.updateRepaintRangeFromBox(line, delta); line->adjustBlockDirectionPosition(delta); } + if (inRenderFlowThread()) + line->setContainingRegion(regionAtBlockOffset(line->lineTopWithLeading())); if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) { Vector<RenderBox*>::iterator end = cleanLineFloats->end(); for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) { @@ -1599,6 +1604,8 @@ void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState) LayoutRect logicalLayoutOverflow(0, blockLogicalHeight, 1, bottomLayoutOverflow - blockLogicalHeight); LayoutRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight); trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom()); + if (inRenderFlowThread()) + trailingFloatsLineBox->setContainingRegion(regionAtBlockOffset(trailingFloatsLineBox->lineTopWithLeading())); } const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set(); @@ -1793,6 +1800,8 @@ RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState, layoutState.updateRepaintRangeFromBox(curr, paginationDelta); curr->adjustBlockDirectionPosition(paginationDelta); } + if (inRenderFlowThread()) + curr->setContainingRegion(regionAtBlockOffset(curr->lineTopWithLeading())); } // If a new float has been inserted before this line or before its last known float, just do a full layout. @@ -2627,7 +2636,7 @@ InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resol wordMeasurement.startOffset = lastSpace; float additionalTmpW; - if (wordTrailingSpaceWidth && currentCharacterIsSpace) + if (wordTrailingSpaceWidth && c == ' ') additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) - wordTrailingSpaceWidth; else additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout); diff --git a/Source/WebCore/rendering/RenderBox.cpp b/Source/WebCore/rendering/RenderBox.cpp index e999113bf..44f3de11a 100644 --- a/Source/WebCore/rendering/RenderBox.cpp +++ b/Source/WebCore/rendering/RenderBox.cpp @@ -68,6 +68,10 @@ typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap; static OverrideSizeMap* gOverrideHeightMap = 0; static OverrideSizeMap* gOverrideWidthMap = 0; +// Used by grid elements to properly size their grid items. +static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = 0; +static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = 0; + bool RenderBox::s_hadOverflowClip = false; RenderBox::RenderBox(Node* node) @@ -133,6 +137,7 @@ void RenderBox::clearRenderBoxRegionInfo() void RenderBox::willBeDestroyed() { clearOverrideSize(); + clearContainingBlockOverrideSize(); RenderBlock::removePercentHeightDescendantIfNeeded(this); @@ -738,6 +743,50 @@ LayoutUnit RenderBox::overrideLogicalContentHeight() const return gOverrideHeightMap->get(this); } +LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const +{ + ASSERT(hasOverrideContainingBlockLogicalWidth()); + return gOverrideContainingBlockLogicalWidthMap->get(this); +} + +LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const +{ + ASSERT(hasOverrideContainingBlockLogicalHeight()); + return gOverrideContainingBlockLogicalHeightMap->get(this); +} + +bool RenderBox::hasOverrideContainingBlockLogicalWidth() const +{ + return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this); +} + +bool RenderBox::hasOverrideContainingBlockLogicalHeight() const +{ + return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this); +} + +void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth) +{ + if (!gOverrideContainingBlockLogicalWidthMap) + gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap; + gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth); +} + +void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight) +{ + if (!gOverrideContainingBlockLogicalHeightMap) + gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap; + gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight); +} + +void RenderBox::clearContainingBlockOverrideSize() +{ + if (gOverrideContainingBlockLogicalWidthMap) + gOverrideContainingBlockLogicalWidthMap->remove(this); + if (gOverrideContainingBlockLogicalHeightMap) + gOverrideContainingBlockLogicalHeightMap->remove(this); +} + LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const { LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth(); @@ -1251,10 +1300,22 @@ LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStar LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const { + if (hasOverrideContainingBlockLogicalWidth()) + return overrideContainingBlockContentLogicalWidth(); + RenderBlock* cb = containingBlock(); return cb->availableLogicalWidth(); } +LayoutUnit RenderBox::containingBlockLogicalHeightForContent() const +{ + if (hasOverrideContainingBlockLogicalHeight()) + return overrideContainingBlockContentLogicalHeight(); + + RenderBlock* cb = containingBlock(); + return cb->availableLogicalHeight(); +} + LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const { if (!region) @@ -1262,6 +1323,8 @@ LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion RenderBlock* cb = containingBlock(); RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region); + // FIXME: It's unclear if a region's content should use the containing block's override logical width. + // If it should, the following line should call containingBlockLogicalWidthForContent. LayoutUnit result = cb->availableLogicalWidth(); RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop()); if (!boxInfo) @@ -1285,6 +1348,9 @@ LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* re LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const { + if (hasOverrideContainingBlockLogicalHeight()) + return overrideContainingBlockContentLogicalHeight(); + RenderBlock* cb = containingBlock(); if (cb->hasOverrideHeight()) return cb->overrideLogicalContentHeight(); @@ -2194,11 +2260,13 @@ LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const bool skippedAutoHeightContainingBlock = false; RenderBlock* cb = containingBlock(); + const RenderBox* containingBlockChild = this; LayoutUnit rootMarginBorderPaddingHeight = 0; while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb)) { if (cb->isBody() || cb->isRoot()) rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight(); skippedAutoHeightContainingBlock = true; + containingBlockChild = cb; cb = cb->containingBlock(); cb->addPercentHeightDescendant(const_cast<RenderBox*>(this)); } @@ -2214,7 +2282,9 @@ LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const bool includeBorderPadding = isTable(); if (isHorizontalWritingMode() != cb->isHorizontalWritingMode()) - availableHeight = cb->contentLogicalWidth(); + availableHeight = containingBlockChild->containingBlockLogicalWidthForContent(); + else if (hasOverrideContainingBlockLogicalHeight()) + availableHeight = overrideContainingBlockContentLogicalHeight(); else if (cb->isTableCell()) { if (!skippedAutoHeightContainingBlock) { // Table cells violate what the CSS spec says to do with heights. Basically we @@ -2361,7 +2431,7 @@ LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(SizeType sizeType, Lengt if (isOutOfFlowPositioned()) availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb)); else { - availableHeight = toRenderBox(cb)->availableLogicalHeight(); + availableHeight = containingBlockLogicalHeightForContent(); // It is necessary to use the border-box to match WinIE's broken // box model. This is essential for sizing inside // table cells using percentage heights. @@ -2429,7 +2499,7 @@ LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h) const } // FIXME: This is wrong if the containingBlock has a perpendicular writing mode. - return containingBlock()->availableLogicalHeight(); + return containingBlockLogicalHeightForContent(); } void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const @@ -2959,8 +3029,14 @@ static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const { if (isReplaced()) { - computePositionedLogicalHeightReplaced(computedValues); - return; + // FIXME: For regions with height auto, we want to compute width using the normal block sizing code. + // For now, regions are replaced elements and this code can be removed once the RenderRegion + // will inherit from RenderBlock instead of RenderReplaced. + // (see https://bugs.webkit.org/show_bug.cgi?id=74132 ) + if (!isRenderRegion() || (isRenderRegion() && shouldComputeSizeAsReplaced())) { + computePositionedLogicalHeightReplaced(computedValues); + return; + } } // The following is based off of the W3C Working Draft from April 11, 2006 of diff --git a/Source/WebCore/rendering/RenderBox.h b/Source/WebCore/rendering/RenderBox.h index 156b72921..c1de3e736 100644 --- a/Source/WebCore/rendering/RenderBox.h +++ b/Source/WebCore/rendering/RenderBox.h @@ -305,6 +305,14 @@ public: void clearOverrideLogicalContentHeight(); void clearOverrideLogicalContentWidth(); + LayoutUnit overrideContainingBlockContentLogicalWidth() const; + LayoutUnit overrideContainingBlockContentLogicalHeight() const; + bool hasOverrideContainingBlockLogicalWidth() const; + bool hasOverrideContainingBlockLogicalHeight() const; + void setOverrideContainingBlockContentLogicalWidth(LayoutUnit); + void setOverrideContainingBlockContentLogicalHeight(LayoutUnit); + void clearContainingBlockOverrideSize(); + virtual LayoutSize offsetFromContainer(RenderObject*, const LayoutPoint&, bool* offsetDependsOnPoint = 0) const; LayoutUnit adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const; @@ -368,6 +376,8 @@ public: virtual void repaintDuringLayoutIfMoved(const LayoutRect&); virtual LayoutUnit containingBlockLogicalWidthForContent() const; + LayoutUnit containingBlockLogicalHeightForContent() const; + LayoutUnit containingBlockLogicalWidthForContentInRegion(RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage) const; LayoutUnit containingBlockAvailableLineWidthInRegion(RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage) const; LayoutUnit perpendicularContainingBlockLogicalHeight() const; diff --git a/Source/WebCore/rendering/RenderFlowThread.cpp b/Source/WebCore/rendering/RenderFlowThread.cpp index 13809b00d..4aa170a2c 100644 --- a/Source/WebCore/rendering/RenderFlowThread.cpp +++ b/Source/WebCore/rendering/RenderFlowThread.cpp @@ -737,7 +737,7 @@ void RenderFlowThread::resetRegionsOverrideLogicalContentHeight() // We need to reset the override logical content height for regions with auto logical height // only if the flow thread content needs layout. - if (!selfNeedsLayout()) + if (!needsLayout()) return; // FIXME: optimize this to iterate the region chain only if the flow thread has auto logical height @@ -753,6 +753,9 @@ void RenderFlowThread::resetRegionsOverrideLogicalContentHeight() // as we are already inside layout. region->setNeedsLayout(true); } + // Make sure we don't skip any region breaks when we do the layout again. + // Using m_regionsInvalidated to force all the RenderFlowThread children do the layout again. + m_regionsInvalidated = true; } void RenderFlowThread::markAutoLogicalHeightRegionsForLayout() diff --git a/Source/WebCore/rendering/RenderGrid.cpp b/Source/WebCore/rendering/RenderGrid.cpp index e520581b9..492a83f88 100644 --- a/Source/WebCore/rendering/RenderGrid.cpp +++ b/Source/WebCore/rendering/RenderGrid.cpp @@ -161,6 +161,15 @@ void RenderGrid::layoutGridItems() for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) { LayoutPoint childPosition = findChildLogicalPosition(child, columnTracks, rowTracks); + + size_t columnTrack = resolveGridPosition(child->style()->gridItemColumn()); + size_t rowTrack = resolveGridPosition(child->style()->gridItemRow()); + + // Because the grid area cannot be styled, we don't need to adjust + // the grid breadth to account for 'box-sizing'. + child->setOverrideContainingBlockContentLogicalWidth(columnTracks[columnTrack].m_usedBreadth); + child->setOverrideContainingBlockContentLogicalHeight(rowTracks[rowTrack].m_usedBreadth); + // FIXME: Grid items should stretch to fill their cells. Once we // implement grid-{column,row}-align, we can also shrink to fit. For // now, just size as if we were a regular child. diff --git a/Source/WebCore/rendering/RenderInline.cpp b/Source/WebCore/rendering/RenderInline.cpp index 4e27e6d99..db1b185f6 100644 --- a/Source/WebCore/rendering/RenderInline.cpp +++ b/Source/WebCore/rendering/RenderInline.cpp @@ -455,6 +455,7 @@ void RenderInline::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox // We can reuse this block and make it the preBlock of the next continuation. pre = block; pre->removePositionedObjects(0); + pre->removeFloatingObjects(); block = block->containingBlock(); } else { // No anonymous block available for use. Make one. @@ -774,6 +775,47 @@ bool RenderInline::nodeAtPoint(const HitTestRequest& request, HitTestResult& res return m_lineBoxes.hitTest(this, request, result, locationInContainer, accumulatedOffset, hitTestAction); } +namespace { + +class HitTestCulledInlinesGeneratorContext { +public: + HitTestCulledInlinesGeneratorContext(Region& region, const HitTestLocation& location) : m_intersected(false), m_region(region), m_location(location) { } + void operator()(const FloatRect& rect) + { + m_intersected = m_intersected || m_location.intersects(rect); + m_region.unite(enclosingIntRect(rect)); + } + bool intersected() const { return m_intersected; } +private: + bool m_intersected; + Region& m_region; + const HitTestLocation& m_location; +}; + +} // unnamed namespace + +bool RenderInline::hitTestCulledInline(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) +{ + ASSERT(result.isRectBasedTest() && !alwaysCreateLineBoxes()); + if (!visibleToHitTesting()) + return false; + + HitTestLocation tmpLocation(locationInContainer, -toLayoutSize(accumulatedOffset)); + + Region regionResult; + HitTestCulledInlinesGeneratorContext context(regionResult, tmpLocation); + generateCulledLineBoxRects(context, this); + + if (context.intersected()) { + updateHitTestResult(result, tmpLocation.point()); + // We can not use addNodeToRectBasedTestResult to determine if we fully enclose the hit-test area + // because it can only handle rectangular targets. + result.addNodeToRectBasedTestResult(node(), request, locationInContainer); + return regionResult.contains(enclosingIntRect(tmpLocation.boundingBox())); + } + return false; +} + VisiblePosition RenderInline::positionForPoint(const LayoutPoint& point) { // FIXME: Does not deal with relative or sticky positioned inlines (should it?) diff --git a/Source/WebCore/rendering/RenderInline.h b/Source/WebCore/rendering/RenderInline.h index 0b13f632c..845904b65 100644 --- a/Source/WebCore/rendering/RenderInline.h +++ b/Source/WebCore/rendering/RenderInline.h @@ -89,6 +89,8 @@ public: virtual LayoutRect localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine) OVERRIDE; + bool hitTestCulledInline(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset); + protected: virtual void willBeDestroyed(); diff --git a/Source/WebCore/rendering/RenderLayer.cpp b/Source/WebCore/rendering/RenderLayer.cpp index b4b01b057..3c7cf6e56 100644 --- a/Source/WebCore/rendering/RenderLayer.cpp +++ b/Source/WebCore/rendering/RenderLayer.cpp @@ -343,6 +343,9 @@ void RenderLayer::updateLayerPositions(RenderGeometryMap* geometryMap, UpdateLay // to our parent layer. if (geometryMap) geometryMap->pushMappingsToAncestor(this, parent()); + + // Clear our cached clip rect information. + clearClipRects(); if (hasOverflowControls()) { LayoutPoint offsetFromRoot; @@ -494,13 +497,24 @@ void RenderLayer::clearRepaintRects() m_outlineBox = IntRect(); } -void RenderLayer::updateLayerPositionsAfterScroll() +void RenderLayer::updateLayerPositionsAfterDocumentScroll() +{ + ASSERT(this == renderer()->view()->layer()); + + RenderGeometryMap geometryMap(UseTransforms); + updateLayerPositionsAfterScroll(&geometryMap); +} + +void RenderLayer::updateLayerPositionsAfterOverflowScroll() { RenderGeometryMap geometryMap(UseTransforms); RenderView* view = renderer()->view(); if (this != view->layer()) geometryMap.pushMappingsToAncestor(parent(), 0); - updateLayerPositionsAfterScroll(&geometryMap); + + // FIXME: why is it OK to not check the ancestors of this layer in order to + // initialize the HasSeenViewportConstrainedAncestor and HasSeenAncestorWithOverflowClip flags? + updateLayerPositionsAfterScroll(&geometryMap, IsOverflowScroll); } void RenderLayer::updateLayerPositionsAfterScroll(RenderGeometryMap* geometryMap, UpdateLayerPositionsAfterScrollFlags flags) @@ -515,25 +529,32 @@ void RenderLayer::updateLayerPositionsAfterScroll(RenderGeometryMap* geometryMap if (!m_hasVisibleDescendant && !m_hasVisibleContent) return; - updateLayerPosition(); + bool positionChanged = updateLayerPosition(); + if (positionChanged) + flags |= HasChangedAncestor; if (geometryMap) geometryMap->pushMappingsToAncestor(this, parent()); - if ((flags & HasSeenViewportConstrainedAncestor) || renderer()->style()->hasViewportConstrainedPosition()) { - // FIXME: Is it worth passing the offsetFromRoot around like in updateLayerPositions? - // FIXME: We could track the repaint container as we walk down the tree. - computeRepaintRects(renderer()->containerForRepaint(), geometryMap); + if (flags & HasChangedAncestor || flags & HasSeenViewportConstrainedAncestor || flags & IsOverflowScroll) + clearClipRects(); + + if (renderer()->style()->hasViewportConstrainedPosition()) flags |= HasSeenViewportConstrainedAncestor; - } else if ((flags & HasSeenAncestorWithOverflowClip) && !m_canSkipRepaintRectsUpdateOnScroll) { - // If we have seen an overflow clip, we should update our repaint rects as clippedOverflowRectForRepaint - // intersects it with our ancestor overflow clip that may have moved. - computeRepaintRects(renderer()->containerForRepaint(), geometryMap); - } if (renderer()->hasOverflowClip()) flags |= HasSeenAncestorWithOverflowClip; + if (flags & HasSeenViewportConstrainedAncestor + || (flags & IsOverflowScroll && flags & HasSeenAncestorWithOverflowClip && !m_canSkipRepaintRectsUpdateOnScroll)) { + // FIXME: We could track the repaint container as we walk down the tree. + computeRepaintRects(renderer()->containerForRepaint(), geometryMap); + } else { + // Check that our cached rects are correct. + ASSERT(m_repaintRect == renderer()->clippedOverflowRectForRepaint(renderer()->containerForRepaint())); + ASSERT(m_outlineBox == renderer()->outlineBoundsForRepaint(renderer()->containerForRepaint(), geometryMap)); + } + for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) child->updateLayerPositionsAfterScroll(geometryMap, flags); @@ -834,7 +855,7 @@ bool RenderLayer::update3DTransformedDescendantStatus() return has3DTransform(); } -void RenderLayer::updateLayerPosition() +bool RenderLayer::updateLayerPosition() { LayoutPoint localPoint; LayoutSize inlineBoundingBoxOffset; // We don't put this into the RenderLayer x/y for inlines, so we need to subtract it out when done. @@ -850,9 +871,6 @@ void RenderLayer::updateLayerPosition() localPoint += box->topLeftLocationOffset(); } - // Clear our cached clip rect information. - clearClipRects(); - if (!renderer()->isOutOfFlowPositioned() && renderer()->parent()) { // We must adjust our position by walking up the render tree looking for the // nearest enclosing object with a layer. @@ -900,8 +918,11 @@ void RenderLayer::updateLayerPosition() localPoint -= scrollOffset; } + bool positionOrOffsetChanged = false; if (renderer()->isInFlowPositioned()) { - m_offsetForInFlowPosition = toRenderBoxModelObject(renderer())->offsetForInFlowPosition(); + LayoutSize newOffset = toRenderBoxModelObject(renderer())->offsetForInFlowPosition(); + positionOrOffsetChanged = newOffset != m_offsetForInFlowPosition; + m_offsetForInFlowPosition = newOffset; localPoint.move(m_offsetForInFlowPosition); } else { m_offsetForInFlowPosition = LayoutSize(); @@ -909,7 +930,10 @@ void RenderLayer::updateLayerPosition() // FIXME: We'd really like to just get rid of the concept of a layer rectangle and rely on the renderers. localPoint -= inlineBoundingBoxOffset; - setLocation(localPoint.x(), localPoint.y()); + + positionOrOffsetChanged |= location() != localPoint; + setLocation(localPoint); + return positionOrOffsetChanged; } TransformationMatrix RenderLayer::perspectiveTransform() const @@ -1736,7 +1760,7 @@ void RenderLayer::scrollTo(int x, int y) bool inLayout = view ? view->frameView()->isInLayout() : false; if (!inLayout) { // If we're in the middle of layout, we'll just update layers once layout has finished. - updateLayerPositionsAfterScroll(); + updateLayerPositionsAfterOverflowScroll(); if (view) { // Update regions, scrolling may change the clip of a particular region. #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION) @@ -4128,6 +4152,15 @@ void RenderLayer::updateClipRects(const ClipRectsContext& clipRectsContext) ASSERT(clipRectsContext.rootLayer == m_clipRectsCache->m_clipRectsRoot[clipRectsType]); ASSERT(m_clipRectsCache->m_respectingOverflowClip[clipRectsType] == (clipRectsContext.respectOverflowClip == RespectOverflowClip)); ASSERT(m_clipRectsCache->m_scrollbarRelevancy[clipRectsType] == clipRectsContext.overlayScrollbarSizeRelevancy); + +#ifdef CHECK_CACHED_CLIP_RECTS + // This code is useful to check cached clip rects, but is too expensive to leave enabled in debug builds by default. + ClipRectsContext tempContext(clipRectsContext); + tempContext.clipRectsType = TemporaryClipRects; + ClipRects clipRects; + calculateClipRects(tempContext, clipRects); + ASSERT(clipRects == *m_clipRectsCache->m_clipRects[clipRectsType].get()); +#endif return; // We have the correct cached value. } diff --git a/Source/WebCore/rendering/RenderLayer.h b/Source/WebCore/rendering/RenderLayer.h index 0b14a6d6b..65f1070ab 100644 --- a/Source/WebCore/rendering/RenderLayer.h +++ b/Source/WebCore/rendering/RenderLayer.h @@ -309,7 +309,7 @@ public: } const LayoutPoint& location() const { return m_topLeft; } - void setLocation(LayoutUnit x, LayoutUnit y) { m_topLeft = LayoutPoint(x, y); } + void setLocation(const LayoutPoint& p) { m_topLeft = p; } const IntSize& size() const { return m_layerSize; } void setSize(const IntSize& size) { m_layerSize = size; } @@ -390,7 +390,8 @@ public: bool canRender3DTransforms() const; - void updateLayerPosition(); + // Returns true if the position changed. + bool updateLayerPosition(); enum UpdateLayerPositionsFlag { CheckForRepaint = 1, @@ -402,7 +403,9 @@ public: static const UpdateLayerPositionsFlags defaultFlags = CheckForRepaint | IsCompositingUpdateRoot | UpdateCompositingLayers; void updateLayerPositionsAfterLayout(const RenderLayer* rootLayer, UpdateLayerPositionsFlags); - void updateLayerPositionsAfterScroll(); + + void updateLayerPositionsAfterOverflowScroll(); + void updateLayerPositionsAfterDocumentScroll(); bool isPaginated() const { return m_isPaginated; } @@ -740,8 +743,10 @@ private: enum UpdateLayerPositionsAfterScrollFlag { NoFlag = 0, - HasSeenViewportConstrainedAncestor = 1 << 0, - HasSeenAncestorWithOverflowClip = 1 << 1 + IsOverflowScroll = 1 << 0, + HasSeenViewportConstrainedAncestor = 1 << 1, + HasSeenAncestorWithOverflowClip = 1 << 2, + HasChangedAncestor = 1 << 3 }; typedef unsigned UpdateLayerPositionsAfterScrollFlags; void updateLayerPositionsAfterScroll(RenderGeometryMap*, UpdateLayerPositionsAfterScrollFlags = NoFlag); diff --git a/Source/WebCore/rendering/RenderNamedFlowThread.cpp b/Source/WebCore/rendering/RenderNamedFlowThread.cpp index c4efc63c3..d4b9ae5f8 100644 --- a/Source/WebCore/rendering/RenderNamedFlowThread.cpp +++ b/Source/WebCore/rendering/RenderNamedFlowThread.cpp @@ -113,15 +113,20 @@ RenderObject* RenderNamedFlowThread::previousRendererForNode(Node* node) const return 0; } -void RenderNamedFlowThread::addFlowChild(RenderObject* newChild, RenderObject* beforeChild) +void RenderNamedFlowThread::addFlowChild(RenderObject* newChild) { // The child list is used to sort the flow thread's children render objects // based on their corresponding nodes DOM order. The list is needed to avoid searching the whole DOM. + Node* childNode = newChild->node(); + // Do not add anonymous objects. - if (!newChild->node()) + if (!childNode) return; + ASSERT(childNode->isElementNode()); + + RenderObject* beforeChild = nextRendererForNode(childNode); if (beforeChild) m_flowThreadChildList.insertBefore(beforeChild, newChild); else diff --git a/Source/WebCore/rendering/RenderNamedFlowThread.h b/Source/WebCore/rendering/RenderNamedFlowThread.h index a833151bf..2bd438bbc 100644 --- a/Source/WebCore/rendering/RenderNamedFlowThread.h +++ b/Source/WebCore/rendering/RenderNamedFlowThread.h @@ -55,7 +55,7 @@ public: RenderObject* nextRendererForNode(Node*) const; RenderObject* previousRendererForNode(Node*) const; - void addFlowChild(RenderObject* newChild, RenderObject* beforeChild = 0); + void addFlowChild(RenderObject* newChild); void removeFlowChild(RenderObject*); bool hasChildren() const { return !m_flowThreadChildList.isEmpty(); } #ifndef NDEBUG diff --git a/Source/WebCore/rendering/RenderObject.cpp b/Source/WebCore/rendering/RenderObject.cpp index 15dcdd058..110467ad5 100644 --- a/Source/WebCore/rendering/RenderObject.cpp +++ b/Source/WebCore/rendering/RenderObject.cpp @@ -604,7 +604,7 @@ RenderFlowThread* RenderObject::enclosingRenderFlowThread() const return 0; } -RenderNamedFlowThread* RenderObject::enclosingRenderNamedFlowThread() const +RenderNamedFlowThread* RenderObject::renderNamedFlowThreadWrapper() const { RenderObject* object = const_cast<RenderObject*>(this); while (object && object->isAnonymousBlock() && !object->isRenderNamedFlowThread()) @@ -1292,10 +1292,13 @@ RenderLayerModelObject* RenderObject::containerForRepaint() const // If we have a flow thread, then we need to do individual repaints within the RenderRegions instead. // Return the flow thread as a repaint container in order to create a chokepoint that allows us to change // repainting to do individual region repaints. - // FIXME: Composited layers inside a flow thread will bypass this mechanism and will malfunction. It's not - // clear how to address this problem for composited descendants of a RenderFlowThread. - if (!repaintContainer && inRenderFlowThread()) - repaintContainer = enclosingRenderFlowThread(); + if (inRenderFlowThread()) { + RenderFlowThread* parentRenderFlowThread = enclosingRenderFlowThread(); + // If we have already found a repaint container then we will repaint into that container only if it is part of the same + // flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread. + if (!(repaintContainer && repaintContainer->inRenderFlowThread() && repaintContainer->enclosingRenderFlowThread() == parentRenderFlowThread)) + repaintContainer = parentRenderFlowThread; + } return repaintContainer; } @@ -2419,7 +2422,7 @@ void RenderObject::insertedIntoTree() if (!isFloating() && parent()->childrenInline()) parent()->dirtyLinesFromChangedChild(this); - if (RenderNamedFlowThread* containerFlowThread = parent()->enclosingRenderNamedFlowThread()) + if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper()) containerFlowThread->addFlowChild(this); } @@ -2444,12 +2447,10 @@ void RenderObject::willBeRemovedFromTree() if (isOutOfFlowPositioned() && parent()->childrenInline()) parent()->dirtyLinesFromChangedChild(this); - if (inRenderFlowThread()) { - ASSERT(enclosingRenderFlowThread()); - enclosingRenderFlowThread()->removeFlowChildInfo(this); - } + if (inRenderFlowThread()) + removeFromRenderFlowThread(); - if (RenderNamedFlowThread* containerFlowThread = parent()->enclosingRenderNamedFlowThread()) + if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper()) containerFlowThread->removeFlowChild(this); #if ENABLE(SVG) @@ -2458,6 +2459,27 @@ void RenderObject::willBeRemovedFromTree() #endif } +void RenderObject::removeFromRenderFlowThread() +{ + RenderFlowThread* renderFlowThread = enclosingRenderFlowThread(); + ASSERT(renderFlowThread); + // Sometimes we remove the element from the flow, but it's not destroyed at that time. + // It's only until later when we actually destroy it and remove all the children from it. + // Currently, that happens for firstLetter elements and list markers. + // Pass in the flow thread so that we don't have to look it up for all the children. + removeFromRenderFlowThreadRecursive(renderFlowThread); +} + +void RenderObject::removeFromRenderFlowThreadRecursive(RenderFlowThread* renderFlowThread) +{ + if (const RenderObjectChildList* children = virtualChildren()) { + for (RenderObject* child = children->firstChild(); child; child = child->nextSibling()) + child->removeFromRenderFlowThreadRecursive(renderFlowThread); + } + renderFlowThread->removeFlowChildInfo(this); + setInRenderFlowThread(false); +} + void RenderObject::destroyAndCleanupAnonymousWrappers() { // If the tree is destroyed, there is no need for a clean-up phase. @@ -2540,7 +2562,7 @@ void RenderObject::updateDragState(bool dragOn) { bool valueChanged = (dragOn != isDragging()); setIsDragging(dragOn); - if (valueChanged && style()->affectedByDragRules() && node()) + if (valueChanged && node() && (style()->affectedByDrag() || (node()->isElementNode() && toElement(node())->childrenAffectedByDrag()))) node()->setNeedsStyleRecalc(); for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling()) curr->updateDragState(dragOn); diff --git a/Source/WebCore/rendering/RenderObject.h b/Source/WebCore/rendering/RenderObject.h index 9ffbcfb74..258276b36 100644 --- a/Source/WebCore/rendering/RenderObject.h +++ b/Source/WebCore/rendering/RenderObject.h @@ -155,11 +155,9 @@ const int showTreeCharacterOffset = 39; // Base class for all rendering tree objects. class RenderObject : public CachedImageClient { - friend class LayoutRepainter; friend class RenderBlock; friend class RenderLayer; friend class RenderObjectChildList; - friend class RenderSVGContainer; public: // Anonymous objects should pass the document as their node, and they will then automatically be // marked as anonymous in the constructor. @@ -243,7 +241,7 @@ public: // Function to return our enclosing flow thread if we are contained inside one. RenderFlowThread* enclosingRenderFlowThread() const; - RenderNamedFlowThread* enclosingRenderNamedFlowThread() const; + RenderNamedFlowThread* renderNamedFlowThreadWrapper() const; virtual bool isEmpty() const { return firstChild() == 0; } @@ -811,6 +809,7 @@ public: IntRect pixelSnappedAbsoluteClippedOverflowRect() const; virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const; virtual LayoutRect rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const; + virtual LayoutRect outlineBoundsForRepaint(const RenderLayerModelObject* /*repaintContainer*/, const RenderGeometryMap* = 0) const { return LayoutRect(); } // Given a rect in the object's coordinate space, compute a rect suitable for repainting // that rect in view coordinates. @@ -980,14 +979,15 @@ protected: virtual void willBeDestroyed(); void arenaDelete(RenderArena*, void* objectBase); - virtual LayoutRect outlineBoundsForRepaint(const RenderLayerModelObject* /*repaintContainer*/, const RenderGeometryMap* = 0) const { return LayoutRect(); } - virtual bool canBeReplacedWithInlineRunIn() const; virtual void insertedIntoTree(); virtual void willBeRemovedFromTree(); private: + void removeFromRenderFlowThread(); + void removeFromRenderFlowThreadRecursive(RenderFlowThread*); + RenderStyle* cachedFirstLineStyle() const; StyleDifference adjustStyleDifference(StyleDifference, unsigned contextSensitiveProperties) const; diff --git a/Source/WebCore/rendering/RenderRegion.h b/Source/WebCore/rendering/RenderRegion.h index f72b9289d..5617ae802 100644 --- a/Source/WebCore/rendering/RenderRegion.h +++ b/Source/WebCore/rendering/RenderRegion.h @@ -114,12 +114,6 @@ public: // or columns added together. virtual LayoutUnit logicalHeightOfAllFlowThreadContent() const; - bool shouldHaveAutoLogicalHeight() const - { - bool hasSpecifiedEndpointsForHeight = style()->logicalTop().isSpecified() && style()->logicalBottom().isSpecified(); - bool hasAnchoredEndpointsForHeight = isOutOfFlowPositioned() && hasSpecifiedEndpointsForHeight; - return style()->logicalHeight().isAuto() && !hasAnchoredEndpointsForHeight; - } bool hasAutoLogicalHeight() const { return m_hasAutoLogicalHeight; } bool needsOverrideLogicalContentHeightComputation() const; @@ -152,8 +146,15 @@ private: // FIXME: these functions should be revisited once RenderRegion inherits from RenderBlock // instead of RenderReplaced (see https://bugs.webkit.org/show_bug.cgi?id=74132 ) // When width is auto, use normal block/box sizing code except when inline. - virtual bool isInlineBlockOrInlineTable() const OVERRIDE { return isInline() && style()->logicalWidth().isAuto(); } - virtual bool shouldComputeSizeAsReplaced() const OVERRIDE { return !style()->logicalWidth().isAuto(); } + virtual bool isInlineBlockOrInlineTable() const OVERRIDE { return isInline() && !shouldComputeSizeAsReplaced(); } + virtual bool shouldComputeSizeAsReplaced() const OVERRIDE { return !style()->logicalWidth().isAuto() && !style()->logicalHeight().isAuto(); } + + bool shouldHaveAutoLogicalHeight() const + { + bool hasSpecifiedEndpointsForHeight = style()->logicalTop().isSpecified() && style()->logicalBottom().isSpecified(); + bool hasAnchoredEndpointsForHeight = isOutOfFlowPositioned() && hasSpecifiedEndpointsForHeight; + return style()->logicalHeight().isAuto() && !hasAnchoredEndpointsForHeight; + } virtual void insertedIntoTree() OVERRIDE; virtual void willBeRemovedFromTree() OVERRIDE; diff --git a/Source/WebCore/rendering/RenderSlider.cpp b/Source/WebCore/rendering/RenderSlider.cpp index 07b1d7d14..d5b90cad6 100644 --- a/Source/WebCore/rendering/RenderSlider.cpp +++ b/Source/WebCore/rendering/RenderSlider.cpp @@ -106,16 +106,8 @@ void RenderSlider::layout() // FIXME: Find a way to cascade appearance. // http://webkit.org/b/62535 RenderBox* thumbBox = sliderThumbElementOf(node())->renderBox(); - if (thumbBox && thumbBox->isSliderThumb()) { + if (thumbBox && thumbBox->isSliderThumb()) static_cast<RenderSliderThumb*>(thumbBox)->updateAppearance(style()); - if (RenderObject* limiterRenderer = trackLimiterElementOf(node())->renderer()) { - if (limiterRenderer->isSliderThumb()) { - static_cast<RenderSliderThumb*>(limiterRenderer)->updateAppearance(style()); - limiterRenderer->style()->setWidth(thumbBox->style()->width()); - limiterRenderer->style()->setHeight(thumbBox->style()->height()); - } - } - } RenderBlock::layout(); } diff --git a/Source/WebCore/rendering/RenderSnapshottedPlugIn.cpp b/Source/WebCore/rendering/RenderSnapshottedPlugIn.cpp index 272f04b93..972b2bf90 100644 --- a/Source/WebCore/rendering/RenderSnapshottedPlugIn.cpp +++ b/Source/WebCore/rendering/RenderSnapshottedPlugIn.cpp @@ -72,7 +72,7 @@ void RenderSnapshottedPlugIn::updateSnapshot(PassRefPtr<Image> image) void RenderSnapshottedPlugIn::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset) { - if (plugInImageElement()->displayState() < HTMLPlugInElement::Playing) { + if (plugInImageElement()->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick) { RenderReplaced::paint(paintInfo, paintOffset); return; } @@ -82,7 +82,7 @@ void RenderSnapshottedPlugIn::paint(PaintInfo& paintInfo, const LayoutPoint& pai void RenderSnapshottedPlugIn::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset) { - if (plugInImageElement()->displayState() < HTMLPlugInElement::Playing) { + if (plugInImageElement()->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick) { paintReplacedSnapshot(paintInfo, paintOffset); paintButton(paintInfo, paintOffset); return; @@ -159,7 +159,7 @@ void RenderSnapshottedPlugIn::repaintButton() CursorDirective RenderSnapshottedPlugIn::getCursor(const LayoutPoint& point, Cursor& overrideCursor) const { - if (plugInImageElement()->displayState() < HTMLPlugInElement::Playing) { + if (plugInImageElement()->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick) { overrideCursor = handCursor(); return SetCursor; } @@ -174,7 +174,12 @@ void RenderSnapshottedPlugIn::handleEvent(Event* event) MouseEvent* mouseEvent = static_cast<MouseEvent*>(event); if (event->type() == eventNames().clickEvent && mouseEvent->button() == LeftButton) { - plugInImageElement()->setDisplayState(HTMLPlugInElement::Playing); + if (m_isMouseInButtonRect) + plugInImageElement()->setDisplayState(HTMLPlugInElement::Playing); + else { + plugInImageElement()->setDisplayState(HTMLPlugInElement::PlayingWithPendingMouseClick); + plugInImageElement()->setPendingClickEvent(mouseEvent); + } if (widget()) { if (Frame* frame = document()->frame()) frame->loader()->client()->recreatePlugin(widget()); diff --git a/Source/WebCore/rendering/RenderTable.cpp b/Source/WebCore/rendering/RenderTable.cpp index 7527c47a9..7d5cfe94f 100644 --- a/Source/WebCore/rendering/RenderTable.cpp +++ b/Source/WebCore/rendering/RenderTable.cpp @@ -326,6 +326,28 @@ LayoutUnit RenderTable::convertStyleLogicalWidthToComputedWidth(const Length& st return minimumValueForLength(styleLogicalWidth, availableWidth, view()) + borders; } +LayoutUnit RenderTable::convertStyleLogicalHeightToComputedHeight(const Length& styleLogicalHeight) +{ + LayoutUnit computedLogicalHeight = 0; + if (styleLogicalHeight.isFixed()) { + // HTML tables size as though CSS height includes border/padding, CSS tables do not. + LayoutUnit borders = LayoutUnit(); + // FIXME: We cannot apply box-sizing: content-box on <table> which other browsers allow. + if ((node() && node()->hasTagName(tableTag)) || style()->boxSizing() == BORDER_BOX) { + LayoutUnit borderAndPaddingBefore = borderBefore() + (collapseBorders() ? LayoutUnit() : paddingBefore()); + LayoutUnit borderAndPaddingAfter = borderAfter() + (collapseBorders() ? LayoutUnit() : paddingAfter()); + borders = borderAndPaddingBefore + borderAndPaddingAfter; + } + computedLogicalHeight = styleLogicalHeight.value() - borders; + } else if (styleLogicalHeight.isPercent()) + computedLogicalHeight = computePercentageLogicalHeight(styleLogicalHeight); + else if (styleLogicalHeight.isViewportPercentage()) + computedLogicalHeight = minimumValueForLength(styleLogicalHeight, 0, view()); + else + ASSERT_NOT_REACHED(); + return max<LayoutUnit>(0, computedLogicalHeight); +} + void RenderTable::layoutCaption(RenderTableCaption* caption) { LayoutRect captionRect(caption->frameRect()); @@ -442,18 +464,23 @@ void RenderTable::layout() if (!isOutOfFlowPositioned()) updateLogicalHeight(); - Length logicalHeightLength = style()->logicalHeight(); LayoutUnit computedLogicalHeight = 0; - if (logicalHeightLength.isFixed()) { - // HTML tables size as though CSS height includes border/padding, CSS tables do not. - LayoutUnit borders = 0; - // FIXME: We cannot apply box-sizing: content-box on <table> which other browsers allow. - if ((node() && node()->hasTagName(tableTag)) || style()->boxSizing() == BORDER_BOX) - borders = borderAndPaddingBefore + borderAndPaddingAfter; - computedLogicalHeight = logicalHeightLength.value() - borders; - } else if (logicalHeightLength.isPercent()) - computedLogicalHeight = computePercentageLogicalHeight(logicalHeightLength); - computedLogicalHeight = max<LayoutUnit>(0, computedLogicalHeight); + + Length logicalHeightLength = style()->logicalHeight(); + if (logicalHeightLength.isSpecified() && logicalHeightLength.isPositive()) + computedLogicalHeight = convertStyleLogicalHeightToComputedHeight(logicalHeightLength); + + Length logicalMaxHeightLength = style()->logicalMaxHeight(); + if (logicalMaxHeightLength.isSpecified() && !logicalMaxHeightLength.isNegative()) { + LayoutUnit computedMaxLogicalHeight = convertStyleLogicalHeightToComputedHeight(logicalMaxHeightLength); + computedLogicalHeight = min(computedLogicalHeight, computedMaxLogicalHeight); + } + + Length logicalMinHeightLength = style()->logicalMinHeight(); + if (logicalMinHeightLength.isSpecified() && !logicalMinHeightLength.isNegative()) { + LayoutUnit computedMinLogicalHeight = convertStyleLogicalHeightToComputedHeight(logicalMinHeightLength); + computedLogicalHeight = max(computedLogicalHeight, computedMinLogicalHeight); + } distributeExtraLogicalHeight(floorToInt(computedLogicalHeight - totalSectionLogicalHeight)); diff --git a/Source/WebCore/rendering/RenderTable.h b/Source/WebCore/rendering/RenderTable.h index 589b9de13..55a450957 100644 --- a/Source/WebCore/rendering/RenderTable.h +++ b/Source/WebCore/rendering/RenderTable.h @@ -291,6 +291,7 @@ private: virtual void updateLogicalWidth() OVERRIDE; LayoutUnit convertStyleLogicalWidthToComputedWidth(const Length& styleLogicalWidth, LayoutUnit availableWidth); + LayoutUnit convertStyleLogicalHeightToComputedHeight(const Length& styleLogicalHeight); virtual LayoutRect overflowClipRect(const LayoutPoint& location, RenderRegion*, OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize); diff --git a/Source/WebCore/rendering/RenderTheme.cpp b/Source/WebCore/rendering/RenderTheme.cpp index 47acfc8ec..0432dc32b 100644 --- a/Source/WebCore/rendering/RenderTheme.cpp +++ b/Source/WebCore/rendering/RenderTheme.cpp @@ -1024,17 +1024,14 @@ void RenderTheme::paintSliderTicks(RenderObject* o, const PaintInfo& paintInfo, tickRect.setWidth(floor(tickSize.width() * zoomFactor)); tickRect.setHeight(floor(tickSize.height() * zoomFactor)); tickRect.setY(floor(rect.y() + rect.height() / 2.0 + sliderTickOffsetFromTrackCenter() * zoomFactor)); - if (o->style()->isLeftToRightDirection()) - tickRegionSideMargin = trackBounds.x() + (thumbSize.width() - tickSize.width() * zoomFactor) / 2.0; - else - tickRegionSideMargin = trackBounds.x() - thumbSize.width() / 2.0; - tickRegionWidth = trackBounds.width(); + tickRegionSideMargin = trackBounds.x() + (thumbSize.width() - tickSize.width() * zoomFactor) / 2.0; + tickRegionWidth = trackBounds.width() - thumbSize.width(); } else { tickRect.setWidth(floor(tickSize.height() * zoomFactor)); tickRect.setHeight(floor(tickSize.width() * zoomFactor)); tickRect.setX(floor(rect.x() + rect.width() / 2.0 + sliderTickOffsetFromTrackCenter() * zoomFactor)); tickRegionSideMargin = trackBounds.y() + (thumbSize.width() - tickSize.width() * zoomFactor) / 2.0; - tickRegionWidth = trackBounds.height(); + tickRegionWidth = trackBounds.height() - thumbSize.width(); } RefPtr<HTMLCollection> options = dataList->options(); GraphicsContextStateSaver stateSaver(*paintInfo.context); diff --git a/Source/WebCore/rendering/RenderingAllInOne.cpp b/Source/WebCore/rendering/RenderingAllInOne.cpp index 2526622f7..3e155dba3 100644 --- a/Source/WebCore/rendering/RenderingAllInOne.cpp +++ b/Source/WebCore/rendering/RenderingAllInOne.cpp @@ -25,6 +25,7 @@ // This all-in-one cpp file cuts down on template bloat to allow us to build our Windows release build. + #include "AutoTableLayout.cpp" #include "BidiRun.cpp" #include "CounterNode.cpp" @@ -119,4 +120,3 @@ #include "RootInlineBox.cpp" #include "ScrollBehavior.cpp" #include "break_lines.cpp" - diff --git a/Source/WebCore/rendering/RootInlineBox.cpp b/Source/WebCore/rendering/RootInlineBox.cpp index 6c9330362..fb1ab2aa6 100644 --- a/Source/WebCore/rendering/RootInlineBox.cpp +++ b/Source/WebCore/rendering/RootInlineBox.cpp @@ -33,6 +33,7 @@ #include "PaintInfo.h" #include "RenderArena.h" #include "RenderBlock.h" +#include "RenderFlowThread.h" #include "RenderView.h" #include "VerticalPositionCache.h" #include <wtf/unicode/Unicode.h> @@ -52,8 +53,6 @@ RootInlineBox::RootInlineBox(RenderBlock* block) , m_lineBottom(0) , m_lineTopWithLeading(0) , m_lineBottomWithLeading(0) - , m_paginationStrut(0) - , m_paginatedLineWidth(0) { setIsHorizontal(block->isHorizontalWritingMode()); } @@ -251,6 +250,30 @@ void RootInlineBox::childRemoved(InlineBox* box) } } +void RootInlineBox::setContainingRegion(RenderRegion* region) +{ + ASSERT(!isDirty()); + ASSERT(block()->inRenderFlowThread()); + LineFragmentationData* fragmentationData = ensureLineFragmentationData(); + fragmentationData->m_containingRegion = region; + fragmentationData->m_hasContainingRegion = !!region; +} + +RootInlineBox::LineFragmentationData* RootInlineBox::LineFragmentationData::sanitize(const RenderBlock* block) +{ + ASSERT(block->inRenderFlowThread()); + if (!m_containingRegion) + return this; + + RenderFlowThread* flowThread = block->enclosingRenderFlowThread(); + const RenderRegionList& regionList = flowThread->renderRegionList(); + // For pointer types the hash function is |safeToCompareToEmptyOrDeleted|. There shouldn't be any problems if m_containingRegion was deleted. + if (!regionList.contains(m_containingRegion)) + m_containingRegion = 0; + + return this; +} + LayoutUnit RootInlineBox::alignBoxesInBlockDirection(LayoutUnit heightOfBlock, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache) { #if ENABLE(SVG) diff --git a/Source/WebCore/rendering/RootInlineBox.h b/Source/WebCore/rendering/RootInlineBox.h index 120afaa31..e7c3e54b6 100644 --- a/Source/WebCore/rendering/RootInlineBox.h +++ b/Source/WebCore/rendering/RootInlineBox.h @@ -28,6 +28,7 @@ namespace WebCore { class EllipsisBox; class HitTestResult; +class RenderRegion; struct BidiStatus; struct GapRects; @@ -53,14 +54,18 @@ public: LayoutUnit lineTopWithLeading() const { return m_lineTopWithLeading; } LayoutUnit lineBottomWithLeading() const { return m_lineBottomWithLeading; } - LayoutUnit paginationStrut() const { return m_paginationStrut; } - void setPaginationStrut(LayoutUnit s) { m_paginationStrut = s; } + LayoutUnit paginationStrut() const { return m_fragmentationData ? m_fragmentationData->m_paginationStrut : LayoutUnit(0); } + void setPaginationStrut(LayoutUnit strut) { ensureLineFragmentationData()->m_paginationStrut = strut; } - bool isFirstAfterPageBreak() const { return m_isFirstAfterPageBreak; } - void setIsFirstAfterPageBreak(bool isFirstAfterPageBreak) { m_isFirstAfterPageBreak = isFirstAfterPageBreak; } + bool isFirstAfterPageBreak() const { return m_fragmentationData ? m_fragmentationData->m_isFirstAfterPageBreak : false; } + void setIsFirstAfterPageBreak(bool isFirstAfterPageBreak) { ensureLineFragmentationData()->m_isFirstAfterPageBreak = isFirstAfterPageBreak; } - LayoutUnit paginatedLineWidth() const { return m_paginatedLineWidth; } - void setPaginatedLineWidth(LayoutUnit width) { m_paginatedLineWidth = width; } + LayoutUnit paginatedLineWidth() const { return m_fragmentationData ? m_fragmentationData->m_paginatedLineWidth : LayoutUnit(0); } + void setPaginatedLineWidth(LayoutUnit width) { ensureLineFragmentationData()->m_paginatedLineWidth = width; } + + RenderRegion* containingRegion() const { return m_fragmentationData ? m_fragmentationData->sanitize(block())->m_containingRegion : 0; } + bool hasContainingRegion() const { return m_fragmentationData ? m_fragmentationData->m_hasContainingRegion : false; } + void setContainingRegion(RenderRegion*); LayoutUnit selectionTop() const; LayoutUnit selectionBottom() const; @@ -193,6 +198,15 @@ private: LayoutUnit beforeAnnotationsAdjustment() const; + struct LineFragmentationData; + LineFragmentationData* ensureLineFragmentationData() + { + if (!m_fragmentationData) + m_fragmentationData = adoptPtr(new LineFragmentationData()); + + return m_fragmentationData.get(); + } + // This folds into the padding at the end of InlineFlowBox on 64-bit. unsigned m_lineBreakPos; @@ -207,8 +221,32 @@ private: LayoutUnit m_lineTopWithLeading; LayoutUnit m_lineBottomWithLeading; - LayoutUnit m_paginationStrut; - LayoutUnit m_paginatedLineWidth; + struct LineFragmentationData { + WTF_MAKE_NONCOPYABLE(LineFragmentationData); WTF_MAKE_FAST_ALLOCATED; + public: + LineFragmentationData() + : m_containingRegion(0) + , m_paginationStrut(0) + , m_paginatedLineWidth(0) + , m_isFirstAfterPageBreak(false) + , m_hasContainingRegion(false) + { + + } + + LineFragmentationData* sanitize(const RenderBlock*); + + // It should not be assumed the |containingRegion| is always valid. + // It can also be 0 if the flow has no region chain or an invalid pointer if the region is no longer in the chain. + // Use |sanitize| to filter an invalid region. + RenderRegion* m_containingRegion; + LayoutUnit m_paginationStrut; + LayoutUnit m_paginatedLineWidth; + unsigned m_isFirstAfterPageBreak : 1; + unsigned m_hasContainingRegion : 1; // We need to keep this to differentiate between the case of a void region and an invalid region. + }; + + OwnPtr<LineFragmentationData> m_fragmentationData; // Floats hanging off the line are pushed into this vector during layout. It is only // good for as long as the line has not been marked dirty. diff --git a/Source/WebCore/rendering/TextAutosizer.cpp b/Source/WebCore/rendering/TextAutosizer.cpp index 36067fd78..358840dc4 100644 --- a/Source/WebCore/rendering/TextAutosizer.cpp +++ b/Source/WebCore/rendering/TextAutosizer.cpp @@ -33,6 +33,8 @@ #include "Settings.h" #include "StyleInheritedData.h" +#include <algorithm> + namespace WebCore { struct TextAutosizingWindowInfo { @@ -94,11 +96,12 @@ void TextAutosizer::processCluster(RenderBlock* cluster, RenderBlock* container, { ASSERT(isAutosizingCluster(cluster)); - // FIXME: Many pages set a max-width on their content. So especially for the RenderView, - // instead of just taking the width of |cluster| we should find the lowest common ancestor of - // the first and last descendant text node of the cluster (i.e. the deepest wrapper block that - // contains all the text), and use its width instead. - RenderBlock* lowestCommonAncestor = cluster; + // Many pages set a max-width on their content. So especially for the + // RenderView, instead of just taking the width of |cluster| we find + // the lowest common ancestor of the first and last descendant text node of + // the cluster (i.e. the deepest wrapper block that contains all the text), + // and use its width instead. + const RenderBlock* lowestCommonAncestor = findDeepestBlockContainingAllText(cluster); float commonAncestorWidth = lowestCommonAncestor->contentLogicalWidth(); float multiplier = 1; @@ -201,8 +204,11 @@ bool TextAutosizer::isAutosizingContainer(const RenderObject* renderer) // "Autosizing containers" are the smallest unit for which we can // enable/disable Text Autosizing. // - Must not be inline, as different multipliers on one line looks terrible. - // - Must not be list items, as items in the same list should look consistent. - return renderer->isRenderBlock() && !renderer->isInline() && !renderer->isListItem(); + // - Must not be list items, as items in the same list should look consistent (*). + // * except for those list items positioned out of the list's flow. + return renderer->isRenderBlock() + && !renderer->isInline() + && (!renderer->isListItem() || renderer->isOutOfFlowPositioned()); } bool TextAutosizer::isAutosizingCluster(const RenderBlock* renderer) @@ -297,6 +303,70 @@ RenderObject* TextAutosizer::nextInPreOrderSkippingDescendantsOfContainers(const return 0; } +const RenderBlock* TextAutosizer::findDeepestBlockContainingAllText(const RenderBlock* cluster) +{ + ASSERT(isAutosizingCluster(cluster)); + + size_t firstDepth = 0; + const RenderObject* firstTextLeaf = findFirstTextLeafNotInCluster(cluster, firstDepth, FirstToLast); + if (!firstTextLeaf) + return cluster; + + size_t lastDepth = 0; + const RenderObject* lastTextLeaf = findFirstTextLeafNotInCluster(cluster, lastDepth, LastToFirst); + ASSERT(lastTextLeaf); + + // Equalize the depths if necessary. Only one of the while loops below will get executed. + const RenderObject* firstNode = firstTextLeaf; + const RenderObject* lastNode = lastTextLeaf; + while (firstDepth > lastDepth) { + firstNode = firstNode->parent(); + --firstDepth; + } + while (lastDepth > firstDepth) { + lastNode = lastNode->parent(); + --lastDepth; + } + + // Go up from both nodes until the parent is the same. Both pointers will point to the LCA then. + while (firstNode != lastNode) { + firstNode = firstNode->parent(); + lastNode = lastNode->parent(); + } + + if (firstNode->isRenderBlock()) + return toRenderBlock(firstNode); + + // containingBlock() should never leave the cluster, since it only skips ancestors when finding the + // container of position:absolute/fixed blocks, and those cannot exist between a cluster and its text + // nodes lowest common ancestor as isAutosizingCluster would have made them into their own independent + // cluster. + RenderBlock* containingBlock = firstNode->containingBlock(); + ASSERT(containingBlock->isDescendantOf(cluster)); + + return containingBlock; +} + +const RenderObject* TextAutosizer::findFirstTextLeafNotInCluster(const RenderObject* parent, size_t& depth, TraversalDirection direction) +{ + if (parent->isEmpty()) + return parent->isText() ? parent : 0; + + ++depth; + const RenderObject* child = (direction == FirstToLast) ? parent->firstChild() : parent->lastChild(); + while (child) { + if (!isAutosizingContainer(child) || !isAutosizingCluster(toRenderBlock(child))) { + const RenderObject* leaf = findFirstTextLeafNotInCluster(child, depth, direction); + if (leaf) + return leaf; + } + child = (direction == FirstToLast) ? child->nextSibling() : child->previousSibling(); + } + --depth; + + return 0; +} + } // namespace WebCore #endif // ENABLE(TEXT_AUTOSIZING) diff --git a/Source/WebCore/rendering/TextAutosizer.h b/Source/WebCore/rendering/TextAutosizer.h index 2e2e70e6b..a709b1168 100644 --- a/Source/WebCore/rendering/TextAutosizer.h +++ b/Source/WebCore/rendering/TextAutosizer.h @@ -55,6 +55,11 @@ public: static float computeAutosizedFontSize(float specifiedSize, float multiplier); private: + enum TraversalDirection { + FirstToLast, + LastToFirst + }; + explicit TextAutosizer(Document*); void processCluster(RenderBlock* cluster, RenderBlock* container, RenderObject* subtreeRoot, const TextAutosizingWindowInfo&); @@ -71,6 +76,14 @@ private: // Use to traverse the tree of descendants, excluding descendants of containers (but returning the containers themselves). static RenderObject* nextInPreOrderSkippingDescendantsOfContainers(const RenderObject* current, const RenderObject* stayWithin); + // Finds the lowest common ancestor of the first and the last descendant + // text node (excluding those belonging to other autosizing clusters). + static const RenderBlock* findDeepestBlockContainingAllText(const RenderBlock* cluster); + + // Depending on the traversal direction specified, finds the first or the last leaf text node child that doesn't + // belong to any cluster. + static const RenderObject* findFirstTextLeafNotInCluster(const RenderObject*, size_t& depth, TraversalDirection); + Document* m_document; }; diff --git a/Source/WebCore/rendering/style/RenderStyle.cpp b/Source/WebCore/rendering/style/RenderStyle.cpp index 6ecaa0417..a51658b00 100644 --- a/Source/WebCore/rendering/style/RenderStyle.cpp +++ b/Source/WebCore/rendering/style/RenderStyle.cpp @@ -61,8 +61,6 @@ struct SameSizeAsBorderValue { COMPILE_ASSERT(sizeof(BorderValue) == sizeof(SameSizeAsBorderValue), BorderValue_should_not_grow); struct SameSizeAsRenderStyle : public RefCounted<SameSizeAsRenderStyle> { - unsigned m_bitfields; - void* dataRefs[7]; void* ownPtrs[1]; #if ENABLE(SVG) @@ -207,6 +205,7 @@ void RenderStyle::copyNonInheritedFrom(const RenderStyle* other) noninherited_flags._page_break_before = other->noninherited_flags._page_break_before; noninherited_flags._page_break_after = other->noninherited_flags._page_break_after; noninherited_flags._page_break_inside = other->noninherited_flags._page_break_inside; + noninherited_flags.explicitInheritance = other->noninherited_flags.explicitInheritance; #if ENABLE(SVG) if (m_svgStyle != other->m_svgStyle) m_svgStyle.access()->copyNonInheritedFrom(other->m_svgStyle.get()); @@ -491,7 +490,8 @@ StyleDifference RenderStyle::diff(const RenderStyle* other, unsigned& changedCon || rareInheritedData->m_imageResolution != other->rareInheritedData->m_imageResolution #endif || rareInheritedData->m_lineSnap != other->rareInheritedData->m_lineSnap - || rareInheritedData->m_lineAlign != other->rareInheritedData->m_lineAlign) + || rareInheritedData->m_lineAlign != other->rareInheritedData->m_lineAlign + || rareInheritedData->listStyleImage != other->rareInheritedData->listStyleImage) return StyleDifferenceLayout; if (!rareInheritedData->shadowDataEquivalent(*other->rareInheritedData.get())) @@ -507,7 +507,6 @@ StyleDifference RenderStyle::diff(const RenderStyle* other, unsigned& changedCon #endif if (inherited->line_height != other->inherited->line_height - || inherited->list_style_image != other->inherited->list_style_image || inherited->font != other->inherited->font || inherited->horizontal_border_spacing != other->inherited->horizontal_border_spacing || inherited->vertical_border_spacing != other->inherited->vertical_border_spacing @@ -966,11 +965,11 @@ static float calcConstraintScaleFor(const IntRect& rect, const RoundedRect::Radi return factor; } -StyleImage* RenderStyle::listStyleImage() const { return inherited->list_style_image.get(); } +StyleImage* RenderStyle::listStyleImage() const { return rareInheritedData->listStyleImage.get(); } void RenderStyle::setListStyleImage(PassRefPtr<StyleImage> v) { - if (inherited->list_style_image != v) - inherited.access()->list_style_image = v; + if (rareInheritedData->listStyleImage != v) + rareInheritedData.access()->listStyleImage = v; } Color RenderStyle::color() const { return inherited->color; } diff --git a/Source/WebCore/rendering/style/RenderStyle.h b/Source/WebCore/rendering/style/RenderStyle.h index 31996fa05..74044f82f 100644 --- a/Source/WebCore/rendering/style/RenderStyle.h +++ b/Source/WebCore/rendering/style/RenderStyle.h @@ -134,77 +134,6 @@ class RenderStyle: public RefCounted<RenderStyle> { friend class StyleResolver; // Sets members directly. protected: - class RenderStyleBitfields { - public: - RenderStyleBitfields() - : m_affectedByUncommonAttributeSelectors(false) - , m_unique(false) - , m_affectedByEmpty(false) - , m_emptyState(false) - , m_childrenAffectedByFirstChildRules(false) - , m_childrenAffectedByLastChildRules(false) - , m_childrenAffectedByDirectAdjacentRules(false) - , m_childrenAffectedByForwardPositionalRules(false) - , m_childrenAffectedByBackwardPositionalRules(false) - , m_firstChildState(false) - , m_lastChildState(false) - , m_explicitInheritance(false) - , m_childIndex(0) - { - } - - bool affectedByUncommonAttributeSelectors() const { return m_affectedByUncommonAttributeSelectors; } - void setAffectedByUncommonAttributeSelectors(bool value) { m_affectedByUncommonAttributeSelectors = value; } - bool unique() const { return m_unique; } - void setUnique(bool value) { m_unique = value; } - bool affectedByEmpty() const { return m_affectedByEmpty; } - void setAffectedByEmpty(bool value) { m_affectedByEmpty = value; } - bool emptyState() const { return m_emptyState; } - void setEmptyState(bool value) { m_emptyState = value; } - bool childrenAffectedByFirstChildRules() const { return m_childrenAffectedByFirstChildRules; } - void setChildrenAffectedByFirstChildRules(bool value) { m_childrenAffectedByFirstChildRules = value; } - bool childrenAffectedByLastChildRules() const { return m_childrenAffectedByLastChildRules; } - void setChildrenAffectedByLastChildRules(bool value) { m_childrenAffectedByLastChildRules = value; } - bool childrenAffectedByDirectAdjacentRules() const { return m_childrenAffectedByDirectAdjacentRules; } - void setChildrenAffectedByDirectAdjacentRules(bool value) { m_childrenAffectedByDirectAdjacentRules = value; } - bool childrenAffectedByForwardPositionalRules() const { return m_childrenAffectedByForwardPositionalRules; } - void setChildrenAffectedByForwardPositionalRules(bool value) { m_childrenAffectedByForwardPositionalRules = value; } - bool childrenAffectedByBackwardPositionalRules() const { return m_childrenAffectedByBackwardPositionalRules; } - void setChildrenAffectedByBackwardPositionalRules(bool value) { m_childrenAffectedByBackwardPositionalRules = value; } - bool firstChildState() const { return m_firstChildState; } - void setFirstChildState(bool value) { m_firstChildState = value; } - bool lastChildState() const { return m_lastChildState; } - void setLastChildState(bool value) { m_lastChildState = value; } - bool explicitInheritance() const { return m_explicitInheritance; } - void setExplicitInheritance(bool value) { m_explicitInheritance = value; } - - unsigned childIndex() const { return m_childIndex; } - void setChildIndex(unsigned index) { m_childIndex = index; } - - private: - // The following bitfield is 32-bits long, which optimizes padding with the - // int refCount in the base class. Beware when adding more bits. - unsigned m_affectedByUncommonAttributeSelectors : 1; - unsigned m_unique : 1; - - // Bits for dynamic child matching. - unsigned m_affectedByEmpty : 1; - unsigned m_emptyState : 1; - - // We optimize for :first-child and :last-child. The other positional child selectors like nth-child or - // *-child-of-type, we will just give up and re-evaluate whenever children change at all. - unsigned m_childrenAffectedByFirstChildRules : 1; - unsigned m_childrenAffectedByLastChildRules : 1; - unsigned m_childrenAffectedByDirectAdjacentRules : 1; - unsigned m_childrenAffectedByForwardPositionalRules : 1; - unsigned m_childrenAffectedByBackwardPositionalRules : 1; - unsigned m_firstChildState : 1; - unsigned m_lastChildState : 1; - unsigned m_explicitInheritance : 1; - unsigned m_childIndex : 20; // Plenty of bits to cache an index. - }; - RenderStyleBitfields m_bitfields; - // non-inherited attributes DataRef<StyleBoxData> m_box; DataRef<StyleVisualData> visual; @@ -300,6 +229,11 @@ protected: && _affectedByDrag == other._affectedByDrag && _pseudoBits == other._pseudoBits && _unicodeBidi == other._unicodeBidi + && explicitInheritance == other.explicitInheritance + && unique == other.unique + && emptyState == other.emptyState + && firstChildState == other.firstChildState + && lastChildState == other.lastChildState && _isLink == other._isLink; } @@ -316,13 +250,18 @@ protected: unsigned _table_layout : 1; // ETableLayout unsigned _unicodeBidi : 3; // EUnicodeBidi + // 31 bits unsigned _page_break_before : 2; // EPageBreak - // 32 bits unsigned _page_break_after : 2; // EPageBreak unsigned _page_break_inside : 2; // EPageBreak unsigned _styleType : 6; // PseudoId unsigned _pseudoBits : 7; + unsigned explicitInheritance : 1; // Explicitly inherits a non-inherited property + unsigned unique : 1; // Style can not be shared. + unsigned emptyState : 1; + unsigned firstChildState : 1; + unsigned lastChildState : 1; bool affectedByHover() const { return _affectedByHover; } void setAffectedByHover(bool value) { _affectedByHover = value; } @@ -338,7 +277,7 @@ protected: unsigned _affectedByDrag : 1; unsigned _isLink : 1; // If you add more style bits here, you will also need to update RenderStyle::copyNonInheritedFrom() - // 54 bits + // 59 bits } noninherited_flags; // !END SYNC! @@ -379,6 +318,11 @@ protected: noninherited_flags._page_break_inside = initialPageBreak(); noninherited_flags._styleType = NOPSEUDO; noninherited_flags._pseudoBits = 0; + noninherited_flags.explicitInheritance = false; + noninherited_flags.unique = false; + noninherited_flags.emptyState = false; + noninherited_flags.firstChildState = false; + noninherited_flags.lastChildState = false; noninherited_flags.setAffectedByHover(false); noninherited_flags.setAffectedByActive(false); noninherited_flags.setAffectedByDrag(false); @@ -419,13 +363,13 @@ public: const HashMap<AtomicString, String>* variables() { return &(rareInheritedData->m_variables->m_data); } #endif - bool affectedByHoverRules() const { return noninherited_flags.affectedByHover(); } - bool affectedByActiveRules() const { return noninherited_flags.affectedByActive(); } - bool affectedByDragRules() const { return noninherited_flags.affectedByDrag(); } + bool affectedByHover() const { return noninherited_flags.affectedByHover(); } + bool affectedByActive() const { return noninherited_flags.affectedByActive(); } + bool affectedByDrag() const { return noninherited_flags.affectedByDrag(); } - void setAffectedByHoverRules(bool b) { noninherited_flags.setAffectedByHover(b); } - void setAffectedByActiveRules(bool b) { noninherited_flags.setAffectedByActive(b); } - void setAffectedByDragRules(bool b) { noninherited_flags.setAffectedByDrag(b); } + void setAffectedByHover() { noninherited_flags.setAffectedByHover(true); } + void setAffectedByActive() { noninherited_flags.setAffectedByActive(true); } + void setAffectedByDrag() { noninherited_flags.setAffectedByDrag(true); } bool operator==(const RenderStyle& other) const; bool operator!=(const RenderStyle& other) const { return !(*this == other); } @@ -710,7 +654,6 @@ public: EFillRepeat maskRepeatX() const { return static_cast<EFillRepeat>(rareNonInheritedData->m_mask.repeatX()); } EFillRepeat maskRepeatY() const { return static_cast<EFillRepeat>(rareNonInheritedData->m_mask.repeatY()); } CompositeOperator maskComposite() const { return static_cast<CompositeOperator>(rareNonInheritedData->m_mask.composite()); } - EFillAttachment maskAttachment() const { return static_cast<EFillAttachment>(rareNonInheritedData->m_mask.attachment()); } EFillBox maskClip() const { return static_cast<EFillBox>(rareNonInheritedData->m_mask.clip()); } EFillBox maskOrigin() const { return static_cast<EFillBox>(rareNonInheritedData->m_mask.origin()); } Length maskXPosition() const { return rareNonInheritedData->m_mask.xPosition(); } @@ -1527,39 +1470,21 @@ public: void setWritingMode(WritingMode v) { inherited_flags.m_writingMode = v; } - // To tell if this style matched attribute selectors. This makes it impossible to share. - bool affectedByUncommonAttributeSelectors() const { return m_bitfields.affectedByUncommonAttributeSelectors(); } - void setAffectedByUncommonAttributeSelectors() { m_bitfields.setAffectedByUncommonAttributeSelectors(true); } - - bool unique() const { return m_bitfields.unique(); } - void setUnique() { m_bitfields.setUnique(true); } - - // Methods for indicating the style is affected by dynamic updates (e.g., children changing, our position changing in our sibling list, etc.) - bool affectedByEmpty() const { return m_bitfields.affectedByEmpty(); } - bool emptyState() const { return m_bitfields.emptyState(); } - void setEmptyState(bool b) { m_bitfields.setAffectedByEmpty(true); m_bitfields.setUnique(true); m_bitfields.setEmptyState(b); } - bool childrenAffectedByPositionalRules() const { return childrenAffectedByForwardPositionalRules() || childrenAffectedByBackwardPositionalRules(); } - bool childrenAffectedByFirstChildRules() const { return m_bitfields.childrenAffectedByFirstChildRules(); } - void setChildrenAffectedByFirstChildRules() { m_bitfields.setChildrenAffectedByFirstChildRules(true); } - bool childrenAffectedByLastChildRules() const { return m_bitfields.childrenAffectedByLastChildRules(); } - void setChildrenAffectedByLastChildRules() { m_bitfields.setChildrenAffectedByLastChildRules(true); } - bool childrenAffectedByDirectAdjacentRules() const { return m_bitfields.childrenAffectedByDirectAdjacentRules(); } - void setChildrenAffectedByDirectAdjacentRules() { m_bitfields.setChildrenAffectedByDirectAdjacentRules(true); } - bool childrenAffectedByForwardPositionalRules() const { return m_bitfields.childrenAffectedByForwardPositionalRules(); } - void setChildrenAffectedByForwardPositionalRules() { m_bitfields.setChildrenAffectedByForwardPositionalRules(true); } - bool childrenAffectedByBackwardPositionalRules() const { return m_bitfields.childrenAffectedByBackwardPositionalRules(); } - void setChildrenAffectedByBackwardPositionalRules() { m_bitfields.setChildrenAffectedByBackwardPositionalRules(true); } - bool firstChildState() const { return m_bitfields.firstChildState(); } - void setFirstChildState() { m_bitfields.setUnique(true); m_bitfields.setFirstChildState(true); } - bool lastChildState() const { return m_bitfields.lastChildState(); } - void setLastChildState() { m_bitfields.setUnique(true); m_bitfields.setLastChildState(true); } - unsigned childIndex() const { return m_bitfields.childIndex(); } - void setChildIndex(unsigned index) { m_bitfields.setUnique(true); m_bitfields.setChildIndex(index); } + // A unique style is one that has matches something that makes it impossible to share. + bool unique() const { return noninherited_flags.unique; } + void setUnique() { noninherited_flags.unique = true; } + + bool emptyState() const { return noninherited_flags.emptyState; } + void setEmptyState(bool b) { setUnique(); noninherited_flags.emptyState = b; } + bool firstChildState() const { return noninherited_flags.firstChildState; } + void setFirstChildState() { setUnique(); noninherited_flags.firstChildState = true; } + bool lastChildState() const { return noninherited_flags.lastChildState; } + void setLastChildState() { setUnique(); noninherited_flags.lastChildState = true; } Color visitedDependentColor(int colorProperty) const; - void setHasExplicitlyInheritedProperties() { m_bitfields.setExplicitInheritance(true); } - bool hasExplicitlyInheritedProperties() const { return m_bitfields.explicitInheritance(); } + void setHasExplicitlyInheritedProperties() { noninherited_flags.explicitInheritance = true; } + bool hasExplicitlyInheritedProperties() const { return noninherited_flags.explicitInheritance; } void reportMemoryUsage(MemoryObjectInfo*) const; @@ -1674,7 +1599,7 @@ public: static Order initialRTLOrdering() { return LogicalOrder; } static float initialTextStrokeWidth() { return 0; } static unsigned short initialColumnCount() { return 1; } - static ColumnSpan initialColumnSpan() { return ColumnSpanOne; } + static ColumnSpan initialColumnSpan() { return ColumnSpanNone; } static const TransformOperations& initialTransform() { DEFINE_STATIC_LOCAL(TransformOperations, ops, ()); return ops; } static Length initialTransformOriginX() { return Length(50.0, Percent); } static Length initialTransformOriginY() { return Length(50.0, Percent); } diff --git a/Source/WebCore/rendering/style/RenderStyleConstants.h b/Source/WebCore/rendering/style/RenderStyleConstants.h index 72e0c4c33..bfc1a5eab 100644 --- a/Source/WebCore/rendering/style/RenderStyleConstants.h +++ b/Source/WebCore/rendering/style/RenderStyleConstants.h @@ -81,7 +81,7 @@ enum PseudoId { PUBLIC_PSEUDOID_MASK = ((1 << FIRST_INTERNAL_PSEUDOID) - 1) & ~((1 << FIRST_PUBLIC_PSEUDOID) - 1) }; -enum ColumnSpan { ColumnSpanOne = 0, ColumnSpanAll}; +enum ColumnSpan { ColumnSpanNone = 0, ColumnSpanAll }; enum EBorderCollapse { BSEPARATE = 0, BCOLLAPSE = 1 }; diff --git a/Source/WebCore/rendering/style/StyleInheritedData.cpp b/Source/WebCore/rendering/style/StyleInheritedData.cpp index 021740f15..b72395631 100644 --- a/Source/WebCore/rendering/style/StyleInheritedData.cpp +++ b/Source/WebCore/rendering/style/StyleInheritedData.cpp @@ -23,7 +23,6 @@ #include "StyleInheritedData.h" #include "RenderStyle.h" -#include "StyleImage.h" namespace WebCore { @@ -31,7 +30,6 @@ StyleInheritedData::StyleInheritedData() : horizontal_border_spacing(RenderStyle::initialHorizontalBorderSpacing()) , vertical_border_spacing(RenderStyle::initialVerticalBorderSpacing()) , line_height(RenderStyle::initialLineHeight()) - , list_style_image(RenderStyle::initialListStyleImage()) , color(RenderStyle::initialColor()) , visitedLinkColor(RenderStyle::initialColor()) { @@ -46,7 +44,6 @@ StyleInheritedData::StyleInheritedData(const StyleInheritedData& o) , horizontal_border_spacing(o.horizontal_border_spacing) , vertical_border_spacing(o.vertical_border_spacing) , line_height(o.line_height) - , list_style_image(o.list_style_image) , font(o.font) , color(o.color) , visitedLinkColor(o.visitedLinkColor) @@ -56,7 +53,6 @@ StyleInheritedData::StyleInheritedData(const StyleInheritedData& o) bool StyleInheritedData::operator==(const StyleInheritedData& o) const { return line_height == o.line_height - && StyleImage::imagesEquivalent(list_style_image.get(), o.list_style_image.get()) && font == o.font && color == o.color && visitedLinkColor == o.visitedLinkColor diff --git a/Source/WebCore/rendering/style/StyleInheritedData.h b/Source/WebCore/rendering/style/StyleInheritedData.h index 6cb7bc5bb..06a79273e 100644 --- a/Source/WebCore/rendering/style/StyleInheritedData.h +++ b/Source/WebCore/rendering/style/StyleInheritedData.h @@ -34,8 +34,6 @@ namespace WebCore { -class StyleImage; - class StyleInheritedData : public RefCounted<StyleInheritedData> { public: static PassRefPtr<StyleInheritedData> create() { return adoptRef(new StyleInheritedData); } @@ -55,8 +53,6 @@ public: // make a difference currently because of padding Length line_height; - RefPtr<StyleImage> list_style_image; - Font font; Color color; Color visitedLinkColor; diff --git a/Source/WebCore/rendering/style/StyleRareInheritedData.cpp b/Source/WebCore/rendering/style/StyleRareInheritedData.cpp index 434e3ccf0..c02c10591 100644 --- a/Source/WebCore/rendering/style/StyleRareInheritedData.cpp +++ b/Source/WebCore/rendering/style/StyleRareInheritedData.cpp @@ -27,12 +27,14 @@ #include "RenderStyle.h" #include "RenderStyleConstants.h" #include "ShadowData.h" +#include "StyleImage.h" #include "WebCoreMemoryInstrumentation.h" #include <wtf/MemoryObjectInfo.h> namespace WebCore { struct SameSizeAsStyleRareInheritedData : public RefCounted<SameSizeAsStyleRareInheritedData> { + void* styleImage; Color firstColor; float firstFloat; Color colors[5]; @@ -62,7 +64,8 @@ struct SameSizeAsStyleRareInheritedData : public RefCounted<SameSizeAsStyleRareI COMPILE_ASSERT(sizeof(StyleRareInheritedData) == sizeof(SameSizeAsStyleRareInheritedData), StyleRareInheritedData_should_bit_pack); StyleRareInheritedData::StyleRareInheritedData() - : textStrokeWidth(RenderStyle::initialTextStrokeWidth()) + : listStyleImage(RenderStyle::initialListStyleImage()) + , textStrokeWidth(RenderStyle::initialTextStrokeWidth()) , indent(RenderStyle::initialTextIndent()) , m_effectiveZoom(RenderStyle::initialZoom()) , widows(RenderStyle::initialWidows()) @@ -118,6 +121,7 @@ StyleRareInheritedData::StyleRareInheritedData() StyleRareInheritedData::StyleRareInheritedData(const StyleRareInheritedData& o) : RefCounted<StyleRareInheritedData>() + , listStyleImage(o.listStyleImage) , textStrokeColor(o.textStrokeColor) , textStrokeWidth(o.textStrokeWidth) , textFillColor(o.textFillColor) @@ -260,7 +264,8 @@ bool StyleRareInheritedData::operator==(const StyleRareInheritedData& o) const #if ENABLE(CSS_VARIABLES) && m_variables == o.m_variables #endif - && m_lineAlign == o.m_lineAlign; + && m_lineAlign == o.m_lineAlign + && StyleImage::imagesEquivalent(listStyleImage.get(), o.listStyleImage.get()); } bool StyleRareInheritedData::shadowDataEquivalent(const StyleRareInheritedData& o) const diff --git a/Source/WebCore/rendering/style/StyleRareInheritedData.h b/Source/WebCore/rendering/style/StyleRareInheritedData.h index d07e04c33..22388336a 100644 --- a/Source/WebCore/rendering/style/StyleRareInheritedData.h +++ b/Source/WebCore/rendering/style/StyleRareInheritedData.h @@ -41,6 +41,7 @@ namespace WebCore { class CursorList; class QuotesData; class ShadowData; +class StyleImage; // This struct is for rarely used inherited CSS3, CSS2, and WebKit-specific properties. // By grouping them together, we save space, and only allocate this object when someone @@ -60,6 +61,8 @@ public: void reportMemoryUsage(MemoryObjectInfo*) const; + RefPtr<StyleImage> listStyleImage; + Color textStrokeColor; float textStrokeWidth; Color textFillColor; diff --git a/Source/WebCore/rendering/svg/RenderSVGResourceContainer.cpp b/Source/WebCore/rendering/svg/RenderSVGResourceContainer.cpp index 310e586b9..e311c1c21 100644 --- a/Source/WebCore/rendering/svg/RenderSVGResourceContainer.cpp +++ b/Source/WebCore/rendering/svg/RenderSVGResourceContainer.cpp @@ -151,6 +151,7 @@ void RenderSVGResourceContainer::addClient(RenderObject* client) void RenderSVGResourceContainer::removeClient(RenderObject* client) { ASSERT(client); + removeClientFromCache(client, false); m_clients.remove(client); } diff --git a/Source/WebCore/svg/SVGElement.cpp b/Source/WebCore/svg/SVGElement.cpp index 6f0e822b5..ce806c5c3 100644 --- a/Source/WebCore/svg/SVGElement.cpp +++ b/Source/WebCore/svg/SVGElement.cpp @@ -537,14 +537,6 @@ void SVGElement::attributeChanged(const QualifiedName& name, const AtomicString& { StyledElement::attributeChanged(name, newValue); - // When an animated SVG property changes through SVG DOM, svgAttributeChanged() is called, not attributeChanged(). - // Next time someone tries to access the XML attributes, the synchronization code starts. During that synchronization - // SVGAnimatedPropertySynchronizer may call ElementAttributeData::removeAttribute(), which in turn calls attributeChanged(). - // At this point we're not allowed to call svgAttributeChanged() again - it may lead to extra work being done, or crashes - // see bug https://bugs.webkit.org/show_bug.cgi?id=40994. - if (isSynchronizingSVGAttributes()) - return; - if (isIdAttributeName(name)) { document()->accessSVGExtensions()->removeAllAnimationElementsFromTarget(this); document()->accessSVGExtensions()->removeAllElementReferencesForTarget(this); @@ -574,19 +566,15 @@ void SVGElement::clearHasPendingResourcesIfPossible() void SVGElement::updateAnimatedSVGAttribute(const QualifiedName& name) const { - if (isSynchronizingSVGAttributes() || areSVGAttributesValid()) + if (!attributeData() || !attributeData()->m_animatedSVGAttributesAreDirty) return; - setIsSynchronizingSVGAttributes(); - SVGElement* nonConstThis = const_cast<SVGElement*>(this); if (name == anyQName()) { nonConstThis->localAttributeToPropertyMap().synchronizeProperties(nonConstThis); - setAreSVGAttributesValid(); + attributeData()->m_animatedSVGAttributesAreDirty = false; } else nonConstThis->localAttributeToPropertyMap().synchronizeProperty(nonConstThis, name); - - clearIsSynchronizingSVGAttributes(); } SVGAttributeToPropertyMap& SVGElement::localAttributeToPropertyMap() diff --git a/Source/WebCore/svg/SVGElement.h b/Source/WebCore/svg/SVGElement.h index 417e154ab..9426b7851 100644 --- a/Source/WebCore/svg/SVGElement.h +++ b/Source/WebCore/svg/SVGElement.h @@ -84,7 +84,7 @@ public: virtual AffineTransform* supplementalTransform() { return 0; } - void invalidateSVGAttributes() { clearAreSVGAttributesValid(); } + void invalidateSVGAttributes() { ensureAttributeData()->m_animatedSVGAttributesAreDirty = true; } const HashSet<SVGElementInstance*>& instancesForElement() const; diff --git a/Source/WebCore/testing/InternalSettings.cpp b/Source/WebCore/testing/InternalSettings.cpp index 97c086fca..c748eabc4 100644 --- a/Source/WebCore/testing/InternalSettings.cpp +++ b/Source/WebCore/testing/InternalSettings.cpp @@ -26,15 +26,12 @@ #include "config.h" #include "InternalSettings.h" -#include "Chrome.h" -#include "ChromeClient.h" #include "Document.h" #include "ExceptionCode.h" #include "Frame.h" #include "FrameView.h" #include "Language.h" #include "LocaleToScriptMapping.h" -#include "MockPagePopupDriver.h" #include "Page.h" #include "RuntimeEnabledFeatures.h" #include "Settings.h" @@ -175,22 +172,9 @@ InternalSettings::InternalSettings(Page* page) { } -#if ENABLE(PAGE_POPUP) -PagePopupController* InternalSettings::pagePopupController() -{ - return m_pagePopupDriver ? m_pagePopupDriver->pagePopupController() : 0; -} -#endif - void InternalSettings::reset() { - page()->setPagination(Pagination()); page()->setPageScaleFactor(1, IntPoint(0, 0)); -#if ENABLE(PAGE_POPUP) - m_pagePopupDriver.clear(); - if (page()->chrome()) - page()->chrome()->client()->resetPagePopupDriver(); -#endif m_backup.restoreTo(page(), settings()); m_backup = Backup(page(), settings()); @@ -269,12 +253,6 @@ bool InternalSettings::unifiedTextCheckingEnabled(ExceptionCode& ec) return settings()->unifiedTextCheckerEnabled(); } -void InternalSettings::setPageScaleFactor(float scaleFactor, int x, int y, ExceptionCode& ec) -{ - InternalSettingsGuardForPage(); - page()->setPageScaleFactor(scaleFactor, IntPoint(x, y)); -} - void InternalSettings::setShadowDOMEnabled(bool enabled, ExceptionCode& ec) { #if ENABLE(SHADOW_DOM) @@ -558,70 +536,6 @@ bool InternalSettings::shouldDisplayTrackKind(const String& kind, ExceptionCode& #endif } -void InternalSettings::setPagination(const String& mode, int gap, int pageLength, ExceptionCode& ec) -{ - if (!page()) { - ec = INVALID_ACCESS_ERR; - return; - } - - Pagination pagination; - if (mode == "Unpaginated") - pagination.mode = Pagination::Unpaginated; - else if (mode == "LeftToRightPaginated") - pagination.mode = Pagination::LeftToRightPaginated; - else if (mode == "RightToLeftPaginated") - pagination.mode = Pagination::RightToLeftPaginated; - else if (mode == "TopToBottomPaginated") - pagination.mode = Pagination::TopToBottomPaginated; - else if (mode == "BottomToTopPaginated") - pagination.mode = Pagination::BottomToTopPaginated; - else { - ec = SYNTAX_ERR; - return; - } - - pagination.gap = gap; - pagination.pageLength = pageLength; - page()->setPagination(pagination); -} - -void InternalSettings::setEnableMockPagePopup(bool enabled, ExceptionCode& ec) -{ -#if ENABLE(PAGE_POPUP) - InternalSettingsGuardForPage(); - if (!page()->chrome()) - return; - if (!enabled) { - page()->chrome()->client()->resetPagePopupDriver(); - return; - } - if (!m_pagePopupDriver) - m_pagePopupDriver = MockPagePopupDriver::create(page()->mainFrame()); - page()->chrome()->client()->setPagePopupDriver(m_pagePopupDriver.get()); -#else - UNUSED_PARAM(enabled); - UNUSED_PARAM(ec); -#endif -} - -String InternalSettings::configurationForViewport(float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode& ec) -{ - if (!page()) { - ec = INVALID_ACCESS_ERR; - return String(); - } - - const int defaultLayoutWidthForNonMobilePages = 980; - - ViewportArguments arguments = page()->viewportArguments(); - ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight)); - restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio); - restrictScaleFactorToInitialScaleIfNotUserScalable(attributes); - - return "viewport size " + String::number(attributes.layoutSize.width()) + "x" + String::number(attributes.layoutSize.height()) + " scale " + String::number(attributes.initialScale) + " with limits [" + String::number(attributes.minimumScale) + ", " + String::number(attributes.maximumScale) + "] and userScalable " + (attributes.userScalable ? "true" : "false"); -} - void InternalSettings::setMemoryInfoEnabled(bool enabled, ExceptionCode& ec) { InternalSettingsGuardForSettings(); diff --git a/Source/WebCore/testing/InternalSettings.h b/Source/WebCore/testing/InternalSettings.h index a30fafffc..f379f2858 100644 --- a/Source/WebCore/testing/InternalSettings.h +++ b/Source/WebCore/testing/InternalSettings.h @@ -39,9 +39,7 @@ typedef int ExceptionCode; class Frame; class Document; -class MockPagePopupDriver; class Page; -class PagePopupController; class Settings; class InternalSettings : public RefCountedSupplement<Page, InternalSettings> { @@ -100,9 +98,6 @@ public: static InternalSettings* from(Page*); virtual ~InternalSettings(); -#if ENABLE(PAGE_POPUP) - PagePopupController* pagePopupController(); -#endif void reset(); void setForceCompositingMode(bool enabled, ExceptionCode&); @@ -117,7 +112,6 @@ public: void setFixedElementsLayoutRelativeToFrame(bool, ExceptionCode&); void setUnifiedTextCheckingEnabled(bool, ExceptionCode&); bool unifiedTextCheckingEnabled(ExceptionCode&); - void setPageScaleFactor(float scaleFactor, int x, int y, ExceptionCode&); void setTouchEventEmulationEnabled(bool enabled, ExceptionCode&); void setDeviceSupportsTouch(bool enabled, ExceptionCode&); void setDeviceSupportsMouse(bool enabled, ExceptionCode&); @@ -148,12 +142,8 @@ public: void setSyncXHRInDocumentsEnabled(bool, ExceptionCode&); void setWindowFocusRestricted(bool, ExceptionCode&); void setDialogElementEnabled(bool, ExceptionCode&); - void setPagination(const String& mode, int gap, ExceptionCode& ec) { setPagination(mode, gap, 0, ec); } - void setPagination(const String& mode, int gap, int pageLength, ExceptionCode&); void setShouldDisplayTrackKind(const String& kind, bool enabled, ExceptionCode&); bool shouldDisplayTrackKind(const String& kind, ExceptionCode&); - void setEnableMockPagePopup(bool, ExceptionCode&); - String configurationForViewport(float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode&); void setMemoryInfoEnabled(bool, ExceptionCode&); void setStorageBlockingPolicy(const String&, ExceptionCode&); void setLangAttributeAwareFormControlUIEnabled(bool); @@ -168,9 +158,6 @@ private: Page* m_page; Backup m_backup; -#if ENABLE(PAGE_POPUP) - OwnPtr<MockPagePopupDriver> m_pagePopupDriver; -#endif }; } // namespace WebCore diff --git a/Source/WebCore/testing/InternalSettings.idl b/Source/WebCore/testing/InternalSettings.idl index c92d98b20..d37b3f8c2 100644 --- a/Source/WebCore/testing/InternalSettings.idl +++ b/Source/WebCore/testing/InternalSettings.idl @@ -37,7 +37,6 @@ void setFixedElementsLayoutRelativeToFrame(in boolean enabled) raises(DOMException); void setUnifiedTextCheckingEnabled(in boolean enabled) raises (DOMException); boolean unifiedTextCheckingEnabled() raises (DOMException); - void setPageScaleFactor(in float scaleFactor, in long x, in long y) raises(DOMException); void setTouchEventEmulationEnabled(in boolean enabled) raises(DOMException); void setDeviceSupportsTouch(in boolean enabled) raises(DOMException); void setDeviceSupportsMouse(in boolean enabled) raises(DOMException); @@ -70,8 +69,6 @@ void setDialogElementEnabled(in boolean enabled) raises(DOMException); void setLangAttributeAwareFormControlUIEnabled(in boolean enabled); - void setPagination(in DOMString mode, in long gap, in [Optional] long pageLength) raises(DOMException); - void setEnableMockPagePopup(in boolean enabled) raises(DOMException); [Conditional=VIDEO_TRACK] void setShouldDisplayTrackKind(in DOMString kind, in boolean enabled) raises (DOMException); [Conditional=VIDEO_TRACK] boolean shouldDisplayTrackKind(in DOMString trackKind) raises (DOMException); void setMemoryInfoEnabled(in boolean enabled) raises(DOMException); diff --git a/Source/WebCore/testing/Internals.cpp b/Source/WebCore/testing/Internals.cpp index ea794b772..94a3b052e 100644 --- a/Source/WebCore/testing/Internals.cpp +++ b/Source/WebCore/testing/Internals.cpp @@ -28,6 +28,8 @@ #include "BackForwardController.h" #include "CachedResourceLoader.h" +#include "Chrome.h" +#include "ChromeClient.h" #include "ClientRect.h" #include "ClientRectList.h" #include "ComposedShadowTreeWalker.h" @@ -62,6 +64,7 @@ #include "IntRect.h" #include "Language.h" #include "MallocStatistics.h" +#include "MockPagePopupDriver.h" #include "NodeRenderingContext.h" #include "Page.h" #include "PrintContext.h" @@ -112,6 +115,10 @@ namespace WebCore { +#if ENABLE(PAGE_POPUP) +static MockPagePopupDriver* s_pagePopupDriver = 0; +#endif + using namespace HTMLNames; #if ENABLE(INSPECTOR) @@ -213,9 +220,17 @@ void Internals::resetToConsistentState(Page* page) { ASSERT(page); + page->setPageScaleFactor(1, IntPoint(0, 0)); + page->setPagination(Pagination()); TextRun::setAllowsRoundingHacks(false); WebCore::overrideUserPreferredLanguages(Vector<String>()); WebCore::Settings::setUsesOverlayScrollbars(false); +#if ENABLE(PAGE_POPUP) + delete s_pagePopupDriver; + s_pagePopupDriver = 0; + if (page->chrome()) + page->chrome()->client()->resetPagePopupDriver(); +#endif #if ENABLE(INSPECTOR) && ENABLE(JAVASCRIPT_DEBUGGER) if (page->inspectorController()) page->inspectorController()->setProfilerEnabled(false); @@ -665,13 +680,30 @@ void Internals::setFormControlStateOfPreviousHistoryItem(PassRefPtr<DOMStringLis ec = INVALID_ACCESS_ERR; } +void Internals::setEnableMockPagePopup(bool enabled, ExceptionCode& ec) +{ +#if ENABLE(PAGE_POPUP) + Document* document = contextDocument(); + if (!document || !document->page() || !document->page()->chrome()) + return; + Page* page = document->page(); + if (!enabled) { + page->chrome()->client()->resetPagePopupDriver(); + return; + } + if (!s_pagePopupDriver) + s_pagePopupDriver = MockPagePopupDriver::create(page->mainFrame()).leakPtr(); + page->chrome()->client()->setPagePopupDriver(s_pagePopupDriver); +#else + UNUSED_PARAM(enabled); + UNUSED_PARAM(ec); +#endif +} + #if ENABLE(PAGE_POPUP) PassRefPtr<PagePopupController> Internals::pagePopupController() { - InternalSettings* settings = this->settings(); - if (!settings) - return 0; - return settings->pagePopupController(); + return s_pagePopupDriver ? s_pagePopupDriver->pagePopupController() : 0; } #endif @@ -828,14 +860,51 @@ void Internals::setScrollViewPosition(Document* document, long x, long y, Except frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue); } -void Internals::setPagination(Document*, const String& mode, int gap, int pageLength, ExceptionCode& ec) +void Internals::setPagination(Document* document, const String& mode, int gap, int pageLength, ExceptionCode& ec) { - settings()->setPagination(mode, gap, pageLength, ec); + if (!document || !document->page()) { + ec = INVALID_ACCESS_ERR; + return; + } + Page* page = document->page(); + + Pagination pagination; + if (mode == "Unpaginated") + pagination.mode = Pagination::Unpaginated; + else if (mode == "LeftToRightPaginated") + pagination.mode = Pagination::LeftToRightPaginated; + else if (mode == "RightToLeftPaginated") + pagination.mode = Pagination::RightToLeftPaginated; + else if (mode == "TopToBottomPaginated") + pagination.mode = Pagination::TopToBottomPaginated; + else if (mode == "BottomToTopPaginated") + pagination.mode = Pagination::BottomToTopPaginated; + else { + ec = SYNTAX_ERR; + return; + } + + pagination.gap = gap; + pagination.pageLength = pageLength; + page->setPagination(pagination); } -String Internals::configurationForViewport(Document*, float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode& ec) +String Internals::configurationForViewport(Document* document, float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode& ec) { - return settings()->configurationForViewport(devicePixelRatio, deviceWidth, deviceHeight, availableWidth, availableHeight, ec); + if (!document || !document->page()) { + ec = INVALID_ACCESS_ERR; + return String(); + } + Page* page = document->page(); + + const int defaultLayoutWidthForNonMobilePages = 980; + + ViewportArguments arguments = page->viewportArguments(); + ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight)); + restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio); + restrictScaleFactorToInitialScaleIfNotUserScalable(attributes); + + return "viewport size " + String::number(attributes.layoutSize.width()) + "x" + String::number(attributes.layoutSize.height()) + " scale " + String::number(attributes.initialScale) + " with limits [" + String::number(attributes.minimumScale) + ", " + String::number(attributes.maximumScale) + "] and userScalable " + (attributes.userScalable ? "true" : "false"); } bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionCode& ec) @@ -1470,6 +1539,17 @@ String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int heig return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft); } +void Internals::setPageScaleFactor(float scaleFactor, int x, int y, ExceptionCode& ec) +{ + Document* document = contextDocument(); + if (!document || !document->page()) { + ec = INVALID_ACCESS_ERR; + return; + } + Page* page = document->page(); + page->setPageScaleFactor(scaleFactor, IntPoint(x, y)); +} + #if ENABLE(FULLSCREEN_API) void Internals::webkitWillEnterFullScreenForElement(Document* document, Element* element) { diff --git a/Source/WebCore/testing/Internals.h b/Source/WebCore/testing/Internals.h index 68e65e4cb..b99f3e3ab 100644 --- a/Source/WebCore/testing/Internals.h +++ b/Source/WebCore/testing/Internals.h @@ -118,6 +118,7 @@ public: #endif PassRefPtr<DOMStringList> formControlStateOfPreviousHistoryItem(ExceptionCode&); void setFormControlStateOfPreviousHistoryItem(PassRefPtr<DOMStringList>, ExceptionCode&); + void setEnableMockPagePopup(bool, ExceptionCode&); #if ENABLE(PAGE_POPUP) PassRefPtr<PagePopupController> pagePopupController(); #endif @@ -231,6 +232,8 @@ public: String pageProperty(String, int, ExceptionCode& = ASSERT_NO_EXCEPTION) const; String pageSizeAndMarginsInPixels(int, int, int, int, int, int, int, ExceptionCode& = ASSERT_NO_EXCEPTION) const; + void setPageScaleFactor(float scaleFactor, int x, int y, ExceptionCode&); + #if ENABLE(FULLSCREEN_API) void webkitWillEnterFullScreenForElement(Document*, Element*); void webkitDidEnterFullScreenForElement(Document*, Element*); diff --git a/Source/WebCore/testing/Internals.idl b/Source/WebCore/testing/Internals.idl index 703bea3aa..167d0e56c 100644 --- a/Source/WebCore/testing/Internals.idl +++ b/Source/WebCore/testing/Internals.idl @@ -78,6 +78,7 @@ #endif DOMString[] formControlStateOfPreviousHistoryItem() raises(DOMException); void setFormControlStateOfPreviousHistoryItem(in DOMString[] values) raises(DOMException); + void setEnableMockPagePopup(in boolean enabled) raises(DOMException); #if defined(ENABLE_PAGE_POPUP) && ENABLE_PAGE_POPUP readonly attribute PagePopupController pagePopupController; #endif @@ -195,6 +196,7 @@ DOMString pageProperty(in DOMString propertyName, in long pageNumber) raises (DOMException); DOMString pageSizeAndMarginsInPixels(in long pageIndex, in long width, in long height, in long marginTop, in long marginRight, in long marginBottom, in long marginLeft) raises (DOMException); + void setPageScaleFactor(in float scaleFactor, in long x, in long y) raises(DOMException); #if defined(ENABLE_FULLSCREEN_API) && ENABLE_FULLSCREEN_API void webkitWillEnterFullScreenForElement(in Document document, in Element element); diff --git a/Source/WebCore/xml/parser/CharacterReferenceParserInlines.h b/Source/WebCore/xml/parser/CharacterReferenceParserInlines.h index fe20e527a..159cf93a6 100644 --- a/Source/WebCore/xml/parser/CharacterReferenceParserInlines.h +++ b/Source/WebCore/xml/parser/CharacterReferenceParserInlines.h @@ -44,7 +44,7 @@ inline void unconsumeCharacters(SegmentedString& source, const StringBuilder& co source.push(consumedCharacters[0]); source.push(consumedCharacters[1]); } else - source.prepend(SegmentedString(String(consumedCharacters.characters(), consumedCharacters.length()))); + source.prepend(SegmentedString(consumedCharacters.toStringPreserveCapacity())); } template <typename ParserFunctions> diff --git a/Source/WebKit/blackberry/Api/WebPage.cpp b/Source/WebKit/blackberry/Api/WebPage.cpp index 8c24a51cd..775887c06 100644 --- a/Source/WebKit/blackberry/Api/WebPage.cpp +++ b/Source/WebKit/blackberry/Api/WebPage.cpp @@ -56,6 +56,7 @@ #include "EditorClientBlackBerry.h" #include "FocusController.h" #include "Frame.h" +#include "FrameLoadRequest.h" #include "FrameLoaderClientBlackBerry.h" #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD #include "GeolocationClientMock.h" @@ -372,7 +373,6 @@ WebPagePrivate::WebPagePrivate(WebPage* webPage, WebPageClient* client, const In , m_overflowExceedsContentsSize(false) , m_resetVirtualViewportOnCommitted(true) , m_shouldUseFixedDesktopMode(false) - , m_needTouchEvents(false) , m_preventIdleDimmingCount(0) #if ENABLE(TOUCH_EVENTS) , m_preventDefaultOnTouchStart(false) @@ -703,7 +703,10 @@ void WebPagePrivate::load(const BlackBerry::Platform::String& url, const BlackBe request.setSuggestedSaveName(suggestedSaveName); - m_mainFrame->loader()->load(request, "" /* name */, false); + FrameLoadRequest frameRequest(m_mainFrame, request); + frameRequest.setFrameName(""); + frameRequest.setShouldCheckNewWindowPolicy(true); + m_mainFrame->loader()->load(frameRequest); } void WebPage::load(const BlackBerry::Platform::String& url, const BlackBerry::Platform::String& networkToken, bool isInitial) @@ -748,7 +751,7 @@ void WebPagePrivate::loadString(const BlackBerry::Platform::String& string, cons extractMIMETypeFromMediaType(contentType), extractCharsetFromMediaType(contentType), !failingURL.empty() ? parseUrl(failingURL) : KURL()); - m_mainFrame->loader()->load(request, substituteData, false); + m_mainFrame->loader()->load(FrameLoadRequest(m_mainFrame, request, substituteData)); } void WebPage::loadString(const BlackBerry::Platform::String& string, const BlackBerry::Platform::String& baseURL, const BlackBerry::Platform::String& mimeType, const BlackBerry::Platform::String& failingURL) @@ -4010,7 +4013,7 @@ bool WebPage::touchEvent(const Platform::TouchEvent& event) bool handled = false; - if (d->m_needTouchEvents && !event.m_type != Platform::TouchEvent::TouchInjected) + if (!event.m_type != Platform::TouchEvent::TouchInjected) handled = d->m_mainFrame->eventHandler()->handleTouchEvent(PlatformTouchEvent(&tEvent)); if (d->m_preventDefaultOnTouchStart) { @@ -5796,6 +5799,7 @@ void WebPagePrivate::didChangeSettings(WebSettings* webSettings) coreSettings->setFirstScheduledLayoutDelay(webSettings->firstScheduledLayoutDelay()); coreSettings->setUseCache(webSettings->useWebKitCache()); + coreSettings->setCookieEnabled(webSettings->areCookiesEnabled()); #if ENABLE(SQL_DATABASE) // DatabaseTracker can only be initialized for once, so it doesn't @@ -5918,11 +5922,6 @@ bool WebPage::isWebGLEnabled() const return d->m_page->settings()->webGLEnabled(); } -void WebPagePrivate::setNeedTouchEvents(bool value) -{ - m_needTouchEvents = value; -} - void WebPagePrivate::frameUnloaded(const Frame* frame) { m_inputHandler->frameUnloaded(frame); diff --git a/Source/WebKit/blackberry/Api/WebPageClient.h b/Source/WebKit/blackberry/Api/WebPageClient.h index 896f24c67..c86b674ba 100644 --- a/Source/WebKit/blackberry/Api/WebPageClient.h +++ b/Source/WebKit/blackberry/Api/WebPageClient.h @@ -103,7 +103,6 @@ public: virtual void notifyRunLayoutTestsFinished() = 0; virtual void notifyInRegionScrollableAreasChanged(const std::vector<Platform::ScrollViewBase*>&) = 0; - virtual void notifyNoMouseMoveOrTouchMoveHandlers() = 0; virtual void notifyDocumentOnLoad(bool) = 0; diff --git a/Source/WebKit/blackberry/Api/WebPage_p.h b/Source/WebKit/blackberry/Api/WebPage_p.h index 10a209e33..b0df6e12c 100644 --- a/Source/WebKit/blackberry/Api/WebPage_p.h +++ b/Source/WebKit/blackberry/Api/WebPage_p.h @@ -490,7 +490,6 @@ public: bool m_overflowExceedsContentsSize; bool m_resetVirtualViewportOnCommitted; bool m_shouldUseFixedDesktopMode; - bool m_needTouchEvents; int m_preventIdleDimmingCount; #if ENABLE(TOUCH_EVENTS) diff --git a/Source/WebKit/blackberry/ChangeLog b/Source/WebKit/blackberry/ChangeLog index 8950d4e85..981a30d4e 100644 --- a/Source/WebKit/blackberry/ChangeLog +++ b/Source/WebKit/blackberry/ChangeLog @@ -1,3 +1,132 @@ +2012-11-28 Otto Derek Cheung <otcheung@rim.com> + + [BlackBerry] CookieJarBlackBerry will use document settings for cookiesEnabled + https://bugs.webkit.org/show_bug.cgi?id=103560 + + Reviewed by Rob Buis. + + PR 253490 + + Syncing platform Websetting's cookieEnabled value with Page->setting's cookieEnabled + value. + + * Api/WebPage.cpp: + (BlackBerry::WebKit::WebPagePrivate::didChangeSettings): + +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * Api/WebPage.cpp: + (BlackBerry::WebKit::WebPagePrivate::load): + (BlackBerry::WebKit::WebPagePrivate::loadString): + * WebCoreSupport/FrameLoaderClientBlackBerry.cpp: + (WebCore::FrameLoaderClientBlackBerry::dispatchDidFailProvisionalLoad): + +2012-11-27 Jacky Jiang <zhajiang@rim.com> + + [BlackBerry] http:// origins can navigate to privileged local:// origins + https://bugs.webkit.org/show_bug.cgi?id=103437 + + Reviewed by Yong Li. + + PR: 251489 + When we aren't allowed to display the destination origin, we shouldn't + even create the window for it. In this way we can block the remote + origins(like http://) window.open local origins(like file:// and + local://) and avoid further security issues. + Chrome and Safari will open a blank window and fail to load. Firefox + will fail to open the window and report a load failure error which has + the same behavior as us. I would prefer this way as the window would + be useless and the calls after that would be harmful to us. + + * WebCoreSupport/ChromeClientBlackBerry.cpp: + (WebCore::ChromeClientBlackBerry::createWindow): + +2012-11-27 Andrew Lo <anlo@rim.com> + + [BlackBerry] Remove unnecessary backing store suspension in InputHandler::ensureFocusTextElementVisible + https://bugs.webkit.org/show_bug.cgi?id=103441 + + Reviewed by Rob Buis. + Internally reviewed by Mike Fenton. + + Remove unnecessary backing store suspension in + InputHandler::ensureFocusTextElementVisible. + + Not necessary anymore since both zoom and scroll adjustments + happen in an animation. + + * WebKitSupport/InputHandler.cpp: + (BlackBerry::WebKit::InputHandler::ensureFocusTextElementVisible): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * Api/WebPage.cpp: + (BlackBerry::WebKit::WebPagePrivate::load): + (BlackBerry::WebKit::WebPagePrivate::loadString): + * WebCoreSupport/FrameLoaderClientBlackBerry.cpp: + (WebCore::FrameLoaderClientBlackBerry::dispatchDidFailProvisionalLoad): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * Api/WebPage.cpp: + (BlackBerry::WebKit::WebPagePrivate::load): + (BlackBerry::WebKit::WebPagePrivate::loadString): + * WebCoreSupport/FrameLoaderClientBlackBerry.cpp: + (WebCore::FrameLoaderClientBlackBerry::dispatchDidFailProvisionalLoad): + +2012-11-26 Genevieve Mak <gmak@rim.com> + + [BlackBerry] Form controls don't show pressed state. + https://bugs.webkit.org/show_bug.cgi?id=103292 + + Reviewed by Rob Buis. + + Reviewed internally by Eli Fidler and Mike Lattanzio. + We weren't sending touch events to webpages unless they + had JS touch event listeners which form controls don't have. + Now send them always and do a little cleanup. + PR #249791 + + * Api/WebPage.cpp: + (BlackBerry::WebKit::WebPagePrivate::WebPagePrivate): + (BlackBerry::WebKit::WebPage::touchEvent): + * Api/WebPageClient.h: + * Api/WebPage_p.h: + (WebPagePrivate): + * WebCoreSupport/ChromeClientBlackBerry.cpp: + (WebCore::ChromeClientBlackBerry::needTouchEvents): + +2012-11-26 Nima Ghanavatian <nghanavatian@rim.com> + + [BlackBerry] Null check calls associated with retrieving the caret rect. + https://bugs.webkit.org/show_bug.cgi?id=103281 + + Reviewed by Rob Buis. + + Some of these calls can return null, which could lead to a crash. + + Internally reviewed by Gen Mak. + + * WebKitSupport/InputHandler.cpp: + (BlackBerry::WebKit::InputHandler::requestSpellingCheckingOptions): + 2012-11-26 Jonathan Dong <jonathan.dong@torchmobile.com.cn> [BlackBerry] Should not autofill username and password when there're more than one password inputs on the same page diff --git a/Source/WebKit/blackberry/WebCoreSupport/ChromeClientBlackBerry.cpp b/Source/WebKit/blackberry/WebCoreSupport/ChromeClientBlackBerry.cpp index 78c12b2c9..657414010 100644 --- a/Source/WebKit/blackberry/WebCoreSupport/ChromeClientBlackBerry.cpp +++ b/Source/WebKit/blackberry/WebCoreSupport/ChromeClientBlackBerry.cpp @@ -215,8 +215,17 @@ bool ChromeClientBlackBerry::shouldForceDocumentStyleSelectorUpdate() return !m_webPagePrivate->m_webSettings->isJavaScriptEnabled() && !m_webPagePrivate->m_inputHandler->processingChange(); } -Page* ChromeClientBlackBerry::createWindow(Frame*, const FrameLoadRequest& request, const WindowFeatures& features, const NavigationAction&) -{ +Page* ChromeClientBlackBerry::createWindow(Frame* frame, const FrameLoadRequest& request, const WindowFeatures& features, const NavigationAction&) +{ + // Bail out early when we aren't allowed to display the target origin, otherwise, + // it would be harmful and the window would be useless. This is the same check + // as the one in FrameLoader::loadFrameRequest(). + const KURL& url = request.resourceRequest().url(); + if (!request.requester()->canDisplay(url)) { + frame->loader()->reportLocalLoadFailed(frame, url.string()); + return 0; + } + #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD if (m_webPagePrivate->m_dumpRenderTree && !m_webPagePrivate->m_dumpRenderTree->allowsOpeningWindow()) return 0; @@ -248,7 +257,7 @@ Page* ChromeClientBlackBerry::createWindow(Frame*, const FrameLoadRequest& reque if (features.dialog) flags |= WebPageClient::FlagWindowIsDialog; - WebPage* webPage = m_webPagePrivate->m_client->createWindow(x, y, width, height, flags, request.resourceRequest().url().string(), request.frameName()); + WebPage* webPage = m_webPagePrivate->m_client->createWindow(x, y, width, height, flags, url.string(), request.frameName()); if (!webPage) return 0; @@ -656,7 +665,6 @@ PlatformPageClient ChromeClientBlackBerry::platformPageClient() const #if ENABLE(TOUCH_EVENTS) void ChromeClientBlackBerry::needTouchEvents(bool value) { - m_webPagePrivate->setNeedTouchEvents(value); } #endif diff --git a/Source/WebKit/blackberry/WebCoreSupport/FrameLoaderClientBlackBerry.cpp b/Source/WebKit/blackberry/WebCoreSupport/FrameLoaderClientBlackBerry.cpp index 0b92aec37..80fc06b6a 100644 --- a/Source/WebKit/blackberry/WebCoreSupport/FrameLoaderClientBlackBerry.cpp +++ b/Source/WebKit/blackberry/WebCoreSupport/FrameLoaderClientBlackBerry.cpp @@ -34,6 +34,7 @@ #include "CredentialTransformData.h" #include "DumpRenderTreeClient.h" #include "ExternalExtension.h" +#include "FrameLoadRequest.h" #include "FrameNetworkingContextBlackBerry.h" #include "FrameView.h" #include "HTMLFormElement.h" @@ -750,7 +751,7 @@ void FrameLoaderClientBlackBerry::dispatchDidFailProvisionalLoad(const ResourceE } m_loadingErrorPage = true; - m_frame->loader()->load(originalRequest, errorData, false); + m_frame->loader()->load(FrameLoadRequest(m_frame, originalRequest, errorData)); } void FrameLoaderClientBlackBerry::dispatchWillSubmitForm(FramePolicyFunction function, PassRefPtr<FormState>) diff --git a/Source/WebKit/blackberry/WebKitSupport/InputHandler.cpp b/Source/WebKit/blackberry/WebKitSupport/InputHandler.cpp index 115b2fbc4..ca0fdf4bd 100644 --- a/Source/WebKit/blackberry/WebKitSupport/InputHandler.cpp +++ b/Source/WebKit/blackberry/WebKitSupport/InputHandler.cpp @@ -743,6 +743,9 @@ void InputHandler::requestSpellingCheckingOptions(imf_sp_text_t& spellCheckingOp if (m_webPage->focusedOrMainFrame()->selection()->selectionType() != VisibleSelection::CaretSelection) return; + if (!m_currentFocusElement || !m_currentFocusElement->document() || !m_currentFocusElement->document()->frame()) + return; + // imf_sp_text_t should be generated in pixel viewport coordinates. WebCore::IntRect caretRect = m_webPage->focusedOrMainFrame()->selection()->selection().visibleStart().absoluteCaretBounds(); caretRect = m_webPage->focusedOrMainFrame()->view()->contentsToRootView(caretRect); @@ -1120,8 +1123,6 @@ void InputHandler::ensureFocusTextElementVisible(CaretScrollType scrollType) int fontHeight = selectionFocusRect.height(); - m_webPage->suspendBackingStore(); - // If the text is too small, zoom in to make it a minimum size. // The minimum size being defined as 3 mm is a good value based on my observations. static const int s_minimumTextHeightInPixels = Graphics::Screen::primaryScreen()->heightInMMToPixels(3); @@ -1221,7 +1222,6 @@ void InputHandler::ensureFocusTextElementVisible(CaretScrollType scrollType) m_webPage->m_userPerformedManualScroll = true; m_webPage->client()->animateBlockZoom(zoomScaleRequired, m_webPage->m_finalBlockPoint); } - m_webPage->resumeBackingStore(); } void InputHandler::ensureFocusPluginElementVisible() diff --git a/Source/WebKit/chromium/ChangeLog b/Source/WebKit/chromium/ChangeLog index 24abafb25..293f6f11b 100644 --- a/Source/WebKit/chromium/ChangeLog +++ b/Source/WebKit/chromium/ChangeLog @@ -1,3 +1,650 @@ +2012-11-29 Miguel Garcia <miguelg@chromium.org> + + Fix typo in description of openDateTimeChooser documentation + https://bugs.webkit.org/show_bug.cgi?id=103622 + + Reviewed by Kent Tamura. + + + * public/WebViewClient.h: + (WebViewClient): + +2012-11-28 Robert Kroeger <rjkroege@chromium.org> + + remove unused PlatformGestureCurve code + https://bugs.webkit.org/show_bug.cgi?id=103296 + + Reviewed by Adam Barth. + + Previous CLs have made the Chromium embedder provide gesture fling + curve implementation to WebKit. Consequently no platform uses the + gestural fling code currently found in WebKit. This CL removes this code. + + Code removal only: covered by existing tests. + + * WebKit.gypi: + * tests/PlatformGestureCurveTest.cpp: Removed. + +2012-11-28 Mark Pilgrim <pilgrim@chromium.org> + + [Chromium] Remove pluginsScriptableObject from PlatformSupport + https://bugs.webkit.org/show_bug.cgi?id=103542 + + Reviewed by Adam Barth. + + Part of a refactoring series. See tracking bug 82948. + + * src/PlatformSupport.cpp: + (WebCore): + * src/WebPluginContainerImpl.h: + (WebPluginContainerImpl): + +2012-11-28 Mark Pilgrim <pilgrim@chromium.org> + + [Chromium][Win] Remove ensureFontLoaded from PlatformSupport + https://bugs.webkit.org/show_bug.cgi?id=97696 + + Reviewed by Adam Barth. + + Move ensureFontLoaded() from PlatformSupport to + FontPlatformDataChromiumWin. Part of a refactoring series; see + tracking bug 82948. + + * src/PlatformSupport.cpp: + (WebCore): + +2012-11-28 Eric Uhrhane <ericu@chromium.org> + + [chromium] Add unit tests for ChromeClientImpl::getNavigationPolicy + https://bugs.webkit.org/show_bug.cgi?id=102424 + + Reviewed by Adam Barth. + + This tests a bunch of basic scenarios regarding what will produce a + popup, a new foreground/background tab, or a new window. + + * WebKit.gypi: Added test file. + * src/WebViewImpl.h: + (WebViewImpl): Added friend declaration for setCurrentInputEventForTest. + * tests/ChromeClientImplTest.cpp: Added. + +2012-11-28 Alexandre Elias <aelias@chromium.org> + + [chromium] Handle pinch correctly in slow-scrolling area + https://bugs.webkit.org/show_bug.cgi?id=102740 + + Reviewed by James Robinson. + + With the nonmodal gesture event model, pinch zoom gestures involve + interleaved pinch and scroll events. This caused a bug on slow-scroll + areas: the scroll events were sent to the main thread and + the pinch events were handled in the impl thread. + + This patch makes it so that scroll events are always handled in the impl + thread if a pinch is active. + + * src/WebCompositorInputHandlerImpl.cpp: + (WebKit::WebCompositorInputHandlerImpl::WebCompositorInputHandlerImpl): + (WebKit::WebCompositorInputHandlerImpl::handleInputEventInternal): + * src/WebCompositorInputHandlerImpl.h: + * tests/WebCompositorInputHandlerImplTest.cpp: + (WebKit::TEST_F): + (WebKit): + +2012-11-28 Sadrul Habib Chowdhury <sadrul@chromium.org> + + [chromium] Allow plugins to opt-in to receive synthetic mouse events out of touch events. + https://bugs.webkit.org/show_bug.cgi?id=103092 + + Reviewed by Tony Chang. + + A plugin can now request to receive raw touch events, or to receive mouse events synthesized + from the touch events, or to not receive any touch events at all. + + * public/WebPluginContainer.h: + (WebPluginContainer): + * src/WebInputEventConversion.cpp: + (WebKit::updateWebMouseEventFromWebCoreMouseEvent): + (WebKit::WebMouseEventBuilder::WebMouseEventBuilder): + (WebKit): + * src/WebInputEventConversion.h: + (WebMouseEventBuilder): + * src/WebPluginContainerImpl.cpp: + (WebKit::WebPluginContainerImpl::setIsAcceptingTouchEvents): + (WebKit): + (WebKit::WebPluginContainerImpl::requestTouchEventType): + (WebKit::WebPluginContainerImpl::WebPluginContainerImpl): + (WebKit::WebPluginContainerImpl::~WebPluginContainerImpl): + * src/WebPluginContainerImpl.h: + (WebPluginContainerImpl): + +2012-11-28 David Grogan <dgrogan@chromium.org> + + IndexedDB: Remove setVersion from WK API + https://bugs.webkit.org/show_bug.cgi?id=103456 + + Reviewed by Darin Fisher. + + These are the last vestiges of this ancient API. The bulk of the + removal was done in bug 94972. + + * public/WebIDBCallbacks.h: + * public/WebIDBDatabase.h: + +2012-11-28 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed. Rolled DEPS. + + * DEPS: + +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * src/WebFrameImpl.cpp: + (WebKit::WebFrameImpl::loadRequest): + (WebKit::WebFrameImpl::loadData): + * src/WebSharedWorkerImpl.cpp: + (WebKit::WebSharedWorkerImpl::initializeLoader): + +2012-11-27 Eberhard Graether <egraether@google.com> + + [chromium] Add WebLayerTreeViewClient API to request font atlas + https://bugs.webkit.org/show_bug.cgi?id=102958 + + Reviewed by James Robinson. + + This change makes the font atlas creation accessible to the WebLayerTreeView. + + * src/WebViewImpl.cpp: + (WebKit::WebViewImpl::createFontAtlas): + (WebKit): + * src/WebViewImpl.h: + (WebViewImpl): + +2012-11-27 Joshua Bell <jsbell@chromium.org> + + IndexedDB: Simplify transaction timers and event tracking + https://bugs.webkit.org/show_bug.cgi?id=102984 + + Reviewed by Tony Chang. + + Remove now-unused didCompleteTaskEvents() method. + + * src/IDBTransactionBackendProxy.cpp: + * src/IDBTransactionBackendProxy.h: + (IDBTransactionBackendProxy): + * src/WebIDBTransactionImpl.cpp: + * src/WebIDBTransactionImpl.h: + +2012-11-27 Alpha Lam <hclam@chromium.org> + + [chromium] Implement full-featured image cache + https://bugs.webkit.org/show_bug.cgi?id=99784 + + Reviewed by Stephen White. + + Added ImageFrameGeneratorTest to test cache logic and generation + of new cache entries. + + ImageFrameGeneratorTest.cacheHit + Test that a complete cached entry is reused. + + ImageFrameGeneratorTest.cacheMissWithScale + Cache miss for a scaled image but cache hit on a full size image. + Scaled image is created from cached full size image. + + ImageFrameGeneratorTest.cacheMissWithDecodeAndScale + Cache miss for both scaled image and full size image. + + ImageFrameGeneratorTest.cacheMissWithIncompleteDecode + Test the logic for handling incomplete cache objects. + + * WebKit.gypi: + * src/WebKit.cpp: + (WebKit::initializeWithoutV8): + * src/WebSettingsImpl.cpp: + (WebKit::WebSettingsImpl::setDeferredImageDecodingEnabled): + * tests/DeferredImageDecoderTest.cpp: + (WebCore::DeferredImageDecoderTest::SetUp): + (WebCore::DeferredImageDecoderTest::decoderBeingDestroyed): + (WebCore::DeferredImageDecoderTest::frameBufferRequested): + (DeferredImageDecoderTest): + (WebCore::DeferredImageDecoderTest::frameStatus): + * tests/ImageFrameGeneratorTest.cpp: Added. + (WebCore): + (WebCore::fullSize): + (WebCore::scaledSize): + (MockImageDecoderFactory): + (WebCore::MockImageDecoderFactory::create): + (WebCore::MockImageDecoderFactory::MockImageDecoderFactory): + (ImageFrameGeneratorTest): + (WebCore::ImageFrameGeneratorTest::SetUp): + (WebCore::ImageFrameGeneratorTest::TearDown): + (WebCore::ImageFrameGeneratorTest::decoderBeingDestroyed): + (WebCore::ImageFrameGeneratorTest::frameBufferRequested): + (WebCore::ImageFrameGeneratorTest::frameStatus): + (WebCore::ImageFrameGeneratorTest::createCompleteImage): + (WebCore::ImageFrameGeneratorTest::setFrameStatus): + (WebCore::TEST_F): + * tests/MockImageDecoder.h: + (MockImageDecoderClient): + (WebCore::MockImageDecoder::frameBufferAtIndex): + +2012-11-27 David Grogan <dgrogan@chromium.org> + + IndexedDB: Remove IDBDatabase.setVersion API + https://bugs.webkit.org/show_bug.cgi?id=94972 + + Reviewed by Tony Chang. + + * src/IDBCallbacksProxy.cpp: + * src/IDBCallbacksProxy.h: + (IDBCallbacksProxy): + * src/IDBDatabaseBackendProxy.cpp: + * src/IDBDatabaseBackendProxy.h: + (IDBDatabaseBackendProxy): + * src/WebIDBCallbacksImpl.cpp: + * src/WebIDBCallbacksImpl.h: + (WebIDBCallbacksImpl): + * src/WebIDBDatabaseImpl.cpp: + * src/WebIDBDatabaseImpl.h: + (WebIDBDatabaseImpl): + +2012-11-27 Eberhard Graether <egraether@google.com> + + Plumbing showPaintRects out of InspectorPageAgent to use a different drawing implementation if available. + https://bugs.webkit.org/show_bug.cgi?id=102452 + + Reviewed by Pavel Feldman. + + This change makes the showPaintRects setting in the Web Inspector's settings notify InspectorClient + when changed. And the default paint rects drawing is not used if an alternative is available. + This allows Chromium to draw the paint rects in the compositor's HUDLayer. + + * public/WebView.h: + (WebView): + * src/InspectorClientImpl.cpp: + (WebKit::InspectorClientImpl::overridesShowPaintRects): + (WebKit): + (WebKit::InspectorClientImpl::setShowPaintRects): + * src/InspectorClientImpl.h: + (InspectorClientImpl): + * src/WebViewImpl.cpp: + (WebKit::WebViewImpl::setShowPaintRects): + (WebKit): + * src/WebViewImpl.h: + (WebViewImpl): + +2012-11-27 Tony Chang <tony@chromium.org> + + [chromium] Unreviewed build fix on Linux clang. + + ../../third_party/WebKit/Source/WebKit/chromium/src/FrameLoaderClientImpl.cpp:1055:63: error: + C++98 requires an accessible copy constructor for class 'WebKit::WebCachedURLRequest' when binding + a reference to a temporary; was private [-Werror,-Wbind-to-temporary-copy] + + * src/FrameLoaderClientImpl.cpp: + (WebKit::FrameLoaderClientImpl::dispatchWillRequestResource): + +2012-11-27 Marja Hölttä <marja@chromium.org> + + Add callbacks to the FrameLoaderClient when a resource is requested + https://bugs.webkit.org/show_bug.cgi?id=92761 + + Reviewed by Adam Barth. + + In Chromium, when an extension script cancels a network + request (which happens out of process), we'd like to + notify content scripts running on the current page about + which elements failed to load because the requests were + cancelled (as opposed to e.g. the network request just + didn't work). Since the resource request itself does not + carry any information what DOM element is was made for, + currently a content script has to search the DOM tree and + guess which requests will be cancelled by its counter + part. By adding these callbacks, the embedder can make + this connection explictly. + + * WebKit.gyp: + * public/WebCachedURLRequest.h: Added. + (WebKit): + (WebCachedURLRequest): + (WebKit::WebCachedURLRequest::~WebCachedURLRequest): + * public/WebFrameClient.h: + (WebKit): + (WebFrameClient): + (WebKit::WebFrameClient::willRequestResource): + * src/FrameLoaderClientImpl.cpp: + (WebKit::FrameLoaderClientImpl::dispatchWillRequestResource): + (WebKit): + * src/FrameLoaderClientImpl.h: + (FrameLoaderClientImpl): + * src/WebCachedURLRequest.cpp: Added. + (WebKit): + (WebKit::WebCachedURLRequest::reset): + (WebKit::WebCachedURLRequest::urlRequest): + (WebKit::WebCachedURLRequest::charset): + (WebKit::WebCachedURLRequest::forPreload): + (WebKit::WebCachedURLRequest::initiatorName): + (WebKit::WebCachedURLRequest::initiatorElement): + (WebKit::WebCachedURLRequest::WebCachedURLRequest): + +2012-11-27 Keishi Hattori <keishi@webkit.org> + + Add WebLocalizedString for validation type badinput + https://bugs.webkit.org/show_bug.cgi?id=103381 + + Reviewed by Kent Tamura. + + * src/LocalizedStrings.cpp: + (WebCore::validationMessageBadInputForNumberText): Using the newly added WebLocalizedString enum. + (WebCore::validationMessageBadInputForDateTimeText): Ditto. + +2012-11-27 Alec Flett <alecflett@chromium.org> + + IndexedDB: stub out IDBDatabaseBackendInterface::createTransaction + https://bugs.webkit.org/show_bug.cgi?id=102730 + + Reviewed by Darin Fisher. + + Add support for new createTransaction() method in both sides + of the WebKit API. + + * public/WebIDBDatabase.h: + (WebIDBDatabase): + (WebKit::WebIDBDatabase::createTransaction): + * src/IDBDatabaseBackendProxy.cpp: + (WebKit): + (WebKit::IDBDatabaseBackendProxy::createTransaction): + * src/IDBDatabaseBackendProxy.h: + (IDBDatabaseBackendProxy): + * src/WebIDBDatabaseImpl.cpp: + (WebKit::WebIDBDatabaseImpl::createTransaction): + (WebKit): + * src/WebIDBDatabaseImpl.h: + (WebIDBDatabaseImpl): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * src/WebFrameImpl.cpp: + (WebKit::WebFrameImpl::loadRequest): + (WebKit::WebFrameImpl::loadData): + * src/WebSharedWorkerImpl.cpp: + (WebKit::WebSharedWorkerImpl::initializeLoader): + +2012-11-25 Kent Tamura <tkent@chromium.org> + + Implement ValidityState::badInput + https://bugs.webkit.org/show_bug.cgi?id=102861 + + Reviewed by Hajime Morita. + + * src/LocalizedStrings.cpp: + Add placeholder implementations for new localized string functions. + We'll update them in another patch. + (WebCore::validationMessageBadInputForNumberText): + (WebCore::validationMessageBadInputForDateTimeText): + +2012-11-26 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135798. + http://trac.webkit.org/changeset/135798 + https://bugs.webkit.org/show_bug.cgi?id=103354 + + Broke the chrome mac build (Requested by noel_ on #webkit). + + * WebKit.gypi: + * src/WebKit.cpp: + (WebKit::initializeWithoutV8): + * src/WebSettingsImpl.cpp: + (WebKit::WebSettingsImpl::setDeferredImageDecodingEnabled): + * tests/DeferredImageDecoderTest.cpp: + (WebCore::DeferredImageDecoderTest::SetUp): + (WebCore::DeferredImageDecoderTest::decoderBeingDestroyed): + * tests/ImageFrameGeneratorTest.cpp: Removed. + * tests/MockImageDecoder.h: + (MockImageDecoderClient): + (WebCore::MockImageDecoder::frameBufferAtIndex): + +2012-11-26 Alexandre Elias <aelias@chromium.org> + + [chromium] Touchscreen fling handling + https://bugs.webkit.org/show_bug.cgi?id=103278 + + Reviewed by James Robinson. + + The fling logic for touchpad can fall through to bad + performance in several ways. This patch introduces an alternate + path for touchscreen fling that simplifies it as follows: + + - Stop generating wheel events, to prevent unnecessary scrollBegin hit + tests and to avoid falling back to slow path if a wheel handler is + registered. + + - Drop the event on ScrollStatusIgnored. There's no real reason to + send the event to the WebKit thread here. + + - Don't call transferActiveWheelFlingAnimation. This type of + transition shouldn't be needed with touchscreen flings. + + * src/WebCompositorInputHandlerImpl.cpp: + (WebKit::WebCompositorInputHandlerImpl::handleGestureFling): + (WebKit::WebCompositorInputHandlerImpl::animate): + (WebKit::WebCompositorInputHandlerImpl::cancelCurrentFling): + (WebKit::WebCompositorInputHandlerImpl::scrollBy): + * src/WebCompositorInputHandlerImpl.h: + +2012-11-26 Kentaro Hara <haraken@chromium.org> + + [V8] Remove WorkerContextExecutionProxy.{h,cpp} + https://bugs.webkit.org/show_bug.cgi?id=103325 + + Reviewed by Adam Barth. + + Now WorkerContextExecutionProxy.{h,cpp} are empty. + + No tests. No change in behavior. + + * src/WebKit.cpp: + * src/WebWorkerClientImpl.cpp: + +2012-11-26 James Robinson <jamesr@chromium.org> + + [chromium] Remove deprecated and unused WebGraphicsContext3D compositor binding calls + https://bugs.webkit.org/show_bug.cgi?id=103322 + + Reviewed by Adam Barth. + + * src/WebViewImpl.cpp: + * src/WebViewImpl.h: + (WebViewImpl): + +2012-11-26 Alpha Lam <hclam@chromium.org> + + [chromium] Implement full-featured image cache + https://bugs.webkit.org/show_bug.cgi?id=99784 + + Reviewed by James Robinson. + + Added ImageFrameGeneratorTest to test cache logic and generation + of new cache entries. + + ImageFrameGeneratorTest.cacheHit + Test that a complete cached entry is reused. + + ImageFrameGeneratorTest.cacheMissWithScale + Cache miss for a scaled image but cache hit on a full size image. + Scaled image is created from cached full size image. + + ImageFrameGeneratorTest.cacheMissWithDecodeAndScale + Cache miss for both scaled image and full size image. + + ImageFrameGeneratorTest.cacheMissWithIncompleteDecode + Test the logic for handling incomplete cache objects. + + * WebKit.gypi: + * src/WebKit.cpp: + (WebKit::initializeWithoutV8): + * src/WebSettingsImpl.cpp: + (WebKit::WebSettingsImpl::setDeferredImageDecodingEnabled): + * tests/DeferredImageDecoderTest.cpp: + (WebCore::DeferredImageDecoderTest::SetUp): + (WebCore::DeferredImageDecoderTest::decoderBeingDestroyed): + (WebCore::DeferredImageDecoderTest::frameBufferRequested): + (DeferredImageDecoderTest): + (WebCore::DeferredImageDecoderTest::frameStatus): + * tests/ImageFrameGeneratorTest.cpp: Added. + (WebCore): + (WebCore::fullSize): + (WebCore::scaledSize): + (MockImageDecoderFactory): + (WebCore::MockImageDecoderFactory::create): + (WebCore::MockImageDecoderFactory::MockImageDecoderFactory): + (ImageFrameGeneratorTest): + (WebCore::ImageFrameGeneratorTest::SetUp): + (WebCore::ImageFrameGeneratorTest::TearDown): + (WebCore::ImageFrameGeneratorTest::decoderBeingDestroyed): + (WebCore::ImageFrameGeneratorTest::frameBufferRequested): + (WebCore::ImageFrameGeneratorTest::frameStatus): + (WebCore::ImageFrameGeneratorTest::createCompleteImage): + (WebCore::ImageFrameGeneratorTest::setFrameStatus): + (WebCore::TEST_F): + * tests/MockImageDecoder.h: + (MockImageDecoderClient): + (WebCore::MockImageDecoder::frameBufferAtIndex): + +2012-11-26 Varun Jain <varunjain@chromium.org> + + LongPress and LongTap gestures should start drag/drop and open context menu respectively. + https://bugs.webkit.org/show_bug.cgi?id=101545 + + Reviewed by Antonio Gomes. + + For LongPress, we simulate drag by sending a mouse down and mouse drag + events. If a drag is not started (because maybe there is no draggable + element), then we show context menu instead (which is the current + behavior for LongPress). For LongTap, we use the existing functions that + LongPress uses to summon the context menu. LongPress initiated drag and + drop can be enabled/disabled by the platform using the Setting + touchDragDropEnabled which is disabled by default. + + * public/WebSettings.h: + * src/WebSettingsImpl.cpp: + (WebKit::WebSettingsImpl::setTouchDragDropEnabled): + (WebKit): + * src/WebSettingsImpl.h: + (WebSettingsImpl): + +2012-11-26 Yusuf Ozuysal <yusufo@google.com> + + Add hasTouchEventhandlersAt to WebView API + https://bugs.webkit.org/show_bug.cgi?id=102541 + + Reviewed by James Robinson. + + Adds hasTouchEventHandlersAt to WebWidget API to check for touch event handlers at a + given point. This will be used to distinguish between events not processed by + touch event handlers and event not hitting any touch event handlers. Both are + returning the same ACK message currently. Default implementation returns true to + continue the same behavior as we currently have. + + * public/WebWidget.h: + (WebWidget): + (WebKit::WebWidget::hasTouchEventHandlersAt): + * src/WebViewImpl.cpp: + (WebKit::WebViewImpl::hasTouchEventHandlersAt): + (WebKit): + * src/WebViewImpl.h: + (WebViewImpl): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * src/WebFrameImpl.cpp: + (WebKit::WebFrameImpl::loadRequest): + (WebKit::WebFrameImpl::loadData): + * src/WebSharedWorkerImpl.cpp: + (WebKit::WebSharedWorkerImpl::initializeLoader): + +2012-11-26 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed. Rolled DEPS. + + * DEPS: + +2012-11-26 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135743. + http://trac.webkit.org/changeset/135743 + https://bugs.webkit.org/show_bug.cgi?id=103280 + + Caused compile failure 'SK_DISABLE_DITHER_32BIT_GRADIENT' + macro redefined (Requested by rjkroege on #webkit). + + * skia_webkit.gyp: + +2012-11-26 Mike Reed <reed@google.com> + + add SK_DISABLE_DITHER_32BIT_GRADIENT define, in preparation for rebaselining + https://bugs.webkit.org/show_bug.cgi?id=103272 + + Reviewed by NOBODY. Unreviewed. + + No behavior change, as this define already exists on the chrome side in SkUserConfig.h + + * skia_webkit.gyp: + +2012-11-26 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135735. + http://trac.webkit.org/changeset/135735 + https://bugs.webkit.org/show_bug.cgi?id=103270 + + Caused breakage across the Chromium tree. (Requested by + rjkroege_ on #webkit). + + * skia_webkit.gyp: + +2012-11-26 Mike Reed <reed@google.com> + + add SK_DISABLE_DITHER_32BIT_GRADIENT define, in preparation for rebaselining + https://bugs.webkit.org/show_bug.cgi?id=103269 + + Reviewed by NOBODY. Unreviewed. + + No behavior change, as this define already exists on the chrome side in SkUserConfig.h + + * skia_webkit.gyp: + +2012-11-26 Scott Violet <sky@chromium.org> + + [chromium] Make use_default_render_theme compile the right set of files + https://bugs.webkit.org/show_bug.cgi?id=102952 + + Reviewed by Kent Tamura. + + * WebKit.gyp: Adds WebRenderTheme.* and updates rules as to when to compile them. + * features.gypi: Removes use_default_render_theme default values as common.gypi sets them. + * public/default: Added. + * public/default/WebRenderTheme.h: Copy of linux/WebRenderTheme.h + * src/default: Added. + * src/default/WebRenderTheme.cpp: Copy of linux/WebRenderTheme.cpp + 2012-11-24 Silvia Pfeiffer <silviapf@chromium.org> [chromium] Remove traces of MediaControlRootElement diff --git a/Source/WebKit/chromium/DEPS b/Source/WebKit/chromium/DEPS index 31ff1844f..c04782eb3 100644 --- a/Source/WebKit/chromium/DEPS +++ b/Source/WebKit/chromium/DEPS @@ -32,7 +32,7 @@ vars = { 'chromium_svn': 'http://src.chromium.org/svn/trunk/src', - 'chromium_rev': '169306' + 'chromium_rev': '169895' } deps = { diff --git a/Source/WebKit/chromium/WebKit.gyp b/Source/WebKit/chromium/WebKit.gyp index 92afddaa0..0e6f0c9a0 100644 --- a/Source/WebKit/chromium/WebKit.gyp +++ b/Source/WebKit/chromium/WebKit.gyp @@ -108,6 +108,7 @@ 'public/WebBindings.h', 'public/WebBlob.h', 'public/WebCache.h', + 'public/WebCachedURLRequest.h', 'public/WebColorChooser.h', 'public/WebColorChooserClient.h', 'public/WebColorName.h', @@ -288,6 +289,7 @@ 'public/WebWorkerInfo.h', 'public/android/WebInputEventFactory.h', 'public/android/WebSandboxSupport.h', + 'public/default/WebRenderTheme.h', 'public/gtk/WebInputEventFactory.h', 'public/linux/WebFontRenderStyle.h', 'public/linux/WebFontRendering.h', @@ -432,6 +434,7 @@ 'src/PrerendererClientImpl.h', 'src/PrerendererClientImpl.cpp', 'src/android/WebInputEventFactory.cpp', + 'src/default/WebRenderTheme.cpp', 'src/linux/WebFontInfo.cpp', 'src/linux/WebFontRendering.cpp', 'src/linux/WebFontRenderStyle.cpp', @@ -489,6 +492,7 @@ 'src/WebBlob.cpp', 'src/WebBlobData.cpp', 'src/WebCache.cpp', + 'src/WebCachedURLRequest.cpp', 'src/WebColorName.cpp', 'src/WebCommon.cpp', 'src/WebCompositorInputHandlerImpl.cpp', @@ -840,6 +844,20 @@ }], ], }], + ['use_default_render_theme==1', { + 'sources/': [ + ['exclude', 'src/linux/WebRenderTheme.cpp'], + ['exclude', 'public/linux/WebRenderTheme.h'], + ], + 'include_dirs': [ + 'public/default', + ], + }, { # else use_default_render_theme==0 + 'sources/': [ + ['exclude', 'src/default/WebRenderTheme.cpp'], + ['exclude', 'public/default/WebRenderTheme.h'], + ], + }], ], 'target_conditions': [ ['OS=="android"', { diff --git a/Source/WebKit/chromium/WebKit.gypi b/Source/WebKit/chromium/WebKit.gypi index dd5d6cf1b..3ad3e20da 100644 --- a/Source/WebKit/chromium/WebKit.gypi +++ b/Source/WebKit/chromium/WebKit.gypi @@ -57,6 +57,7 @@ 'tests/AssociatedURLLoaderTest.cpp', 'tests/Canvas2DLayerBridgeTest.cpp', 'tests/Canvas2DLayerManagerTest.cpp', + 'tests/ChromeClientImplTest.cpp', 'tests/ClipboardChromiumTest.cpp', 'tests/CompositorFakeWebGraphicsContext3D.h', 'tests/DateTimeFormatTest.cpp', @@ -80,6 +81,7 @@ 'tests/IDBKeyPathTest.cpp', 'tests/IDBLevelDBCodingTest.cpp', 'tests/IDBRequestTest.cpp', + 'tests/ImageFrameGeneratorTest.cpp', 'tests/ImageLayerChromiumTest.cpp', 'tests/MockImageDecoder.h', 'tests/KeyboardTest.cpp', @@ -95,7 +97,6 @@ 'tests/PODRedBlackTreeTest.cpp', 'tests/PaintAggregatorTest.cpp', 'tests/PlatformContextSkiaTest.cpp', - 'tests/PlatformGestureCurveTest.cpp', 'tests/PopupContainerTest.cpp', 'tests/RegionTest.cpp', 'tests/RenderTableCellTest.cpp', diff --git a/Source/WebKit/chromium/features.gypi b/Source/WebKit/chromium/features.gypi index 8e2aaf317..a7bf6367a 100644 --- a/Source/WebKit/chromium/features.gypi +++ b/Source/WebKit/chromium/features.gypi @@ -146,13 +146,11 @@ 'enable_touch_events%': 1, 'enable_touch_icon_loading%' : 0, 'enable_mutation_observers%': 1, - 'use_default_render_theme%': 0, }, 'use_accelerated_compositing%': '<(use_accelerated_compositing)', 'enable_skia_text%': '<(enable_skia_text)', 'enable_svg%': '<(enable_svg)', 'enable_touch_events%': '<(enable_touch_events)', - 'use_default_render_theme%': '<(use_default_render_theme)', 'conditions': [ ['OS=="android"', { 'feature_defines': [ diff --git a/Source/WebKit/chromium/public/WebCachedURLRequest.h b/Source/WebKit/chromium/public/WebCachedURLRequest.h new file mode 100644 index 000000000..5006a749d --- /dev/null +++ b/Source/WebKit/chromium/public/WebCachedURLRequest.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WebCachedURLRequest_h +#define WebCachedURLRequest_h + +#include "WebElement.h" +#include "platform/WebCommon.h" +#include "platform/WebPrivateOwnPtr.h" +#include "platform/WebString.h" + +namespace WebCore { class CachedResourceRequest; } + +namespace WebKit { + +class WebElement; +class WebString; +class WebURLRequest; +class WrappedResourceRequest; + +class WebCachedURLRequest { +public: + ~WebCachedURLRequest() { reset(); } + WEBKIT_EXPORT void reset(); + + WEBKIT_EXPORT const WebURLRequest& urlRequest() const; + WEBKIT_EXPORT WebString charset() const; + WEBKIT_EXPORT bool forPreload() const; + WEBKIT_EXPORT WebString initiatorName() const; + WEBKIT_EXPORT WebElement initiatorElement() const; + +#if WEBKIT_IMPLEMENTATION + explicit WebCachedURLRequest(WebCore::CachedResourceRequest*); +#endif + +private: + WebCachedURLRequest(const WebCachedURLRequest&); + WebCachedURLRequest& operator=(const WebCachedURLRequest&); + + WebCore::CachedResourceRequest* m_private; + mutable WebPrivateOwnPtr<WrappedResourceRequest> m_resourceRequestWrapper; +}; + +} // namespace WebKit + +#endif diff --git a/Source/WebKit/chromium/public/WebFrameClient.h b/Source/WebKit/chromium/public/WebFrameClient.h index bda3c0389..c2eee586a 100644 --- a/Source/WebKit/chromium/public/WebFrameClient.h +++ b/Source/WebKit/chromium/public/WebFrameClient.h @@ -50,6 +50,7 @@ namespace WebKit { class WebApplicationCacheHost; class WebApplicationCacheHostClient; +class WebCachedURLRequest; class WebCookieJar; class WebDataSource; class WebDOMEvent; @@ -251,6 +252,9 @@ public: // the client keeps such an association. virtual void removeIdentifierForRequest(unsigned identifier) { } + // An element will request a resource. + virtual void willRequestResource(WebFrame*, const WebCachedURLRequest&) { } + // A request is about to be sent out, and the client may modify it. Request // is writable, and changes to the URL, for example, will change the request // made. If this request is the result of a redirect, then redirectResponse diff --git a/Source/WebKit/chromium/public/WebIDBCallbacks.h b/Source/WebKit/chromium/public/WebIDBCallbacks.h index b91b0f5a2..09861f133 100644 --- a/Source/WebKit/chromium/public/WebIDBCallbacks.h +++ b/Source/WebKit/chromium/public/WebIDBCallbacks.h @@ -53,7 +53,6 @@ public: virtual void onSuccess(WebIDBCursor*, const WebIDBKey& key, const WebIDBKey& primaryKey, const WebSerializedScriptValue&) { WEBKIT_ASSERT_NOT_REACHED(); } virtual void onSuccess(WebIDBDatabase*) { WEBKIT_ASSERT_NOT_REACHED(); } virtual void onSuccess(const WebIDBKey&) { WEBKIT_ASSERT_NOT_REACHED(); } - virtual void onSuccess(WebIDBTransaction*) { WEBKIT_ASSERT_NOT_REACHED(); } virtual void onSuccess(const WebSerializedScriptValue&) { WEBKIT_ASSERT_NOT_REACHED(); } virtual void onSuccess(const WebSerializedScriptValue&, const WebIDBKey&, const WebIDBKeyPath&) { WEBKIT_ASSERT_NOT_REACHED(); } virtual void onSuccess(long long) { WEBKIT_ASSERT_NOT_REACHED(); } diff --git a/Source/WebKit/chromium/public/WebIDBDatabase.h b/Source/WebKit/chromium/public/WebIDBDatabase.h index b92799039..3aef7bdb0 100644 --- a/Source/WebKit/chromium/public/WebIDBDatabase.h +++ b/Source/WebKit/chromium/public/WebIDBDatabase.h @@ -56,13 +56,15 @@ public: return 0; } virtual void deleteObjectStore(long long objectStoreId, const WebIDBTransaction& transaction, WebExceptionCode& ec) { WEBKIT_ASSERT_NOT_REACHED(); } - virtual void setVersion(const WebString& version, WebIDBCallbacks* callbacks, WebExceptionCode&) { WEBKIT_ASSERT_NOT_REACHED(); } + // FIXME: Remove this as part of https://bugs.webkit.org/show_bug.cgi?id=102733. // Transfers ownership of the WebIDBTransaction to the caller. virtual WebIDBTransaction* transaction(const WebVector<long long>&, unsigned short mode) { WEBKIT_ASSERT_NOT_REACHED(); return 0; } + // Transfers ownership of the WebIDBTransaction to the caller. + virtual WebIDBTransaction* createTransaction(long long id, const WebVector<long long>&, unsigned short mode) { WEBKIT_ASSERT_NOT_REACHED(); return 0; } virtual void close() { WEBKIT_ASSERT_NOT_REACHED(); } virtual void forceClose() { WEBKIT_ASSERT_NOT_REACHED(); } diff --git a/Source/WebKit/chromium/public/WebPluginContainer.h b/Source/WebKit/chromium/public/WebPluginContainer.h index 1229014da..aad631f67 100644 --- a/Source/WebKit/chromium/public/WebPluginContainer.h +++ b/Source/WebKit/chromium/public/WebPluginContainer.h @@ -47,6 +47,12 @@ struct WebRect; class WebPluginContainer { public: + enum TouchEventRequestType { + TouchEventRequestTypeNone, + TouchEventRequestTypeRaw, + TouchEventRequestTypeSynthesizedMouse, + }; + // Returns the element containing this plugin. virtual WebElement element() = 0; @@ -111,9 +117,12 @@ public: // content. The rectangle is in the plugin's coordinate system. virtual bool isRectTopmost(const WebRect&) = 0; - // Notifies when the plugin starts/stops accepting touch events. + // Notifies when the plugin starts/stops accepting touch events. This is deprecated, use requestTouchEventType instead. virtual void setIsAcceptingTouchEvents(bool) = 0; + // Notifies when the plugin changes the kind of touch-events it accepts. + virtual void requestTouchEventType(TouchEventRequestType) = 0; + // Notifies when the plugin starts/stops accepting wheel events. Without // calling the function with true, the container might not always able to // receive wheel events in some cases (such as when threaded compositing diff --git a/Source/WebKit/chromium/public/WebSettings.h b/Source/WebKit/chromium/public/WebSettings.h index 2d356fa6a..4c9d0cc64 100644 --- a/Source/WebKit/chromium/public/WebSettings.h +++ b/Source/WebKit/chromium/public/WebSettings.h @@ -158,6 +158,7 @@ public: virtual void setTextAutosizingEnabled(bool) = 0; virtual void setTextAutosizingFontScaleFactor(float) = 0; virtual void setTextDirectionSubmenuInclusionBehaviorNeverIncluded() = 0; + virtual void setTouchDragDropEnabled(bool) = 0; virtual void setUnifiedTextCheckerEnabled(bool) = 0; virtual void setUserStyleSheetLocation(const WebURL&) = 0; virtual void setUsesEncodingDetector(bool) = 0; diff --git a/Source/WebKit/chromium/public/WebView.h b/Source/WebKit/chromium/public/WebView.h index 2ec1b1bad..7a7d3f4c7 100644 --- a/Source/WebKit/chromium/public/WebView.h +++ b/Source/WebKit/chromium/public/WebView.h @@ -471,6 +471,7 @@ public: virtual bool isSelectionEditable() const = 0; + virtual void setShowPaintRects(bool) = 0; virtual void setShowFPSCounter(bool) = 0; // Benchmarking support ------------------------------------------------- diff --git a/Source/WebKit/chromium/public/WebViewClient.h b/Source/WebKit/chromium/public/WebViewClient.h index 5b3cbc0b1..c6e175dba 100644 --- a/Source/WebKit/chromium/public/WebViewClient.h +++ b/Source/WebKit/chromium/public/WebViewClient.h @@ -225,7 +225,7 @@ public: WebFileChooserCompletion*) { return false; } // Ask users to choose date/time for the specified parameters. When a user - // chooses a value, an implemenattion of this function should call + // chooses a value, an implementation of this function should call // WebDateTimeChooserCompletion::didChooseValue or didCancelChooser. If the // implementation opened date/time chooser UI successfully, it should return // true. This function is used only if ExternalDateTimeChooser is used. diff --git a/Source/WebKit/chromium/public/WebWidget.h b/Source/WebKit/chromium/public/WebWidget.h index f2b394439..da23951f9 100644 --- a/Source/WebKit/chromium/public/WebWidget.h +++ b/Source/WebKit/chromium/public/WebWidget.h @@ -157,6 +157,9 @@ public: // the event has been processed, false otherwise. virtual bool handleInputEvent(const WebInputEvent&) { return false; } + // Check whether the given point hits any registered touch event handlers. + virtual bool hasTouchEventHandlersAt(const WebPoint&) { return true; } + // Called to inform the WebWidget that mouse capture was lost. virtual void mouseCaptureLost() { } diff --git a/Source/WebKit/chromium/public/default/WebRenderTheme.h b/Source/WebKit/chromium/public/default/WebRenderTheme.h new file mode 100644 index 000000000..ae517c664 --- /dev/null +++ b/Source/WebKit/chromium/public/default/WebRenderTheme.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2009 Joel Stanley. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WebRenderTheme_h +#define WebRenderTheme_h + +#include "../platform/WebCommon.h" + +namespace WebKit { + +// Set caret blink interval for text input areas. +WEBKIT_EXPORT void setCaretBlinkInterval(double); + +} // namespace WebKit + +#endif diff --git a/Source/WebKit/chromium/src/FrameLoaderClientImpl.cpp b/Source/WebKit/chromium/src/FrameLoaderClientImpl.cpp index 9d0aab495..fdf56b5f6 100644 --- a/Source/WebKit/chromium/src/FrameLoaderClientImpl.cpp +++ b/Source/WebKit/chromium/src/FrameLoaderClientImpl.cpp @@ -65,6 +65,7 @@ #if ENABLE(REQUEST_AUTOCOMPLETE) #include "WebAutofillClient.h" #endif +#include "WebCachedURLRequest.h" #include "WebDOMEvent.h" #include "WebDataSourceImpl.h" #include "WebDevToolsAgentPrivate.h" @@ -1048,6 +1049,14 @@ void FrameLoaderClientImpl::dispatchUnableToImplementPolicy(const ResourceError& m_webFrame->client()->unableToImplementPolicyWithError(m_webFrame, error); } +void FrameLoaderClientImpl::dispatchWillRequestResource(CachedResourceRequest* request) +{ + if (m_webFrame->client()) { + WebCachedURLRequest urlRequest(request); + m_webFrame->client()->willRequestResource(m_webFrame, urlRequest); + } +} + void FrameLoaderClientImpl::dispatchWillSendSubmitEvent(PassRefPtr<FormState> prpFormState) { if (m_webFrame->client()) diff --git a/Source/WebKit/chromium/src/FrameLoaderClientImpl.h b/Source/WebKit/chromium/src/FrameLoaderClientImpl.h index 2aa624bdf..78fea62fa 100644 --- a/Source/WebKit/chromium/src/FrameLoaderClientImpl.h +++ b/Source/WebKit/chromium/src/FrameLoaderClientImpl.h @@ -118,6 +118,7 @@ public: virtual void dispatchDecidePolicyForNavigationAction(WebCore::FramePolicyFunction function, const WebCore::NavigationAction& action, const WebCore::ResourceRequest& request, PassRefPtr<WebCore::FormState> form_state); virtual void cancelPolicyCheck(); virtual void dispatchUnableToImplementPolicy(const WebCore::ResourceError&); + virtual void dispatchWillRequestResource(WebCore::CachedResourceRequest*); virtual void dispatchWillSendSubmitEvent(PassRefPtr<WebCore::FormState>); virtual void dispatchWillSubmitForm(WebCore::FramePolicyFunction, PassRefPtr<WebCore::FormState>); virtual void revertToProvisionalState(WebCore::DocumentLoader*) { } diff --git a/Source/WebKit/chromium/src/IDBCallbacksProxy.cpp b/Source/WebKit/chromium/src/IDBCallbacksProxy.cpp index 81cb549e5..837cc32a6 100644 --- a/Source/WebKit/chromium/src/IDBCallbacksProxy.cpp +++ b/Source/WebKit/chromium/src/IDBCallbacksProxy.cpp @@ -87,11 +87,6 @@ void IDBCallbacksProxy::onSuccess(PassRefPtr<IDBKey> idbKey) m_callbacks->onSuccess(WebIDBKey(idbKey)); } -void IDBCallbacksProxy::onSuccess(PassRefPtr<IDBTransactionBackendInterface> backend) -{ - m_callbacks->onSuccess(new WebIDBTransactionImpl(backend)); -} - void IDBCallbacksProxy::onSuccess(PassRefPtr<DOMStringList> domStringList) { m_callbacks->onSuccess(WebDOMStringList(domStringList)); diff --git a/Source/WebKit/chromium/src/IDBCallbacksProxy.h b/Source/WebKit/chromium/src/IDBCallbacksProxy.h index c940698f7..65f3b740a 100644 --- a/Source/WebKit/chromium/src/IDBCallbacksProxy.h +++ b/Source/WebKit/chromium/src/IDBCallbacksProxy.h @@ -51,7 +51,6 @@ public: virtual void onSuccess(PassRefPtr<WebCore::IDBCursorBackendInterface>, PassRefPtr<WebCore::IDBKey>, PassRefPtr<WebCore::IDBKey> primaryKey, PassRefPtr<WebCore::SerializedScriptValue>); virtual void onSuccess(PassRefPtr<WebCore::IDBDatabaseBackendInterface>); virtual void onSuccess(PassRefPtr<WebCore::IDBKey>); - virtual void onSuccess(PassRefPtr<WebCore::IDBTransactionBackendInterface>); virtual void onSuccess(PassRefPtr<WebCore::SerializedScriptValue>); virtual void onSuccess(PassRefPtr<WebCore::SerializedScriptValue>, PassRefPtr<WebCore::IDBKey>, const WebCore::IDBKeyPath&); virtual void onSuccess(int64_t); diff --git a/Source/WebKit/chromium/src/IDBDatabaseBackendProxy.cpp b/Source/WebKit/chromium/src/IDBDatabaseBackendProxy.cpp index 0bc95466d..91a419a3e 100644 --- a/Source/WebKit/chromium/src/IDBDatabaseBackendProxy.cpp +++ b/Source/WebKit/chromium/src/IDBDatabaseBackendProxy.cpp @@ -85,15 +85,19 @@ void IDBDatabaseBackendProxy::deleteObjectStore(int64_t objectStoreId, IDBTransa m_webIDBDatabase->deleteObjectStore(objectStoreId, *transactionProxy->getWebIDBTransaction(), ec); } -void IDBDatabaseBackendProxy::setVersion(const String& version, PassRefPtr<IDBCallbacks> callbacks, PassRefPtr<IDBDatabaseCallbacks> databaseCallbacks, ExceptionCode& ec) +// FIXME: Remove this as part of https://bugs.webkit.org/show_bug.cgi?id=102733. +PassRefPtr<IDBTransactionBackendInterface> IDBDatabaseBackendProxy::transaction(const Vector<int64_t>& objectStoreIds, unsigned short mode) { - ASSERT(m_webIDBDatabase); - m_webIDBDatabase->setVersion(version, new WebIDBCallbacksImpl(callbacks), ec); + OwnPtr<WebIDBTransaction> transaction = adoptPtr(m_webIDBDatabase->transaction(objectStoreIds, mode)); + if (!transaction) + return 0; + + return IDBTransactionBackendProxy::create(transaction.release()); } -PassRefPtr<IDBTransactionBackendInterface> IDBDatabaseBackendProxy::transaction(const Vector<int64_t>& objectStoreIds, unsigned short mode) +PassRefPtr<IDBTransactionBackendInterface> IDBDatabaseBackendProxy::createTransaction(int64_t id, const Vector<int64_t>& objectStoreIds, unsigned short mode) { - OwnPtr<WebIDBTransaction> transaction = adoptPtr(m_webIDBDatabase->transaction(objectStoreIds, mode)); + OwnPtr<WebIDBTransaction> transaction = adoptPtr(m_webIDBDatabase->createTransaction(id, objectStoreIds, mode)); if (!transaction) return 0; diff --git a/Source/WebKit/chromium/src/IDBDatabaseBackendProxy.h b/Source/WebKit/chromium/src/IDBDatabaseBackendProxy.h index aa8fdf0c9..4e7cce29e 100644 --- a/Source/WebKit/chromium/src/IDBDatabaseBackendProxy.h +++ b/Source/WebKit/chromium/src/IDBDatabaseBackendProxy.h @@ -46,8 +46,9 @@ public: virtual PassRefPtr<WebCore::IDBObjectStoreBackendInterface> createObjectStore(int64_t, const String& name, const WebCore::IDBKeyPath&, bool autoIncrement, WebCore::IDBTransactionBackendInterface*, WebCore::ExceptionCode&); virtual void deleteObjectStore(int64_t, WebCore::IDBTransactionBackendInterface*, WebCore::ExceptionCode&); - virtual void setVersion(const String& version, PassRefPtr<WebCore::IDBCallbacks>, PassRefPtr<WebCore::IDBDatabaseCallbacks>, WebCore::ExceptionCode&); + // FIXME: Remove this as part of https://bugs.webkit.org/show_bug.cgi?id=102733. virtual PassRefPtr<WebCore::IDBTransactionBackendInterface> transaction(const Vector<int64_t>&, unsigned short mode); + virtual PassRefPtr<WebCore::IDBTransactionBackendInterface> createTransaction(int64_t, const Vector<int64_t>&, unsigned short mode); virtual void close(PassRefPtr<WebCore::IDBDatabaseCallbacks>); private: diff --git a/Source/WebKit/chromium/src/IDBTransactionBackendProxy.cpp b/Source/WebKit/chromium/src/IDBTransactionBackendProxy.cpp index 572963c13..6e0134c2a 100644 --- a/Source/WebKit/chromium/src/IDBTransactionBackendProxy.cpp +++ b/Source/WebKit/chromium/src/IDBTransactionBackendProxy.cpp @@ -72,11 +72,6 @@ void IDBTransactionBackendProxy::abort() m_webIDBTransaction->abort(); } -void IDBTransactionBackendProxy::didCompleteTaskEvents() -{ - m_webIDBTransaction->didCompleteTaskEvents(); -} - void IDBTransactionBackendProxy::setCallbacks(IDBTransactionCallbacks* callbacks) { m_webIDBTransaction->setCallbacks(new WebIDBTransactionCallbacksImpl(callbacks)); diff --git a/Source/WebKit/chromium/src/IDBTransactionBackendProxy.h b/Source/WebKit/chromium/src/IDBTransactionBackendProxy.h index 0a6a53b84..8ead3164c 100644 --- a/Source/WebKit/chromium/src/IDBTransactionBackendProxy.h +++ b/Source/WebKit/chromium/src/IDBTransactionBackendProxy.h @@ -44,7 +44,6 @@ public: virtual PassRefPtr<WebCore::IDBObjectStoreBackendInterface> objectStore(int64_t, WebCore::ExceptionCode&); virtual void commit(); virtual void abort(); - virtual void didCompleteTaskEvents(); virtual void setCallbacks(WebCore::IDBTransactionCallbacks*); WebIDBTransaction* getWebIDBTransaction() const { return m_webIDBTransaction.get(); } diff --git a/Source/WebKit/chromium/src/InspectorClientImpl.cpp b/Source/WebKit/chromium/src/InspectorClientImpl.cpp index 220b7db74..3d69376d7 100644 --- a/Source/WebKit/chromium/src/InspectorClientImpl.cpp +++ b/Source/WebKit/chromium/src/InspectorClientImpl.cpp @@ -163,6 +163,16 @@ void InspectorClientImpl::autoZoomPageToFitWidth() agent->autoZoomPageToFitWidth(); } +bool InspectorClientImpl::overridesShowPaintRects() +{ + return m_inspectedWebView->isAcceleratedCompositingActive(); +} + +void InspectorClientImpl::setShowPaintRects(bool show) +{ + m_inspectedWebView->setShowPaintRects(show); +} + bool InspectorClientImpl::canShowFPSCounter() { return true; diff --git a/Source/WebKit/chromium/src/InspectorClientImpl.h b/Source/WebKit/chromium/src/InspectorClientImpl.h index a759257af..b9e3b8419 100644 --- a/Source/WebKit/chromium/src/InspectorClientImpl.h +++ b/Source/WebKit/chromium/src/InspectorClientImpl.h @@ -77,6 +77,9 @@ public: virtual void overrideDeviceMetrics(int, int, float, bool); virtual void autoZoomPageToFitWidth(); + virtual bool overridesShowPaintRects(); + virtual void setShowPaintRects(bool); + virtual bool canShowFPSCounter(); virtual void setShowFPSCounter(bool); diff --git a/Source/WebKit/chromium/src/LocalizedStrings.cpp b/Source/WebKit/chromium/src/LocalizedStrings.cpp index a5c2024fa..309611381 100644 --- a/Source/WebKit/chromium/src/LocalizedStrings.cpp +++ b/Source/WebKit/chromium/src/LocalizedStrings.cpp @@ -504,4 +504,16 @@ String validationMessageStepMismatchText(const String& base, const String& step) return query(WebLocalizedString::ValidationStepMismatch, base, step); } +String validationMessageBadInputForNumberText() +{ + return query(WebLocalizedString::ValidationBadInputForNumber); +} + +#if ENABLE(INPUT_MULTIPLE_FIELDS_UI) +String validationMessageBadInputForDateTimeText() +{ + return query(WebLocalizedString::ValidationBadInputForDateTime); +} +#endif + } // namespace WebCore diff --git a/Source/WebKit/chromium/src/PlatformSupport.cpp b/Source/WebKit/chromium/src/PlatformSupport.cpp index d7a4fbbfc..d7f0dccea 100644 --- a/Source/WebKit/chromium/src/PlatformSupport.cpp +++ b/Source/WebKit/chromium/src/PlatformSupport.cpp @@ -104,19 +104,6 @@ using namespace WebKit; namespace WebCore { -// Font ----------------------------------------------------------------------- - -#if OS(WINDOWS) -bool PlatformSupport::ensureFontLoaded(HFONT font) -{ - WebSandboxSupport* ss = WebKit::Platform::current()->sandboxSupport(); - - // if there is no sandbox, then we can assume the font - // was able to be loaded successfully already - return ss ? ss->ensureFontLoaded(font) : true; -} -#endif - // Indexed Database ----------------------------------------------------------- PassRefPtr<IDBFactoryBackendInterface> PlatformSupport::idbFactory() @@ -135,14 +122,6 @@ bool PlatformSupport::plugins(bool refresh, Vector<PluginInfo>* results) return true; // FIXME: There is no need for this function to return a value. } -NPObject* PlatformSupport::pluginScriptableObject(Widget* widget) -{ - if (!widget || !widget->isPluginContainer()) - return 0; - - return static_cast<WebPluginContainerImpl*>(widget)->scriptableObject(); -} - // Theming -------------------------------------------------------------------- #if OS(WINDOWS) && !ENABLE(DEFAULT_RENDER_THEME) diff --git a/Source/WebKit/chromium/src/WebCachedURLRequest.cpp b/Source/WebKit/chromium/src/WebCachedURLRequest.cpp new file mode 100644 index 000000000..370c541d1 --- /dev/null +++ b/Source/WebKit/chromium/src/WebCachedURLRequest.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebCachedURLRequest.h" + +#include "CachedResourceRequest.h" +#include "Element.h" +#include "WrappedResourceRequest.h" +#include <public/WebURLRequest.h> + +using namespace WebCore; + +namespace WebKit { + +void WebCachedURLRequest::reset() +{ + m_resourceRequestWrapper.reset(0); + m_private = 0; +} + +const WebURLRequest& WebCachedURLRequest::urlRequest() const +{ + if (!m_resourceRequestWrapper.get()) + m_resourceRequestWrapper.reset(new WrappedResourceRequest(m_private->resourceRequest())); + else + m_resourceRequestWrapper->bind(m_private->resourceRequest()); + return *m_resourceRequestWrapper.get(); +} + +WebString WebCachedURLRequest::charset() const +{ + return WebString(m_private->charset()); +} + +bool WebCachedURLRequest::forPreload() const +{ + return m_private->forPreload(); +} + +WebString WebCachedURLRequest::initiatorName() const +{ + return WebString(m_private->initiatorName()); +} + +WebElement WebCachedURLRequest::initiatorElement() const +{ + return WebElement(m_private->initiatorElement()); +} + +WebCachedURLRequest::WebCachedURLRequest(CachedResourceRequest* request) + : m_private(request) +{ +} + +} // namespace WebKit diff --git a/Source/WebKit/chromium/src/WebCompositorInputHandlerImpl.cpp b/Source/WebKit/chromium/src/WebCompositorInputHandlerImpl.cpp index 74836d55f..0f8dbcc95 100644 --- a/Source/WebKit/chromium/src/WebCompositorInputHandlerImpl.cpp +++ b/Source/WebKit/chromium/src/WebCompositorInputHandlerImpl.cpp @@ -69,7 +69,8 @@ WebCompositorInputHandlerImpl::WebCompositorInputHandlerImpl() , m_expectScrollUpdateEnd(false) , m_expectPinchUpdateEnd(false) #endif - , m_gestureScrollStarted(false) + , m_gestureScrollOnImplThread(false) + , m_gesturePinchOnImplThread(false) { } @@ -118,7 +119,7 @@ WebCompositorInputHandlerImpl::EventDisposition WebCompositorInputHandlerImpl::h WebInputHandlerClient::ScrollStatus scrollStatus = m_inputHandlerClient->scrollBegin(WebPoint(wheelEvent.x, wheelEvent.y), WebInputHandlerClient::ScrollInputTypeWheel); switch (scrollStatus) { case WebInputHandlerClient::ScrollStatusStarted: { - TRACE_EVENT_INSTANT2("cc", "WebCompositorInputHandlerImpl::handleInput wheel scroll", "deltaX", -wheelEvent.deltaX, "deltaY", -wheelEvent.deltaY); + TRACE_EVENT_INSTANT2("webkit", "WebCompositorInputHandlerImpl::handleInput wheel scroll", "deltaX", -wheelEvent.deltaX, "deltaY", -wheelEvent.deltaY); bool didScroll = m_inputHandlerClient->scrollByIfPossible(WebPoint(wheelEvent.x, wheelEvent.y), IntSize(-wheelEvent.deltaX, -wheelEvent.deltaY)); m_inputHandlerClient->scrollEnd(); return didScroll ? DidHandle : DropEvent; @@ -131,7 +132,7 @@ WebCompositorInputHandlerImpl::EventDisposition WebCompositorInputHandlerImpl::h return DidNotHandle; } } else if (event.type == WebInputEvent::GestureScrollBegin) { - ASSERT(!m_gestureScrollStarted); + ASSERT(!m_gestureScrollOnImplThread); ASSERT(!m_expectScrollUpdateEnd); #ifndef NDEBUG m_expectScrollUpdateEnd = true; @@ -140,7 +141,7 @@ WebCompositorInputHandlerImpl::EventDisposition WebCompositorInputHandlerImpl::h WebInputHandlerClient::ScrollStatus scrollStatus = m_inputHandlerClient->scrollBegin(WebPoint(gestureEvent.x, gestureEvent.y), WebInputHandlerClient::ScrollInputTypeGesture); switch (scrollStatus) { case WebInputHandlerClient::ScrollStatusStarted: - m_gestureScrollStarted = true; + m_gestureScrollOnImplThread = true; return DidHandle; case WebInputHandlerClient::ScrollStatusOnMainThread: return DidNotHandle; @@ -150,7 +151,7 @@ WebCompositorInputHandlerImpl::EventDisposition WebCompositorInputHandlerImpl::h } else if (event.type == WebInputEvent::GestureScrollUpdate) { ASSERT(m_expectScrollUpdateEnd); - if (!m_gestureScrollStarted) + if (!m_gestureScrollOnImplThread && !m_gesturePinchOnImplThread) return DidNotHandle; const WebGestureEvent& gestureEvent = *static_cast<const WebGestureEvent*>(&event); @@ -162,11 +163,11 @@ WebCompositorInputHandlerImpl::EventDisposition WebCompositorInputHandlerImpl::h #ifndef NDEBUG m_expectScrollUpdateEnd = false; #endif - if (!m_gestureScrollStarted) + if (!m_gestureScrollOnImplThread) return DidNotHandle; m_inputHandlerClient->scrollEnd(); - m_gestureScrollStarted = false; + m_gestureScrollOnImplThread = false; return DidHandle; } else if (event.type == WebInputEvent::GesturePinchBegin) { ASSERT(!m_expectPinchUpdateEnd); @@ -174,12 +175,14 @@ WebCompositorInputHandlerImpl::EventDisposition WebCompositorInputHandlerImpl::h m_expectPinchUpdateEnd = true; #endif m_inputHandlerClient->pinchGestureBegin(); + m_gesturePinchOnImplThread = true; return DidHandle; } else if (event.type == WebInputEvent::GesturePinchEnd) { ASSERT(m_expectPinchUpdateEnd); #ifndef NDEBUG m_expectPinchUpdateEnd = false; #endif + m_gesturePinchOnImplThread = false; m_inputHandlerClient->pinchGestureEnd(); return DidHandle; } else if (event.type == WebInputEvent::GesturePinchUpdate) { @@ -205,26 +208,30 @@ WebCompositorInputHandlerImpl::EventDisposition WebCompositorInputHandlerImpl::h WebInputHandlerClient::ScrollStatus scrollStatus = m_inputHandlerClient->scrollBegin(WebPoint(gestureEvent.x, gestureEvent.y), WebInputHandlerClient::ScrollInputTypeGesture); switch (scrollStatus) { case WebInputHandlerClient::ScrollStatusStarted: { - m_inputHandlerClient->scrollEnd(); - m_wheelFlingCurve = adoptPtr(Platform::current()->createFlingAnimationCurve(gestureEvent.data.flingStart.sourceDevice, WebFloatPoint(gestureEvent.data.flingStart.velocityX, gestureEvent.data.flingStart.velocityY), WebSize())); - TRACE_EVENT_ASYNC_BEGIN0("cc", "WebCompositorInputHandlerImpl::handleGestureFling::started", this); - m_wheelFlingParameters.delta = WebFloatPoint(gestureEvent.data.flingStart.velocityX, gestureEvent.data.flingStart.velocityY); - m_wheelFlingParameters.point = WebPoint(gestureEvent.x, gestureEvent.y); - m_wheelFlingParameters.globalPoint = WebPoint(gestureEvent.globalX, gestureEvent.globalY); - m_wheelFlingParameters.modifiers = gestureEvent.modifiers; - m_wheelFlingParameters.sourceDevice = gestureEvent.data.flingStart.sourceDevice; + if (gestureEvent.data.flingStart.sourceDevice == WebGestureEvent::Touchpad) + m_inputHandlerClient->scrollEnd(); + m_flingCurve = adoptPtr(Platform::current()->createFlingAnimationCurve(gestureEvent.data.flingStart.sourceDevice, WebFloatPoint(gestureEvent.data.flingStart.velocityX, gestureEvent.data.flingStart.velocityY), WebSize())); + TRACE_EVENT_ASYNC_BEGIN0("webkit", "WebCompositorInputHandlerImpl::handleGestureFling::started", this); + m_flingParameters.delta = WebFloatPoint(gestureEvent.data.flingStart.velocityX, gestureEvent.data.flingStart.velocityY); + m_flingParameters.point = WebPoint(gestureEvent.x, gestureEvent.y); + m_flingParameters.globalPoint = WebPoint(gestureEvent.globalX, gestureEvent.globalY); + m_flingParameters.modifiers = gestureEvent.modifiers; + m_flingParameters.sourceDevice = gestureEvent.data.flingStart.sourceDevice; m_inputHandlerClient->scheduleAnimation(); return DidHandle; } case WebInputHandlerClient::ScrollStatusOnMainThread: { - TRACE_EVENT_INSTANT0("cc", "WebCompositorInputHandlerImpl::handleGestureFling::scrollOnMainThread"); + TRACE_EVENT_INSTANT0("webkit", "WebCompositorInputHandlerImpl::handleGestureFling::scrollOnMainThread"); return DidNotHandle; } case WebInputHandlerClient::ScrollStatusIgnored: { - TRACE_EVENT_INSTANT0("cc", "WebCompositorInputHandlerImpl::handleGestureFling::ignored"); - // We still pass the curve to the main thread if there's nothing scrollable, in case something - // registers a handler before the curve is over. - return DidNotHandle; + TRACE_EVENT_INSTANT0("webkit", "WebCompositorInputHandlerImpl::handleGestureFling::ignored"); + if (gestureEvent.data.flingStart.sourceDevice == WebGestureEvent::Touchpad) { + // We still pass the curve to the main thread if there's nothing scrollable, in case something + // registers a handler before the curve is over. + return DidNotHandle; + } + return DropEvent; } } return DidNotHandle; @@ -234,7 +241,7 @@ void WebCompositorInputHandlerImpl::bindToClient(WebInputHandlerClient* client) { ASSERT(!m_inputHandlerClient); - TRACE_EVENT_INSTANT0("cc", "WebCompositorInputHandlerImpl::bindToClient"); + TRACE_EVENT_INSTANT0("webkit", "WebCompositorInputHandlerImpl::bindToClient"); if (!s_compositors) s_compositors = new HashSet<WebCompositorInputHandlerImpl*>; s_compositors->add(this); @@ -244,71 +251,94 @@ void WebCompositorInputHandlerImpl::bindToClient(WebInputHandlerClient* client) void WebCompositorInputHandlerImpl::animate(double monotonicTime) { - if (!m_wheelFlingCurve) + if (!m_flingCurve) return; - if (!m_wheelFlingParameters.startTime) { - m_wheelFlingParameters.startTime = monotonicTime; + if (!m_flingParameters.startTime) { + m_flingParameters.startTime = monotonicTime; m_inputHandlerClient->scheduleAnimation(); return; } - if (m_wheelFlingCurve->apply(monotonicTime - m_wheelFlingParameters.startTime, this)) + if (m_flingCurve->apply(monotonicTime - m_flingParameters.startTime, this)) m_inputHandlerClient->scheduleAnimation(); else { - TRACE_EVENT_INSTANT0("cc", "WebCompositorInputHandlerImpl::animate::flingOver"); + TRACE_EVENT_INSTANT0("webkit", "WebCompositorInputHandlerImpl::animate::flingOver"); cancelCurrentFling(); } } bool WebCompositorInputHandlerImpl::cancelCurrentFling() { - bool hadFlingAnimation = m_wheelFlingCurve; - if (hadFlingAnimation) - TRACE_EVENT_ASYNC_END0("cc", "WebCompositorInputHandlerImpl::handleGestureFling::started", this); + bool hadFlingAnimation = m_flingCurve; + if (hadFlingAnimation && m_flingParameters.sourceDevice == WebGestureEvent::Touchscreen) { + m_inputHandlerClient->scrollEnd(); + TRACE_EVENT_ASYNC_END0("webkit", "WebCompositorInputHandlerImpl::handleGestureFling::started", this); + } - TRACE_EVENT_INSTANT1("cc", "WebCompositorInputHandlerImpl::cancelCurrentFling", "hadFlingAnimation", hadFlingAnimation); - m_wheelFlingCurve.clear(); - m_wheelFlingParameters = WebActiveWheelFlingParameters(); + TRACE_EVENT_INSTANT1("webkit", "WebCompositorInputHandlerImpl::cancelCurrentFling", "hadFlingAnimation", hadFlingAnimation); + m_flingCurve.clear(); + m_flingParameters = WebActiveWheelFlingParameters(); return hadFlingAnimation; } -void WebCompositorInputHandlerImpl::scrollBy(const WebPoint& increment) +bool WebCompositorInputHandlerImpl::touchpadFlingScroll(const WebPoint& increment) { - if (increment == WebPoint()) - return; - - TRACE_EVENT2("cc", "WebCompositorInputHandlerImpl::scrollBy", "x", increment.x, "y", increment.y); WebMouseWheelEvent syntheticWheel; syntheticWheel.type = WebInputEvent::MouseWheel; syntheticWheel.deltaX = increment.x; syntheticWheel.deltaY = increment.y; syntheticWheel.hasPreciseScrollingDeltas = true; - syntheticWheel.x = m_wheelFlingParameters.point.x; - syntheticWheel.y = m_wheelFlingParameters.point.y; - syntheticWheel.globalX = m_wheelFlingParameters.globalPoint.x; - syntheticWheel.globalY = m_wheelFlingParameters.globalPoint.y; - syntheticWheel.modifiers = m_wheelFlingParameters.modifiers; + syntheticWheel.x = m_flingParameters.point.x; + syntheticWheel.y = m_flingParameters.point.y; + syntheticWheel.globalX = m_flingParameters.globalPoint.x; + syntheticWheel.globalY = m_flingParameters.globalPoint.y; + syntheticWheel.modifiers = m_flingParameters.modifiers; WebCompositorInputHandlerImpl::EventDisposition disposition = handleInputEventInternal(syntheticWheel); switch (disposition) { case DidHandle: - m_wheelFlingParameters.cumulativeScroll.width += increment.x; - m_wheelFlingParameters.cumulativeScroll.height += increment.y; + return true; case DropEvent: break; case DidNotHandle: - TRACE_EVENT_INSTANT0("cc", "WebCompositorInputHandlerImpl::scrollBy::AbortFling"); + TRACE_EVENT_INSTANT0("webkit", "WebCompositorInputHandlerImpl::scrollBy::AbortFling"); // If we got a DidNotHandle, that means we need to deliver wheels on the main thread. // In this case we need to schedule a commit and transfer the fling curve over to the main // thread and run the rest of the wheels from there. // This can happen when flinging a page that contains a scrollable subarea that we can't // scroll on the thread if the fling starts outside the subarea but then is flung "under" the // pointer. - m_client->transferActiveWheelFlingAnimation(m_wheelFlingParameters); + m_client->transferActiveWheelFlingAnimation(m_flingParameters); cancelCurrentFling(); break; } + + return false; +} + +void WebCompositorInputHandlerImpl::scrollBy(const WebPoint& increment) +{ + if (increment == WebPoint()) + return; + + TRACE_EVENT2("webkit", "WebCompositorInputHandlerImpl::scrollBy", "x", increment.x, "y", increment.y); + + bool didScroll = false; + + switch (m_flingParameters.sourceDevice) { + case WebGestureEvent::Touchpad: + didScroll = touchpadFlingScroll(increment); + break; + case WebGestureEvent::Touchscreen: + didScroll = m_inputHandlerClient->scrollByIfPossible(m_flingParameters.point, IntSize(-increment.x, -increment.y)); + break; + } + + if (didScroll) { + m_flingParameters.cumulativeScroll.width += increment.x; + m_flingParameters.cumulativeScroll.height += increment.y; + } } } diff --git a/Source/WebKit/chromium/src/WebCompositorInputHandlerImpl.h b/Source/WebKit/chromium/src/WebCompositorInputHandlerImpl.h index efe7f53b4..5c79addff 100644 --- a/Source/WebKit/chromium/src/WebCompositorInputHandlerImpl.h +++ b/Source/WebKit/chromium/src/WebCompositorInputHandlerImpl.h @@ -78,12 +78,15 @@ private: EventDisposition handleGestureFling(const WebGestureEvent&); + // Returns true if we scrolled by the increment. + bool touchpadFlingScroll(const WebPoint& increment); + // Returns true if we actually had an active fling to cancel. bool cancelCurrentFling(); - OwnPtr<WebGestureCurve> m_wheelFlingCurve; + OwnPtr<WebGestureCurve> m_flingCurve; // Parameters for the active fling animation, stored in case we need to transfer it out later. - WebActiveWheelFlingParameters m_wheelFlingParameters; + WebActiveWheelFlingParameters m_flingParameters; WebCompositorInputHandlerClient* m_client; int m_identifier; @@ -93,7 +96,8 @@ private: bool m_expectScrollUpdateEnd; bool m_expectPinchUpdateEnd; #endif - bool m_gestureScrollStarted; + bool m_gestureScrollOnImplThread; + bool m_gesturePinchOnImplThread; static int s_nextAvailableIdentifier; static HashSet<WebCompositorInputHandlerImpl*>* s_compositors; diff --git a/Source/WebKit/chromium/src/WebFrameImpl.cpp b/Source/WebKit/chromium/src/WebFrameImpl.cpp index eacf9aba8..5d32afd85 100644 --- a/Source/WebKit/chromium/src/WebFrameImpl.cpp +++ b/Source/WebKit/chromium/src/WebFrameImpl.cpp @@ -957,7 +957,7 @@ void WebFrameImpl::loadRequest(const WebURLRequest& request) return; } - frame()->loader()->load(resourceRequest, false); + frame()->loader()->load(FrameLoadRequest(frame(), resourceRequest)); } void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item) @@ -976,8 +976,6 @@ void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item) void WebFrameImpl::loadData(const WebData& data, const WebString& mimeType, const WebString& textEncoding, const WebURL& baseURL, const WebURL& unreachableURL, bool replace) { ASSERT(frame()); - SubstituteData substData(data, mimeType, textEncoding, unreachableURL); - ASSERT(substData.isValid()); // If we are loading substitute data to replace an existing load, then // inherit all of the properties of that original request. This way, @@ -990,7 +988,9 @@ void WebFrameImpl::loadData(const WebData& data, const WebString& mimeType, cons request = frame()->loader()->originalRequest(); request.setURL(baseURL); - frame()->loader()->load(request, substData, false); + FrameLoadRequest frameRequest(frame(), request, SubstituteData(data, mimeType, textEncoding, unreachableURL)); + ASSERT(frameRequest.substituteData().isValid()); + frame()->loader()->load(frameRequest); if (replace) { // Do this to force WebKit to treat the load as replacing the currently // loaded page. diff --git a/Source/WebKit/chromium/src/WebIDBCallbacksImpl.cpp b/Source/WebKit/chromium/src/WebIDBCallbacksImpl.cpp index 8d12cfa3e..dcf303b39 100644 --- a/Source/WebKit/chromium/src/WebIDBCallbacksImpl.cpp +++ b/Source/WebKit/chromium/src/WebIDBCallbacksImpl.cpp @@ -86,11 +86,6 @@ void WebIDBCallbacksImpl::onSuccess(const WebIDBKey& key) m_callbacks->onSuccess(key); } -void WebIDBCallbacksImpl::onSuccess(WebIDBTransaction* webKitInstance) -{ - m_callbacks->onSuccess(IDBTransactionBackendProxy::create(adoptPtr(webKitInstance))); -} - void WebIDBCallbacksImpl::onSuccess(const WebSerializedScriptValue& serializedScriptValue) { m_callbacks->onSuccess(serializedScriptValue); diff --git a/Source/WebKit/chromium/src/WebIDBCallbacksImpl.h b/Source/WebKit/chromium/src/WebIDBCallbacksImpl.h index ba4448428..8f8c02aaa 100644 --- a/Source/WebKit/chromium/src/WebIDBCallbacksImpl.h +++ b/Source/WebKit/chromium/src/WebIDBCallbacksImpl.h @@ -46,7 +46,6 @@ public: virtual void onSuccess(WebIDBCursor*, const WebIDBKey&, const WebIDBKey& primaryKey, const WebSerializedScriptValue&); virtual void onSuccess(WebIDBDatabase*); virtual void onSuccess(const WebIDBKey&); - virtual void onSuccess(WebIDBTransaction*); virtual void onSuccess(const WebSerializedScriptValue&); virtual void onSuccess(const WebSerializedScriptValue&, const WebIDBKey&, const WebIDBKeyPath&); virtual void onSuccess(const WebIDBKey&, const WebIDBKey& primaryKey, const WebSerializedScriptValue&); diff --git a/Source/WebKit/chromium/src/WebIDBDatabaseImpl.cpp b/Source/WebKit/chromium/src/WebIDBDatabaseImpl.cpp index 59abd5329..622465de4 100644 --- a/Source/WebKit/chromium/src/WebIDBDatabaseImpl.cpp +++ b/Source/WebKit/chromium/src/WebIDBDatabaseImpl.cpp @@ -75,9 +75,15 @@ void WebIDBDatabaseImpl::deleteObjectStore(long long objectStoreId, const WebIDB m_databaseBackend->deleteObjectStore(objectStoreId, transaction.getIDBTransactionBackendInterface(), ec); } -void WebIDBDatabaseImpl::setVersion(const WebString& version, WebIDBCallbacks* callbacks, WebExceptionCode& ec) +WebIDBTransaction* WebIDBDatabaseImpl::createTransaction(long long id, const WebVector<long long>& objectStoreIds, unsigned short mode) { - m_databaseBackend->setVersion(version, IDBCallbacksProxy::create(adoptPtr(callbacks)), m_databaseCallbacks, ec); + Vector<int64_t> objectStoreIdList(objectStoreIds.size()); + for (size_t i = 0; i < objectStoreIds.size(); ++i) + objectStoreIdList[i] = objectStoreIds[i]; + RefPtr<IDBTransactionBackendInterface> transaction = m_databaseBackend->createTransaction(id, objectStoreIdList, mode); + if (!transaction) + return 0; + return new WebIDBTransactionImpl(transaction); } WebIDBTransaction* WebIDBDatabaseImpl::transaction(const WebVector<long long>& objectStoreIds, unsigned short mode) diff --git a/Source/WebKit/chromium/src/WebIDBDatabaseImpl.h b/Source/WebKit/chromium/src/WebIDBDatabaseImpl.h index e728742c6..ebd4d48f9 100644 --- a/Source/WebKit/chromium/src/WebIDBDatabaseImpl.h +++ b/Source/WebKit/chromium/src/WebIDBDatabaseImpl.h @@ -54,8 +54,9 @@ public: virtual WebIDBObjectStore* createObjectStore(long long, const WebString& name, const WebIDBKeyPath&, bool autoIncrement, const WebIDBTransaction&, WebExceptionCode&); virtual void deleteObjectStore(long long objectStoreId, const WebIDBTransaction&, WebExceptionCode&); - virtual void setVersion(const WebString& version, WebIDBCallbacks*, WebExceptionCode&); + // FIXME: Remove this as part of https://bugs.webkit.org/show_bug.cgi?id=102733. virtual WebIDBTransaction* transaction(const WebVector<long long>& names, unsigned short mode); + virtual WebIDBTransaction* createTransaction(long long id, const WebVector<long long>&, unsigned short mode); virtual void forceClose(); virtual void close(); diff --git a/Source/WebKit/chromium/src/WebIDBTransactionImpl.cpp b/Source/WebKit/chromium/src/WebIDBTransactionImpl.cpp index 40d7d7563..41f4c9d20 100644 --- a/Source/WebKit/chromium/src/WebIDBTransactionImpl.cpp +++ b/Source/WebKit/chromium/src/WebIDBTransactionImpl.cpp @@ -65,11 +65,6 @@ void WebIDBTransactionImpl::abort() m_backend->abort(); } -void WebIDBTransactionImpl::didCompleteTaskEvents() -{ - m_backend->didCompleteTaskEvents(); -} - void WebIDBTransactionImpl::setCallbacks(WebIDBTransactionCallbacks* callbacks) { RefPtr<IDBTransactionCallbacks> idbCallbacks = IDBTransactionCallbacksProxy::create(adoptPtr(callbacks)); diff --git a/Source/WebKit/chromium/src/WebIDBTransactionImpl.h b/Source/WebKit/chromium/src/WebIDBTransactionImpl.h index 0fb653767..4272cbe10 100644 --- a/Source/WebKit/chromium/src/WebIDBTransactionImpl.h +++ b/Source/WebKit/chromium/src/WebIDBTransactionImpl.h @@ -44,7 +44,6 @@ public: virtual WebIDBObjectStore* objectStore(long long indexId, WebExceptionCode&); virtual void commit(); virtual void abort(); - virtual void didCompleteTaskEvents(); virtual void setCallbacks(WebIDBTransactionCallbacks*); virtual WebCore::IDBTransactionBackendInterface* getIDBTransactionBackendInterface() const; diff --git a/Source/WebKit/chromium/src/WebInputEventConversion.cpp b/Source/WebKit/chromium/src/WebInputEventConversion.cpp index 5cf24d0c1..dcde40f32 100644 --- a/Source/WebKit/chromium/src/WebInputEventConversion.cpp +++ b/Source/WebKit/chromium/src/WebInputEventConversion.cpp @@ -407,7 +407,7 @@ static IntPoint convertLocationForRenderObject(const LayoutPoint& location, cons return roundedIntPoint(renderObject.absoluteToLocal(location, UseTransforms | SnapOffsetForTransforms)); } -static void updateWebMouseEventFromWebCoreMouseEvent(const MouseEvent& event, const Widget& widget, const WebCore::RenderObject& renderObject, WebMouseEvent& webEvent) +static void updateWebMouseEventFromWebCoreMouseEvent(const MouseRelatedEvent& event, const Widget& widget, const WebCore::RenderObject& renderObject, WebMouseEvent& webEvent) { webEvent.timeStampSeconds = event.timeStamp() / millisPerSecond; webEvent.modifiers = getWebInputModifiers(event); @@ -473,6 +473,37 @@ WebMouseEventBuilder::WebMouseEventBuilder(const Widget* widget, const WebCore:: clickCount = event.detail(); } +WebMouseEventBuilder::WebMouseEventBuilder(const Widget* widget, const WebCore::RenderObject* renderObject, const TouchEvent& event) +{ + if (event.touches()->length() != 1) { + if (event.touches()->length() || event.type() != eventNames().touchendEvent || event.changedTouches()->length() != 1) + return; + } + + const Touch* touch = event.touches()->length() == 1 ? event.touches()->item(0) : event.changedTouches()->item(0); + if (touch->identifier()) + return; + + if (event.type() == eventNames().touchstartEvent) + type = MouseDown; + else if (event.type() == eventNames().touchmoveEvent) + type = MouseMove; + else if (event.type() == eventNames().touchendEvent) + type = MouseUp; + else + return; + + updateWebMouseEventFromWebCoreMouseEvent(event, *widget, *renderObject, *this); + + button = WebMouseEvent::ButtonLeft; + modifiers |= WebInputEvent::LeftButtonDown; + clickCount = (type == MouseDown || type == MouseUp); + + IntPoint localPoint = convertLocationForRenderObject(LayoutPoint(touch->pageX(), touch->pageY()), *renderObject); + x = localPoint.x(); + y = localPoint.y(); +} + WebMouseWheelEventBuilder::WebMouseWheelEventBuilder(const Widget* widget, const WebCore::RenderObject* renderObject, const WheelEvent& event) { if (event.type() != eventNames().mousewheelEvent) diff --git a/Source/WebKit/chromium/src/WebInputEventConversion.h b/Source/WebKit/chromium/src/WebInputEventConversion.h index 3512646eb..181d1e5c2 100644 --- a/Source/WebKit/chromium/src/WebInputEventConversion.h +++ b/Source/WebKit/chromium/src/WebInputEventConversion.h @@ -105,6 +105,7 @@ public: class WebMouseEventBuilder : public WebMouseEvent { public: WebMouseEventBuilder(const WebCore::Widget*, const WebCore::RenderObject*, const WebCore::MouseEvent&); + WebMouseEventBuilder(const WebCore::Widget*, const WebCore::RenderObject*, const WebCore::TouchEvent&); }; // Converts a WebCore::WheelEvent to a corresponding WebMouseWheelEvent. diff --git a/Source/WebKit/chromium/src/WebKit.cpp b/Source/WebKit/chromium/src/WebKit.cpp index 243d08e62..a517d155e 100644 --- a/Source/WebKit/chromium/src/WebKit.cpp +++ b/Source/WebKit/chromium/src/WebKit.cpp @@ -43,7 +43,6 @@ #include "V8RecursionScope.h" #include "WebMediaPlayerClientImpl.h" #include "WebSocket.h" -#include "WorkerContextExecutionProxy.h" #include "platform/WebKitPlatformSupport.h" #include "v8.h" #include <public/Platform.h> @@ -134,6 +133,7 @@ void initializeWithoutV8(WebKitPlatformSupport* webKitPlatformSupport) ASSERT(!s_webKitPlatformSupport); s_webKitPlatformSupport = webKitPlatformSupport; Platform::initialize(s_webKitPlatformSupport); + WebCore::ImageDecodingStore::initializeOnce(); WTF::initializeThreading(); WTF::initializeMainThread(); diff --git a/Source/WebKit/chromium/src/WebPluginContainerImpl.cpp b/Source/WebKit/chromium/src/WebPluginContainerImpl.cpp index 075fc0548..1059df748 100644 --- a/Source/WebKit/chromium/src/WebPluginContainerImpl.cpp +++ b/Source/WebKit/chromium/src/WebPluginContainerImpl.cpp @@ -523,10 +523,15 @@ bool WebPluginContainerImpl::isRectTopmost(const WebRect& rect) void WebPluginContainerImpl::setIsAcceptingTouchEvents(bool acceptingTouchEvents) { - if (m_isAcceptingTouchEvents == acceptingTouchEvents) + requestTouchEventType(acceptingTouchEvents ? TouchEventRequestTypeRaw : TouchEventRequestTypeNone); +} + +void WebPluginContainerImpl::requestTouchEventType(TouchEventRequestType requestType) +{ + if (m_touchEventRequestType == requestType) return; - m_isAcceptingTouchEvents = acceptingTouchEvents; - if (m_isAcceptingTouchEvents) + m_touchEventRequestType = requestType; + if (m_touchEventRequestType != TouchEventRequestTypeNone) m_element->document()->didAddTouchEventHandler(); else m_element->document()->didRemoveTouchEventHandler(); @@ -667,7 +672,7 @@ WebPluginContainerImpl::WebPluginContainerImpl(WebCore::HTMLPlugInElement* eleme , m_textureId(0) , m_ioSurfaceId(0) #endif - , m_isAcceptingTouchEvents(false) + , m_touchEventRequestType(TouchEventRequestTypeNone) , m_wantsWheelEvents(false) { } @@ -681,7 +686,7 @@ WebPluginContainerImpl::~WebPluginContainerImpl() GraphicsLayerChromium::unregisterContentsLayer(m_ioSurfaceLayer->layer()); #endif - if (m_isAcceptingTouchEvents) + if (m_touchEventRequestType != TouchEventRequestTypeNone) m_element->document()->didRemoveTouchEventHandler(); for (size_t i = 0; i < m_pluginLoadObservers.size(); ++i) @@ -819,9 +824,28 @@ void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event) void WebPluginContainerImpl::handleTouchEvent(TouchEvent* event) { - if (!m_isAcceptingTouchEvents) + switch (m_touchEventRequestType) { + case TouchEventRequestTypeNone: + return; + case TouchEventRequestTypeRaw: { + WebTouchEventBuilder webEvent(this, m_element->renderer(), *event); + if (webEvent.type == WebInputEvent::Undefined) + return; + WebCursorInfo cursorInfo; + if (m_webPlugin->handleInputEvent(webEvent, cursorInfo)) + event->setDefaultHandled(); + // FIXME: Can a plugin change the cursor from a touch-event callback? + return; + } + case TouchEventRequestTypeSynthesizedMouse: + synthesizeMouseEventIfPossible(event); return; - WebTouchEventBuilder webEvent(this, m_element->renderer(), *event); + } +} + +void WebPluginContainerImpl::handleGestureEvent(GestureEvent* event) +{ + WebGestureEventBuilder webEvent(this, m_element->renderer(), *event); if (webEvent.type == WebInputEvent::Undefined) return; WebCursorInfo cursorInfo; @@ -830,15 +854,15 @@ void WebPluginContainerImpl::handleTouchEvent(TouchEvent* event) // FIXME: Can a plugin change the cursor from a touch-event callback? } -void WebPluginContainerImpl::handleGestureEvent(GestureEvent* event) +void WebPluginContainerImpl::synthesizeMouseEventIfPossible(TouchEvent* event) { - WebGestureEventBuilder webEvent(this, m_element->renderer(), *event); + WebMouseEventBuilder webEvent(this, m_element->renderer(), *event); if (webEvent.type == WebInputEvent::Undefined) return; + WebCursorInfo cursorInfo; if (m_webPlugin->handleInputEvent(webEvent, cursorInfo)) event->setDefaultHandled(); - // FIXME: Can a plugin change the cursor from a touch-event callback? } void WebPluginContainerImpl::calculateGeometry(const IntRect& frameRect, diff --git a/Source/WebKit/chromium/src/WebPluginContainerImpl.h b/Source/WebKit/chromium/src/WebPluginContainerImpl.h index b4958fe19..70293a822 100644 --- a/Source/WebKit/chromium/src/WebPluginContainerImpl.h +++ b/Source/WebKit/chromium/src/WebPluginContainerImpl.h @@ -114,6 +114,7 @@ public: virtual void setOpaque(bool); virtual bool isRectTopmost(const WebRect&); virtual void setIsAcceptingTouchEvents(bool); + virtual void requestTouchEventType(TouchEventRequestType); virtual void setWantsWheelEvents(bool); virtual WebPoint windowToLocalPoint(const WebPoint&); @@ -149,7 +150,7 @@ public: void didFinishLoading(); void didFailLoading(const WebCore::ResourceError&); - NPObject* scriptableObject(); + virtual NPObject* scriptableObject() OVERRIDE; void willDestroyPluginLoadObserver(WebPluginLoadObserver*); @@ -175,6 +176,8 @@ private: void handleTouchEvent(WebCore::TouchEvent*); void handleGestureEvent(WebCore::GestureEvent*); + void synthesizeMouseEventIfPossible(WebCore::TouchEvent*); + void calculateGeometry(const WebCore::IntRect& frameRect, WebCore::IntRect& windowRect, WebCore::IntRect& clipRect, @@ -201,7 +204,7 @@ private: // scrollbars. OwnPtr<ScrollbarGroup> m_scrollbarGroup; - bool m_isAcceptingTouchEvents; + TouchEventRequestType m_touchEventRequestType; bool m_wantsWheelEvents; }; diff --git a/Source/WebKit/chromium/src/WebSettingsImpl.cpp b/Source/WebKit/chromium/src/WebSettingsImpl.cpp index 20fcc1b96..6a33786ac 100644 --- a/Source/WebKit/chromium/src/WebSettingsImpl.cpp +++ b/Source/WebKit/chromium/src/WebSettingsImpl.cpp @@ -31,8 +31,8 @@ #include "config.h" #include "WebSettingsImpl.h" +#include "DeferredImageDecoder.h" #include "FontRenderingMode.h" -#include "ImageDecodingStore.h" #include "Settings.h" #include <public/WebString.h> #include <public/WebURL.h> @@ -346,6 +346,11 @@ void WebSettingsImpl::setTextDirectionSubmenuInclusionBehaviorNeverIncluded() m_settings->setTextDirectionSubmenuInclusionBehavior(WebCore::TextDirectionSubmenuNeverIncluded); } +void WebSettingsImpl::setTouchDragDropEnabled(bool enabled) +{ + m_settings->setTouchDragDropEnabled(enabled); +} + void WebSettingsImpl::setOfflineWebApplicationCacheEnabled(bool enabled) { m_settings->setOfflineWebApplicationCacheEnabled(enabled); @@ -500,10 +505,7 @@ void WebSettingsImpl::setDeferred2dCanvasEnabled(bool enabled) void WebSettingsImpl::setDeferredImageDecodingEnabled(bool enabled) { - if (!m_deferredImageDecodingEnabled && enabled) - ImageDecodingStore::initializeOnMainThread(); - if (m_deferredImageDecodingEnabled && !enabled) - ImageDecodingStore::shutdown(); + DeferredImageDecoder::setEnabled(enabled); m_deferredImageDecodingEnabled = enabled; } diff --git a/Source/WebKit/chromium/src/WebSettingsImpl.h b/Source/WebKit/chromium/src/WebSettingsImpl.h index 98520eadf..ab92562fa 100644 --- a/Source/WebKit/chromium/src/WebSettingsImpl.h +++ b/Source/WebKit/chromium/src/WebSettingsImpl.h @@ -153,6 +153,7 @@ public: virtual void setTextAutosizingEnabled(bool); virtual void setTextAutosizingFontScaleFactor(float); virtual void setTextDirectionSubmenuInclusionBehaviorNeverIncluded(); + virtual void setTouchDragDropEnabled(bool); virtual void setUnifiedTextCheckerEnabled(bool); virtual void setUserStyleSheetLocation(const WebURL&); virtual void setUsesEncodingDetector(bool); diff --git a/Source/WebKit/chromium/src/WebSharedWorkerImpl.cpp b/Source/WebKit/chromium/src/WebSharedWorkerImpl.cpp index 5cf999851..119d9acb6 100644 --- a/Source/WebKit/chromium/src/WebSharedWorkerImpl.cpp +++ b/Source/WebKit/chromium/src/WebSharedWorkerImpl.cpp @@ -34,6 +34,7 @@ #include "CrossThreadTask.h" #include "DatabaseTask.h" #include "Document.h" +#include "FrameLoadRequest.h" #include "GroupSettings.h" #include "KURL.h" #include "MessageEvent.h" @@ -130,10 +131,9 @@ void WebSharedWorkerImpl::initializeLoader(const WebURL& url) // Construct substitute data source for the 'shadow page'. We only need it // to have same origin as the worker so the loading checks work correctly. CString content(""); - int len = static_cast<int>(content.length()); - RefPtr<SharedBuffer> buf(SharedBuffer::create(content.data(), len)); - SubstituteData substData(buf, String("text/html"), String("UTF-8"), KURL()); - webFrame->frame()->loader()->load(ResourceRequest(url), substData, false); + int length = static_cast<int>(content.length()); + RefPtr<SharedBuffer> buffer(SharedBuffer::create(content.data(), length)); + webFrame->frame()->loader()->load(FrameLoadRequest(webFrame->frame(), ResourceRequest(url), SubstituteData(buffer, "text/html", "UTF-8", KURL()))); // This document will be used as 'loading context' for the worker. m_loadingDocument = webFrame->frame()->document(); diff --git a/Source/WebKit/chromium/src/WebViewImpl.cpp b/Source/WebKit/chromium/src/WebViewImpl.cpp index 7aa12048f..f66ae48c4 100644 --- a/Source/WebKit/chromium/src/WebViewImpl.cpp +++ b/Source/WebKit/chromium/src/WebViewImpl.cpp @@ -848,6 +848,15 @@ void WebViewImpl::setShowFPSCounter(bool show) settingsImpl()->setShowFPSCounter(show); } +void WebViewImpl::setShowPaintRects(bool show) +{ + if (isAcceleratedCompositingActive()) { + TRACE_EVENT0("webkit", "WebViewImpl::setShowPaintRects"); + m_layerTreeView->setShowPaintRects(show); + } + settingsImpl()->setShowPaintRects(show); +} + bool WebViewImpl::handleKeyEvent(const WebKeyboardEvent& event) { ASSERT((event.type == WebInputEvent::RawKeyDown) @@ -1274,6 +1283,11 @@ void WebViewImpl::hasTouchEventHandlers(bool hasTouchHandlers) m_client->hasTouchEventHandlers(hasTouchHandlers); } +bool WebViewImpl::hasTouchEventHandlersAt(const WebPoint& point) +{ + return true; +} + #if !OS(DARWIN) // Mac has no way to open a context menu based on a keyboard event. bool WebViewImpl::sendContextMenuEvent(const WebKeyboardEvent& event) @@ -4105,17 +4119,6 @@ private: } // namespace -WebGraphicsContext3D* WebViewImpl::createContext3D() -{ - // Temporarily, if the output surface can't be created, create a WebGraphicsContext3D - // directly. This allows bootstrapping the output surface system while downstream - // users of the API still use the old approach. - WebKit::WebGraphicsContext3D::Attributes attributes; - attributes.antialias = false; - attributes.shareResources = true; - return m_client->createGraphicsContext3D(attributes); -} - WebCompositorOutputSurface* WebViewImpl::createOutputSurface() { return m_client->createOutputSurface(); @@ -4180,11 +4183,6 @@ void WebViewImpl::didCompleteSwapBuffers() m_client->didCompleteSwapBuffers(); } -void WebViewImpl::didRebindGraphicsContext(bool success) -{ - didRecreateOutputSurface(success); -} - void WebViewImpl::didRecreateOutputSurface(bool success) { // Switch back to software rendering mode, if necessary @@ -4214,6 +4212,12 @@ void WebViewImpl::scheduleComposite() m_client->scheduleComposite(); } +void WebViewImpl::createFontAtlas(SkBitmap& bitmap, WebRect asciiToRectTable[128], int& fontHeight) +{ + TRACE_EVENT0("webkit", "WebViewImpl::loadFontAtlas"); + bitmap = WebCore::CompositorHUDFontAtlas::generateFontAtlas(asciiToRectTable, fontHeight); +} + void WebViewImpl::updateLayerTreeViewport() { if (!page() || !m_nonCompositedContentHost || !m_layerTreeView) diff --git a/Source/WebKit/chromium/src/WebViewImpl.h b/Source/WebKit/chromium/src/WebViewImpl.h index da5f69b9e..6246cab0e 100644 --- a/Source/WebKit/chromium/src/WebViewImpl.h +++ b/Source/WebKit/chromium/src/WebViewImpl.h @@ -152,6 +152,7 @@ public: virtual void setNeedsRedraw(); virtual bool isInputThrottled() const; virtual bool handleInputEvent(const WebInputEvent&); + virtual bool hasTouchEventHandlersAt(const WebPoint&); virtual void mouseCaptureLost(); virtual void setFocus(bool enable); virtual bool setComposition( @@ -308,6 +309,7 @@ public: #endif virtual void transferActiveWheelFlingAnimation(const WebActiveWheelFlingParameters&); virtual WebViewBenchmarkSupport* benchmarkSupport(); + virtual void setShowPaintRects(bool); virtual void setShowFPSCounter(bool); // WebLayerTreeViewClient @@ -315,8 +317,6 @@ public: virtual void didBeginFrame(); virtual void updateAnimations(double monotonicFrameBeginTime); virtual void applyScrollAndScale(const WebSize&, float); - virtual WebGraphicsContext3D* createContext3D() OVERRIDE; - virtual void didRebindGraphicsContext(bool success) OVERRIDE; virtual WebCompositorOutputSurface* createOutputSurface() OVERRIDE; virtual void didRecreateOutputSurface(bool success) OVERRIDE; virtual WebInputHandler* createInputHandler() OVERRIDE; @@ -325,6 +325,7 @@ public: virtual void didCommitAndDrawFrame(); virtual void didCompleteSwapBuffers(); virtual void scheduleComposite(); + virtual void createFontAtlas(SkBitmap&, WebRect[128], int&); // WebViewImpl @@ -610,6 +611,7 @@ private: friend class WebView; // So WebView::Create can call our constructor friend class WTF::RefCounted<WebViewImpl>; + friend void setCurrentInputEventForTest(const WebInputEvent*); enum DragAction { DragEnter, diff --git a/Source/WebKit/chromium/src/WebWorkerClientImpl.cpp b/Source/WebKit/chromium/src/WebWorkerClientImpl.cpp index 96f04fa4b..2c0fb9ac8 100644 --- a/Source/WebKit/chromium/src/WebWorkerClientImpl.cpp +++ b/Source/WebKit/chromium/src/WebWorkerClientImpl.cpp @@ -50,7 +50,6 @@ #include "ScriptExecutionContext.h" #include "Worker.h" #include "WorkerContext.h" -#include "WorkerContextExecutionProxy.h" #include "WorkerScriptController.h" #include "WorkerMessagingProxy.h" #include <wtf/Threading.h> diff --git a/Source/WebKit/chromium/src/default/WebRenderTheme.cpp b/Source/WebKit/chromium/src/default/WebRenderTheme.cpp new file mode 100644 index 000000000..a7b29f909 --- /dev/null +++ b/Source/WebKit/chromium/src/default/WebRenderTheme.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2010 Joel Stanley. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebRenderTheme.h" + +#include "RenderThemeChromiumDefault.h" +#include "WebView.h" + +using WebCore::RenderTheme; +using WebCore::RenderThemeChromiumDefault; + +namespace WebKit { + +void setCaretBlinkInterval(double interval) +{ + RenderThemeChromiumDefault::setCaretBlinkInterval(interval); +} + +} // namespace WebKit diff --git a/Source/WebKit/chromium/tests/ChromeClientImplTest.cpp b/Source/WebKit/chromium/tests/ChromeClientImplTest.cpp new file mode 100644 index 000000000..779c1cdd2 --- /dev/null +++ b/Source/WebKit/chromium/tests/ChromeClientImplTest.cpp @@ -0,0 +1,268 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include <gtest/gtest.h> + +#include "Chrome.h" +#include "WebFrameClient.h" +#include "WebInputEvent.h" +#include "WebView.h" +#include "WebViewClient.h" +#include "WebViewImpl.h" + +using namespace WebKit; + +namespace WebKit { + +void setCurrentInputEventForTest(const WebInputEvent* event) +{ + WebViewImpl::m_currentInputEvent = event; +} + +} + +namespace { + +class TestWebWidgetClient : public WebWidgetClient { +public: + ~TestWebWidgetClient() { } +}; + +class TestWebViewClient : public WebViewClient { +public: + explicit TestWebViewClient(WebNavigationPolicy* target) : m_target(target) { } + ~TestWebViewClient() { } + + virtual void show(WebNavigationPolicy policy) + { + *m_target = policy; + } + +private: + WebNavigationPolicy* m_target; +}; + +class TestWebFrameClient : public WebFrameClient { +public: + ~TestWebFrameClient() { } +}; + +class GetNavigationPolicyTest : public testing::Test { +public: + GetNavigationPolicyTest() + : m_result(WebNavigationPolicyIgnore) + , m_webViewClient(&m_result) + { + } + +protected: + virtual void SetUp() + { + m_webView = static_cast<WebViewImpl*>(WebView::create(&m_webViewClient)); + m_webView->initializeMainFrame(&m_webFrameClient); + m_chromeClientImpl = static_cast<ChromeClientImpl*>(m_webView->page()->chrome()->client()); + m_result = WebNavigationPolicyIgnore; + } + + virtual void TearDown() + { + m_webView->close(); + } + + WebNavigationPolicy getNavigationPolicyWithMouseEvent(int modifiers, WebMouseEvent::Button button, bool asPopup) + { + WebMouseEvent event; + event.modifiers = modifiers; + event.type = WebInputEvent::MouseUp; + event.button = button; + setCurrentInputEventForTest(&event); + m_chromeClientImpl->setScrollbarsVisible(!asPopup); + m_chromeClientImpl->show(); + setCurrentInputEventForTest(0); + return m_result; + } + + bool isNavigationPolicyPopup() + { + m_chromeClientImpl->show(); + return m_result == WebNavigationPolicyNewPopup; + } + +protected: + WebNavigationPolicy m_result; + TestWebViewClient m_webViewClient; + WebViewImpl* m_webView; + TestWebFrameClient m_webFrameClient; + ChromeClientImpl* m_chromeClientImpl; +}; + +TEST_F(GetNavigationPolicyTest, LeftClick) +{ + int modifiers = 0; + WebMouseEvent::Button button = WebMouseEvent::ButtonLeft; + bool asPopup = false; + EXPECT_EQ(WebNavigationPolicyNewForegroundTab, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, LeftClickPopup) +{ + int modifiers = 0; + WebMouseEvent::Button button = WebMouseEvent::ButtonLeft; + bool asPopup = true; + EXPECT_EQ(WebNavigationPolicyNewPopup, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, ShiftLeftClick) +{ + int modifiers = WebInputEvent::ShiftKey; + WebMouseEvent::Button button = WebMouseEvent::ButtonLeft; + bool asPopup = false; + EXPECT_EQ(WebNavigationPolicyNewWindow, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, ShiftLeftClickPopup) +{ + int modifiers = WebInputEvent::ShiftKey; + WebMouseEvent::Button button = WebMouseEvent::ButtonLeft; + bool asPopup = true; + EXPECT_EQ(WebNavigationPolicyNewPopup, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, ControlOrMetaLeftClick) +{ +#if OS(DARWIN) + int modifiers = WebInputEvent::MetaKey; +#else + int modifiers = WebInputEvent::ControlKey; +#endif + WebMouseEvent::Button button = WebMouseEvent::ButtonLeft; + bool asPopup = false; + EXPECT_EQ(WebNavigationPolicyNewBackgroundTab, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, ControlOrMetaLeftClickPopup) +{ +#if OS(DARWIN) + int modifiers = WebInputEvent::MetaKey; +#else + int modifiers = WebInputEvent::ControlKey; +#endif + WebMouseEvent::Button button = WebMouseEvent::ButtonLeft; + bool asPopup = true; + EXPECT_EQ(WebNavigationPolicyNewBackgroundTab, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, ControlOrMetaAndShiftLeftClick) +{ +#if OS(DARWIN) + int modifiers = WebInputEvent::MetaKey; +#else + int modifiers = WebInputEvent::ControlKey; +#endif + modifiers |= WebInputEvent::ShiftKey; + WebMouseEvent::Button button = WebMouseEvent::ButtonLeft; + bool asPopup = false; + EXPECT_EQ(WebNavigationPolicyNewForegroundTab, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, ControlOrMetaAndShiftLeftClickPopup) +{ +#if OS(DARWIN) + int modifiers = WebInputEvent::MetaKey; +#else + int modifiers = WebInputEvent::ControlKey; +#endif + modifiers |= WebInputEvent::ShiftKey; + WebMouseEvent::Button button = WebMouseEvent::ButtonLeft; + bool asPopup = true; + EXPECT_EQ(WebNavigationPolicyNewForegroundTab, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, MiddleClick) +{ + int modifiers = 0; + bool asPopup = false; + WebMouseEvent::Button button = WebMouseEvent::ButtonMiddle; + EXPECT_EQ(WebNavigationPolicyNewBackgroundTab, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, MiddleClickPopup) +{ + int modifiers = 0; + bool asPopup = true; + WebMouseEvent::Button button = WebMouseEvent::ButtonMiddle; + EXPECT_EQ(WebNavigationPolicyNewBackgroundTab, + getNavigationPolicyWithMouseEvent(modifiers, button, asPopup)); +} + +TEST_F(GetNavigationPolicyTest, NoToolbarsForcesPopup) +{ + m_chromeClientImpl->setToolbarsVisible(false); + EXPECT_TRUE(isNavigationPolicyPopup()); + m_chromeClientImpl->setToolbarsVisible(true); + EXPECT_FALSE(isNavigationPolicyPopup()); +} + +TEST_F(GetNavigationPolicyTest, NoStatusbarForcesPopup) +{ + m_chromeClientImpl->setStatusbarVisible(false); + EXPECT_TRUE(isNavigationPolicyPopup()); + m_chromeClientImpl->setStatusbarVisible(true); + EXPECT_FALSE(isNavigationPolicyPopup()); +} + +TEST_F(GetNavigationPolicyTest, NoMenubarForcesPopup) +{ + m_chromeClientImpl->setMenubarVisible(false); + EXPECT_TRUE(isNavigationPolicyPopup()); + m_chromeClientImpl->setMenubarVisible(true); + EXPECT_FALSE(isNavigationPolicyPopup()); +} + +TEST_F(GetNavigationPolicyTest, NotResizableForcesPopup) +{ + m_chromeClientImpl->setResizable(false); + EXPECT_TRUE(isNavigationPolicyPopup()); + m_chromeClientImpl->setResizable(true); + EXPECT_FALSE(isNavigationPolicyPopup()); +} + +} // namespace diff --git a/Source/WebKit/chromium/tests/DeferredImageDecoderTest.cpp b/Source/WebKit/chromium/tests/DeferredImageDecoderTest.cpp index 4bcc29882..7fd4017a6 100644 --- a/Source/WebKit/chromium/tests/DeferredImageDecoderTest.cpp +++ b/Source/WebKit/chromium/tests/DeferredImageDecoderTest.cpp @@ -73,7 +73,8 @@ class DeferredImageDecoderTest : public ::testing::Test, public MockImageDecoder public: virtual void SetUp() { - ImageDecodingStore::initializeOnMainThread(); + ImageDecodingStore::initializeOnce(); + DeferredImageDecoder::setEnabled(true); m_data = SharedBuffer::create(whitePNG, sizeof(whitePNG)); m_actualDecoder = new MockImageDecoder(this); m_actualDecoder->setSize(1, 1); @@ -90,10 +91,19 @@ public: virtual void decoderBeingDestroyed() { - m_frameBufferRequestCount = m_actualDecoder->frameBufferRequestCount(); m_actualDecoder = 0; } + virtual void frameBufferRequested() + { + ++m_frameBufferRequestCount; + } + + virtual ImageFrame::FrameStatus frameStatus() + { + return ImageFrame::FrameComplete; + } + protected: // Don't own this but saves the pointer to query states. MockImageDecoder* m_actualDecoder; diff --git a/Source/WebKit/chromium/tests/IDBDatabaseBackendTest.cpp b/Source/WebKit/chromium/tests/IDBDatabaseBackendTest.cpp index e97bc7f6d..0eb7fae66 100644 --- a/Source/WebKit/chromium/tests/IDBDatabaseBackendTest.cpp +++ b/Source/WebKit/chromium/tests/IDBDatabaseBackendTest.cpp @@ -88,7 +88,6 @@ public: m_wasSuccessDBCalled = true; } virtual void onSuccess(PassRefPtr<IDBKey>) OVERRIDE { } - virtual void onSuccess(PassRefPtr<IDBTransactionBackendInterface>) OVERRIDE { } virtual void onSuccess(PassRefPtr<SerializedScriptValue>) OVERRIDE { } virtual void onSuccess(PassRefPtr<SerializedScriptValue>, PassRefPtr<IDBKey>, const IDBKeyPath&) OVERRIDE { }; virtual void onSuccess(int64_t) OVERRIDE { } @@ -153,9 +152,9 @@ public: virtual PassRefPtr<IDBObjectStoreBackendInterface> createObjectStore(int64_t, const String& name, const IDBKeyPath&, bool autoIncrement, IDBTransactionBackendInterface*, ExceptionCode&) { return 0; } virtual void deleteObjectStore(const String& name, IDBTransactionBackendInterface*, ExceptionCode&) { } virtual void deleteObjectStore(int64_t, IDBTransactionBackendInterface*, ExceptionCode&) { } - virtual void setVersion(const String& version, PassRefPtr<IDBCallbacks>, PassRefPtr<IDBDatabaseCallbacks>, ExceptionCode&) { } - virtual PassRefPtr<IDBTransactionBackendInterface> transaction(DOMStringList* storeNames, unsigned short mode, ExceptionCode&) { return 0; } + // FIXME: Remove this as part of https://bugs.webkit.org/show_bug.cgi?id=102733. virtual PassRefPtr<IDBTransactionBackendInterface> transaction(const Vector<int64_t>&, unsigned short mode) { return 0; } + virtual PassRefPtr<IDBTransactionBackendInterface> createTransaction(int64_t, const Vector<int64_t>&, unsigned short mode) { return 0; } virtual void close(PassRefPtr<IDBDatabaseCallbacks>) { diff --git a/Source/WebKit/chromium/tests/IDBRequestTest.cpp b/Source/WebKit/chromium/tests/IDBRequestTest.cpp index a0734e14c..8a7a3f4a7 100644 --- a/Source/WebKit/chromium/tests/IDBRequestTest.cpp +++ b/Source/WebKit/chromium/tests/IDBRequestTest.cpp @@ -94,7 +94,6 @@ TEST_F(IDBRequestTest, EventsAfterStopping) request->onSuccess(DOMStringList::create()); request->onSuccess(PassRefPtr<IDBCursorBackendInterface>(), IDBKey::createInvalid(), IDBKey::createInvalid(), SerializedScriptValue::nullValue()); request->onSuccess(IDBKey::createInvalid()); - request->onSuccess(PassRefPtr<IDBTransactionBackendInterface>()); request->onSuccess(SerializedScriptValue::nullValue()); request->onSuccess(SerializedScriptValue::nullValue(), IDBKey::createInvalid(), IDBKeyPath()); request->onSuccess(IDBKey::createInvalid(), IDBKey::createInvalid(), SerializedScriptValue::nullValue()); diff --git a/Source/WebKit/chromium/tests/ImageFrameGeneratorTest.cpp b/Source/WebKit/chromium/tests/ImageFrameGeneratorTest.cpp new file mode 100644 index 000000000..da0a2f864 --- /dev/null +++ b/Source/WebKit/chromium/tests/ImageFrameGeneratorTest.cpp @@ -0,0 +1,197 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include "ImageFrameGenerator.h" + +#include "ImageDecodingStore.h" +#include "MockImageDecoder.h" +#include "SharedBuffer.h" +#include <gtest/gtest.h> + +using namespace WebCore; + +namespace { + +class ImageFrameGeneratorTest; + +// Helper methods to generate standard sizes. +SkISize fullSize() { return SkISize::Make(100, 100); } +SkISize scaledSize() { return SkISize::Make(50, 50); } + +class ImageFrameGeneratorTest; + +class MockImageDecoderFactory : public ImageDecoderFactory { +public: + static PassOwnPtr<MockImageDecoderFactory> create(ImageFrameGeneratorTest* test) + { + return adoptPtr(new MockImageDecoderFactory(test)); + } + + virtual PassOwnPtr<ImageDecoder> create(); + +private: + MockImageDecoderFactory(ImageFrameGeneratorTest* test) + : m_test(test) + { + } + + ImageFrameGeneratorTest* m_test; +}; + +class ImageFrameGeneratorTest : public ::testing::Test, public MockImageDecoderClient { +public: + virtual void SetUp() + { + ImageDecodingStore::initializeOnce(); + m_data = SharedBuffer::create(); + m_generator = ImageFrameGenerator::create(fullSize(), m_data, true); + m_generator->setImageDecoderFactoryForTesting(MockImageDecoderFactory::create(this)); + m_frameBufferRequestCount = 0; + m_frameStatus = ImageFrame::FrameEmpty; + } + + virtual void TearDown() + { + ImageDecodingStore::shutdown(); + } + + virtual void decoderBeingDestroyed() + { + } + + virtual void frameBufferRequested() + { + ++m_frameBufferRequestCount; + } + + virtual ImageFrame::FrameStatus frameStatus() + { + return m_frameStatus; + } + +protected: + PassOwnPtr<ScaledImageFragment> createCompleteImage(const SkISize& size) + { + SkBitmap bitmap; + bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height()); + bitmap.allocPixels(); + return ScaledImageFragment::create(size, bitmap, true); + } + + void setFrameStatus(ImageFrame::FrameStatus status) { m_frameStatus = status; } + + RefPtr<SharedBuffer> m_data; + RefPtr<ImageFrameGenerator> m_generator; + int m_frameBufferRequestCount; + ImageFrame::FrameStatus m_frameStatus; +}; + +PassOwnPtr<ImageDecoder> MockImageDecoderFactory::create() +{ + MockImageDecoder* decoder = new MockImageDecoder(m_test); + decoder->setSize(fullSize().width(), fullSize().height()); + return adoptPtr(decoder); +} + +TEST_F(ImageFrameGeneratorTest, cacheHit) +{ + const ScaledImageFragment* fullImage = ImageDecodingStore::instance()->insertAndLockCache( + m_generator.get(), createCompleteImage(fullSize())); + EXPECT_EQ(fullSize(), fullImage->scaledSize()); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), fullImage); + + const ScaledImageFragment* tempImage = m_generator->decodeAndScale(fullSize()); + EXPECT_EQ(fullImage, tempImage); + EXPECT_EQ(fullSize(), tempImage->scaledSize()); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage); + EXPECT_EQ(0, m_frameBufferRequestCount); +} + +TEST_F(ImageFrameGeneratorTest, cacheMissWithScale) +{ + const ScaledImageFragment* fullImage = ImageDecodingStore::instance()->insertAndLockCache( + m_generator.get(), createCompleteImage(fullSize())); + EXPECT_EQ(fullSize(), fullImage->scaledSize()); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), fullImage); + + // Cache miss because of scaled size not found. + const ScaledImageFragment* scaledImage = m_generator->decodeAndScale(scaledSize()); + EXPECT_NE(fullImage, scaledImage); + EXPECT_EQ(scaledSize(), scaledImage->scaledSize()); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), scaledImage); + + // Cache hit. + const ScaledImageFragment* tempImage = m_generator->decodeAndScale(scaledSize()); + EXPECT_EQ(scaledImage, tempImage); + EXPECT_EQ(scaledSize(), tempImage->scaledSize()); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage); + EXPECT_EQ(0, m_frameBufferRequestCount); +} + +TEST_F(ImageFrameGeneratorTest, cacheMissWithDecodeAndScale) +{ + setFrameStatus(ImageFrame::FrameComplete); + + // Cache miss. + const ScaledImageFragment* scaledImage = m_generator->decodeAndScale(scaledSize()); + EXPECT_EQ(1, m_frameBufferRequestCount); + EXPECT_EQ(scaledSize(), scaledImage->scaledSize()); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), scaledImage); + + // Cache hit. + const ScaledImageFragment* fullImage = m_generator->decodeAndScale(fullSize()); + EXPECT_NE(scaledImage, fullImage); + EXPECT_EQ(fullSize(), fullImage->scaledSize()); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), fullImage); + + // Cache hit. + const ScaledImageFragment* tempImage = m_generator->decodeAndScale(scaledSize()); + EXPECT_EQ(scaledImage, tempImage); + EXPECT_EQ(scaledSize(), tempImage->scaledSize()); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage); + EXPECT_EQ(1, m_frameBufferRequestCount); +} + +// Test that incomplete frames are not cached. +TEST_F(ImageFrameGeneratorTest, cacheMissWithIncompleteDecode) +{ + setFrameStatus(ImageFrame::FramePartial); + + const ScaledImageFragment* tempImage = m_generator->decodeAndScale(scaledSize()); + EXPECT_EQ(1, m_frameBufferRequestCount); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage); + + tempImage = m_generator->decodeAndScale(fullSize()); + EXPECT_EQ(2, m_frameBufferRequestCount); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage); + + tempImage = m_generator->decodeAndScale(scaledSize()); + EXPECT_EQ(3, m_frameBufferRequestCount); + ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage); +} + +} // namespace diff --git a/Source/WebKit/chromium/tests/MockImageDecoder.h b/Source/WebKit/chromium/tests/MockImageDecoder.h index c9c0d01d6..8b4f40382 100644 --- a/Source/WebKit/chromium/tests/MockImageDecoder.h +++ b/Source/WebKit/chromium/tests/MockImageDecoder.h @@ -32,6 +32,8 @@ namespace WebCore { class MockImageDecoderClient { public: virtual void decoderBeingDestroyed() = 0; + virtual void frameBufferRequested() = 0; + virtual ImageFrame::FrameStatus frameStatus() = 0; }; class MockImageDecoder : public ImageDecoder { @@ -55,9 +57,11 @@ public: virtual ImageFrame* frameBufferAtIndex(size_t) { ++m_frameBufferRequestCount; + m_client->frameBufferRequested(); m_frameBufferCache.resize(1); m_frameBufferCache[0].setSize(size().width(), size().height()); + m_frameBufferCache[0].setStatus(m_client->frameStatus()); return &m_frameBufferCache[0]; } diff --git a/Source/WebKit/chromium/tests/PlatformGestureCurveTest.cpp b/Source/WebKit/chromium/tests/PlatformGestureCurveTest.cpp deleted file mode 100644 index 0e83a84e1..000000000 --- a/Source/WebKit/chromium/tests/PlatformGestureCurveTest.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "PlatformGestureCurve.h" - -#include "ActivePlatformGestureAnimation.h" -#include "PlatformGestureCurveTarget.h" -#include "TouchFlingPlatformGestureCurve.h" -#include "WheelFlingPlatformGestureCurve.h" -#include <gtest/gtest.h> -#include <wtf/OwnPtr.h> - -namespace { - -using namespace WebCore; - -class MockPlatformGestureCurveTarget : public PlatformGestureCurveTarget { -public: - virtual void scrollBy(const IntPoint& delta) - { - m_cumulativeDelta = m_cumulativeDelta + delta; - } - - IntPoint cumulativeDelta() const { return m_cumulativeDelta; } - void resetCumulativeDelta() { m_cumulativeDelta = IntPoint(); } - -private: - IntPoint m_cumulativeDelta; -}; - -TEST(PlatformGestureCurve, flingCurve) -{ - MockPlatformGestureCurveTarget target; - OwnPtr<ActivePlatformGestureAnimation> animation = ActivePlatformGestureAnimation::create(WheelFlingPlatformGestureCurve::create(FloatPoint(100, 0)), &target); - - // Note: the expectations below are dependent on the value of sigma hard-coded in the Rayleigh - // curve. If sigma changes, these test expectations will also change. - EXPECT_TRUE(animation->animate(0)); - EXPECT_TRUE(animation->animate(0.25)); - EXPECT_TRUE(animation->animate(0.45)); // Use non-uniform tick spacing. - EXPECT_TRUE(animation->animate(0.75)); - EXPECT_TRUE(animation->animate(1000)); - EXPECT_FALSE(animation->animate(1001)); - // Since the Rayleigh CDF maxes out at 1, we expect the cumulative scroll increments to - // match the input velocity parameter. - EXPECT_NEAR(target.cumulativeDelta().x(), 100, 1); - EXPECT_EQ(target.cumulativeDelta().y(), 0); - - // Test animation when not starting at t = 0. - double baseTime = 42.42; - animation = ActivePlatformGestureAnimation::create(WheelFlingPlatformGestureCurve::create(FloatPoint(100, 0)), &target); - target.resetCumulativeDelta(); - - EXPECT_TRUE(animation->animate(baseTime + 0.35)); - EXPECT_TRUE(animation->animate(baseTime + 1.35)); - EXPECT_TRUE(animation->animate(baseTime + 1000)); - EXPECT_FALSE(animation->animate(baseTime + 1001)); - EXPECT_NEAR(target.cumulativeDelta().x(), 100, 1); - - animation = ActivePlatformGestureAnimation::create(WheelFlingPlatformGestureCurve::create(FloatPoint(50, 150)), &target); - target.resetCumulativeDelta(); - - // Test animation with both horizontal and vertical scroll velocities. - EXPECT_TRUE(animation->animate(0)); - EXPECT_TRUE(animation->animate(0.25)); - EXPECT_TRUE(animation->animate(0.45)); - EXPECT_TRUE(animation->animate(0.75)); - EXPECT_TRUE(animation->animate(1000)); - EXPECT_FALSE(animation->animate(1001)); - EXPECT_NEAR(target.cumulativeDelta().x(), 50, 1); - EXPECT_NEAR(target.cumulativeDelta().y(), 150, 1); -} - -TEST(PlatformGestureCurve, flingCurveTouch) -{ - double initialVelocity = 5000; - MockPlatformGestureCurveTarget target; - // Explicitly parametrized to make test non-brittle in face of - // parameter changes. - OwnPtr<ActivePlatformGestureAnimation> animation = ActivePlatformGestureAnimation::create(TouchFlingPlatformGestureCurve::create(FloatPoint(initialVelocity, 0), -5.70762e+03f, 1.72e+02f, 3.7e+00f, 1.3f), &target); - - // Note: the expectations below are dependent on the curve parameters hard - // coded into the create call above. - EXPECT_TRUE(animation->animate(0)); - EXPECT_TRUE(animation->animate(0.25)); - EXPECT_TRUE(animation->animate(0.45f)); // Use non-uniform tick spacing. - EXPECT_TRUE(animation->animate(1)); - EXPECT_FALSE(animation->animate(1.5)); - EXPECT_NEAR(target.cumulativeDelta().x(), 1193, 1); - EXPECT_EQ(target.cumulativeDelta().y(), 0); -} - -} // namespace anonymous diff --git a/Source/WebKit/chromium/tests/WebCompositorInputHandlerImplTest.cpp b/Source/WebKit/chromium/tests/WebCompositorInputHandlerImplTest.cpp index 395fdcf3d..36fee689d 100644 --- a/Source/WebKit/chromium/tests/WebCompositorInputHandlerImplTest.cpp +++ b/Source/WebKit/chromium/tests/WebCompositorInputHandlerImplTest.cpp @@ -259,7 +259,76 @@ TEST_F(WebCompositorInputHandlerImplTest, gesturePinch) m_inputHandler->handleInputEvent(gesture); } -TEST_F(WebCompositorInputHandlerImplTest, gestureFlingStarted) +TEST_F(WebCompositorInputHandlerImplTest, gesturePinchAfterScrollOnMainThread) +{ + // Scrolls will start by being sent to the main thread. + m_expectedDisposition = DidNotHandle; + VERIFY_AND_RESET_MOCKS(); + + EXPECT_CALL(m_mockInputHandlerClient, scrollBegin(::testing::_, ::testing::_)) + .WillOnce(testing::Return(WebInputHandlerClient::ScrollStatusOnMainThread)); + + gesture.type = WebInputEvent::GestureScrollBegin; + m_inputHandler->handleInputEvent(gesture); + + VERIFY_AND_RESET_MOCKS(); + + gesture.type = WebInputEvent::GestureScrollUpdate; + gesture.data.scrollUpdate.deltaY = 40; + m_inputHandler->handleInputEvent(gesture); + + // However, after the pinch gesture starts, they should go to the impl + // thread. + m_expectedDisposition = DidHandle; + VERIFY_AND_RESET_MOCKS(); + + gesture.type = WebInputEvent::GesturePinchBegin; + EXPECT_CALL(m_mockInputHandlerClient, pinchGestureBegin()); + m_inputHandler->handleInputEvent(gesture); + + VERIFY_AND_RESET_MOCKS(); + + gesture.type = WebInputEvent::GesturePinchUpdate; + gesture.data.pinchUpdate.scale = 1.5; + gesture.x = 7; + gesture.y = 13; + EXPECT_CALL(m_mockInputHandlerClient, pinchGestureUpdate(1.5, WebPoint(7, 13))); + m_inputHandler->handleInputEvent(gesture); + + VERIFY_AND_RESET_MOCKS(); + + gesture.type = WebInputEvent::GestureScrollUpdate; + gesture.data.scrollUpdate.deltaY = -40; // -Y means scroll down - i.e. in the +Y direction. + EXPECT_CALL(m_mockInputHandlerClient, scrollByIfPossible(testing::_, testing::Field(&WebSize::height, testing::Gt(0)))) + .WillOnce(testing::Return(true)); + m_inputHandler->handleInputEvent(gesture); + + VERIFY_AND_RESET_MOCKS(); + + gesture.type = WebInputEvent::GesturePinchUpdate; + gesture.data.pinchUpdate.scale = 0.5; + gesture.x = 9; + gesture.y = 6; + EXPECT_CALL(m_mockInputHandlerClient, pinchGestureUpdate(.5, WebPoint(9, 6))); + m_inputHandler->handleInputEvent(gesture); + + VERIFY_AND_RESET_MOCKS(); + + gesture.type = WebInputEvent::GesturePinchEnd; + EXPECT_CALL(m_mockInputHandlerClient, pinchGestureEnd()); + m_inputHandler->handleInputEvent(gesture); + + // After the pinch gesture ends, they should go to back to the main + // thread. + m_expectedDisposition = DidNotHandle; + VERIFY_AND_RESET_MOCKS(); + + gesture.type = WebInputEvent::GestureScrollEnd; + gesture.data.scrollUpdate.deltaY = 0; + m_inputHandler->handleInputEvent(gesture); +} + +TEST_F(WebCompositorInputHandlerImplTest, gestureFlingStartedTouchpad) { // We shouldn't send any events to the widget for this gesture. m_expectedDisposition = DidHandle; @@ -272,16 +341,18 @@ TEST_F(WebCompositorInputHandlerImplTest, gestureFlingStarted) gesture.type = WebInputEvent::GestureFlingStart; gesture.data.flingStart.velocityX = 10; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchpad; m_inputHandler->handleInputEvent(gesture); VERIFY_AND_RESET_MOCKS(); // Verify that a GestureFlingCancel during an animation cancels it. gesture.type = WebInputEvent::GestureFlingCancel; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchpad; m_inputHandler->handleInputEvent(gesture); } -TEST_F(WebCompositorInputHandlerImplTest, gestureFlingFailed) +TEST_F(WebCompositorInputHandlerImplTest, gestureFlingOnMainThreadTouchpad) { // We should send all events to the widget for this gesture. m_expectedDisposition = DidNotHandle; @@ -291,16 +362,18 @@ TEST_F(WebCompositorInputHandlerImplTest, gestureFlingFailed) .WillOnce(testing::Return(WebInputHandlerClient::ScrollStatusOnMainThread)); gesture.type = WebInputEvent::GestureFlingStart; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchpad; m_inputHandler->handleInputEvent(gesture); VERIFY_AND_RESET_MOCKS(); // Even if we didn't start a fling ourselves, we still need to send the cancel event to the widget. gesture.type = WebInputEvent::GestureFlingCancel; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchpad; m_inputHandler->handleInputEvent(gesture); } -TEST_F(WebCompositorInputHandlerImplTest, gestureFlingIgnored) +TEST_F(WebCompositorInputHandlerImplTest, gestureFlingIgnoredTouchpad) { m_expectedDisposition = DidNotHandle; VERIFY_AND_RESET_MOCKS(); @@ -309,16 +382,18 @@ TEST_F(WebCompositorInputHandlerImplTest, gestureFlingIgnored) .WillOnce(testing::Return(WebInputHandlerClient::ScrollStatusIgnored)); gesture.type = WebInputEvent::GestureFlingStart; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchpad; m_inputHandler->handleInputEvent(gesture); VERIFY_AND_RESET_MOCKS(); // Even if we didn't start a fling ourselves, we still need to send the cancel event to the widget. gesture.type = WebInputEvent::GestureFlingCancel; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchpad; m_inputHandler->handleInputEvent(gesture); } -TEST_F(WebCompositorInputHandlerImplTest, gestureFlingAnimates) +TEST_F(WebCompositorInputHandlerImplTest, gestureFlingAnimatesTouchpad) { // We shouldn't send any events to the widget for this gesture. m_expectedDisposition = DidHandle; @@ -333,6 +408,7 @@ TEST_F(WebCompositorInputHandlerImplTest, gestureFlingAnimates) int modifiers = 7; gesture.data.flingStart.velocityX = flingDelta.x; gesture.data.flingStart.velocityY = flingDelta.y; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchpad; gesture.x = flingPoint.x; gesture.y = flingPoint.y; gesture.globalX = flingGlobalPoint.x; @@ -405,7 +481,7 @@ TEST_F(WebCompositorInputHandlerImplTest, gestureFlingAnimates) m_inputHandler->handleInputEvent(gesture); } -TEST_F(WebCompositorInputHandlerImplTest, gestureFlingTransferResets) +TEST_F(WebCompositorInputHandlerImplTest, gestureFlingTransferResetsTouchpad) { // We shouldn't send any events to the widget for this gesture. m_expectedDisposition = DidHandle; @@ -419,6 +495,7 @@ TEST_F(WebCompositorInputHandlerImplTest, gestureFlingTransferResets) int modifiers = 1; gesture.data.flingStart.velocityX = flingDelta.x; gesture.data.flingStart.velocityY = flingDelta.y; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchpad; gesture.x = flingPoint.x; gesture.y = flingPoint.y; gesture.globalX = flingGlobalPoint.x; @@ -500,6 +577,7 @@ TEST_F(WebCompositorInputHandlerImplTest, gestureFlingTransferResets) modifiers = 2; gesture.data.flingStart.velocityX = flingDelta.x; gesture.data.flingStart.velocityY = flingDelta.y; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchpad; gesture.x = flingPoint.x; gesture.y = flingPoint.y; gesture.globalX = flingGlobalPoint.x; @@ -550,4 +628,121 @@ TEST_F(WebCompositorInputHandlerImplTest, gestureFlingTransferResets) m_inputHandler->animate(30.2); } +TEST_F(WebCompositorInputHandlerImplTest, gestureFlingStartedTouchscreen) +{ + // We shouldn't send any events to the widget for this gesture. + m_expectedDisposition = DidHandle; + VERIFY_AND_RESET_MOCKS(); + + EXPECT_CALL(m_mockInputHandlerClient, scrollBegin(testing::_, testing::_)) + .WillOnce(testing::Return(WebInputHandlerClient::ScrollStatusStarted)); + EXPECT_CALL(m_mockInputHandlerClient, scheduleAnimation()); + + gesture.type = WebInputEvent::GestureFlingStart; + gesture.data.flingStart.velocityX = 10; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchscreen; + m_inputHandler->handleInputEvent(gesture); + + VERIFY_AND_RESET_MOCKS(); + + EXPECT_CALL(m_mockInputHandlerClient, scrollEnd()); + + // Verify that a GestureFlingCancel during an animation cancels it. + gesture.type = WebInputEvent::GestureFlingCancel; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchscreen; + m_inputHandler->handleInputEvent(gesture); +} + +TEST_F(WebCompositorInputHandlerImplTest, gestureFlingOnMainThreadTouchscreen) +{ + // We should send all events to the widget for this gesture. + m_expectedDisposition = DidNotHandle; + VERIFY_AND_RESET_MOCKS(); + + EXPECT_CALL(m_mockInputHandlerClient, scrollBegin(testing::_, testing::_)) + .WillOnce(testing::Return(WebInputHandlerClient::ScrollStatusOnMainThread)); + + gesture.type = WebInputEvent::GestureFlingStart; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchscreen; + m_inputHandler->handleInputEvent(gesture); + + VERIFY_AND_RESET_MOCKS(); + + // Even if we didn't start a fling ourselves, we still need to send the cancel event to the widget. + gesture.type = WebInputEvent::GestureFlingCancel; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchscreen; + m_inputHandler->handleInputEvent(gesture); +} + +TEST_F(WebCompositorInputHandlerImplTest, gestureFlingIgnoredTouchscreen) +{ + m_expectedDisposition = DropEvent; + VERIFY_AND_RESET_MOCKS(); + + EXPECT_CALL(m_mockInputHandlerClient, scrollBegin(testing::_, testing::_)) + .WillOnce(testing::Return(WebInputHandlerClient::ScrollStatusIgnored)); + + gesture.type = WebInputEvent::GestureFlingStart; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchscreen; + m_inputHandler->handleInputEvent(gesture); + + m_expectedDisposition = DidNotHandle; + VERIFY_AND_RESET_MOCKS(); + + // Even if we didn't start a fling ourselves, we still need to send the cancel event to the widget. + gesture.type = WebInputEvent::GestureFlingCancel; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchscreen; + m_inputHandler->handleInputEvent(gesture); +} + +TEST_F(WebCompositorInputHandlerImplTest, gestureFlingAnimatesTouchscreen) +{ + // We shouldn't send any events to the widget for this gesture. + m_expectedDisposition = DidHandle; + VERIFY_AND_RESET_MOCKS(); + + // On the fling start, we should schedule an animation but not actually start + // scrolling. + gesture.type = WebInputEvent::GestureFlingStart; + WebFloatPoint flingDelta = WebFloatPoint(1000, 0); + WebPoint flingPoint = WebPoint(7, 13); + WebPoint flingGlobalPoint = WebPoint(17, 23); + int modifiers = 7; + gesture.data.flingStart.velocityX = flingDelta.x; + gesture.data.flingStart.velocityY = flingDelta.y; + gesture.data.flingStart.sourceDevice = WebGestureEvent::Touchscreen; + gesture.x = flingPoint.x; + gesture.y = flingPoint.y; + gesture.globalX = flingGlobalPoint.x; + gesture.globalY = flingGlobalPoint.y; + gesture.modifiers = modifiers; + EXPECT_CALL(m_mockInputHandlerClient, scheduleAnimation()); + EXPECT_CALL(m_mockInputHandlerClient, scrollBegin(testing::_, testing::_)) + .WillOnce(testing::Return(WebInputHandlerClient::ScrollStatusStarted)); + m_inputHandler->handleInputEvent(gesture); + + testing::Mock::VerifyAndClearExpectations(&m_mockInputHandlerClient); + // The first animate call should let us pick up an animation start time, but we + // shouldn't actually move anywhere just yet. The first frame after the fling start + // will typically include the last scroll from the gesture that lead to the scroll + // (either wheel or gesture scroll), so there should be no visible hitch. + EXPECT_CALL(m_mockInputHandlerClient, scheduleAnimation()); + m_inputHandler->animate(10); + + testing::Mock::VerifyAndClearExpectations(&m_mockInputHandlerClient); + + // The second call should start scrolling in the -X direction. + EXPECT_CALL(m_mockInputHandlerClient, scheduleAnimation()); + EXPECT_CALL(m_mockInputHandlerClient, scrollByIfPossible(testing::_, testing::Field(&WebSize::width, testing::Lt(0)))) + .WillOnce(testing::Return(true)); + m_inputHandler->animate(10.1); + + testing::Mock::VerifyAndClearExpectations(&m_mockInputHandlerClient); + + EXPECT_CALL(m_mockClient, didHandleInputEvent()); + EXPECT_CALL(m_mockInputHandlerClient, scrollEnd()); + gesture.type = WebInputEvent::GestureFlingCancel; + m_inputHandler->handleInputEvent(gesture); +} + } diff --git a/Source/WebKit/efl/ChangeLog b/Source/WebKit/efl/ChangeLog index 2007c5354..0310650bd 100644 --- a/Source/WebKit/efl/ChangeLog +++ b/Source/WebKit/efl/ChangeLog @@ -1,3 +1,77 @@ +2012-11-29 Ryuan Choi <ryuan.choi@samsung.com> + + [EFL] Broken rendering occurs when scrolling in ewk_view_single. + https://bugs.webkit.org/show_bug.cgi?id=77325 + + Reviewed by Gyuyoung Kim. + + After r104687, broken rendering occurs when scrolling contents. + It's because scrollWidth can be smaller than width of image buffer. + + This patch fixes it and renames parameter to avoid confusion. + + * ewk/ewk_view_single.cpp: + (_ewk_view_screen_move): + (_ewk_view_single_scroll_process_single): + +2012-11-28 Ryuan Choi <ryuan.choi@gmail.com> + + [EFL] Generate big_button_theme.edj + https://bugs.webkit.org/show_bug.cgi?id=103511 + + Reviewed by Gyuyoung Kim. + + big_button_theme.edj, binary file which is used for test, should be generated. + + * DefaultTheme/CMakeLists.txt: + Introduced macro and new target to share files of default theme instead + of adding many files for big_button_theme. + * DefaultTheme/widget/button/button.edc: + Implemented for big_button_theme. + +2012-11-28 Ryuan Choi <ryuan.choi@gmail.com> + + [EFL] Refactor theme to choose whether to support foreground color of selection + https://bugs.webkit.org/show_bug.cgi?id=102037 + + Reviewed by Kenneth Rohde Christiansen. + + * DefaultTheme/default.edc: + Refactored color classes from active/inactive to foreground/background. + +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * ewk/ewk_frame.cpp: + (_ewk_frame_contents_set_internal): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * ewk/ewk_frame.cpp: + (ewk_frame_uri_set): + (_ewk_frame_contents_set_internal): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * ewk/ewk_frame.cpp: + (_ewk_frame_contents_set_internal): + 2012-11-24 Viatcheslav Ostapenko <v.ostapenko@samsung.com> [EFL] Layout test comes to crash on WK1 diff --git a/Source/WebKit/efl/DefaultTheme/CMakeLists.txt b/Source/WebKit/efl/DefaultTheme/CMakeLists.txt index 850749e14..ded410845 100644 --- a/Source/WebKit/efl/DefaultTheme/CMakeLists.txt +++ b/Source/WebKit/efl/DefaultTheme/CMakeLists.txt @@ -1,110 +1,116 @@ -SET(DefaultTheme_RESOURCE_NAME default.edj) -SET(DefaultTheme_DIR "${WEBKIT_DIR}/efl/DefaultTheme") +MACRO (GENERATE_THEME _target_name _name _option) + SET(DefaultTheme_DIR "${WEBKIT_DIR}/efl/DefaultTheme") + + ADD_CUSTOM_COMMAND( + OUTPUT ${THEME_BINARY_DIR}/${_name} + COMMAND ${EDJE_CC_EXECUTABLE} -v ${_option} default.edc ${THEME_BINARY_DIR}/${_name} + DEPENDS + default.edc + widget/button/button.edc + widget/button/img_button_focus.png + widget/button/img_button_hover.png + widget/button/img_button_normal.png + widget/button/img_button_press.png + widget/check/check.edc + widget/check/img_check_off_focus.png + widget/check/img_check_off_hover.png + widget/check/img_check_off.png + widget/check/img_check_on_focus.png + widget/check/img_check_on_hover.png + widget/check/img_check_on.png + widget/combo/combo.edc + widget/combo/combo_focus_button.png + widget/combo/combo_focus.png + widget/combo/combo_hover_button.png + widget/combo/combo_hover.png + widget/combo/combo_normal_button.png + widget/combo/combo_normal.png + widget/combo/combo_press_button.png + widget/combo/combo_press.png + widget/combo/icon.png + widget/entry/entry.edc + widget/entry/img_focused.png + widget/entry/img_hovered.png + widget/entry/img_normal.png + widget/file/file.edc + widget/file/file_focus.png + widget/file/file_hover.png + widget/file/file_normal.png + widget/file/file_press.png + widget/mediacontrol/fullscreenbutton/enterfullscreenbutton.png + widget/mediacontrol/fullscreenbutton/exitfullscreenbutton.png + widget/mediacontrol/fullscreenbutton/fullscreen_button.edc + widget/mediacontrol/mutebutton/mute_button.edc + widget/mediacontrol/mutebutton/mutebutton.png + widget/mediacontrol/mutebutton/unmutebutton.png + widget/mediacontrol/playpausebutton/pausebutton.png + widget/mediacontrol/playpausebutton/playbutton.png + widget/mediacontrol/playpausebutton/playpause_button.edc + widget/mediacontrol/seekbackwardbutton/seekbackward_button.edc + widget/mediacontrol/seekbackwardbutton/seekbackwardbutton.png + widget/mediacontrol/seekforwardbutton/seekforward_button.edc + widget/mediacontrol/seekforwardbutton/seekforwardbutton.png + widget/mediacontrol/togglecaptionsbutton/closedcaption_disabled.png + widget/mediacontrol/togglecaptionsbutton/closedcaption.png + widget/mediacontrol/togglecaptionsbutton/toggle_captions_button.edc + widget/progressbar/bt_base.png + widget/progressbar/progressbar.edc + widget/progressbar/shelf_inset.png + widget/radio/img_radio_off_focus.png + widget/radio/img_radio_off_hover.png + widget/radio/img_radio_off.png + widget/radio/img_radio_on_focus.png + widget/radio/img_radio_on_hover.png + widget/radio/img_radio_on.png + widget/radio/radio.edc + widget/scrollbar/scrollbar.edc + widget/scrollbar/scrollbar_h.png + widget/scrollbar/scrollbar_knob_h.png + widget/scrollbar/scrollbar_knob_v.png + widget/scrollbar/scrollbar_v.png + widget/search/cancel/cancel_normal_button2.png + widget/search/cancel/cancel_normal_button.png + widget/search/cancel/search_cancel.edc + widget/search/decoration/decoration_normal_button.png + widget/search/decoration/search_decoration.edc + widget/search/field/field_focused.png + widget/search/field/field_hovered.png + widget/search/field/field_normal.png + widget/search/field/search_field.edc + widget/slider/slider.edc + widget/slider/slider_fill_h.png + widget/slider/slider_fill_v.png + widget/slider/slider_h.png + widget/slider/slider_thumb_h.png + widget/slider/slider_thumb_press_h.png + widget/slider/slider_thumb_press_v.png + widget/slider/slider_thumb_v.png + widget/slider/slider_v.png + widget/spinner/sp_bg.png + widget/spinner/sp_down_default.png + widget/spinner/sp_down_hover.png + widget/spinner/sp_down_pressed.png + widget/spinner/spinner.edc + widget/spinner/sp_up_default.png + widget/spinner/sp_up_hover.png + widget/spinner/sp_up_pressed.png + WORKING_DIRECTORY ${DefaultTheme_DIR} + VERBATIM + ) + + ADD_CUSTOM_TARGET(${_target_name} ALL + DEPENDS ${THEME_BINARY_DIR}/${_name} + ) +ENDMACRO() SET(DefaultTheme_DEFINITION "") IF (ENABLE_PROGRESS_ELEMENT) LIST(APPEND DefaultTheme_DEFINITION "-DENABLE_PROGRESS_ELEMENT") ENDIF () -ADD_CUSTOM_COMMAND( - OUTPUT ${THEME_BINARY_DIR}/${DefaultTheme_RESOURCE_NAME} - COMMAND ${EDJE_CC_EXECUTABLE} -v ${DefaultTheme_DEFINITION} default.edc ${THEME_BINARY_DIR}/${DefaultTheme_RESOURCE_NAME} - DEPENDS - default.edc - widget/button/button.edc - widget/button/img_button_focus.png - widget/button/img_button_hover.png - widget/button/img_button_normal.png - widget/button/img_button_press.png - widget/check/check.edc - widget/check/img_check_off_focus.png - widget/check/img_check_off_hover.png - widget/check/img_check_off.png - widget/check/img_check_on_focus.png - widget/check/img_check_on_hover.png - widget/check/img_check_on.png - widget/combo/combo.edc - widget/combo/combo_focus_button.png - widget/combo/combo_focus.png - widget/combo/combo_hover_button.png - widget/combo/combo_hover.png - widget/combo/combo_normal_button.png - widget/combo/combo_normal.png - widget/combo/combo_press_button.png - widget/combo/combo_press.png - widget/combo/icon.png - widget/entry/entry.edc - widget/entry/img_focused.png - widget/entry/img_hovered.png - widget/entry/img_normal.png - widget/file/file.edc - widget/file/file_focus.png - widget/file/file_hover.png - widget/file/file_normal.png - widget/file/file_press.png - widget/mediacontrol/fullscreenbutton/enterfullscreenbutton.png - widget/mediacontrol/fullscreenbutton/exitfullscreenbutton.png - widget/mediacontrol/fullscreenbutton/fullscreen_button.edc - widget/mediacontrol/mutebutton/mute_button.edc - widget/mediacontrol/mutebutton/mutebutton.png - widget/mediacontrol/mutebutton/unmutebutton.png - widget/mediacontrol/playpausebutton/pausebutton.png - widget/mediacontrol/playpausebutton/playbutton.png - widget/mediacontrol/playpausebutton/playpause_button.edc - widget/mediacontrol/seekbackwardbutton/seekbackward_button.edc - widget/mediacontrol/seekbackwardbutton/seekbackwardbutton.png - widget/mediacontrol/seekforwardbutton/seekforward_button.edc - widget/mediacontrol/seekforwardbutton/seekforwardbutton.png - widget/mediacontrol/togglecaptionsbutton/closedcaption_disabled.png - widget/mediacontrol/togglecaptionsbutton/closedcaption.png - widget/mediacontrol/togglecaptionsbutton/toggle_captions_button.edc - widget/progressbar/bt_base.png - widget/progressbar/progressbar.edc - widget/progressbar/shelf_inset.png - widget/radio/img_radio_off_focus.png - widget/radio/img_radio_off_hover.png - widget/radio/img_radio_off.png - widget/radio/img_radio_on_focus.png - widget/radio/img_radio_on_hover.png - widget/radio/img_radio_on.png - widget/radio/radio.edc - widget/scrollbar/scrollbar.edc - widget/scrollbar/scrollbar_h.png - widget/scrollbar/scrollbar_knob_h.png - widget/scrollbar/scrollbar_knob_v.png - widget/scrollbar/scrollbar_v.png - widget/search/cancel/cancel_normal_button2.png - widget/search/cancel/cancel_normal_button.png - widget/search/cancel/search_cancel.edc - widget/search/decoration/decoration_normal_button.png - widget/search/decoration/search_decoration.edc - widget/search/field/field_focused.png - widget/search/field/field_hovered.png - widget/search/field/field_normal.png - widget/search/field/search_field.edc - widget/slider/slider.edc - widget/slider/slider_fill_h.png - widget/slider/slider_fill_v.png - widget/slider/slider_h.png - widget/slider/slider_thumb_h.png - widget/slider/slider_thumb_press_h.png - widget/slider/slider_thumb_press_v.png - widget/slider/slider_thumb_v.png - widget/slider/slider_v.png - widget/spinner/sp_bg.png - widget/spinner/sp_down_default.png - widget/spinner/sp_down_hover.png - widget/spinner/sp_down_pressed.png - widget/spinner/spinner.edc - widget/spinner/sp_up_default.png - widget/spinner/sp_up_hover.png - widget/spinner/sp_up_pressed.png - WORKING_DIRECTORY ${DefaultTheme_DIR} - VERBATIM -) +GENERATE_THEME(DefaultTheme "default.edj" "${DefaultTheme_DEFINITION}") +INSTALL(FILES "${THEME_BINARY_DIR}/default.edj" DESTINATION ${DATA_INSTALL_DIR}/themes) -ADD_CUSTOM_TARGET(DefaultTheme ALL - DEPENDS ${THEME_BINARY_DIR}/${DefaultTheme_RESOURCE_NAME} -) - -INSTALL(FILES ${THEME_BINARY_DIR}/${DefaultTheme_RESOURCE_NAME} DESTINATION ${DATA_INSTALL_DIR}/themes) +IF (ENABLE_API_TESTS) + GENERATE_THEME(BigButtonTheme "big_button_theme.edj" "-DBIG_BUTTON_THEME_FOR_TESTING") +ENDIF () diff --git a/Source/WebKit/efl/DefaultTheme/default.edc b/Source/WebKit/efl/DefaultTheme/default.edc index e234839d7..2ac69c5c3 100644 --- a/Source/WebKit/efl/DefaultTheme/default.edc +++ b/Source/WebKit/efl/DefaultTheme/default.edc @@ -21,14 +21,14 @@ color_classes { color_class { - name: "webkit/selection/active"; - color: 255 255 255 255; /* foreground */ - color2: 86 86 209 255; /* background */ + name: "webkit/selection/foreground"; + color: 255 255 255 255; /* active */ + color2: 255 255 255 255; /* inactive */ } color_class { - name: "webkit/selection/inactive"; - color: 255 255 255 255; /* foreground */ - color2: 0 0 128 128; /* background */ + name: "webkit/selection/background"; + color: 86 86 209 255; /* active */ + color2: 0 0 128 128; /* inactive */ } color_class { name: "webkit/focus_ring"; diff --git a/Source/WebKit/efl/DefaultTheme/widget/button/button.edc b/Source/WebKit/efl/DefaultTheme/widget/button/button.edc index 78cc72a54..b435ed139 100644 --- a/Source/WebKit/efl/DefaultTheme/widget/button/button.edc +++ b/Source/WebKit/efl/DefaultTheme/widget/button/button.edc @@ -113,7 +113,11 @@ } rel2 { relative: 1.0 1.0; +#ifdef BIG_BUTTON_THEME_FOR_TESTING + offset: -285 -11; +#else offset: -16 -11; +#endif } } } diff --git a/Source/WebKit/efl/ewk/ewk_frame.cpp b/Source/WebKit/efl/ewk/ewk_frame.cpp index dec55d698..af38e4a08 100644 --- a/Source/WebKit/efl/ewk/ewk_frame.cpp +++ b/Source/WebKit/efl/ewk/ewk_frame.cpp @@ -30,6 +30,7 @@ #include "DocumentMarkerController.h" #include "EventHandler.h" #include "FocusController.h" +#include "FrameLoadRequest.h" #include "FrameLoaderClientEfl.h" #include "FrameView.h" #include "HTMLCollection.h" @@ -338,7 +339,7 @@ Eina_Bool ewk_frame_uri_set(Evas_Object* ewkFrame, const char* uri) WebCore::KURL kurl(WebCore::KURL(), WTF::String::fromUTF8(uri)); WebCore::ResourceRequest req(kurl); WebCore::FrameLoader* loader = smartData->frame->loader(); - loader->load(req, false); + loader->load(WebCore::FrameLoadRequest(smartData->frame, req)); return true; } @@ -416,7 +417,7 @@ static Eina_Bool _ewk_frame_contents_set_internal(Ewk_Frame_Smart_Data* smartDat baseKURL, unreachableKURL); WebCore::ResourceRequest request(baseKURL); - smartData->frame->loader()->load(request, substituteData, false); + smartData->frame->loader()->load(WebCore::FrameLoadRequest(smartData->frame, request, substituteData)); return true; } diff --git a/Source/WebKit/efl/ewk/ewk_view_single.cpp b/Source/WebKit/efl/ewk/ewk_view_single.cpp index c1fc6cd02..c5779ab3f 100644 --- a/Source/WebKit/efl/ewk/ewk_view_single.cpp +++ b/Source/WebKit/efl/ewk/ewk_view_single.cpp @@ -101,10 +101,10 @@ static void _ewk_view_single_smart_resize(Evas_Object* ewkView, Evas_Coord width } } -static inline void _ewk_view_screen_move(uint32_t* image, size_t destinationX, size_t destinationY, size_t sourceX, size_t sourceY, size_t copyWidth, size_t copyHeight, size_t frameWidth) +static inline void _ewk_view_screen_move(uint32_t* image, size_t destinationX, size_t destinationY, size_t sourceX, size_t sourceY, size_t copyWidth, size_t copyHeight, size_t imageWidth) { - uint32_t* sourceBegin = image + (frameWidth * sourceY) + sourceX; - uint32_t* destinationBegin = image + (frameWidth * destinationY) + destinationX; + uint32_t* sourceBegin = image + (imageWidth * sourceY) + sourceX; + uint32_t* destinationBegin = image + (imageWidth * destinationY) + destinationX; size_t copyLength = copyWidth * 4; const int moveLineUpDown = sourceY >= destinationY ? 1 : -1; @@ -113,15 +113,15 @@ static inline void _ewk_view_screen_move(uint32_t* image, size_t destinationX, s uint32_t* source, * destination; if (sourceX >= destinationX) { for (size_t i = 0; i < copyHeight; i++) { - source = sourceBegin + (frameWidth * startHeight); - destination = destinationBegin + (frameWidth * startHeight); + source = sourceBegin + (imageWidth * startHeight); + destination = destinationBegin + (imageWidth * startHeight); startHeight = startHeight + moveLineUpDown; memcpy(destination, source, copyLength); } } else { for (size_t i = 0; i < copyHeight; i++) { - source = sourceBegin + (frameWidth * startHeight); - destination = destinationBegin + (frameWidth * startHeight); + source = sourceBegin + (imageWidth * startHeight); + destination = destinationBegin + (imageWidth * startHeight); startHeight = startHeight + moveLineUpDown; memmove(destination, source, copyLength); } @@ -176,7 +176,7 @@ static inline void _ewk_view_single_scroll_process_single(Ewk_View_Smart_Data* s int copyWidth = scrollWidth - abs(scrollRequest->dx); int copyHeight = scrollHeight - abs(scrollRequest->dy); if (scrollRequest->dx || scrollRequest->dy) { - _ewk_view_screen_move(static_cast<uint32_t*>(pixels), destinationX, destinationY, sourceX, sourceY, copyWidth, copyHeight, scrollWidth); + _ewk_view_screen_move(static_cast<uint32_t*>(pixels), destinationX, destinationY, sourceX, sourceY, copyWidth, copyHeight, width); evas_object_image_data_update_add(smartData->backing_store, destinationX, destinationY, copyWidth, copyHeight); } diff --git a/Source/WebKit/gtk/ChangeLog b/Source/WebKit/gtk/ChangeLog index bf9641b43..e56a9f561 100644 --- a/Source/WebKit/gtk/ChangeLog +++ b/Source/WebKit/gtk/ChangeLog @@ -1,3 +1,41 @@ +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * webkit/webkitwebframe.cpp: + (webkit_web_frame_load_uri): + (webkit_web_frame_load_data): + (webkit_web_frame_load_request): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * webkit/webkitwebframe.cpp: + (webkit_web_frame_load_uri): + (webkit_web_frame_load_data): + (webkit_web_frame_load_request): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * webkit/webkitwebframe.cpp: + (webkit_web_frame_load_uri): + (webkit_web_frame_load_data): + (webkit_web_frame_load_request): + 2012-11-25 Kaustubh Atrawalkar <kaustubh@motorola.com> Remove deprecated load-done signal diff --git a/Source/WebKit/gtk/webkit/webkitwebframe.cpp b/Source/WebKit/gtk/webkit/webkitwebframe.cpp index 80800c2c5..1e7c4c3f3 100644 --- a/Source/WebKit/gtk/webkit/webkitwebframe.cpp +++ b/Source/WebKit/gtk/webkit/webkitwebframe.cpp @@ -33,6 +33,7 @@ #include "DocumentFragment.h" #include "DocumentLoader.h" #include "DocumentLoaderGtk.h" +#include "FrameLoadRequest.h" #include "FrameLoader.h" #include "FrameLoaderClientGtk.h" #include "FrameSelection.h" @@ -674,7 +675,7 @@ void webkit_web_frame_load_uri(WebKitWebFrame* frame, const gchar* uri) if (!coreFrame) return; - coreFrame->loader()->load(ResourceRequest(KURL(KURL(), String::fromUTF8(uri))), false); + coreFrame->loader()->load(FrameLoadRequest(coreFrame, ResourceRequest(KURL(KURL(), String::fromUTF8(uri))))); } static void webkit_web_frame_load_data(WebKitWebFrame* frame, const gchar* content, const gchar* mimeType, const gchar* encoding, const gchar* baseURL, const gchar* unreachableURL) @@ -693,7 +694,7 @@ static void webkit_web_frame_load_data(WebKitWebFrame* frame, const gchar* conte KURL(KURL(), String::fromUTF8(unreachableURL)), KURL(KURL(), String::fromUTF8(unreachableURL))); - coreFrame->loader()->load(request, substituteData, false); + coreFrame->loader()->load(FrameLoadRequest(coreFrame, request, substituteData)); } /** @@ -762,7 +763,7 @@ void webkit_web_frame_load_request(WebKitWebFrame* frame, WebKitNetworkRequest* if (!coreFrame) return; - coreFrame->loader()->load(core(request), false); + coreFrame->loader()->load(FrameLoadRequest(coreFrame->document()->securityOrigin(), core(request))); } /** diff --git a/Source/WebKit/mac/Carbon/HIWebView.mm b/Source/WebKit/mac/Carbon/HIWebView.mm index 284dcea16..9235d11dd 100644 --- a/Source/WebKit/mac/Carbon/HIWebView.mm +++ b/Source/WebKit/mac/Carbon/HIWebView.mm @@ -36,7 +36,7 @@ #import "WebHTMLViewInternal.h" #import "WebKit.h" #import <WebKitSystemInterface.h> -#import <objc/objc-runtime.h> +#import <wtf/ObjcRuntimeExtras.h> @interface NSWindow (AppKitSecretsHIWebViewKnows) - (void)_removeWindowRef; @@ -1166,8 +1166,7 @@ UpdateCommandStatus( HIWebView* inView, const HICommand* inCommand ) // Can't use -performSelector:withObject: here because the method we're calling returns BOOL, while // -performSelector:withObject:'s return value is assumed to be an id. - BOOL (*validationFunction)(id, SEL, id) = (BOOL (*)(id, SEL, id))objc_msgSend; - if (validationFunction(resp, @selector(validateUserInterfaceItem:), proxy)) + if (wtfObjcMsgSend<BOOL>(resp, @selector(validateUserInterfaceItem:), proxy)) EnableMenuItem( inCommand->menu.menuRef, inCommand->menu.menuItemIndex ); else DisableMenuItem( inCommand->menu.menuRef, inCommand->menu.menuItemIndex ); diff --git a/Source/WebKit/mac/ChangeLog b/Source/WebKit/mac/ChangeLog index a1eafcd63..50e12ae99 100644 --- a/Source/WebKit/mac/ChangeLog +++ b/Source/WebKit/mac/ChangeLog @@ -1,3 +1,90 @@ +2012-11-28 Beth Dakin <bdakin@apple.com> + + https://bugs.webkit.org/show_bug.cgi?id=102970 + [WK1] REGRESSION (r129545): Main frame doesn't rubberband unless + WebFrameLoadDelegate implements -webView:didFirstLayoutInFrame: + + Reviewed by Sam Weinig. + + We should always register for DidFirstLayout in WK1 since we do work + at that time besides just calling the delegate function. + * WebView/WebView.mm: + (-[WebView _cacheFrameLoadDelegateImplementations]): + +2012-11-27 Michael Saboff <msaboff@apple.com> + + TextIterator unnecessarily converts 8 bit strings to 16 bits + https://bugs.webkit.org/show_bug.cgi?id=103295 + + Reviewed by Brent Fulgham. + + Updated _stringForRange to use plainText() instead of removed plainTextToMallocAllocatedBuffer(). + + * WebView/WebFrame.mm: + (-[WebFrame _stringForRange:]): + +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * Plugins/WebPluginController.mm: + * WebView/WebFrame.mm: + (-[WebFrame loadRequest:]): + (-[WebFrame _loadData:MIMEType:textEncodingName:baseURL:unreachableURL:]): + +2012-11-27 Pratik Solanki <psolanki@apple.com> + + objc/objc-runtime.h does not exist on all PLATFORM(MAC) + https://bugs.webkit.org/show_bug.cgi?id=101780 + + Reviewed by Brent Fulgham. + + Clean up header includes so we don't include objc/objc-runtime.h. + + * Carbon/HIWebView.mm: + (UpdateCommandStatus): Use wtfObjcMsgSend template instead of objc_msgSend. + * Plugins/WebNetscapePluginView.mm: + * Plugins/WebPluginContainerCheck.mm: + (-[WebPluginContainerCheck _continueWithPolicy:]): Use wtfObjcMsgSend template instead of objc_msgSend. + * Plugins/WebPluginController.mm: + * WebCoreSupport/WebCachedFramePlatformData.h: + * WebCoreSupport/WebDeviceOrientationClient.mm: + * WebView/WebDelegateImplementationCaching.mm: + * WebView/WebHTMLView.mm: + * WebView/WebPDFDocumentExtras.mm: + * WebView/WebPolicyDelegate.mm: + (-[WebPolicyDecisionListener _usePolicy:]): Use wtfObjcMsgSend template instead of objc_msgSend. + * WebView/WebView.mm: + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * Plugins/WebPluginController.mm: + * WebView/WebFrame.mm: + (-[WebFrame loadRequest:]): + (-[WebFrame _loadData:MIMEType:textEncodingName:baseURL:unreachableURL:]): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * Plugins/WebPluginController.mm: + * WebView/WebFrame.mm: + (-[WebFrame loadRequest:]): + (-[WebFrame _loadData:MIMEType:textEncodingName:baseURL:unreachableURL:]): + 2012-11-23 Alexis Menard <alexis@webkit.org> [CSS3 Backgrounds and Borders] Implement new CSS3 background-position parsing. diff --git a/Source/WebKit/mac/Plugins/WebNetscapePluginView.mm b/Source/WebKit/mac/Plugins/WebNetscapePluginView.mm index 6a1eb640a..1e1bd385b 100644 --- a/Source/WebKit/mac/Plugins/WebNetscapePluginView.mm +++ b/Source/WebKit/mac/Plugins/WebNetscapePluginView.mm @@ -77,7 +77,7 @@ #import <WebCore/npruntime_impl.h> #import <WebKit/DOMPrivate.h> #import <WebKit/WebUIDelegate.h> -#import <objc/objc-runtime.h> +#import <objc/runtime.h> #import <runtime/InitializeThreading.h> #import <runtime/JSLock.h> #import <wtf/Assertions.h> diff --git a/Source/WebKit/mac/Plugins/WebPluginContainerCheck.mm b/Source/WebKit/mac/Plugins/WebPluginContainerCheck.mm index 30368a879..67c93d2ae 100644 --- a/Source/WebKit/mac/Plugins/WebPluginContainerCheck.mm +++ b/Source/WebKit/mac/Plugins/WebPluginContainerCheck.mm @@ -42,7 +42,7 @@ #import <WebCore/FrameLoaderTypes.h> #import <WebCore/SecurityOrigin.h> #import <wtf/Assertions.h> -#import <objc/objc-runtime.h> +#import <wtf/ObjcRuntimeExtras.h> using namespace WebCore; @@ -87,9 +87,9 @@ using namespace WebCore; - (void)_continueWithPolicy:(PolicyAction)policy { if (_contextInfo) - ((void (*)(id, SEL, BOOL, id))objc_msgSend)(_resultObject, _resultSelector, (policy == PolicyUse), _contextInfo); + wtfObjcMsgSend<void>(_resultObject, _resultSelector, (policy == PolicyUse), _contextInfo); else - ((void (*)(id, SEL, BOOL))objc_msgSend)(_resultObject, _resultSelector, (policy == PolicyUse)); + wtfObjcMsgSend<void>(_resultObject, _resultSelector, (policy == PolicyUse)); // this will call indirectly call cancel [_controller _webPluginContainerCancelCheckIfAllowedToLoadRequest:self]; diff --git a/Source/WebKit/mac/Plugins/WebPluginController.mm b/Source/WebKit/mac/Plugins/WebPluginController.mm index 3ff109086..4c007e3db 100644 --- a/Source/WebKit/mac/Plugins/WebPluginController.mm +++ b/Source/WebKit/mac/Plugins/WebPluginController.mm @@ -50,6 +50,7 @@ #import <Foundation/NSURLRequest.h> #import <WebCore/DocumentLoader.h> #import <WebCore/Frame.h> +#import <WebCore/FrameLoadRequest.h> #import <WebCore/FrameLoader.h> #import <WebCore/HTMLMediaElement.h> #import <WebCore/HTMLNames.h> @@ -57,7 +58,7 @@ #import <WebCore/ResourceRequest.h> #import <WebCore/ScriptController.h> #import <WebCore/WebCoreURLResponse.h> -#import <objc/objc-runtime.h> +#import <objc/runtime.h> #import <runtime/JSLock.h> #import <wtf/text/WTFString.h> @@ -401,7 +402,10 @@ static void cancelOutstandingCheck(const void *item, void *context) LOG_ERROR("could not load URL %@", [request URL]); return; } - core(frame)->loader()->load(request, target, false); + FrameLoadRequest frameRequest(core(frame), request); + frameRequest.setFrameName(target); + frameRequest.setShouldCheckNewWindowPolicy(true); + core(frame)->loader()->load(frameRequest); } } diff --git a/Source/WebKit/mac/WebCoreSupport/WebCachedFramePlatformData.h b/Source/WebKit/mac/WebCoreSupport/WebCachedFramePlatformData.h index 9bdb51560..f7481b828 100644 --- a/Source/WebKit/mac/WebCoreSupport/WebCachedFramePlatformData.h +++ b/Source/WebKit/mac/WebCoreSupport/WebCachedFramePlatformData.h @@ -26,7 +26,6 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#import <objc/objc-runtime.h> #import <WebCore/CachedFramePlatformData.h> #import <wtf/ObjcRuntimeExtras.h> #import <wtf/RetainPtr.h> diff --git a/Source/WebKit/mac/WebCoreSupport/WebDeviceOrientationClient.mm b/Source/WebKit/mac/WebCoreSupport/WebDeviceOrientationClient.mm index 669c0c288..511cc10ea 100644 --- a/Source/WebKit/mac/WebCoreSupport/WebDeviceOrientationClient.mm +++ b/Source/WebKit/mac/WebCoreSupport/WebDeviceOrientationClient.mm @@ -28,7 +28,6 @@ #import "WebDeviceOrientationInternal.h" #import "WebDeviceOrientationProvider.h" #import "WebViewInternal.h" -#import <objc/objc-runtime.h> #import <wtf/ObjcRuntimeExtras.h> using namespace WebCore; diff --git a/Source/WebKit/mac/WebView/WebDelegateImplementationCaching.mm b/Source/WebKit/mac/WebView/WebDelegateImplementationCaching.mm index aac4cbfb0..6246a1d19 100644 --- a/Source/WebKit/mac/WebView/WebDelegateImplementationCaching.mm +++ b/Source/WebKit/mac/WebView/WebDelegateImplementationCaching.mm @@ -32,7 +32,6 @@ #import "WebKitLogging.h" #import "WebView.h" #import "WebViewData.h" -#import <objc/objc-runtime.h> #import <wtf/ObjcRuntimeExtras.h> @implementation WebView (WebDelegateImplementationCaching) diff --git a/Source/WebKit/mac/WebView/WebFrame.mm b/Source/WebKit/mac/WebView/WebFrame.mm index f91ffd8e5..89b9b8171 100644 --- a/Source/WebKit/mac/WebView/WebFrame.mm +++ b/Source/WebKit/mac/WebView/WebFrame.mm @@ -67,6 +67,7 @@ #import <WebCore/EventHandler.h> #import <WebCore/EventNames.h> #import <WebCore/Frame.h> +#import <WebCore/FrameLoadRequest.h> #import <WebCore/FrameLoader.h> #import <WebCore/FrameLoaderStateMachine.h> #import <WebCore/FrameTree.h> @@ -497,15 +498,7 @@ static inline WebDataSource *dataSource(DocumentLoader* loader) - (NSString *)_stringForRange:(DOMRange *)range { - // This will give a system malloc'd buffer that can be turned directly into an NSString - unsigned length; - UChar* buf = plainTextToMallocAllocatedBuffer(core(range), length, true); - - if (!buf) - return [NSString string]; - - // Transfer buffer ownership to NSString - return [[[NSString alloc] initWithCharactersNoCopy:buf length:length freeWhenDone:YES] autorelease]; + return plainText(core(range), TextIteratorDefaultBehavior, true); } - (BOOL)_shouldFlattenCompositingLayers:(CGContextRef)context @@ -1369,7 +1362,7 @@ static bool needsMicrosoftMessengerDOMDocumentWorkaround() if (!resourceRequest.url().isValid() && !resourceRequest.url().isEmpty()) resourceRequest.setURL([NSURL URLWithString:[@"file:" stringByAppendingString:[[request URL] absoluteString]]]); - coreFrame->loader()->load(resourceRequest, false); + coreFrame->loader()->load(FrameLoadRequest(coreFrame, resourceRequest)); } static NSURL *createUniqueWebDataURL() @@ -1400,7 +1393,7 @@ static NSURL *createUniqueWebDataURL() SubstituteData substituteData(WebCore::SharedBuffer::wrapNSData(data), MIMEType, encodingName, [unreachableURL absoluteURL], responseURL); - _private->coreFrame->loader()->load(request, substituteData, false); + _private->coreFrame->loader()->load(FrameLoadRequest(_private->coreFrame, request, substituteData)); } diff --git a/Source/WebKit/mac/WebView/WebHTMLView.mm b/Source/WebKit/mac/WebView/WebHTMLView.mm index 8f12e5bf0..9f759ad05 100644 --- a/Source/WebKit/mac/WebView/WebHTMLView.mm +++ b/Source/WebKit/mac/WebView/WebHTMLView.mm @@ -125,7 +125,6 @@ #import <WebKitSystemInterface.h> #import <dlfcn.h> #import <limits> -#import <objc/objc-runtime.h> #import <runtime/InitializeThreading.h> #import <wtf/MainThread.h> #import <wtf/ObjcRuntimeExtras.h> diff --git a/Source/WebKit/mac/WebView/WebPDFDocumentExtras.mm b/Source/WebKit/mac/WebView/WebPDFDocumentExtras.mm index 592edf75b..2cfd9b63c 100644 --- a/Source/WebKit/mac/WebView/WebPDFDocumentExtras.mm +++ b/Source/WebKit/mac/WebView/WebPDFDocumentExtras.mm @@ -29,7 +29,6 @@ #import <wtf/Vector.h> #import <wtf/RetainPtr.h> #import <PDFKit/PDFDocument.h> -#import <objc/objc-runtime.h> #if __MAC_OS_X_VERSION_MIN_REQUIRED == 1050 @interface PDFDocument (Internal) diff --git a/Source/WebKit/mac/WebView/WebPolicyDelegate.mm b/Source/WebKit/mac/WebView/WebPolicyDelegate.mm index f2df74429..409db69a3 100644 --- a/Source/WebKit/mac/WebView/WebPolicyDelegate.mm +++ b/Source/WebKit/mac/WebView/WebPolicyDelegate.mm @@ -29,7 +29,7 @@ #import "WebPolicyDelegatePrivate.h" #import <WebCore/FrameLoaderTypes.h> -#import <objc/objc-runtime.h> +#import <wtf/ObjcRuntimeExtras.h> using namespace WebCore; @@ -91,7 +91,7 @@ NSString *WebActionOriginalURLKey = @"WebActionOriginalURLKey"; - (void)_usePolicy:(PolicyAction)policy { if (_private->target) - ((void (*)(id, SEL, PolicyAction))objc_msgSend)(_private->target, _private->action, policy); + wtfObjcMsgSend<void>(_private->target, _private->action, policy); } - (void)_invalidate diff --git a/Source/WebKit/mac/WebView/WebView.mm b/Source/WebKit/mac/WebView/WebView.mm index fb444b4c1..1b17c67e4 100644 --- a/Source/WebKit/mac/WebView/WebView.mm +++ b/Source/WebKit/mac/WebView/WebView.mm @@ -181,7 +181,7 @@ #import <WebKitSystemInterface.h> #import <mach-o/dyld.h> #import <objc/objc-auto.h> -#import <objc/objc-runtime.h> +#import <objc/runtime.h> #import <runtime/ArrayPrototype.h> #import <runtime/DateInstance.h> #import <runtime/InitializeThreading.h> @@ -1686,9 +1686,7 @@ static inline IMP getMethod(id o, SEL s) // for backwards compatibility. Page* page = core(self); if (page) { - unsigned milestones = 0; - if (cache->didFirstLayoutInFrameFunc) - milestones |= DidFirstLayout; + unsigned milestones = DidFirstLayout; if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc) milestones |= DidFirstVisuallyNonEmptyLayout; page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones)); diff --git a/Source/WebKit/qt/Api/qwebframe.cpp b/Source/WebKit/qt/Api/qwebframe.cpp index 89474dd2e..3fa0e8b71 100644 --- a/Source/WebKit/qt/Api/qwebframe.cpp +++ b/Source/WebKit/qt/Api/qwebframe.cpp @@ -30,6 +30,7 @@ #include "Element.h" #include "FocusController.h" #include "Frame.h" +#include "FrameLoadRequest.h" #include "FrameLoaderClientQt.h" #include "FrameSelection.h" #include "FrameTree.h" @@ -828,7 +829,7 @@ void QWebFrame::setHtml(const QString &html, const QUrl &baseUrl) const QByteArray utf8 = html.toUtf8(); WTF::RefPtr<WebCore::SharedBuffer> data = WebCore::SharedBuffer::create(utf8.constData(), utf8.length()); WebCore::SubstituteData substituteData(data, WTF::String("text/html"), WTF::String("utf-8"), KURL()); - d->frame->loader()->load(request, substituteData, false); + d->frame->loader()->load(WebCore::FrameLoadRequest(d->frame, request, substituteData)); } /*! @@ -858,7 +859,7 @@ void QWebFrame::setContent(const QByteArray &data, const QString &mimeType, cons encoding = extractCharsetFromMediaType(mimeType); } WebCore::SubstituteData substituteData(buffer, WTF::String(actualMimeType), encoding, KURL()); - d->frame->loader()->load(request, substituteData, false); + d->frame->loader()->load(WebCore::FrameLoadRequest(d->frame, request, substituteData)); } /*! diff --git a/Source/WebKit/qt/ChangeLog b/Source/WebKit/qt/ChangeLog index f8ba65ff8..7ec8fbc3e 100644 --- a/Source/WebKit/qt/ChangeLog +++ b/Source/WebKit/qt/ChangeLog @@ -1,3 +1,81 @@ +2012-11-28 Huang Dongsung <luxtella@company100.net> + + [Texmap] REGRESSION(r135620) QtTestBrowser crashes on Google-gravity. + https://bugs.webkit.org/show_bug.cgi?id=103410 + + Reviewed by Noam Rosenthal. + + TextureMapperLayerClientQt::setTextureMapper() must call + flushCompositingStateForThisLayerOnly() of the root layer. + + Currently, PageClientQGraphicsWidget::setRootGraphicsLayer does not flush layer + states of the root layer after setting TextureMapper while + PageClientQWidget::setRootGraphicsLayer() flushes them of the root layer. If + not flushing states, descendant layers can not reach the root layer. It means + descendant layers can not reach the TextureMapper that the root layer has. + + This is already the behavior for PageClientQWidget, which should be the case + for PageClientQGraphicsWidget as well. + + * WebCoreSupport/PageClientQt.cpp: + (WebCore::TextureMapperLayerClientQt::setTextureMapper): + (WebCore::PageClientQWidget::setRootGraphicsLayer): + +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * Api/qwebframe.cpp: + (QWebFrame::QWebFrame): + (QWebFrame::load): + (QWebFrame::setHtml): + (QWebFrame::setContent): + * WebCoreSupport/DumpRenderTreeSupportQt.cpp: + (DumpRenderTreeSupportQt::setAlternateHtml): + (qt_dump_set_accepts_editing): + * WebCoreSupport/FrameLoaderClientQt.cpp: + (WebCore::FrameLoaderClientQt::callErrorPageExtension): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * Api/qwebframe.cpp: + (QWebFrame::setHtml): + (QWebFrame::setContent): + * WebCoreSupport/DumpRenderTreeSupportQt.cpp: + (DumpRenderTreeSupportQt::setAlternateHtml): + * WebCoreSupport/FrameLoaderClientQt.cpp: + (WebCore::FrameLoaderClientQt::callErrorPageExtension): + * WebCoreSupport/QWebFrameAdapter.cpp: + (QWebFrameAdapter::load): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * Api/qwebframe.cpp: + (QWebFrame::QWebFrame): + (QWebFrame::load): + (QWebFrame::setHtml): + (QWebFrame::setContent): + * WebCoreSupport/DumpRenderTreeSupportQt.cpp: + (DumpRenderTreeSupportQt::setAlternateHtml): + (qt_dump_set_accepts_editing): + * WebCoreSupport/FrameLoaderClientQt.cpp: + (WebCore::FrameLoaderClientQt::callErrorPageExtension): + 2012-11-26 Pierre Rossi <pierre.rossi@gmail.com> [Qt] REGRESSION(r135575): It made all tests assert diff --git a/Source/WebKit/qt/WebCoreSupport/DumpRenderTreeSupportQt.cpp b/Source/WebKit/qt/WebCoreSupport/DumpRenderTreeSupportQt.cpp index 8d08c4a10..9a3be3523 100644 --- a/Source/WebKit/qt/WebCoreSupport/DumpRenderTreeSupportQt.cpp +++ b/Source/WebKit/qt/WebCoreSupport/DumpRenderTreeSupportQt.cpp @@ -40,6 +40,7 @@ #include "Element.h" #include "FocusController.h" #include "Frame.h" +#include "FrameLoadRequest.h" #include "FrameLoaderClientQt.h" #include "FrameView.h" #include "GCController.h" @@ -926,7 +927,7 @@ void DumpRenderTreeSupportQt::setAlternateHtml(QWebFrameAdapter* adapter, const const QByteArray utf8 = html.toUtf8(); WTF::RefPtr<WebCore::SharedBuffer> data = WebCore::SharedBuffer::create(utf8.constData(), utf8.length()); WebCore::SubstituteData substituteData(data, WTF::String("text/html"), WTF::String("utf-8"), failingUrl); - coreFrame->loader()->load(request, substituteData, false); + coreFrame->loader()->load(WebCore::FrameLoadRequest(coreFrame, request, substituteData)); } void DumpRenderTreeSupportQt::confirmComposition(QWebPageAdapter *adapter, const char* text) diff --git a/Source/WebKit/qt/WebCoreSupport/FrameLoaderClientQt.cpp b/Source/WebKit/qt/WebCoreSupport/FrameLoaderClientQt.cpp index 7a23ee268..8028bf91e 100644 --- a/Source/WebKit/qt/WebCoreSupport/FrameLoaderClientQt.cpp +++ b/Source/WebKit/qt/WebCoreSupport/FrameLoaderClientQt.cpp @@ -37,6 +37,7 @@ #include "CSSPropertyNames.h" #include "DocumentLoader.h" #include "FormState.h" +#include "FrameLoadRequest.h" #include "FrameNetworkingContextQt.h" #include "FrameTree.h" #include "FrameView.h" @@ -1153,7 +1154,7 @@ bool FrameLoaderClientQt::callErrorPageExtension(const WebCore::ResourceError& e WebCore::ResourceRequest request(baseUrl); WTF::RefPtr<WebCore::SharedBuffer> buffer = WebCore::SharedBuffer::create(output.content.constData(), output.content.length()); WebCore::SubstituteData substituteData(buffer, output.contentType, output.encoding, failingUrl); - m_frame->loader()->load(request, substituteData, false); + m_frame->loader()->load(WebCore::FrameLoadRequest(m_frame, request, substituteData)); return true; } diff --git a/Source/WebKit/qt/WebCoreSupport/PageClientQt.cpp b/Source/WebKit/qt/WebCoreSupport/PageClientQt.cpp index 369307cba..d2b090af2 100644 --- a/Source/WebKit/qt/WebCoreSupport/PageClientQt.cpp +++ b/Source/WebKit/qt/WebCoreSupport/PageClientQt.cpp @@ -100,6 +100,7 @@ void TextureMapperLayerClientQt::setTextureMapper(const PassOwnPtr<TextureMapper { m_frame->d->textureMapper = textureMapper; m_frame->d->rootTextureMapperLayer->setTextureMapper(m_frame->d->textureMapper.get()); + syncRootLayer(); } TextureMapperLayerClientQt::~TextureMapperLayerClientQt() @@ -123,7 +124,6 @@ void PageClientQWidget::setRootGraphicsLayer(GraphicsLayer* layer) if (layer) { TextureMapperLayerClient = adoptPtr(new TextureMapperLayerClientQt(page->mainFrame(), layer)); TextureMapperLayerClient->setTextureMapper(TextureMapper::create()); - TextureMapperLayerClient->syncRootLayer(); return; } TextureMapperLayerClient.clear(); diff --git a/Source/WebKit/qt/WebCoreSupport/QWebFrameAdapter.cpp b/Source/WebKit/qt/WebCoreSupport/QWebFrameAdapter.cpp index e86413cf0..380b74954 100644 --- a/Source/WebKit/qt/WebCoreSupport/QWebFrameAdapter.cpp +++ b/Source/WebKit/qt/WebCoreSupport/QWebFrameAdapter.cpp @@ -22,6 +22,7 @@ #include "QWebFrameAdapter.h" #include "Frame.h" +#include "FrameLoadRequest.h" #include "FrameLoaderClientQt.h" #include "QWebPageAdapter.h" #if ENABLE(GESTURE_EVENTS) @@ -132,7 +133,7 @@ void QWebFrameAdapter::load(const QNetworkRequest& req, QNetworkAccessManager::O if (!body.isEmpty()) request.setHTTPBody(WebCore::FormData::create(body.constData(), body.size())); - frame->loader()->load(request, false); + frame->loader()->load(WebCore::FrameLoadRequest(frame, request)); if (frame->tree()->parent()) pageAdapter->insideOpenCall = false; diff --git a/Source/WebKit/win/ChangeLog b/Source/WebKit/win/ChangeLog index 2e40dad52..74d351c4e 100644 --- a/Source/WebKit/win/ChangeLog +++ b/Source/WebKit/win/ChangeLog @@ -1,3 +1,38 @@ +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * WebFrame.cpp: + (WebFrame::loadRequest): + (WebFrame::loadData): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * WebFrame.cpp: + (WebFrame::loadRequest): + (WebFrame::loadData): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * WebFrame.cpp: + (WebFrame::loadRequest): + (WebFrame::loadData): + 2012-11-21 Allan Sandfeld Jensen <allan.jensen@digia.com> Disambiguate innerNodeFramePoint and mainFramePoint diff --git a/Source/WebKit/win/WebFrame.cpp b/Source/WebKit/win/WebFrame.cpp index ee9cdd8c4..c859e6a25 100644 --- a/Source/WebKit/win/WebFrame.cpp +++ b/Source/WebKit/win/WebFrame.cpp @@ -556,7 +556,7 @@ HRESULT STDMETHODCALLTYPE WebFrame::loadRequest( if (!coreFrame) return E_FAIL; - coreFrame->loader()->load(requestImpl->resourceRequest(), false); + coreFrame->loader()->load(FrameLoadRequest(coreFrame, requestImpl->resourceRequest())); return S_OK; } @@ -580,7 +580,7 @@ void WebFrame::loadData(PassRefPtr<WebCore::SharedBuffer> data, BSTR mimeType, B // This method is only called from IWebFrame methods, so don't ASSERT that the Frame pointer isn't null. if (Frame* coreFrame = core(this)) - coreFrame->loader()->load(request, substituteData, false); + coreFrame->loader()->load(FrameLoadRequest(coreFrame, request, substituteData)); } diff --git a/Source/WebKit/wince/ChangeLog b/Source/WebKit/wince/ChangeLog index 0b1cae131..d46a6549d 100644 --- a/Source/WebKit/wince/ChangeLog +++ b/Source/WebKit/wince/ChangeLog @@ -1,3 +1,35 @@ +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * WebView.cpp: + (WebView::load): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * WebView.cpp: + (WebView::load): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * WebView.cpp: + (WebView::load): + 2012-11-20 Sheriff Bot <webkit.review.bot@gmail.com> Unreviewed, rolling out r135295. diff --git a/Source/WebKit/wince/WebView.cpp b/Source/WebKit/wince/WebView.cpp index fcc04d7db..9059a4022 100644 --- a/Source/WebKit/wince/WebView.cpp +++ b/Source/WebKit/wince/WebView.cpp @@ -32,6 +32,7 @@ #include "EditorClientWinCE.h" #include "FocusController.h" #include "Frame.h" +#include "FrameLoadRequest.h" #include "FrameLoader.h" #include "FrameLoaderClientWinCE.h" #include "FrameView.h" @@ -218,7 +219,7 @@ void WebView::load(const String &url) void WebView::load(const WebCore::ResourceRequest &request) { - frame()->loader()->load(request, false); + frame()->loader()->load(FrameLoadRequest(frame(), request)); } void WebView::reload() diff --git a/Source/WebKit/wx/ChangeLog b/Source/WebKit/wx/ChangeLog index 4c43edc8e..eb1d3763f 100644 --- a/Source/WebKit/wx/ChangeLog +++ b/Source/WebKit/wx/ChangeLog @@ -1,3 +1,35 @@ +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * WebFrame.cpp: + (WebKit::WebFrame::SetPageSource): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * WebFrame.cpp: + (WebKit::WebFrame::SetPageSource): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * WebFrame.cpp: + (WebKit::WebFrame::SetPageSource): + 2012-11-20 Sheriff Bot <webkit.review.bot@gmail.com> Unreviewed, rolling out r135295. diff --git a/Source/WebKit/wx/WebFrame.cpp b/Source/WebKit/wx/WebFrame.cpp index b374113c0..ccf54e38f 100644 --- a/Source/WebKit/wx/WebFrame.cpp +++ b/Source/WebKit/wx/WebFrame.cpp @@ -32,6 +32,7 @@ #include "FloatRect.h" #include "FormState.h" #include "Frame.h" +#include "FrameLoadRequest.h" #include "FrameLoader.h" #include "FrameLoaderClientWx.h" #include "FrameView.h" @@ -322,7 +323,7 @@ void WebFrame::SetPageSource(const wxString& source, const wxString& baseUrl, co WebCore::SubstituteData substituteData(sharedBuffer, mimetype, WTF::String("UTF-8"), WebCore::blankURL(), url); m_impl->frame->loader()->stop(); - m_impl->frame->loader()->load(WebCore::ResourceRequest(url), substituteData, false); + m_impl->frame->loader()->load(WebCore::FrameLoadRequest(m_impl->frame, WebCore::ResourceRequest(url), substituteData)); } } diff --git a/Source/WebKit2/ChangeLog b/Source/WebKit2/ChangeLog index bbe9d54db..b80559488 100644 --- a/Source/WebKit2/ChangeLog +++ b/Source/WebKit2/ChangeLog @@ -1,3 +1,1033 @@ +2012-11-28 Jocelyn Turcotte <jocelyn.turcotte@digia.com> + + [Qt] The WebView should be flickable only using touch events + https://bugs.webkit.org/show_bug.cgi?id=100964 + + Reviewed by Kenneth Rohde Christiansen. + + Let a user interacting with the WebView using a mouse the same way that a + desktop browser would. + This allows normal behaviors like text selecting, hover events, mouse cursors + as well as avoid touch highlighting and touch adjustment. + + To do so we let all mouse events to be handled by the page directly instead + of sending them to QtWebPageEventHandler. Since unhandled mouse events aren't + pushed back to the PageClient like touch events does, this have the intended + behavior of not letting mouse events affect QQuickFlickable. + + * UIProcess/API/qt/qquickwebview.cpp: + * UIProcess/API/qt/qquickwebview_p_p.h: + (QQuickWebViewFlickablePrivate): + +2012-11-29 Andras Becsi <andras.becsi@digia.com> + + [Qt] Fix installation of QtWebProcess binary + https://bugs.webkit.org/show_bug.cgi?id=101735 + + Reviewed by Simon Hausmann. + + If available use QLibraryInfo::LibraryExecutablesPath to find + the web process and the plugin process and deploy both helper + processes to QT_INSTALL_LIBEXECS. + + The effective fallback used to find the helper processes becomes: + 1. Application directory + 2. Qt library executables directory (QLibraryInfo::LibraryExecutablesPath) + 3. Qt binaries directory (QLibraryInfo::BinariesPath) + 4. No absolute path used + + * PluginProcess.pro: + * Shared/qt/ProcessExecutablePathQt.cpp: + (WebKit::executablePath): + * WebProcess.pro: + +2012-11-28 Ryuan Choi <ryuan.choi@gmail.com> + + [EFL] Generate big_button_theme.edj + https://bugs.webkit.org/show_bug.cgi?id=103511 + + Reviewed by Gyuyoung Kim. + + * UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.cpp: + (EWK2UnitTest::EWK2UnitTestEnvironment::pathForTheme): + (EWK2UnitTest): + * UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.h: + (EWK2UnitTestEnvironment): + * UIProcess/API/efl/tests/resources/big_button_theme.edj: Removed. + * UIProcess/API/efl/tests/test_ewk2_view.cpp: Modified to use generated big_button_theme.edj + (TEST_F): + +2012-11-28 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135973. + http://trac.webkit.org/changeset/135973 + https://bugs.webkit.org/show_bug.cgi?id=103604 + + It made API test crash on EFL bots (Requested by gyuyoung on + #webkit). + + * UIProcess/API/efl/ewk_view.cpp: + (createEwkView): + +2012-11-28 Michael Pruett <michael@68k.org> + + IndexedDB: Remove duplicate toWireString() and createFromWire() methods in JSC SerializedScriptValue + https://bugs.webkit.org/show_bug.cgi?id=103554 + + Reviewed by Kentaro Hara. + + In r135022, duplicate createFromWire() and toWireString() methods + were added to the JSC version of SerializedScriptValue. In + order to allow the JSC SerializedScriptValue to compile when + ENABLE(INDEXED_DATABASE) is turned on, these new methods have + been removed and the old methods have been moved outside the + ENABLE(INDEXED_DATABASE) guard. + + * win/WebKit2.def: + * win/WebKit2CFLite.def: + +2012-11-28 Sam Weinig <sam@webkit.org> + + Fix 32bit build. + + * Shared/mac/ObjCObjectGraphCoders.mm: + (WebKit::WebContextObjCObjectGraphDecoderImpl::decode): + (WebKit::InjectedBundleObjCObjectGraphDecoderImpl::decode): + +2012-11-28 Sam Weinig <sam@webkit.org> + + Add an objc object graph wrapper and coder for WKConnection message bodies + https://bugs.webkit.org/show_bug.cgi?id=103589 + + Reviewed by Anders Carlsson. + + Adds a new type of UserMessageCoder for objc object graphs that allows encoding/decoding + WKBrowsingContextController across the wire. + + * Shared/APIClient.h: + (APIClient): + (WebKit::APIClient::client): + Add accessor for the ClientInterface. + + * Shared/APIObject.h: + Add new TypeObjCObjectGraph type. + + * Shared/mac/ObjCObjectGraph.h: Added. + (ObjCObjectGraph): + (WebKit::ObjCObjectGraph::create): + (WebKit::ObjCObjectGraph::root): + (WebKit::ObjCObjectGraph::ObjCObjectGraph): + (WebKit::ObjCObjectGraph::type): + * Shared/mac/ObjCObjectGraph.mm: Added. + Wraps + + * Shared/mac/ObjCObjectGraphCoders.h: Added. + (WebContextObjCObjectGraphEncoder): + (WebContextObjCObjectGraphDecoder): + (InjectedBundleObjCObjectGraphEncoder): + (InjectedBundleObjCObjectGraphDecoder): + * Shared/mac/ObjCObjectGraphCoders.mm: Added. + (WebKit::typeFromObject): + (ObjCObjectGraphEncoder): + (WebKit::ObjCObjectGraphEncoder::baseEncode): + (WebKit::ObjCObjectGraphEncoder::ObjCObjectGraphEncoder): + (ObjCObjectGraphDecoder): + (WebKit::ObjCObjectGraphDecoder::baseDecode): + (WebKit::ObjCObjectGraphDecoder::ObjCObjectGraphDecoder): + (WebContextObjCObjectGraphEncoderImpl): + (WebKit::WebContextObjCObjectGraphEncoderImpl::WebContextObjCObjectGraphEncoderImpl): + (WebKit::WebContextObjCObjectGraphEncoderImpl::encode): + (WebContextObjCObjectGraphDecoderImpl): + (WebKit::WebContextObjCObjectGraphDecoderImpl::WebContextObjCObjectGraphDecoderImpl): + (WebKit::WebContextObjCObjectGraphDecoderImpl::decode): + (InjectedBundleObjCObjectGraphEncoderImpl): + (WebKit::InjectedBundleObjCObjectGraphEncoderImpl::InjectedBundleObjCObjectGraphEncoderImpl): + (WebKit::InjectedBundleObjCObjectGraphEncoderImpl::encode): + (InjectedBundleObjCObjectGraphDecoderImpl): + (WebKit::InjectedBundleObjCObjectGraphDecoderImpl::InjectedBundleObjCObjectGraphDecoderImpl): + (WebKit::InjectedBundleObjCObjectGraphDecoderImpl::decode): + (WebKit::WebContextObjCObjectGraphEncoder::WebContextObjCObjectGraphEncoder): + (WebKit::WebContextObjCObjectGraphEncoder::encode): + (WebKit::WebContextObjCObjectGraphDecoder::WebContextObjCObjectGraphDecoder): + (WebKit::WebContextObjCObjectGraphDecoder::decode): + (WebKit::InjectedBundleObjCObjectGraphEncoder::InjectedBundleObjCObjectGraphEncoder): + (WebKit::InjectedBundleObjCObjectGraphEncoder::encode): + (WebKit::InjectedBundleObjCObjectGraphDecoder::InjectedBundleObjCObjectGraphDecoder): + (WebKit::InjectedBundleObjCObjectGraphDecoder::decode): + Added. + + * UIProcess/API/mac/WKBrowsingContextController.mm: + (+[WKBrowsingContextController _browsingContextControllerForPageRef:]): + * UIProcess/API/mac/WKBrowsingContextControllerInternal.h: + Expose the accessor to get the WKPageRef from a WKBrowsingContextController and add a + new method to get a WKBrowsingContextController from a WKPageRef. + + * UIProcess/API/mac/WKConnection.mm: + (-[WKConnection sendMessageWithName:body:]): + (didReceiveMessage): + Switch WKConnection to use ObjCObjectGraph to encode the messageBody. + + * UIProcess/WebContextUserMessageCoders.h: + (WebKit::WebContextUserMessageEncoder::encode): + (WebKit::WebContextUserMessageDecoder::decode): + * WebProcess/InjectedBundle/InjectedBundleUserMessageCoders.h: + (WebKit::InjectedBundleUserMessageEncoder::encode): + (WebKit::InjectedBundleUserMessageDecoder::decode): + Proxy to ObjCObjectGraph coders when user message encoding/decoding ObjCObjectGraph APIObjects. + + * WebProcess/InjectedBundle/API/mac/WKWebProcessPlugIn.mm: + (-[WKWebProcessPlugInController _browserContextControllerForBundlePageRef:]): + * WebProcess/InjectedBundle/API/mac/WKWebProcessPlugInInternal.h: + Add method to get WKWebProcessPlugInController from the WKBundlePageRef. + + * WebKit2.xcodeproj/project.pbxproj: + Add new files. + +2012-11-28 Sergio Villar Senin <svillar@igalia.com> + + [WK2][Qt] Add drag&drop support to Flickable webView + https://bugs.webkit.org/show_bug.cgi?id=100778 + + Reviewed by Jocelyn Turcotte. + + Enable the ItemAcceptsDrops flag in the flickable WebView. This + will allow the WebView to receive drag&drop events. + + * UIProcess/API/qt/qquickwebview.cpp: + (QQuickWebViewPrivate::initialize): + +2012-11-28 Shinya Kawanaka <shinyak@chromium.org> + + [Shadow] Move Distribution stuffs from ShadowRoot + https://bugs.webkit.org/show_bug.cgi?id=103481 + + Reviewed by Hajime Morita. + + * win/WebKit2.def: + * win/WebKit2CFLite.def: + +2012-11-28 Tim Horton <timothy_horton@apple.com> + + [mac] Dictionary lookup bubble loses intrarange formatting + https://bugs.webkit.org/show_bug.cgi?id=103496 + <rdar://problem/12762172> + + Reviewed by Alexey Proskuryakov. + + Pass an NSAttributedString (made via WebHTMLConverter on the WebProcess side) through + when showing dictionary popups, so that we preserve more formatting in the yellow dictionary + highlight. Also, remove the fontInfo member from DictionaryPopupInfo, since we don't need it anymore. + + * Shared/DictionaryPopupInfo.cpp: + (WebKit::DictionaryPopupInfo::encode): Don't encode the now-removed fontInfo member. + (WebKit::DictionaryPopupInfo::decode): Don't decode the now-removed fontInfo member. + * Shared/DictionaryPopupInfo.h: Remove the fontInfo member. + * UIProcess/API/mac/PageClientImpl.h: + (PageClientImpl): didPerformDictionaryLookup should take an AttributedString instead of a plain String, and + no longer needs to take the page scale factor. + * UIProcess/API/mac/PageClientImpl.mm: + (WebKit::PageClientImpl::didPerformDictionaryLookup): Use the AttributedString we're handed from the WebProcess + instead of constructing one ourselves; this way, we have all the attributes instead of just a single font. + * UIProcess/PageClient.h: + (PageClient): didPerformDictionaryLookup should take an AttributedString instead of a plain String. + * UIProcess/WebPageProxy.h: + (WebPageProxy): didPerformDictionaryLookup should take an AttributedString instead of a plain String. + * UIProcess/WebPageProxy.messages.in: DidPerformDictionaryLookup should take an AttributedString instead of a plain String. + * UIProcess/mac/WebPageProxyMac.mm: + (WebKit::WebPageProxy::didPerformDictionaryLookup): didPerformDictionaryLookup should take an AttributedString instead of a plain String. + * WebProcess/WebPage/mac/WebPageMac.mm: + (WebKit::WebPage::performDictionaryLookupForRange): performDictionaryLookupForRange should hand WebPageProxy an AttributedString + constructed via WebHTMLConverter instead of a plain text string paired with a single font descriptor. + Also, scale the size of every font attribute by the current pageScaleFactor. + +2012-11-28 peavo@outlook.com <peavo@outlook.com> + + [WinCairo] Crash when requesting favicon. + https://bugs.webkit.org/show_bug.cgi?id=102689 + + Reviewed by Brent Fulgham. + + * win/WebKit2CFLite.def: Link fixes. + * win/WebKit2.def: Link fixes. + +2012-11-28 Christophe Dumez <christophe.dumez@intel.com> + + Regression(r135962): m_pendingSyncBackingStores needs to be cleared in LayerTreeRenderer::purgeGLResources() + https://bugs.webkit.org/show_bug.cgi?id=103527 + + Reviewed by Jocelyn Turcotte. + + Make sure m_pendingSyncBackingStores is cleared in + LayerTreeRenderer::purgeGLResources() to avoid trying to assign + backing store to layers after everything has been invalidated. + + * UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp: + (WebKit::LayerTreeRenderer::purgeGLResources): + +2012-11-28 Christophe Dumez <christophe.dumez@intel.com> + + Regression(r135962): ASSERTION FAILED: !m_pedningSyncBackingStores.contains(layer) + https://bugs.webkit.org/show_bug.cgi?id=103498 + + Reviewed by Kenneth Rohde Christiansen. + + We hit the !m_pedningSyncBackingStores.contains(layer) assertion + in LayerTreeRenderer when 2 asynchronous backing store operations + are pending. The current code checks if the layer already has a + backing store in its guard but this is insufficient as it is not + checking the m_pendingSyncBackingStores hash for pending backing + store changes. + + In this patch, we improve the guards in createBackingStoreIfNeeded() + and removeBackingStoreIfNeeded() to check not only if the layer has + already a backing store but also check m_pendingSyncBackingStores + for pending changes. This is safer and it allows for optimizations + in the cases where we have both a removal and a creation pending. + In those cases, we can simply cancel the pending operation instead + of queueing a new one. + + * UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp: + (WebKit::LayerTreeRenderer::getBackingStore): + (WebKit::LayerTreeRenderer::createBackingStoreIfNeeded): + (WebKit::LayerTreeRenderer::removeBackingStoreIfNeeded): + (WebKit::LayerTreeRenderer::commitPendingBackingStoreOperations): + * UIProcess/CoordinatedGraphics/LayerTreeRenderer.h: + +2012-11-28 Kenneth Rohde Christiansen <kenneth@webkit.org> + + [EFL][WK2] MiniBrowser rendering should not get blurry when scrolled down with different scale values + https://bugs.webkit.org/show_bug.cgi?id=103079 + + Reviewed by Simon Hausmann. + + The problem was caused because we moved the page inside our viewport + in non-discrete units. + + Now instead of changing the content visible in our viewport by + applying scale, and then transforming the CSS offset, we now first + discretely position the page in UI coordinates. + + This patch also removes some dead code. + + * UIProcess/API/efl/EwkViewImpl.cpp: + (EwkViewImpl::transformFromScene): + (EwkViewImpl::displayTimerFired): + + Transform according to the page position. + + * UIProcess/API/efl/EwkViewImpl.h: + (EwkViewImpl::setPagePosition): Now stores a float. + (EwkViewImpl::discretePagePosition): Returns the discrete page position. + (EwkViewImpl): + * UIProcess/efl/PageClientLegacyImpl.cpp: + (WebKit::PageClientLegacyImpl::updateViewportSize): + (WebKit::PageClientLegacyImpl::pageDidRequestScroll): + * UIProcess/efl/PageViewportControllerClientEfl.cpp: + (WebKit::PageViewportControllerClientEfl::PageViewportControllerClientEfl): + (WebKit::PageViewportControllerClientEfl::setViewportPosition): Convert to page position. + (WebKit::PageViewportControllerClientEfl::setContentsScale): + (WebKit::PageViewportControllerClientEfl::didResumeContent): + * UIProcess/efl/PageViewportControllerClientEfl.h: + (WebKit::PageViewportControllerClientEfl::scaleFactor): Use the value + from the view directly. + (WebKit::PageViewportControllerClientEfl::contentPosition): + (PageViewportControllerClientEfl): + +2012-11-28 Mikhail Pozdnyakov <mikhail.pozdnyakov@intel.com> + + [EFL][WK2][AC] No need to export GL properties from EwkViewImpl class + https://bugs.webkit.org/show_bug.cgi?id=103505 + + Reviewed by Kenneth Rohde Christiansen. + + No need to export GL data members from EwkViewImpl class, + those are internal implementation objects not used by anyone outside the class. + + * UIProcess/API/efl/EwkViewImpl.cpp: + (EwkViewImpl::displayTimerFired): + (EwkViewImpl::createGLSurface): + * UIProcess/API/efl/EwkViewImpl.h: + (EwkViewImpl): + (EwkViewImpl::evasGLContext): + (EwkViewImpl::evasGLSurface): + +2012-11-28 Joone Hur <joone.hur@intel.com> + + [EFL][WK2][AC] Clear the viewport with white color + https://bugs.webkit.org/show_bug.cgi?id=103495 + + When initializing a GL surface, we should clear the buffer with white color. + + Reviewed by Kenneth Rohde Christiansen. + + * UIProcess/API/efl/EwkViewImpl.cpp: + (EwkViewImpl::createGLSurface): + +2012-11-27 Jinwoo Song <jinwoo7.song@samsung.com> + + [EFL][WK2] Duplicated WebPageGroup initialization + https://bugs.webkit.org/show_bug.cgi?id=103229 + + Reviewed by Gyuyoung Kim. + + WebPageGroup does not need to be created in creating EwkView when the pageGroupRef is 0 + because the default WebPageGroup(m_defaultPageGroup) is created in WebContext constructor. + + As a side effect on the duplicated initialization, pageGroupID increases even when the EwkView + is created with default context. + + * UIProcess/API/efl/ewk_view.cpp: + (createEwkView): + +2012-11-27 Huang Dongsung <luxtella@company100.net> + + REGRESSION(r135620): ASSERT(m_state.drawsContent && m_state.contentsVisible && !m_size.isEmpty()) hits in TextureMapperLayer::paintSelf(). + https://bugs.webkit.org/show_bug.cgi?id=103171 + + Reviewed by Noam Rosenthal. + + Ensure that TextureMapperLayer has a backing store when the layer has + drawsContent and contentsVisible properties and the size of the layer is not + empty. + + LayerTreeRenderer::setLayerState() must not set a backing store to + TextureMapperLayer because setLayerState() just changes states of + GraphicsLayerTextureMapper instead of TextureMapperLayer. + + Now LayerTreeRenderer::flushLayerChanges() sets a backing store as well as layer + states to TextureMapperLayer. + + * UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp: + (WebKit::LayerTreeRenderer::getBackingStore): + (WebKit::LayerTreeRenderer::prepareContentBackingStore): + (WebKit::LayerTreeRenderer::createBackingStoreIfNeeded): + (WebKit::LayerTreeRenderer::removeBackingStoreIfNeeded): + (WebKit::LayerTreeRenderer::commitPendingBackingStoreOperations): + (WebKit::LayerTreeRenderer::flushLayerChanges): + * UIProcess/CoordinatedGraphics/LayerTreeRenderer.h: + (WebCore): + +2012-11-27 Tim Horton <timothy_horton@apple.com> + + PDFPlugin: Should not be able to edit read-only text annotations + https://bugs.webkit.org/show_bug.cgi?id=103387 + <rdar://problem/12752313> + + Reviewed by Alexey Proskuryakov. + + Don't allow read-only annotations to become active. + + * WebKit2.xcodeproj/project.pbxproj: Add PDFAnnotationTextWidgetDetails.h. + * WebProcess/Plugins/PDF/PDFAnnotationTextWidgetDetails.h: Added. + * WebProcess/Plugins/PDF/PDFPlugin.mm: + (WebKit::PDFPlugin::setActiveAnnotation): Bail if the annotation is read-only. + * WebProcess/Plugins/PDF/PDFPluginTextAnnotation.mm: Move PDFAnnotationTextWidget details category to PDFAnnotationTextWidgetDetails.h + +2012-11-27 Huang Dongsung <luxtella@company100.net> + + Coordinated Graphics: Refactor code managing a backing store in LayerTreeRenderer. + https://bugs.webkit.org/show_bug.cgi?id=103298 + + Reviewed by Noam Rosenthal. + + This patch makes LayerTreeRenderer assign a content backing store to + TextureMapperLayer only in setLayerState(). Currently, createTile() can assign + the backing store to TextureMapperLayer and it can break the invariant condition + of TextureMapperLayer: TextureMapperLayer can have its own backing store only if + the layer has following conditions: drawsContent, contentsVisible and non empty + size. + + In addition, the modified code about creating and removing a backing store + matches the same purpose code of CoordinatedGraphicsLayer and + GraphicsLayerTextureMapepr. + + * UIProcess/CoordinatedGraphics/CoordinatedBackingStore.cpp: + * UIProcess/CoordinatedGraphics/CoordinatedBackingStore.h: + (CoordinatedBackingStore): + * UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp: + (WebKit::layerShouldHaveBackingStore): + (WebKit): + (WebKit::LayerTreeRenderer::setLayerState): + (WebKit::LayerTreeRenderer::getBackingStore): + (WebKit::LayerTreeRenderer::prepareContentBackingStore): + (WebKit::LayerTreeRenderer::createBackingStoreIfNeeded): + (WebKit::LayerTreeRenderer::removeBackingStore): + (WebKit::LayerTreeRenderer::resetBackingStoreSizeToLayerSize): + (WebKit::LayerTreeRenderer::createTile): + (WebKit::LayerTreeRenderer::removeTile): + (WebKit::LayerTreeRenderer::updateTile): + * UIProcess/CoordinatedGraphics/LayerTreeRenderer.h: + * WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.cpp: + (WebCore::CoordinatedGraphicsLayer::adjustContentsScale): + This method does not create a backing store anymore because flushCompositingStateForThisLayerOnly() + can create a backing store if needed. Moreover, we must sync a layer state prior to creating a backing store + after this patch, because LayerTreeRenderer::createTile() does not create a backing store anymore. + +2012-11-27 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * WebProcess/Plugins/PluginView.cpp: + (WebKit::PluginView::performFrameLoadURLRequest): + * WebProcess/WebPage/WebPage.cpp: + (WebKit::WebPage::loadURLRequest): + (WebKit::WebPage::loadData): + +2012-10-22 Jer Noble <jer.noble@apple.com> + + [WK2] [Mac] WebKit Full Screen API should use NSWindow full screen API. + https://bugs.webkit.org/show_bug.cgi?id=100025 + + Reviewed by Dan Bernstein. + + Use the NSWindow full screen API when taking the WebView full screen. To facility the case where the browser window is already + in full screen mode, no longer hide the browser window when entering full screen. Instead, provide a placeholder view with + instructions to click the placeholder to exit full screen. + + * UIProcess/mac/WKFullScreenWindowController.h: + * UIProcess/mac/WKFullScreenWindowController.mm: + (-[WKFullScreenWindowController init]): Set self as the window's delegate; enable window's full screen action. + (-[WKFullScreenWindowController dealloc]): Clear our window's delegate. + (-[WKFullScreenWindowController applicationDidChangeScreenParameters:]): Remove reference to _updateWindowAndDockForFullScreen. + (-[WKFullScreenWindowController enterFullScreen:]): Ditto. Create a WKFullScreenPlaceholderView instead of generic NSImageView. + (-[WKFullScreenWindowController beganEnterFullScreenWithInitialFrame:finalFrame:]): Ditto. Call NSWindow enterFullScreen: API. + (-[WKFullScreenWindowController finishedEnterFullScreenAnimation:]): Show the warning view. + (-[WKFullScreenWindowController exitFullScreen]): Hide the warning view. + (-[WKFullScreenWindowController beganExitFullScreenWithInitialFrame:finalFrame:]): Add special case where we are exiting + from full screen mode when the full screen window is not on screen. + (-[WKFullScreenWindowController finishedExitFullScreenAnimation:]): Remove reference to _updateMenuAndDockForFullScreen. + (-[WKFullScreenWindowController customWindowsToEnterFullScreenForWindow:]): Added. Return the background window and the full screen window. + (-[WKFullScreenWindowController customWindowsToExitFullScreenForWindow:]): Ditto. + (-[WKFullScreenWindowController window:startCustomAnimationToEnterFullScreenWithDuration:]): Added. Call through to _startEnterFullScreenAnimationWithDuration: + (-[WKFullScreenWindowController window:startCustomAnimationToExitFullScreenWithDuration:]): Added. Call through to _startExitFullScreenAnimationWithDuration: + +2012-11-27 Yael Aharon <yael.aharon@intel.com> + + [EFL][WK2] 3D pixel tests are failing + https://bugs.webkit.org/show_bug.cgi?id=102833 + + Reviewed by Kenneth Rohde Christiansen. + + Added an API for generating a snapshot, to be used from WebKitTestRunner. + + * PlatformEfl.cmake: + * UIProcess/API/C/efl/WKView.cpp: + (WKViewGetSnapshot): + * UIProcess/API/C/efl/WKView.h: + * UIProcess/API/efl/EwkViewImpl.cpp: + (EwkViewImpl::onFaviconChanged): + (EwkViewImpl::takeSnapshot): + * UIProcess/API/efl/EwkViewImpl.h: + (EwkViewImpl): + * UIProcess/API/efl/SnapshotImageGL.cpp: Added. + (getImageFromCurrentTexture): + * UIProcess/API/efl/SnapshotImageGL.h: Added. + +2012-11-27 Tim Horton <timothy_horton@apple.com> + + PDFPlugin: Page scale factor should affect subframe PDFs + https://bugs.webkit.org/show_bug.cgi?id=103291 + <rdar://problem/12555249> + + Reviewed by Darin Adler. + + For subframe PDFs, hand PDFKit the pageScaleFactor for the parent page + so it can scale its drawing appropriately. + + * WebProcess/Plugins/PDF/PDFPlugin.h: Add updatePageAndDeviceScaleFactors. + * WebProcess/Plugins/PDF/PDFPlugin.mm: + (WebKit::PDFPlugin::pdfDocumentDidLoad): Call updatePageAndDeviceScaleFactors + instead of manually updating PDFLayerController's device scale factor. + (WebKit::PDFPlugin::updatePageAndDeviceScaleFactors): Hand PDFLayerController + the "underlying" (non-zoom) content scale, which is the product of the + device scale and the page scale. + (WebKit::PDFPlugin::contentsScaleFactorChanged): Use updatePageAndDeviceScaleFactors. + (WebKit::PDFPlugin::geometryDidChange): Use updatePageAndDeviceScaleFactors to keep + PDFLayerController's notion of the page scale up to date when the plugin's + geometry changes. + +2012-11-27 Tim Horton <timothy_horton@apple.com> + + PDFPlugin: Scroll bars do not grow on hover + https://bugs.webkit.org/show_bug.cgi?id=103382 + <rdar://problem/12555262> + + Reviewed by Beth Dakin. + + PDFPlugin needs to forward relevant mouse events to the scrollbars. + In addition, it needs to implement currentMousePosition so ScrollableArea and friends + can find the mouse position at arbitrary times. + + I also took this opportunity to factor some coordinate space conversion functions out. + + * WebProcess/Plugins/PDF/PDFPlugin.h: + (WebKit::PDFPlugin::currentMousePosition): Added. Return the last mouse position in our coordinate space. + (WebKit::PDFPlugin::convertFromRootViewToPlugin): Added. + (WebKit::PDFPlugin::convertFromPluginToPDFView): Added. + (PDFPlugin): + * WebProcess/Plugins/PDF/PDFPlugin.mm: + (WebKit::PDFPlugin::convertFromRootViewToPlugin): Convert a point from content space to plugin space, via the transform we get in geometryDidChange. + (WebKit::PDFPlugin::convertFromPluginToPDFView): Convert a point from plugin space to PDFLayerController's flipped coordinate space. + (WebKit::PDFPlugin::geometryDidChange): Use convertFromPluginToPDFView. + (WebKit::PDFPlugin::nsEventForWebMouseEvent): Cache the mouse position in plugin space instead of PDFLayerController space. Use our new conversion functions. + (WebKit::PDFPlugin::handleMouseEvent): Forward relevant mouse events to scrollbars: + Determine which scrollbar the mouse is over now, and which it was previously over, and use that to: + If the mouse is moved over a scrollbar, send mouseEntered to the scrollbar. + If the mouse is moved out of a scrollbar, send mouseExited to the scrollbar. + If the mouse is currently over a scrollbar, send mouseMoved/Up/Down to the scrollbar instead of PDFLayerController. + If the mouse is currently over the scroll corner, bail, because nobody should get those events. + +2012-11-27 Dan Bernstein <mitz@apple.com> + + Entering Tab View after a bunch of YouTube pages were opened in background tabs makes all of them start playing simultaneously + https://bugs.webkit.org/show_bug.cgi?id=103358 + + Reviewed by Adele Peterson. + + To fix this, this patch adds WKPageSetMayStartMediaWhenInWindow(), which allows the client to + prevent media from starting automatically when the view is put in a window. + + * Shared/WebPageCreationParameters.cpp: + (WebKit::WebPageCreationParameters::encode): Encode mayStartMediaWhenInWindow. + (WebKit::WebPageCreationParameters::decode): Decode mayStartMediaWhenInWindow. + * Shared/WebPageCreationParameters.h: + (WebPageCreationParameters): Added boolean member mayStartMediaWhenInWindow. + * UIProcess/API/C/WKPage.cpp: + (WKPageSetMayStartMediaWhenInWindow): Added. Calls through to WebPageProxy. + * UIProcess/API/C/WKPagePrivate.h: Declared WKPageSetMayStartMediaWhenInWindow. + * UIProcess/WebPageProxy.cpp: + (WebKit::WebPageProxy::WebPageProxy): Added initializiation of m_mayStartMediaWhenInWindow + to true, the value matching the current behavior. + (WebKit::WebPageProxy::setMayStartMediaWhenInWindow): Added. Updates + m_mayStartMediaWhenInWindow and sends a message to the Web process to do the same. + (WebKit::WebPageProxy::creationParameters): Changed to set mayStartMediaWhenInWindow in the + process creation parameters. + * UIProcess/WebPageProxy.h: + (WebPageProxy): Declared setMayStartMediaWhenInWindow() and added member variable + m_mayStartMediaWhenInWindow. + * WebProcess/WebPage/WebPage.cpp: + (WebKit::WebPage::WebPage): Initialized m_mayStartMediaWhenInWindow from the creation + parameters. + (WebKit::WebPage::setIsInWindow): Made starting of media upon being added to a window + conditional on m_mayStartMediaWhenInWindow. + (WebKit::WebPage::setMayStartMediaWhenInWindow): Added. Sets m_mayStartMediaWhenInWindow. If + already in a window when changing from false to true, starts m_setCanStartMediaTimer. + * WebProcess/WebPage/WebPage.h: + (WebPage): Declared setMayStartMediaWhenInWindow() and added member variable m_mayStartMediaWhenInWindow. + * WebProcess/WebPage/WebPage.messages.in: Added SetMayStartMediaWhenInWindow. + +2012-11-27 Pratik Solanki <psolanki@apple.com> + + objc/objc-runtime.h does not exist on all PLATFORM(MAC) + https://bugs.webkit.org/show_bug.cgi?id=101780 + + Reviewed by Brent Fulgham. + + Clean up header includes so we don't include objc/objc-runtime.h. + + * PluginProcess/mac/PluginProcessShim.mm: + * UIProcess/API/mac/PDFViewController.mm: + +2012-11-27 Alexey Proskuryakov <ap@apple.com> + + [WK2] WebPageProxy::relatedPages() cannot assume that this page is known to process + https://bugs.webkit.org/show_bug.cgi?id=103433 + <rdar://problem/12543513> + + Reviewed by Jessie Berlin. + + * UIProcess/WebPageProxy.cpp: (WebKit::WebPageProxy::relatedPages): Removed an incorrect + assertion, and modified code to not rely on its condition being true. + +2012-11-27 Mikhail Pozdnyakov <mikhail.pozdnyakov@intel.com> + + [EFL][Qt][WK2] Tiles not always painted + https://bugs.webkit.org/show_bug.cgi?id=103271 + + Reviewed by Kenneth Rohde Christiansen. + + The problem turned up because visible content was synchromized before the new fixed + layout size had been applied in the web process. + + * UIProcess/PageViewportController.cpp: + (WebKit::PageViewportController::didChangeViewportSize): + (WebKit::PageViewportController::didChangeViewportAttributes): + +2012-11-27 Yael Aharon <yael.aharon@intel.com> + + [EFL] Graphics layer edges are sometimes very pixelated + https://bugs.webkit.org/show_bug.cgi?id=103302 + + Reviewed by Kenneth Rohde Christiansen. + + The call setEnableEdgeDistanceAntialiasing(true) was lost in the refactoring of + http://trac.webkit.org/changeset/135401. + + * UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp: + (WebKit::LayerTreeRenderer::paintToCurrentGLContext): + +2012-11-27 KwangYong Choi <ky0.choi@samsung.com> + + [X11] Allow empty plugin name and description during scan plugin + https://bugs.webkit.org/show_bug.cgi?id=103234 + + Reviewed by Simon Hausmann. + + Empty entries should be allowed when split the output string of scan plugin + because the plugin name and the description can be empty string. + + * UIProcess/Plugins/qt/PluginProcessProxyQt.cpp: + (WebKit::PluginProcessProxy::scanPlugin): + * UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp: + (WebKit::PluginProcessProxy::scanPlugin): + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135819. + http://trac.webkit.org/changeset/135819 + https://bugs.webkit.org/show_bug.cgi?id=103388 + + It broke many tests on Qt and EFL WK2 platforms (Requested by + Ossy on #webkit). + + * Shared/WebPageCreationParameters.cpp: + (WebKit::WebPageCreationParameters::encode): + (WebKit::WebPageCreationParameters::decode): + * Shared/WebPageCreationParameters.h: + (WebPageCreationParameters): + * UIProcess/API/C/WKPage.cpp: + (WKPageCopyRelatedPages): + * UIProcess/API/C/WKPagePrivate.h: + * UIProcess/WebPageProxy.cpp: + (WebKit::WebPageProxy::WebPageProxy): + (WebKit::WebPageProxy::creationParameters): + * UIProcess/WebPageProxy.h: + (WebPageProxy): + * WebProcess/WebPage/WebPage.cpp: + (WebKit::WebPage::WebPage): + (WebKit::WebPage::setIsInWindow): + * WebProcess/WebPage/WebPage.h: + (WebPage): + * WebProcess/WebPage/WebPage.messages.in: + +2012-11-27 Kyungjin Kim <gen.kim@samsung.com> + + [WK2] Expose Accelerated2dCanvas flag set and get in WebKit2 + https://bugs.webkit.org/show_bug.cgi?id=103008 + + Reviewed by Gyuyoung Kim. + + Fix API names in WKPreferences from 2d to 2D. + + * UIProcess/API/C/WKPreferences.cpp: + (WKPreferencesSetAccelerated2DCanvasEnabled): + (WKPreferencesGetAccelerated2DCanvasEnabled): + * UIProcess/API/C/WKPreferencesPrivate.h: + +2012-11-27 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135786. + http://trac.webkit.org/changeset/135786 + https://bugs.webkit.org/show_bug.cgi?id=103379 + + It made 3 plugin tests timeout on several platforms (Requested + by Ossy on #webkit). + + * WebProcess/Plugins/PluginView.cpp: + (WebKit::PluginView::performFrameLoadURLRequest): + * WebProcess/WebPage/WebPage.cpp: + (WebKit::WebPage::loadURLRequest): + (WebKit::WebPage::loadData): + (WebKit::WebPage::linkClicked): + +2012-11-27 Huang Dongsung <luxtella@company100.net> + + Coordinated Graphics: Remove the maskTarget member of CoordinatedGraphicsLayer. + https://bugs.webkit.org/show_bug.cgi?id=103297 + + Reviewed by Noam Rosenthal. + + Remove the maskTarget member of CoordinatedGraphicsLayer, which is not used. + + * WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.cpp: + (WebCore::CoordinatedGraphicsLayer::CoordinatedGraphicsLayer): + (WebCore::CoordinatedGraphicsLayer::setMaskLayer): + * WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.h: + (CoordinatedGraphicsLayer): + +2012-11-26 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135822. + http://trac.webkit.org/changeset/135822 + https://bugs.webkit.org/show_bug.cgi?id=103369 + + Undo the revert of r135818, since that change does not affect + code used by Chromium (Requested by apavlov on #webkit). + + * WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.cpp: + (WebCore::CoordinatedGraphicsLayer::setContentsVisible): + (WebCore::CoordinatedGraphicsLayer::setMaskLayer): + +2012-11-26 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r135818. + http://trac.webkit.org/changeset/135818 + https://bugs.webkit.org/show_bug.cgi?id=103368 + + platform/chromium/virtual/threaded/compositing/visibility + /visibility-simple-webgl-layer.html crash on Mountain Lion + (Requested by apavlov on #webkit). + + * WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.cpp: + (WebCore::CoordinatedGraphicsLayer::setContentsVisible): + (WebCore::CoordinatedGraphicsLayer::setMaskLayer): + +2012-11-26 Dan Bernstein <mitz@apple.com> + + <rdar://problem/11931191> Entering Tab View after a bunch of YouTube pages were opened in background tabs makes all of them start playing simultaneously + https://bugs.webkit.org/show_bug.cgi?id=103358 + + Reviewed by Adele Peterson. + + To fix this, this patch adds WKPageSetMayStartMediaWhenInWindow(), which allows the client to + prevent media from starting automatically when the view is put in a window. + + * Shared/WebPageCreationParameters.cpp: + (WebKit::WebPageCreationParameters::encode): Encode mayStartMediaWhenInWindow. + (WebKit::WebPageCreationParameters::decode): Decode mayStartMediaWhenInWindow. + * Shared/WebPageCreationParameters.h: + (WebPageCreationParameters): Added boolean member mayStartMediaWhenInWindow. + * UIProcess/API/C/WKPage.cpp: + (WKPageSetMayStartMediaWhenInWindow): Added. Calls through to WebPageProxy. + * UIProcess/API/C/WKPagePrivate.h: Declared WKPageSetMayStartMediaWhenInWindow. + * UIProcess/WebPageProxy.cpp: + (WebKit::WebPageProxy::WebPageProxy): Added initializiation of m_mayStartMediaWhenInWindow + to true, the value matching the current behavior. + (WebKit::WebPageProxy::setMayStartMediaWhenInWindow): Added. Updates + m_mayStartMediaWhenInWindow and sends a message to the Web process to do the same. + (WebKit::WebPageProxy::creationParameters): Changed to set mayStartMediaWhenInWindow in the + process creation parameters. + * UIProcess/WebPageProxy.h: + (WebPageProxy): Declared setMayStartMediaWhenInWindow() and added member variable + m_mayStartMediaWhenInWindow. + * WebProcess/WebPage/WebPage.cpp: + (WebKit::WebPage::WebPage): Initialized m_mayStartMediaWhenInWindow from the creation + parameters. + (WebKit::WebPage::setIsInWindow): Made starting of media upon being added to a window + conditional on m_mayStartMediaWhenInWindow. + (WebKit::WebPage::setMayStartMediaWhenInWindow): Added. Sets m_mayStartMediaWhenInWindow. If + already in a window when changing from false to true, starts m_setCanStartMediaTimer. + * WebProcess/WebPage/WebPage.h: + (WebPage): Declared setMayStartMediaWhenInWindow() and added member variable m_mayStartMediaWhenInWindow. + * WebProcess/WebPage/WebPage.messages.in: Added SetMayStartMediaWhenInWindow. + +2012-11-26 Huang Dongsung <luxtella@company100.net> + + Coordinated Graphics: Set visibility to a mask layer in GraphicsLayer::setContentsVisible(). + https://bugs.webkit.org/show_bug.cgi?id=103297 + + Reviewed by Noam Rosenthal. + + GraphicsLayerTextureMapper and CoordinatedGraphicsLayer set the visibility of a + mask layer in setContentsVisible() and setMaskLayer() like setting a size. + This patch is needed because RenderLayerBacking does not set the visibility to a + mask layer like the size. + + This patch does not change user experience because an invisible layer is not + rendered although the mask layer is rendered. In that sense, it is an + optimization patch. + + * WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.cpp: + (WebCore::CoordinatedGraphicsLayer::setContentsVisible): + (WebCore::CoordinatedGraphicsLayer::setMaskLayer): + +2012-11-26 Kyungjin Kim <gen.kim@samsung.com> + + [WK2] Expose Accelerated2dCanvas flag set and get in WebKit2 + https://bugs.webkit.org/show_bug.cgi?id=103008 + + Reviewed by Gyuyoung Kim. + + Add setting APIs for accelerated 2d canvas in WebKit2. + + * Shared/WebPreferencesStore.h: + (WebKit): + * UIProcess/API/C/WKPreferences.cpp: + (WKPreferencesSetAccelerated2dCanvasEnabled): + (WKPreferencesGetAccelerated2dCanvasEnabled): + * UIProcess/API/C/WKPreferencesPrivate.h: + * WebProcess/WebPage/WebPage.cpp: + (WebKit::WebPage::updatePreferences): + +2012-11-26 Tim Horton <timothy_horton@apple.com> + + Ensure that plugins are initialized before using handleEditingCommand/isEditingCommandEnabled/shouldAllowScripting + https://bugs.webkit.org/show_bug.cgi?id=103288 + + Reviewed by Dan Bernstein. + + Other PluginView methods that use m_plugin null-check m_plugin and check + that the plugin has finished initializing before using it. These three + should do the same thing. + + * WebProcess/Plugins/PluginView.cpp: + (WebKit::PluginView::handleEditingCommand): + (WebKit::PluginView::isEditingCommandEnabled): + (WebKit::PluginView::shouldAllowScripting): + +2012-11-26 Tim Horton <timothy_horton@apple.com> + + PDFPlugin: Subframe PDF context menus are in the wrong place + https://bugs.webkit.org/show_bug.cgi?id=103284 + <rdar://problem/12727972> + + Reviewed by Dan Bernstein. + + Event position is in window coordinates, not content coordinates. + Since we have no windowToScreen(), use windowToContents and contentsToScreen + to get to screen coordinate space, which WKPopupContextMenu wants. + + * WebProcess/Plugins/PDF/PDFPlugin.mm: + (WebKit::PDFPlugin::handleContextMenuEvent): + +2012-11-26 Tim Horton <timothy_horton@apple.com> + + PDFPlugin: Ctrl-click opens a link in a PDF in addition to context menu + https://bugs.webkit.org/show_bug.cgi?id=103282 + <rdar://problem/12710892> + + Reviewed by Dan Bernstein. + + Don't send standard mouse events to PDFKit if a click will also show/hide the context menu. + + * WebProcess/Plugins/PDF/PDFPlugin.mm: + (WebKit::PDFPlugin::handleMouseEvent): + +2012-11-26 Ryuan Choi <ryuan.choi@gmail.com> + + [EFL] Unreviewed build fix after r135767 without Tiled Backing Store + https://bugs.webkit.org/show_bug.cgi?id=103320 + + Unreviewed build fix. + + * WebProcess/Plugins/Plugin.cpp: + * WebProcess/Plugins/Plugin.h: + (WebCore): + +2012-11-26 James Simonsen <simonjam@chromium.org> + + Consolidate FrameLoader::load() into one function taking a FrameLoadRequest + https://bugs.webkit.org/show_bug.cgi?id=102151 + + Reviewed by Adam Barth. + + * WebProcess/Plugins/PluginView.cpp: + (WebKit::PluginView::performFrameLoadURLRequest): + * WebProcess/WebPage/WebPage.cpp: + (WebKit::WebPage::loadURLRequest): + (WebKit::WebPage::loadData): + +2012-11-26 Jon Lee <jonlee@apple.com> + + Pass clicks through to the restarted plugin + https://bugs.webkit.org/show_bug.cgi?id=102150 + <rdar://problem/12695575> + + Reviewed by Simon Fraser. + + Expose convertToRootView() as a public function for all plugins. It converts the click point + from local plugin coordinates to root view coordinates. When the events are sent to the + plugin, the coordinate gets converted back to the local reference frame. + * WebProcess/Plugins/Plugin.cpp: + (WebKit::Plugin::convertToRootView): Default implementation should not be reached. + * WebProcess/Plugins/Plugin.h: Promote convertToRootView() from NetscapePlugin.h. + * WebProcess/Plugins/Netscape/NetscapePlugin.h: An implementation already existed. Make the + method virtual. + * WebProcess/Plugins/PluginProxy.h: + * WebProcess/Plugins/PluginProxy.cpp: + (WebKit::PluginProxy::convertToRootView): Apply the transform to the provided point to return + a point in root view coordinates. + + Change the threshold state to PlayingWithPendingMouseClick instead of Playing, since that is + the earliest state where the plugin is playing. + * WebProcess/Plugins/PluginView.cpp: Give the snapshot a little more time to generate. + (WebKit::PluginView::didInitializePlugin): When the plugin has initialized, tell the plugin + element to dispatch the pending mouse click. + (WebKit::PluginView::paint): + (WebKit::PluginView::createWebEvent): Helper function to convert a WebCore mouse event to a + WebMouseEvent. + (WebKit::PluginView::handleEvent): If the event is simulated, there is no source event from + the UI process. So we fabricate one based on the simulated event. + (WebKit::PluginView::invalidateRect): + (WebKit::PluginView::isAcceleratedCompositingEnabled): + * WebProcess/Plugins/PluginView.h: + +2012-11-26 Kalev Lember <kalevlember@gmail.com> + + [GTK] Explicitly link against librt + https://bugs.webkit.org/show_bug.cgi?id=103194 + + Reviewed by Martin Robinson. + + Fixes broken build with undefined references to shm_open / shm_unlink + symbols. SharedMemoryUnix.cpp uses these so we need to link with -lrt. + + * GNUmakefile.am: + +2012-11-26 Christophe Dumez <christophe.dumez@intel.com> + + [EFL][WK2] Add setting to enable / disable HTML5 local storage functionality + https://bugs.webkit.org/show_bug.cgi?id=103224 + + Reviewed by Laszlo Gombos. + + Add API to ewk_settings to enable / disable the HTML5 + local storage functionality. The functionality is + enabled by default. + + * UIProcess/API/efl/ewk_settings.cpp: + (ewk_settings_local_storage_enabled_set): + (ewk_settings_local_storage_enabled_get): + * UIProcess/API/efl/ewk_settings.h: + * UIProcess/API/efl/tests/test_ewk2_settings.cpp: + (TEST_F): Add API test for ewk_settings_local_storage_enabled_get / set. + +2012-11-26 Rafael Brandao <rafael.lobo@openbossa.org> + + [CoordinatedGraphics] Access to LayerTreeRenderer::m_renderQueue should be thread safe + https://bugs.webkit.org/show_bug.cgi?id=101341 + + Reviewed by Noam Rosenthal. + + * UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp: + (WebKit::LayerTreeRenderer::syncRemoteContent): The previous swap already clears the + vector on m_renderQueue. It is also done in a thread-safe way, so clearing it afterward + can be harmful as we've already released the lock. + +2012-11-26 Jaehun Lim <ljaehun.lim@samsung.com> + + Text Autosizing: Add Text Autosizing APIs for WK2 + https://bugs.webkit.org/show_bug.cgi?id=100633 + + Reviewed by Sam Weinig. + + Implement basic Text Autosizing APIs for WK2. + Text Autosizing is a useful feature for mobile browsers. It adjusts the font size + of text in wide columns, and makes text more legible. + This patch adds setting APIs for Text Autosizing in WK2. + + * Shared/WebPreferencesStore.h: + (WebKit): + * UIProcess/API/C/WKPreferences.cpp: + (WKPreferencesSetTextAutosizingEnabled): + (WKPreferencesGetTextAutosizingEnabled): + * UIProcess/API/C/WKPreferences.h: + * WebProcess/WebPage/WebPage.cpp: + (WebKit::WebPage::updatePreferences): + 2012-11-26 Pierre Rossi <pierre.rossi@gmail.com> [Qt] REGRESSION(r135575): It made all tests assert diff --git a/Source/WebKit2/GNUmakefile.am b/Source/WebKit2/GNUmakefile.am index 097cdc1fc..ff5ff1f5b 100644 --- a/Source/WebKit2/GNUmakefile.am +++ b/Source/WebKit2/GNUmakefile.am @@ -566,6 +566,7 @@ Programs_WebKitPluginProcess_LDADD += \ $(PANGO_LIBS) \ $(PNG_LIBS) \ $(SHLWAPI_LIBS) \ + $(SHM_LIBS) \ $(SQLITE3_LIBS) \ $(UNICODE_LIBS) \ $(XRENDER_LIBS) \ diff --git a/Source/WebKit2/PlatformEfl.cmake b/Source/WebKit2/PlatformEfl.cmake index 7734a92a7..dde7c5b4a 100644 --- a/Source/WebKit2/PlatformEfl.cmake +++ b/Source/WebKit2/PlatformEfl.cmake @@ -44,6 +44,7 @@ LIST(APPEND WebKit2_SOURCES UIProcess/API/efl/EwkViewImpl.cpp UIProcess/API/efl/EvasGLContext.cpp UIProcess/API/efl/EvasGLSurface.cpp + UIProcess/API/efl/SnapshotImageGL.cpp UIProcess/API/efl/ewk_auth_request.cpp UIProcess/API/efl/ewk_back_forward_list.cpp UIProcess/API/efl/ewk_back_forward_list_item.cpp diff --git a/Source/WebKit2/PluginProcess.pro b/Source/WebKit2/PluginProcess.pro index 82a8c2f17..545979511 100644 --- a/Source/WebKit2/PluginProcess.pro +++ b/Source/WebKit2/PluginProcess.pro @@ -21,7 +21,8 @@ INCLUDEPATH = \ INSTALLS += target isEmpty(INSTALL_BINS) { - target.path = $$[QT_INSTALL_BINS] + use?(libexecdir): target.path = $$[QT_INSTALL_LIBEXECS] + else: target.path = $$[QT_INSTALL_BINS] } else { target.path = $$INSTALL_BINS } diff --git a/Source/WebKit2/PluginProcess/mac/PluginProcessShim.mm b/Source/WebKit2/PluginProcess/mac/PluginProcessShim.mm index 98476535a..d0afe9267 100644 --- a/Source/WebKit2/PluginProcess/mac/PluginProcessShim.mm +++ b/Source/WebKit2/PluginProcess/mac/PluginProcessShim.mm @@ -30,7 +30,7 @@ #import <Carbon/Carbon.h> #import <WebKitSystemInterface.h> #import <stdio.h> -#import <objc/objc-runtime.h> +#import <objc/message.h> #define DYLD_INTERPOSE(_replacement,_replacee) \ __attribute__((used)) static struct{ const void* replacement; const void* replacee; } _interpose_##_replacee \ diff --git a/Source/WebKit2/Shared/APIClient.h b/Source/WebKit2/Shared/APIClient.h index be6ef3a81..21cb594e5 100644 --- a/Source/WebKit2/Shared/APIClient.h +++ b/Source/WebKit2/Shared/APIClient.h @@ -51,7 +51,9 @@ public: if (client && client->version < currentVersion) memcpy(&m_client, client, APIClientTraits<ClientInterface>::interfaceSizesByVersion[client->version]); } - + + const ClientInterface& client() const { return m_client; } + protected: ClientInterface m_client; }; diff --git a/Source/WebKit2/Shared/APIObject.h b/Source/WebKit2/Shared/APIObject.h index 34181ec93..3119de6dc 100644 --- a/Source/WebKit2/Shared/APIObject.h +++ b/Source/WebKit2/Shared/APIObject.h @@ -130,6 +130,7 @@ public: // Platform specific TypeEditCommandProxy, + TypeObjCObjectGraph, TypeView, #if USE(SOUP) TypeSoupRequestManager, diff --git a/Source/WebKit2/Shared/DictionaryPopupInfo.cpp b/Source/WebKit2/Shared/DictionaryPopupInfo.cpp index f14eea3c7..2376cbdab 100644 --- a/Source/WebKit2/Shared/DictionaryPopupInfo.cpp +++ b/Source/WebKit2/Shared/DictionaryPopupInfo.cpp @@ -37,7 +37,6 @@ namespace WebKit { void DictionaryPopupInfo::encode(CoreIPC::ArgumentEncoder& encoder) const { encoder << origin; - encoder << fontInfo; encoder.encodeEnum(type); #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 @@ -52,8 +51,6 @@ bool DictionaryPopupInfo::decode(CoreIPC::ArgumentDecoder* decoder, DictionaryPo { if (!decoder->decode(result.origin)) return false; - if (!decoder->decode(result.fontInfo)) - return false; if (!decoder->decodeEnum(result.type)) return false; #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 diff --git a/Source/WebKit2/Shared/DictionaryPopupInfo.h b/Source/WebKit2/Shared/DictionaryPopupInfo.h index 27eb6db37..af921dc25 100644 --- a/Source/WebKit2/Shared/DictionaryPopupInfo.h +++ b/Source/WebKit2/Shared/DictionaryPopupInfo.h @@ -26,7 +26,6 @@ #ifndef DictionaryPopupInfo_h #define DictionaryPopupInfo_h -#include "FontInfo.h" #include <WebCore/FloatPoint.h> #if PLATFORM(MAC) @@ -50,7 +49,6 @@ struct DictionaryPopupInfo { }; WebCore::FloatPoint origin; - FontInfo fontInfo; Type type; #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 RetainPtr<CFDictionaryRef> options; diff --git a/Source/WebKit2/Shared/WebPageCreationParameters.cpp b/Source/WebKit2/Shared/WebPageCreationParameters.cpp index 2a4afd938..22e28849c 100644 --- a/Source/WebKit2/Shared/WebPageCreationParameters.cpp +++ b/Source/WebKit2/Shared/WebPageCreationParameters.cpp @@ -57,6 +57,7 @@ void WebPageCreationParameters::encode(CoreIPC::ArgumentEncoder& encoder) const encoder << canRunModal; encoder << deviceScaleFactor; encoder << mediaVolume; + encoder << mayStartMediaWhenInWindow; #if PLATFORM(MAC) encoder << isSmartInsertDeleteEnabled; @@ -119,6 +120,8 @@ bool WebPageCreationParameters::decode(CoreIPC::ArgumentDecoder* decoder, WebPag return false; if (!decoder->decode(parameters.mediaVolume)) return false; + if (!decoder->decode(parameters.mayStartMediaWhenInWindow)) + return false; #if PLATFORM(MAC) if (!decoder->decode(parameters.isSmartInsertDeleteEnabled)) diff --git a/Source/WebKit2/Shared/WebPageCreationParameters.h b/Source/WebKit2/Shared/WebPageCreationParameters.h index 214c04c50..7a580f3e3 100644 --- a/Source/WebKit2/Shared/WebPageCreationParameters.h +++ b/Source/WebKit2/Shared/WebPageCreationParameters.h @@ -85,6 +85,7 @@ struct WebPageCreationParameters { float deviceScaleFactor; float mediaVolume; + bool mayStartMediaWhenInWindow; #if PLATFORM(MAC) bool isSmartInsertDeleteEnabled; diff --git a/Source/WebKit2/Shared/WebPreferencesStore.h b/Source/WebKit2/Shared/WebPreferencesStore.h index 07d62ac69..16cefe25f 100644 --- a/Source/WebKit2/Shared/WebPreferencesStore.h +++ b/Source/WebKit2/Shared/WebPreferencesStore.h @@ -87,6 +87,7 @@ namespace WebKit { macro(CompositingRepaintCountersVisible, compositingRepaintCountersVisible, Bool, bool, false) \ macro(CSSCustomFilterEnabled, cssCustomFilterEnabled, Bool, bool, true) \ macro(WebGLEnabled, webGLEnabled, Bool, bool, false) \ + macro(Accelerated2dCanvasEnabled, accelerated2dCanvasEnabled, Bool, bool, false) \ macro(CSSRegionsEnabled, cssRegionsEnabled, Bool, bool, true) \ macro(CSSGridLayoutEnabled, cssGridLayoutEnabled, Bool, bool, false) \ macro(RegionBasedColumnsEnabled, regionBasedColumnsEnabled, Bool, bool, false) \ @@ -139,6 +140,7 @@ namespace WebKit { macro(PlugInSnapshottingEnabled, plugInSnapshottingEnabled, Bool, bool, false) \ macro(PDFPluginEnabled, pdfPluginEnabled, Bool, bool, false) \ macro(UsesEncodingDetector, usesEncodingDetector, Bool, bool, false) \ + macro(TextAutosizingEnabled, textAutosizingEnabled, Bool, bool, false) \ \ #define FOR_EACH_WEBKIT_DOUBLE_PREFERENCE(macro) \ diff --git a/Source/WebKit2/Shared/mac/ObjCObjectGraph.h b/Source/WebKit2/Shared/mac/ObjCObjectGraph.h new file mode 100644 index 000000000..7160c6f85 --- /dev/null +++ b/Source/WebKit2/Shared/mac/ObjCObjectGraph.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ObjCObjectGraph_h +#define ObjCObjectGraph_h + +#include "APIObject.h" +#include <wtf/RetainPtr.h> + +namespace WebKit { + +class ObjCObjectGraph : public APIObject { +public: + static const Type APIType = TypeObjCObjectGraph; + + static PassRefPtr<ObjCObjectGraph> create(id rootObject) + { + return adoptRef(new ObjCObjectGraph(rootObject)); + } + + id rootObject() const { return m_rootObject.get(); } + +private: + explicit ObjCObjectGraph(id rootObject) + : m_rootObject(rootObject) + { + } + + virtual Type type() const { return APIType; } + + RetainPtr<id> m_rootObject; +}; + +} // namespace WebKit + +#endif // ObjCObjectGraph_h diff --git a/Source/WebKit2/Shared/mac/ObjCObjectGraph.mm b/Source/WebKit2/Shared/mac/ObjCObjectGraph.mm new file mode 100644 index 000000000..822edd151 --- /dev/null +++ b/Source/WebKit2/Shared/mac/ObjCObjectGraph.mm @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ObjCObjectGraph.h" diff --git a/Source/WebKit2/Shared/mac/ObjCObjectGraphCoders.h b/Source/WebKit2/Shared/mac/ObjCObjectGraphCoders.h new file mode 100644 index 000000000..e371e4c51 --- /dev/null +++ b/Source/WebKit2/Shared/mac/ObjCObjectGraphCoders.h @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ObjCObjectGraphCoders_h +#define ObjCObjectGraphCoders_h + +#include "ArgumentDecoder.h" +#include "ArgumentEncoder.h" +#include "ObjCObjectGraph.h" +#include <wtf/RefPtr.h> + +namespace WebKit { + +class WebProcess; +class WebProcessProxy; + +class WebContextObjCObjectGraphEncoder { +public: + explicit WebContextObjCObjectGraphEncoder(ObjCObjectGraph*); + void encode(CoreIPC::ArgumentEncoder&) const; + +private: + ObjCObjectGraph* m_objectGraph; +}; + +class WebContextObjCObjectGraphDecoder { +public: + explicit WebContextObjCObjectGraphDecoder(RefPtr<ObjCObjectGraph>&, WebProcessProxy*); + static bool decode(CoreIPC::ArgumentDecoder*, WebContextObjCObjectGraphDecoder&); + +private: + RefPtr<ObjCObjectGraph>& m_objectGraph; + WebProcessProxy* m_process; +}; + + +class InjectedBundleObjCObjectGraphEncoder { +public: + explicit InjectedBundleObjCObjectGraphEncoder(ObjCObjectGraph*); + void encode(CoreIPC::ArgumentEncoder&) const; + +private: + ObjCObjectGraph* m_objectGraph; +}; + +class InjectedBundleObjCObjectGraphDecoder { +public: + explicit InjectedBundleObjCObjectGraphDecoder(RefPtr<ObjCObjectGraph>&, WebProcess*); + static bool decode(CoreIPC::ArgumentDecoder*, InjectedBundleObjCObjectGraphDecoder&); + +private: + RefPtr<ObjCObjectGraph>& m_objectGraph; + WebProcess* m_process; +}; + +} // namespace WebKit + +#endif // ObjCObjectGraphCoders_h diff --git a/Source/WebKit2/Shared/mac/ObjCObjectGraphCoders.mm b/Source/WebKit2/Shared/mac/ObjCObjectGraphCoders.mm new file mode 100644 index 000000000..d19e981a5 --- /dev/null +++ b/Source/WebKit2/Shared/mac/ObjCObjectGraphCoders.mm @@ -0,0 +1,497 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ObjCObjectGraphCoders.h" + +#import "ArgumentCodersMac.h" + +// For UIProcess side encoding/decoding +#import "WKAPICast.h" +#import "WKBrowsingContextControllerInternal.h" +#import "WebPageProxy.h" +#import "WebProcessProxy.h" + +// For WebProcess side encoding/decoding +#import "WKBundleAPICast.h" +#import "WKWebProcessPlugInBrowserContextControllerInternal.h" +#import "WKWebProcessPlugInBrowserContextControllerPrivate.h" +#import "WKWebProcessPlugInInternal.h" +#import "WebPage.h" +#import "WebProcess.h" + +namespace WebKit { + +enum WebKitNSType { + NullType, + NSDictionaryType, + NSArrayType, + NSStringType, + NSNumberType, + NSDateType, + NSDataType, +#if defined(__LP64__) && defined(__clang__) + WKBrowsingContextControllerType, +#endif + UnknownType, +}; + +static WebKitNSType typeFromObject(id object) +{ + ASSERT(object); + + if ([object isKindOfClass:[NSDictionary class]]) + return NSDictionaryType; + if ([object isKindOfClass:[NSString class]]) + return NSStringType; + if ([object isKindOfClass:[NSArray class]]) + return NSArrayType; + if ([object isKindOfClass:[NSNumber class]]) + return NSNumberType; + if ([object isKindOfClass:[NSDate class]]) + return NSDateType; + if ([object isKindOfClass:[NSData class]]) + return NSDataType; +#if defined(__LP64__) && defined(__clang__) + if ([object isKindOfClass:[WKBrowsingContextController class]]) + return WKBrowsingContextControllerType; +#endif + + return UnknownType; +} + +template<typename Owner> +class ObjCObjectGraphEncoder { +public: + bool baseEncode(CoreIPC::ArgumentEncoder& encoder, WebKitNSType& type) const + { + if (!m_root) { + encoder << static_cast<uint32_t>(NullType); + return true; + } + + type = typeFromObject(m_root); + if (type == UnknownType) { + [NSException raise:NSInvalidArgumentException format:@"Can not encode objects of class type '%@'", NSStringFromClass([m_root class])]; + } + + encoder << static_cast<uint32_t>(type); + + switch (type) { + case NSStringType: { + CoreIPC::encode(encoder, static_cast<NSString *>(m_root)); + return true; + } + case NSArrayType: { + NSArray *array = static_cast<NSArray *>(m_root); + + NSUInteger size = [array count]; + encoder << static_cast<uint64_t>(size); + + for (NSUInteger i = 0; i < size; ++i) + encoder << Owner([array objectAtIndex:i]); + return true; + } + case NSDictionaryType: { + NSDictionary* dictionary = static_cast<NSDictionary *>(m_root); + + NSUInteger size = [dictionary count]; + encoder << static_cast<uint64_t>(size); + + NSArray *keys = [dictionary allKeys]; + NSArray *values = [dictionary allValues]; + for (NSUInteger i = 0; i < size; ++i) { + encoder << Owner([keys objectAtIndex:i]); + encoder << Owner([values objectAtIndex:i]); + } + + return true; + } + case NSNumberType: { + CoreIPC::encode(encoder, static_cast<NSNumber *>(m_root)); + return true; + } + case NSDateType: { + CoreIPC::encode(encoder, static_cast<NSDate *>(m_root)); + return true; + } + case NSDataType: { + CoreIPC::encode(encoder, static_cast<NSData *>(m_root)); + return true; + } + default: + break; + } + + return false; + } + +protected: + ObjCObjectGraphEncoder(id root) + : m_root(root) + { + } + + id m_root; +}; + +template<typename Owner> +class ObjCObjectGraphDecoder { +public: + static bool baseDecode(CoreIPC::ArgumentDecoder* decoder, Owner& coder, WebKitNSType& type) + { + uint32_t typeAsUInt32; + if (!decoder->decode(typeAsUInt32)) + return false; + + type = static_cast<WebKitNSType>(typeAsUInt32); + + switch (type) { + case NSStringType: { + RetainPtr<NSString> string; + if (!CoreIPC::decode(decoder, string)) + return false; + coder.m_root = string; + break; + } + case NSArrayType: { + uint64_t size; + if (!decoder->decodeUInt64(size)) + return false; + + RetainPtr<NSMutableArray> array = adoptNS([[NSMutableArray alloc] initWithCapacity:size]); + for (uint64_t i = 0; i < size; ++i) { + RetainPtr<id> value; + Owner messageCoder(coder, value); + if (!decoder->decode(messageCoder)) + return false; + + [array.get() addObject:value.get()]; + } + + coder.m_root = array; + break; + } + case NSDictionaryType: { + uint64_t size; + if (!decoder->decodeUInt64(size)) + return false; + + RetainPtr<NSMutableDictionary> dictionary = adoptNS([[NSMutableDictionary alloc] initWithCapacity:size]); + for (uint64_t i = 0; i < size; ++i) { + // Try to decode the key name. + RetainPtr<id> key; + Owner keyMessageCoder(coder, key); + if (!decoder->decode(keyMessageCoder)) + return false; + + RetainPtr<id> value; + Owner valueMessageCoder(coder, value); + if (!decoder->decode(valueMessageCoder)) + return false; + + [dictionary.get() setObject:value.get() forKey:key.get()]; + } + + coder.m_root = dictionary; + break; + } + case NSNumberType: { + RetainPtr<NSNumber> number; + if (!CoreIPC::decode(decoder, number)) + return false; + coder.m_root = number; + break; + } + case NSDateType: { + RetainPtr<NSDate> date; + if (!CoreIPC::decode(decoder, date)) + return false; + coder.m_root = date; + break; + } + case NSDataType: { + RetainPtr<NSData> data; + if (!CoreIPC::decode(decoder, data)) + return false; + coder.m_root = data; + break; + } + default: + break; + } + + return true; + } + +protected: + ObjCObjectGraphDecoder(RetainPtr<id>& root) + : m_root(root) + { + } + + RetainPtr<id>& m_root; +}; + + +// WebContext Additions + +class WebContextObjCObjectGraphEncoderImpl : public ObjCObjectGraphEncoder<WebContextObjCObjectGraphEncoderImpl> { +public: + typedef ObjCObjectGraphEncoder<WebContextObjCObjectGraphEncoderImpl> Base; + + explicit WebContextObjCObjectGraphEncoderImpl(id root) + : Base(root) + { + } + + void encode(CoreIPC::ArgumentEncoder& encoder) const + { + WebKitNSType type = NullType; + if (baseEncode(encoder, type)) + return; + + switch (type) { +#if defined(__LP64__) && defined(__clang__) + case WKBrowsingContextControllerType: { + WKBrowsingContextController *browsingContextController = static_cast<WKBrowsingContextController *>(m_root); + + encoder << toImpl(browsingContextController._pageRef)->pageID(); + break; + } +#endif + default: + ASSERT_NOT_REACHED(); + break; + } + } +}; + + +class WebContextObjCObjectGraphDecoderImpl : public ObjCObjectGraphDecoder<WebContextObjCObjectGraphDecoderImpl> { +public: + typedef ObjCObjectGraphDecoder<WebContextObjCObjectGraphDecoderImpl> Base; + + WebContextObjCObjectGraphDecoderImpl(RetainPtr<id>& root, WebProcessProxy* process) + : Base(root) + , m_process(process) + { + } + + WebContextObjCObjectGraphDecoderImpl(WebContextObjCObjectGraphDecoderImpl& userMessageDecoder, RetainPtr<id>& root) + : Base(root) + , m_process(userMessageDecoder.m_process) + { + } + + static bool decode(CoreIPC::ArgumentDecoder* decoder, WebContextObjCObjectGraphDecoderImpl& coder) + { + WebKitNSType type = NullType; + if (!Base::baseDecode(decoder, coder, type)) + return false; + + if (coder.m_root) + return true; + + if (type == NullType || type == UnknownType) { + coder.m_root = [NSNull null]; + return true; + } + + switch (type) { +#if defined(__LP64__) && defined(__clang__) + case WKBrowsingContextControllerType: { + uint64_t pageID; + if (!decoder->decode(pageID)) + return false; + + WebPageProxy* webPage = coder.m_process->webPage(pageID); + if (!webPage) + coder.m_root = [NSNull null]; + else + coder.m_root = [WKBrowsingContextController _browsingContextControllerForPageRef:toAPI(webPage)]; + break; + } +#endif + default: + return false; + } + + return true; + } + +private: + WebProcessProxy* m_process; +}; + + +// InjectedBundle Additions + +class InjectedBundleObjCObjectGraphEncoderImpl : public ObjCObjectGraphEncoder<InjectedBundleObjCObjectGraphEncoderImpl> { +public: + typedef ObjCObjectGraphEncoder<InjectedBundleObjCObjectGraphEncoderImpl> Base; + + explicit InjectedBundleObjCObjectGraphEncoderImpl(id root) + : Base(root) + { + } + + void encode(CoreIPC::ArgumentEncoder& encoder) const + { + WebKitNSType type = NullType; + if (baseEncode(encoder, type)) + return; + + switch (type) { +#if defined(__LP64__) && defined(__clang__) + case WKBrowsingContextControllerType: { + + WKWebProcessPlugInBrowserContextController *browserContextController = static_cast<WKWebProcessPlugInBrowserContextController *>(m_root); + + encoder << toImpl(browserContextController._bundlePageRef)->pageID(); + break; + } +#endif + default: + ASSERT_NOT_REACHED(); + break; + } + } +}; + +class InjectedBundleObjCObjectGraphDecoderImpl : public ObjCObjectGraphDecoder<InjectedBundleObjCObjectGraphDecoderImpl> { +public: + typedef ObjCObjectGraphDecoder<InjectedBundleObjCObjectGraphDecoderImpl> Base; + + InjectedBundleObjCObjectGraphDecoderImpl(RetainPtr<id>& root, WebProcess* process) + : Base(root) + , m_process(process) + { + } + + InjectedBundleObjCObjectGraphDecoderImpl(InjectedBundleObjCObjectGraphDecoderImpl& userMessageDecoder, RetainPtr<id>& root) + : Base(root) + , m_process(userMessageDecoder.m_process) + { + } + + static bool decode(CoreIPC::ArgumentDecoder* decoder, InjectedBundleObjCObjectGraphDecoderImpl& coder) + { + WebKitNSType type = NullType; + if (!Base::baseDecode(decoder, coder, type)) + return false; + + if (coder.m_root) + return true; + + if (type == NullType || type == UnknownType) { + coder.m_root = [NSNull null]; + return true; + } + + switch (type) { +#if defined(__LP64__) && defined(__clang__) + case WKBrowsingContextControllerType: { + uint64_t pageID; + if (!decoder->decode(pageID)) + return false; + + WebPage* webPage = coder.m_process->webPage(pageID); + if (!webPage) + coder.m_root = [NSNull null]; + else + coder.m_root = [[WKWebProcessPlugInController _shared] _browserContextControllerForBundlePageRef:toAPI(webPage)]; + break; + } +#endif + default: + return false; + } + + return true; + } + +private: + WebProcess* m_process; +}; + + +// Adaptors + +WebContextObjCObjectGraphEncoder::WebContextObjCObjectGraphEncoder(ObjCObjectGraph* objectGraph) + : m_objectGraph(objectGraph) +{ +} + +void WebContextObjCObjectGraphEncoder::encode(CoreIPC::ArgumentEncoder& encoder) const +{ + encoder << WebContextObjCObjectGraphEncoderImpl(m_objectGraph->rootObject()); +} + +WebContextObjCObjectGraphDecoder::WebContextObjCObjectGraphDecoder(RefPtr<ObjCObjectGraph>& objectGraph, WebProcessProxy* process) + : m_objectGraph(objectGraph) + , m_process(process) +{ +} + +bool WebContextObjCObjectGraphDecoder::decode(CoreIPC::ArgumentDecoder* decoder, WebContextObjCObjectGraphDecoder& coder) +{ + RetainPtr<id> root; + WebContextObjCObjectGraphDecoderImpl coderImpl(root, coder.m_process); + if (!decoder->decode(coderImpl)) + return false; + + coder.m_objectGraph = ObjCObjectGraph::create(root.get()); + return true; +} + +InjectedBundleObjCObjectGraphEncoder::InjectedBundleObjCObjectGraphEncoder(ObjCObjectGraph* objectGraph) + : m_objectGraph(objectGraph) +{ +} + +void InjectedBundleObjCObjectGraphEncoder::encode(CoreIPC::ArgumentEncoder& encoder) const +{ + encoder << InjectedBundleObjCObjectGraphEncoderImpl(m_objectGraph->rootObject()); +} + +InjectedBundleObjCObjectGraphDecoder::InjectedBundleObjCObjectGraphDecoder(RefPtr<ObjCObjectGraph>& objectGraph, WebProcess* process) + : m_objectGraph(objectGraph) + , m_process(process) +{ +} + +bool InjectedBundleObjCObjectGraphDecoder::decode(CoreIPC::ArgumentDecoder* decoder, InjectedBundleObjCObjectGraphDecoder& coder) +{ + RetainPtr<id> root; + InjectedBundleObjCObjectGraphDecoderImpl coderImpl(root, coder.m_process); + if (!decoder->decode(coderImpl)) + return false; + + coder.m_objectGraph = ObjCObjectGraph::create(root.get()); + return true; +} + +} // namespace WebKit diff --git a/Source/WebKit2/Shared/qt/ProcessExecutablePathQt.cpp b/Source/WebKit2/Shared/qt/ProcessExecutablePathQt.cpp index bba73657f..250b16c80 100644 --- a/Source/WebKit2/Shared/qt/ProcessExecutablePathQt.cpp +++ b/Source/WebKit2/Shared/qt/ProcessExecutablePathQt.cpp @@ -40,7 +40,12 @@ static String executablePath(QString baseName) if (QFile::exists(expectedPath)) return String(expectedPath); - expectedPath = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QDir::separator() + baseName; + QLibraryInfo::LibraryLocation location = QLibraryInfo::BinariesPath; +#if USE(LIBEXECDIR) + location = QLibraryInfo::LibraryExecutablesPath; +#endif + + expectedPath = QLibraryInfo::location(location) + QDir::separator() + baseName; if (QFile::exists(expectedPath)) return String(expectedPath); diff --git a/Source/WebKit2/UIProcess/API/C/WKPage.cpp b/Source/WebKit2/UIProcess/API/C/WKPage.cpp index 259bca727..ef871bb4c 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPage.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPage.cpp @@ -764,3 +764,8 @@ WKArrayRef WKPageCopyRelatedPages(WKPageRef pageRef) { return toAPI(toImpl(pageRef)->relatedPages().leakRef()); } + +void WKPageSetMayStartMediaWhenInWindow(WKPageRef pageRef, bool mayStartMedia) +{ + toImpl(pageRef)->setMayStartMediaWhenInWindow(mayStartMedia); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h b/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h index 3a9de69af..4f0e85ba5 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h @@ -93,6 +93,7 @@ WK_EXPORT WKImageRef WKPageCreateSnapshotOfVisibleContent(WKPageRef page); WK_EXPORT void WKPageSetShouldSendEventsSynchronously(WKPageRef page, bool sync); WK_EXPORT void WKPageSetMediaVolume(WKPageRef page, float volume); +WK_EXPORT void WKPageSetMayStartMediaWhenInWindow(WKPageRef page, bool mayStartMedia); WK_EXPORT WKArrayRef WKPageCopyRelatedPages(WKPageRef page); diff --git a/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp b/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp index 068563d1f..cb4cff018 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp @@ -448,6 +448,16 @@ bool WKPreferencesGetWebGLEnabled(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->webGLEnabled(); } +void WKPreferencesSetAccelerated2DCanvasEnabled(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setAccelerated2dCanvasEnabled(flag); +} + +bool WKPreferencesGetAccelerated2DCanvasEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->accelerated2dCanvasEnabled(); +} + void WKPreferencesSetCSSRegionsEnabled(WKPreferencesRef preferencesRef, bool flag) { toImpl(preferencesRef)->setCSSRegionsEnabled(flag); @@ -953,3 +963,14 @@ bool WKPreferencesGetEncodingDetectorEnabled(WKPreferencesRef preferencesRef) { return toImpl(preferencesRef)->usesEncodingDetector(); } + +void WKPreferencesSetTextAutosizingEnabled(WKPreferencesRef preferencesRef, bool textAutosizingEnabled) +{ + toImpl(preferencesRef)->setTextAutosizingEnabled(textAutosizingEnabled); +} + +bool WKPreferencesGetTextAutosizingEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->textAutosizingEnabled(); +} + diff --git a/Source/WebKit2/UIProcess/API/C/WKPreferences.h b/Source/WebKit2/UIProcess/API/C/WKPreferences.h index ff2e0a006..4033d8cf1 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPreferences.h +++ b/Source/WebKit2/UIProcess/API/C/WKPreferences.h @@ -224,6 +224,10 @@ WK_EXPORT bool WKPreferencesGetPlugInSnapshottingEnabled(WKPreferencesRef prefer WK_EXPORT void WKPreferencesSetEncodingDetectorEnabled(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetEncodingDetectorEnabled(WKPreferencesRef preferencesRef); +// Defaults to false. +WK_EXPORT void WKPreferencesSetTextAutosizingEnabled(WKPreferencesRef preferences, bool textAutosizingEnabled); +WK_EXPORT bool WKPreferencesGetTextAutosizingEnabled(WKPreferencesRef preferences); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h b/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h index af5f73b34..a796bcb43 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h @@ -91,6 +91,10 @@ WK_EXPORT bool WKPreferencesGetCSSCustomFilterEnabled(WKPreferencesRef); WK_EXPORT void WKPreferencesSetWebGLEnabled(WKPreferencesRef, bool); WK_EXPORT bool WKPreferencesGetWebGLEnabled(WKPreferencesRef); +// Defaults to false. +WK_EXPORT void WKPreferencesSetAccelerated2DCanvasEnabled(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetAccelerated2DCanvasEnabled(WKPreferencesRef); + // Defaults to true WK_EXPORT void WKPreferencesSetCSSRegionsEnabled(WKPreferencesRef, bool flag); WK_EXPORT bool WKPreferencesGetCSSRegionsEnabled(WKPreferencesRef); diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKView.cpp b/Source/WebKit2/UIProcess/API/C/efl/WKView.cpp index 80a1ac381..f4436aedd 100644 --- a/Source/WebKit2/UIProcess/API/C/efl/WKView.cpp +++ b/Source/WebKit2/UIProcess/API/C/efl/WKView.cpp @@ -42,3 +42,10 @@ WKPageRef WKViewGetPage(WKViewRef viewRef) return viewImpl->wkPage(); } + +WKImageRef WKViewGetSnapshot(WKViewRef viewRef) +{ + EwkViewImpl* viewImpl = EwkViewImpl::fromEvasObject(toImpl(viewRef)); + + return viewImpl->takeSnapshot(); +} diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKView.h b/Source/WebKit2/UIProcess/API/C/efl/WKView.h index db0da2c27..ca17a9945 100644 --- a/Source/WebKit2/UIProcess/API/C/efl/WKView.h +++ b/Source/WebKit2/UIProcess/API/C/efl/WKView.h @@ -34,6 +34,8 @@ WK_EXPORT WKViewRef WKViewCreateWithFixedLayout(Evas* canvas, WKContextRef conte WK_EXPORT WKPageRef WKViewGetPage(WKViewRef view); +WK_EXPORT WKImageRef WKViewGetSnapshot(WKViewRef viewRef); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.cpp b/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.cpp index 29161ff23..50e4cb205 100644 --- a/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.cpp +++ b/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.cpp @@ -35,11 +35,13 @@ #include "PagePolicyClientEfl.h" #include "PageUIClientEfl.h" #include "ResourceLoadClientEfl.h" +#include "SnapshotImageGL.h" #include "WKDictionary.h" #include "WKGeometry.h" #include "WKNumber.h" #include "WKString.h" #include "WebContext.h" +#include "WebImage.h" #include "WebPageGroup.h" #include "WebPageProxy.h" #include "WebPopupMenuProxyEfl.h" @@ -62,6 +64,7 @@ #include <Edje.h> #include <WebCore/CairoUtilitiesEfl.h> #include <WebCore/Cursor.h> +#include <WebKit2/WKImageCairo.h> #if ENABLE(VIBRATION) #include "VibrationClientEfl.h" @@ -288,8 +291,8 @@ AffineTransform EwkViewImpl::transformFromScene() const AffineTransform transform; #if USE(TILED_BACKING_STORE) - transform.translate(m_scrollPosition.x(), m_scrollPosition.y()); transform.scale(1 / m_scaleFactor); + transform.translate(discretePagePosition().x(), discretePagePosition().y()); #endif Ewk_View_Smart_Data* sd = smartData(); @@ -358,7 +361,7 @@ void EwkViewImpl::displayTimerFired(Timer<EwkViewImpl>*) #if USE(COORDINATED_GRAPHICS) Ewk_View_Smart_Data* sd = smartData(); - evas_gl_make_current(evasGL(), evasGLSurface(), evasGLContext()); + evas_gl_make_current(m_evasGL.get(), evasGLSurface(), evasGLContext()); // We are supposed to clip to the actual viewport, nothing less. IntRect viewport(sd->view.x, sd->view.y, sd->view.w, sd->view.h); @@ -380,8 +383,8 @@ void EwkViewImpl::displayTimerFired(Timer<EwkViewImpl>*) return; RefPtr<cairo_t> graphicsContext = adoptRef(cairo_create(surface.get())); + cairo_translate(graphicsContext.get(), - discretePagePosition().x(), - discretePagePosition().y()); cairo_scale(graphicsContext.get(), m_scaleFactor, m_scaleFactor); - cairo_translate(graphicsContext.get(), -m_scrollPosition.x(), -m_scrollPosition.y()); renderer->paintToGraphicsContext(graphicsContext.get()); evas_object_image_data_update_add(sd->image, 0, 0, viewport.width(), viewport.height()); } @@ -632,7 +635,7 @@ bool EwkViewImpl::createGLSurface(const IntSize& viewSize) } if (!m_evasGLContext) { - m_evasGLContext = EvasGLContext::create(evasGL()); + m_evasGLContext = EvasGLContext::create(m_evasGL.get()); if (!m_evasGLContext) { WARN("Failed to create GLContext."); return false; @@ -650,18 +653,20 @@ bool EwkViewImpl::createGLSurface(const IntSize& viewSize) }; // Replaces if non-null, and frees existing surface after (OwnPtr). - m_evasGLSurface = EvasGLSurface::create(evasGL(), &evasGLConfig, viewSize); + m_evasGLSurface = EvasGLSurface::create(m_evasGL.get(), &evasGLConfig, viewSize); if (!m_evasGLSurface) return false; Evas_Native_Surface nativeSurface; - evas_gl_native_surface_get(evasGL(), evasGLSurface(), &nativeSurface); + evas_gl_native_surface_get(m_evasGL.get(), evasGLSurface(), &nativeSurface); evas_object_image_native_surface_set(sd->image, &nativeSurface); - evas_gl_make_current(evasGL(), evasGLSurface(), evasGLContext()); + evas_gl_make_current(m_evasGL.get(), evasGLSurface(), evasGLContext()); - Evas_GL_API* gl = evas_gl_api_get(evasGL()); + Evas_GL_API* gl = evas_gl_api_get(m_evasGL.get()); gl->glViewport(0, 0, viewSize.width() + sd->view.x, viewSize.height() + sd->view.y); + gl->glClearColor(1.0, 1.0, 1.0, 0); + gl->glClear(GL_COLOR_BUFFER_BIT); return true; } @@ -1012,3 +1017,22 @@ void EwkViewImpl::onFaviconChanged(const char* pageURL, void* eventInfo) viewImpl->informIconChange(); } + +WKImageRef EwkViewImpl::takeSnapshot() +{ + Ewk_View_Smart_Data* sd = smartData(); +#if USE(ACCELERATED_COMPOSITING) + if (!m_isHardwareAccelerated) +#endif + return WKImageCreateFromCairoSurface(createSurfaceForImage(sd->image).get(), 0); + +#if USE(ACCELERATED_COMPOSITING) + Evas_Native_Surface* nativeSurface = evas_object_image_native_surface_get(sd->image); + unsigned char* buffer = getImageFromCurrentTexture(sd->view.w, sd->view.h, nativeSurface->data.opengl.texture_id); + RefPtr<cairo_surface_t> surface = adoptRef(cairo_image_surface_create_for_data(buffer, CAIRO_FORMAT_ARGB32, sd->view.w, sd->view.h, sd->view.w * 4)); + WKImageRef image = WKImageCreateFromCairoSurface(surface.get(), 0); + delete[] buffer; + + return image; +#endif +} diff --git a/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.h b/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.h index 379b57ebe..cb1875672 100644 --- a/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.h +++ b/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.h @@ -28,6 +28,7 @@ #include "WKGeometry.h" #include "WKRetainPtr.h" #include <Evas.h> +#include <WebCore/FloatPoint.h> #include <WebCore/IntRect.h> #include <WebCore/TextDirection.h> #include <WebCore/Timer.h> @@ -200,13 +201,8 @@ public: void setScaleFactor(float scaleFactor) { m_scaleFactor = scaleFactor; } float scaleFactor() const { return m_scaleFactor; } - void setScrollPosition(WebCore::IntPoint position) { m_scrollPosition = position; } - const WebCore::IntPoint scrollPosition() const { return m_scrollPosition; } -#endif -#if USE(ACCELERATED_COMPOSITING) - Evas_GL* evasGL() { return m_evasGL.get(); } - Evas_GL_Context* evasGLContext() { return m_evasGLContext ? m_evasGLContext->context() : 0; } - Evas_GL_Surface* evasGLSurface() { return m_evasGLSurface ? m_evasGLSurface->surface() : 0; } + void setPagePosition(const WebCore::FloatPoint& position) { m_pagePosition = position; } + const WebCore::IntPoint discretePagePosition() const { return roundedIntPoint(m_pagePosition); } #endif // FIXME: needs refactoring (split callback invoke) @@ -215,7 +211,14 @@ public: bool isHardwareAccelerated() const { return m_isHardwareAccelerated; } void setDrawsBackground(bool enable) { m_setDrawsBackground = enable; } + WKImageRef takeSnapshot(); + private: +#if USE(ACCELERATED_COMPOSITING) + Evas_GL_Context* evasGLContext() { return m_evasGLContext ? m_evasGLContext->context() : 0; } + Evas_GL_Surface* evasGLSurface() { return m_evasGLSurface ? m_evasGLSurface->surface() : 0; } +#endif + inline Ewk_View_Smart_Data* smartData() const; void displayTimerFired(WebCore::Timer<EwkViewImpl>*); @@ -259,7 +262,7 @@ private: OwnPtr<EwkBackForwardList> m_backForwardList; #if USE(TILED_BACKING_STORE) float m_scaleFactor; - WebCore::IntPoint m_scrollPosition; + WebCore::FloatPoint m_pagePosition; #endif OwnPtr<EwkSettings> m_settings; RefPtr<EwkWindowFeatures> m_windowFeatures; diff --git a/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp b/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp new file mode 100644 index 000000000..cd901efee --- /dev/null +++ b/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2012 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "config.h" +#include "SnapshotImageGL.h" + +#if USE(ACCELERATED_COMPOSITING) +#if USE(OPENGL_ES_2) +#include <GLES2/gl2.h> +#include <GLES2/gl2ext.h> +#else +#include "OpenGLShims.h" +#endif + +unsigned char* getImageFromCurrentTexture(int width, int height, int textureId) +{ + glBindTexture(GL_TEXTURE_2D, textureId); + unsigned char* buffer = new unsigned char[width * height * 4]; + glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, buffer); + + // Textures are flipped on the Y axis, so we need to flip the image back. + unsigned tmp; + unsigned* buf = reinterpret_cast<unsigned*>(buffer); + + for (int i = 0; i < height / 2; ++i) { + for (int j = 0; j < width; ++j) { + tmp = buf[i * width + j]; + buf[i * width + j] = buf[(height - i - 1) * width + j]; + buf[(height - i - 1) * width + j] = tmp; + } + } + + return buffer; +} + +#endif diff --git a/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.h b/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.h new file mode 100644 index 000000000..6c228b126 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2012 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef SnapshotImageGL_h +#define SnapshotImageGL_h + +#if USE(ACCELERATED_COMPOSITING) +unsigned char* getImageFromCurrentTexture(int width, int height, int textureId); +#endif + +#endif // SnapshotImageGL_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp index c61703078..7f7c49467 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp @@ -332,3 +332,19 @@ Eina_Bool ewk_settings_scripts_can_open_windows_get(const Ewk_Settings* settings return settings->preferences()->javaScriptCanOpenWindowsAutomatically(); } + +Eina_Bool ewk_settings_local_storage_enabled_set(Ewk_Settings* settings, Eina_Bool enable) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); + + settings->preferences()->setLocalStorageEnabled(enable); + + return true; +} + +Eina_Bool ewk_settings_local_storage_enabled_get(const Ewk_Settings* settings) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); + + return settings->preferences()->localStorageEnabled(); +} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_settings.h b/Source/WebKit2/UIProcess/API/efl/ewk_settings.h index 856daaa00..eb8cb1683 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_settings.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_settings.h @@ -391,6 +391,39 @@ EAPI Eina_Bool ewk_settings_scripts_can_open_windows_set(Ewk_Settings *settings, */ EAPI Eina_Bool ewk_settings_scripts_can_open_windows_get(const Ewk_Settings *settings); +/** + * Enables/disables the HTML5 local storage functionality. + * + * Local storage provides simple synchronous storage access. + * HTML5 local storage specification is available at + * http://dev.w3.org/html5/webstorage/. + * + * By default, the HTML5 local storage is enabled. + * + * @param settings settings object to set the HTML5 local storage state + * @param enable @c EINA_TRUE to enable HTML5 local storage, + * @c EINA_FALSE to disable + * + * @return @c EINA_TRUE on success or @c EINA_FALSE on failure + */ +EAPI Eina_Bool ewk_settings_local_storage_enabled_set(Ewk_Settings *settings, Eina_Bool enable); + +/** + * Returns whether the HTML5 local storage functionality is enabled or not. + * + * Local storage provides simple synchronous storage access. + * HTML5 local storage specification is available at + * http://dev.w3.org/html5/webstorage/. + * + * By default, the HTML5 local storage is enabled. + * + * @param settings settings object to query whether HTML5 local storage is enabled + * + * @return @c EINA_TRUE if the HTML5 local storage is enabled + * @c EINA_FALSE if disabled or on failure + */ +EAPI Eina_Bool ewk_settings_local_storage_enabled_get(const Ewk_Settings *settings); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.cpp b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.cpp index f9e0f7b73..e626ee745 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.cpp @@ -60,4 +60,12 @@ CString EWK2UnitTestEnvironment::pathForResource(const char* resource) return builder.toString().utf8(); } +CString EWK2UnitTestEnvironment::pathForTheme(const char* theme) +{ + StringBuilder builder; + builder.appendLiteral(TEST_THEME_DIR "/"); + builder.append(theme); + return builder.toString().utf8(); +} + } // namespace EWK2UnitTest diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.h b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.h index b5e4f0270..888ca0535 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.h +++ b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.h @@ -33,6 +33,7 @@ public: const char* injectedBundleSample() const; CString urlForResource(const char* resource); CString pathForResource(const char* resource); + CString pathForTheme(const char* theme); virtual unsigned int defaultWidth() const { return m_defaultWidth; } virtual unsigned int defaultHeight() const { return m_defaultHeight; } diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/big_button_theme.edj b/Source/WebKit2/UIProcess/API/efl/tests/resources/big_button_theme.edj Binary files differdeleted file mode 100644 index 2f30076db..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/big_button_theme.edj +++ /dev/null diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp index 3402e5bcc..7b7247928 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp @@ -207,3 +207,17 @@ TEST_F(EWK2UnitTestBase, ewk_settings_scripts_can_open_windows) ASSERT_TRUE(ewk_settings_scripts_can_open_windows_set(settings, false)); ASSERT_FALSE(ewk_settings_scripts_can_open_windows_get(settings)); } + +TEST_F(EWK2UnitTestBase, ewk_settings_local_storage_enabled) +{ + Ewk_Settings* settings = ewk_view_settings_get(webView()); + + // HTML5 local storage should be enabled by default. + ASSERT_TRUE(ewk_settings_local_storage_enabled_get(settings)); + + ASSERT_TRUE(ewk_settings_local_storage_enabled_set(settings, false)); + ASSERT_FALSE(ewk_settings_local_storage_enabled_get(settings)); + + ASSERT_TRUE(ewk_settings_local_storage_enabled_set(settings, true)); + ASSERT_TRUE(ewk_settings_local_storage_enabled_get(settings)); +} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_view.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_view.cpp index 1491cc7d9..25fe0698b 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_view.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_view.cpp @@ -219,9 +219,9 @@ TEST_F(EWK2UnitTestBase, ewk_view_theme_set) ewk_view_html_string_load(webView(), buttonHTML, "file:///", 0); EXPECT_TRUE(waitUntilTitleChangedTo("30")); // the result should be same as default theme - ewk_view_theme_set(webView(), environment->pathForResource("big_button_theme.edj").data()); + ewk_view_theme_set(webView(), environment->pathForTheme("big_button_theme.edj").data()); ewk_view_html_string_load(webView(), buttonHTML, "file:///", 0); - EXPECT_TRUE(waitUntilTitleChangedTo("299")); // button of big button theme has 299px as padding (150 to -150) + EXPECT_TRUE(waitUntilTitleChangedTo("299")); // button of big button theme has 299px as padding (15 to -285) } TEST_F(EWK2UnitTestBase, ewk_view_mouse_events_enabled) diff --git a/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm b/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm index 4df0ef1c4..7b03a5645 100644 --- a/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm +++ b/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm @@ -36,7 +36,6 @@ #import "WebPreferences.h" #import <PDFKit/PDFKit.h> #import <WebCore/LocalizedStrings.h> -#import <objc/objc-runtime.h> #import <wtf/ObjcRuntimeExtras.h> #import <wtf/text/CString.h> #import <wtf/text/WTFString.h> diff --git a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h index b019c68dc..8768fd067 100644 --- a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h +++ b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h @@ -128,7 +128,7 @@ private: virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects); - virtual void didPerformDictionaryLookup(const String&, double scaleFactor, const DictionaryPopupInfo&); + virtual void didPerformDictionaryLookup(const AttributedString&, const DictionaryPopupInfo&); virtual void dismissDictionaryLookupPanel(); virtual void showCorrectionPanel(WebCore::AlternativeTextType, const WebCore::FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings); diff --git a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm index 6bdc1b9eb..9ed7feea1 100644 --- a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm +++ b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm @@ -29,6 +29,7 @@ #if USE(DICTATION_ALTERNATIVES) #import <AppKit/NSTextAlternatives.h> #endif +#import "AttributedString.h" #import "ColorSpaceData.h" #import "DataReference.h" #import "DictionaryPopupInfo.h" @@ -471,14 +472,9 @@ void PageClientImpl::flashBackingStoreUpdates(const Vector<IntRect>&) notImplemented(); } -void PageClientImpl::didPerformDictionaryLookup(const String& text, double scaleFactor, const DictionaryPopupInfo& dictionaryPopupInfo) +void PageClientImpl::didPerformDictionaryLookup(const AttributedString& text, const DictionaryPopupInfo& dictionaryPopupInfo) { - NSFontDescriptor *fontDescriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:(NSDictionary *)dictionaryPopupInfo.fontInfo.fontAttributeDictionary.get()]; - NSFont *font = [NSFont fontWithDescriptor:fontDescriptor size:((scaleFactor != 1) ? [fontDescriptor pointSize] * scaleFactor : 0)]; - - RetainPtr<NSMutableAttributedString> attributedString(AdoptNS, [[NSMutableAttributedString alloc] initWithString:nsStringFromWebCoreString(text)]); - [attributedString.get() addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [attributedString.get() length])]; - + RetainPtr<NSAttributedString> attributedString = text.string; NSPoint textBaselineOrigin = dictionaryPopupInfo.origin; #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm index 8604de876..d91019f72 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm +++ b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm @@ -37,6 +37,7 @@ #import "WKURLRequest.h" #import "WKURLRequestNS.h" #import "WebContext.h" +#import "WebPageProxy.h" #import <wtf/RetainPtr.h> #import "WKBrowsingContextLoadDelegate.h" @@ -53,7 +54,6 @@ static inline NSURL *autoreleased(WKURLRef url) return [(NSURL *)WKURLCopyCFURL(kCFAllocatorDefault, wkURL.get()) autorelease]; } - @interface WKBrowsingContextControllerData : NSObject { @public // Underlying WKPageRef. @@ -68,13 +68,6 @@ static inline NSURL *autoreleased(WKURLRef url) @end -@interface WKBrowsingContextController () - -@property(readonly) WKPageRef _pageRef; - -@end - - @implementation WKBrowsingContextController - (void)dealloc @@ -418,6 +411,11 @@ static void setUpPageLoaderClient(WKBrowsingContextController *browsingContext, return self; } ++ (WKBrowsingContextController *)_browsingContextControllerForPageRef:(WKPageRef)pageRef +{ + return (WKBrowsingContextController *)WebKit::toImpl(pageRef)->loaderClient().client().clientInfo; +} + + (NSMutableSet *)customSchemes { static NSMutableSet *customSchemes = [[NSMutableSet alloc] init]; diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h index d1d20ad04..fe895c923 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h +++ b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h @@ -29,6 +29,12 @@ /* This should only be called from associate view. */ - (id)_initWithPageRef:(WKPageRef)pageRef; + +/* Returns a WKBrowsingContextController associated with the WKPageRef. */ ++ (WKBrowsingContextController *)_browsingContextControllerForPageRef:(WKPageRef)pageRef; + +@property(readonly) WKPageRef _pageRef; + + (NSMutableSet *)customSchemes; @end diff --git a/Source/WebKit2/UIProcess/API/mac/WKConnection.mm b/Source/WebKit2/UIProcess/API/mac/WKConnection.mm index 8040a6781..50efb79bc 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKConnection.mm +++ b/Source/WebKit2/UIProcess/API/mac/WKConnection.mm @@ -27,9 +27,7 @@ #import "WKConnection.h" #import "WKConnectionInternal.h" -#import "ArgumentCodersMac.h" -#import "ArgumentDecoder.h" -#import "ArgumentEncoder.h" +#import "ObjCObjectGraph.h" #import "WKConnectionRef.h" #import "WKData.h" #import "WKRetainPtr.h" @@ -64,13 +62,10 @@ using namespace WebKit; - (void)sendMessageWithName:(NSString *)messageName body:(id)messageBody { - OwnPtr<CoreIPC::ArgumentEncoder> messageData = CoreIPC::ArgumentEncoder::create(); - encode(*messageData, messageBody); - WKRetainPtr<WKStringRef> wkMessageName = adoptWK(WKStringCreateWithCFString((CFStringRef)messageName)); - WKRetainPtr<WKDataRef> wkMessageBody = adoptWK(WKDataCreate(messageData->buffer(), messageData->bufferSize())); + RefPtr<ObjCObjectGraph> wkMessageBody = ObjCObjectGraph::create(messageBody); - WKConnectionPostMessage(_data->_connectionRef.get(), wkMessageName.get(), wkMessageBody.get()); + WKConnectionPostMessage(_data->_connectionRef.get(), wkMessageName.get(), (WKTypeRef)wkMessageBody.get()); } #pragma mark Delegates @@ -93,17 +88,10 @@ static void didReceiveMessage(WKConnectionRef, WKStringRef messageName, WKTypeRe { WKConnection *connection = (WKConnection *)clientInfo; if ([connection.delegate respondsToSelector:@selector(connection:didReceiveMessageWithName:body:)]) { - RetainPtr<CFStringRef> cfMessageName = adoptCF(WKStringCopyCFString(kCFAllocatorDefault, messageName)); - - WKDataRef messageData = (WKDataRef)messageBody; - OwnPtr<CoreIPC::ArgumentDecoder> decoder = CoreIPC::ArgumentDecoder::create(WKDataGetBytes(messageData), WKDataGetSize(messageData)); - - RetainPtr<id> messageDictionary; - // FIXME: Don't just silently drop decoding failures on the ground. - if (!decode(decoder.get(), messageDictionary)) - return; + RetainPtr<NSString> nsMessageName = adoptNS((NSString *)WKStringCopyCFString(kCFAllocatorDefault, messageName)); + RetainPtr<id> nsMessageBody = ((ObjCObjectGraph*)messageBody)->rootObject(); - [connection.delegate connection:connection didReceiveMessageWithName:(NSString *)cfMessageName.get() body:messageDictionary.get()]; + [connection.delegate connection:connection didReceiveMessageWithName:nsMessageName.get() body:nsMessageBody.get()]; } } diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp b/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp index 21ed5be10..a45636a79 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp @@ -325,6 +325,7 @@ void QQuickWebViewPrivate::initialize(WKContextRef contextRef, WKPageGroupRef pa q_ptr->setAcceptedMouseButtons(Qt::MouseButtonMask); q_ptr->setAcceptHoverEvents(true); + q_ptr->setFlags(QQuickItem::ItemAcceptsDrops); } void QQuickWebViewPrivate::loadDidStop() @@ -889,15 +890,6 @@ void QQuickWebViewFlickablePrivate::pageDidRequestScroll(const QPoint& pos) m_pageViewportController->pageDidRequestScroll(pos); } -void QQuickWebViewFlickablePrivate::handleMouseEvent(QMouseEvent* event) -{ - if (!pageView->eventHandler()) - return; - - // FIXME: Update the axis locker for mouse events as well. - pageView->eventHandler()->handleInputEvent(event); -} - QQuickWebViewExperimental::QQuickWebViewExperimental(QQuickWebView *webView, QQuickWebViewPrivate* webViewPrivate) : QObject(webView) , q_ptr(webView) diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h b/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h index adedb6a31..8445fe2f7 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h @@ -223,7 +223,6 @@ public: virtual void updateViewportSize(); virtual void pageDidRequestScroll(const QPoint& pos); - virtual void handleMouseEvent(QMouseEvent*); private: QScopedPointer<WebKit::PageViewportController> m_pageViewportController; diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.cpp index dc1b213d4..4c0ced289 100644 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.cpp +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.cpp @@ -92,11 +92,6 @@ void CoordinatedBackingStore::updateTile(int id, const IntRect& sourceRect, cons it->value.setBackBuffer(tileRect, sourceRect, backBuffer, offset); } -bool CoordinatedBackingStore::isEmpty() const -{ - return m_tiles.size() == m_tilesToRemove.size(); -} - PassRefPtr<BitmapTexture> CoordinatedBackingStore::texture() const { HashMap<int, CoordinatedBackingStoreTile>::const_iterator end = m_tiles.end(); diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.h index b0baca635..4038a3724 100644 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.h +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.h @@ -61,7 +61,6 @@ public: void removeTile(int); void removeAllTiles(); void updateTile(int, const WebCore::IntRect&, const WebCore::IntRect&, PassRefPtr<ShareableSurface>, const WebCore::IntPoint&); - bool isEmpty() const; static PassRefPtr<CoordinatedBackingStore> create() { return adoptRef(new CoordinatedBackingStore); } void commitTileOperations(WebCore::TextureMapper*); PassRefPtr<WebCore::BitmapTexture> texture() const; diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp index 0c009ec48..7fae9a011 100644 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp @@ -66,6 +66,11 @@ static FloatPoint boundedScrollPosition(const FloatPoint& scrollPosition, const return FloatPoint(scrollPositionX, scrollPositionY); } +static bool layerShouldHaveBackingStore(GraphicsLayer* layer) +{ + return layer->drawsContent() && layer->contentsAreVisible() && !layer->size().isEmpty(); +} + LayerTreeRenderer::LayerTreeRenderer(LayerTreeCoordinatorProxy* layerTreeCoordinatorProxy) : m_layerTreeCoordinatorProxy(layerTreeCoordinatorProxy) , m_isActive(false) @@ -93,8 +98,11 @@ PassOwnPtr<GraphicsLayer> LayerTreeRenderer::createLayer(WebLayerID) void LayerTreeRenderer::paintToCurrentGLContext(const TransformationMatrix& matrix, float opacity, const FloatRect& clipRect, TextureMapper::PaintFlags PaintFlags) { - if (!m_textureMapper) + if (!m_textureMapper) { m_textureMapper = TextureMapper::create(TextureMapper::OpenGLMode); + static_cast<TextureMapperGL*>(m_textureMapper.get())->setEnableEdgeDistanceAntialiasing(true); + } + ASSERT(m_textureMapper->accelerationMode() == TextureMapper::OpenGLMode); syncRemoteContent(); @@ -351,6 +359,7 @@ void LayerTreeRenderer::setLayerState(WebLayerID id, const WebLayerInfo& layerIn m_fixedLayers.remove(id); assignImageBackingToLayer(layer, layerInfo.imageID); + prepareContentBackingStore(layer); // Never make the root layer clip. layer->setMasksToBounds(layerInfo.isRootLayer ? false : layerInfo.masksToBounds); @@ -403,34 +412,78 @@ void LayerTreeRenderer::setRootLayerID(WebLayerID layerID) m_rootLayer->addChild(layer); } -PassRefPtr<CoordinatedBackingStore> LayerTreeRenderer::getBackingStore(GraphicsLayer* graphicsLayer) +CoordinatedBackingStore* LayerTreeRenderer::getBackingStore(GraphicsLayer* graphicsLayer) { TextureMapperLayer* layer = toTextureMapperLayer(graphicsLayer); ASSERT(layer); - RefPtr<CoordinatedBackingStore> backingStore = static_cast<CoordinatedBackingStore*>(layer->backingStore().get()); - if (!backingStore) { - backingStore = CoordinatedBackingStore::create(); - layer->setBackingStore(backingStore); - } - ASSERT(backingStore); + CoordinatedBackingStore* backingStore = static_cast<CoordinatedBackingStore*>(layer->backingStore().get()); + + BackingStoreMap::iterator it = m_pendingSyncBackingStores.find(layer); + if (it != m_pendingSyncBackingStores.end()) + backingStore = it->value.get(); return backingStore; } -void LayerTreeRenderer::removeBackingStoreIfNeeded(GraphicsLayer* graphicsLayer) +void LayerTreeRenderer::prepareContentBackingStore(GraphicsLayer* graphicsLayer) +{ + if (!layerShouldHaveBackingStore(graphicsLayer)) { + removeBackingStoreIfNeeded(graphicsLayer); + return; + } + + createBackingStoreIfNeeded(graphicsLayer); +} + +void LayerTreeRenderer::createBackingStoreIfNeeded(GraphicsLayer* graphicsLayer) { TextureMapperLayer* layer = toTextureMapperLayer(graphicsLayer); ASSERT(layer); - RefPtr<CoordinatedBackingStore> backingStore = static_cast<CoordinatedBackingStore*>(layer->backingStore().get()); - ASSERT(backingStore); - if (backingStore->isEmpty()) - layer->setBackingStore(0); + + // Make sure the layer does not already have a backing store (committed or pending). + BackingStoreMap::iterator it = m_pendingSyncBackingStores.find(layer); + if (it != m_pendingSyncBackingStores.end()) { + if (!it->value) { + // There is a pending removal, cancel it. + m_pendingSyncBackingStores.remove(it); + } + // There is already a pending addition. + return; + } + if (layer->backingStore()) + return; // The layer already has a backing store (and no pending removal). + + RefPtr<CoordinatedBackingStore> backingStore(CoordinatedBackingStore::create()); + backingStore->setSize(graphicsLayer->size()); + ASSERT(!m_pendingSyncBackingStores.contains(layer)); + m_pendingSyncBackingStores.add(layer, backingStore); } -void LayerTreeRenderer::resetBackingStoreSizeToLayerSize(GraphicsLayer* graphicsLayer) +void LayerTreeRenderer::removeBackingStoreIfNeeded(GraphicsLayer* graphicsLayer) { TextureMapperLayer* layer = toTextureMapperLayer(graphicsLayer); ASSERT(layer); - RefPtr<CoordinatedBackingStore> backingStore = static_cast<CoordinatedBackingStore*>(layer->backingStore().get()); + + // Check if the layout already has a backing store (committed or pending). + BackingStoreMap::iterator it = m_pendingSyncBackingStores.find(layer); + if (it != m_pendingSyncBackingStores.end()) { + if (it->value) { + // There is a pending addition, cancel it. + m_pendingSyncBackingStores.remove(it); + } + // There is already a pending removal. + return; + } + + if (!layer->backingStore()) + return; // The layer has no backing store (and no pending addition). + + ASSERT(!m_pendingSyncBackingStores.contains(layer)); + m_pendingSyncBackingStores.add(layer, 0); +} + +void LayerTreeRenderer::resetBackingStoreSizeToLayerSize(GraphicsLayer* graphicsLayer) +{ + CoordinatedBackingStore* backingStore = getBackingStore(graphicsLayer); ASSERT(backingStore); backingStore->setSize(graphicsLayer->size()); } @@ -439,7 +492,8 @@ void LayerTreeRenderer::createTile(WebLayerID layerID, int tileID, float scale) { GraphicsLayer* layer = layerByID(layerID); ASSERT(layer); - RefPtr<CoordinatedBackingStore> backingStore = getBackingStore(layer); + CoordinatedBackingStore* backingStore = getBackingStore(layer); + ASSERT(backingStore); backingStore->createTile(tileID, scale); resetBackingStoreSizeToLayerSize(layer); } @@ -448,11 +502,13 @@ void LayerTreeRenderer::removeTile(WebLayerID layerID, int tileID) { GraphicsLayer* layer = layerByID(layerID); ASSERT(layer); - RefPtr<CoordinatedBackingStore> backingStore = getBackingStore(layer); + CoordinatedBackingStore* backingStore = getBackingStore(layer); + if (!backingStore) + return; + backingStore->removeTile(tileID); resetBackingStoreSizeToLayerSize(layer); m_backingStoresWithPendingBuffers.add(backingStore); - removeBackingStoreIfNeeded(layer); } void LayerTreeRenderer::updateTile(WebLayerID layerID, int tileID, const TileUpdate& update) @@ -460,6 +516,7 @@ void LayerTreeRenderer::updateTile(WebLayerID layerID, int tileID, const TileUpd GraphicsLayer* layer = layerByID(layerID); ASSERT(layer); RefPtr<CoordinatedBackingStore> backingStore = getBackingStore(layer); + ASSERT(backingStore); backingStore->updateTile(tileID, update.sourceRect, update.tileRect, update.surface, update.offset); resetBackingStoreSizeToLayerSize(layer); m_backingStoresWithPendingBuffers.add(backingStore); @@ -524,13 +581,22 @@ void LayerTreeRenderer::removeReleasedImageBackingsIfNeeded() m_releasedImageBackings.clear(); } -void LayerTreeRenderer::commitTileOperations() +void LayerTreeRenderer::commitPendingBackingStoreOperations() { HashSet<RefPtr<CoordinatedBackingStore> >::iterator end = m_backingStoresWithPendingBuffers.end(); for (HashSet<RefPtr<CoordinatedBackingStore> >::iterator it = m_backingStoresWithPendingBuffers.begin(); it != end; ++it) (*it)->commitTileOperations(m_textureMapper.get()); m_backingStoresWithPendingBuffers.clear(); + + { + BackingStoreMap::iterator end = m_pendingSyncBackingStores.end(); + BackingStoreMap::iterator it = m_pendingSyncBackingStores.begin(); + for (;it != end; ++it) + it->key->setBackingStore(it->value); + + m_pendingSyncBackingStores.clear(); + } } void LayerTreeRenderer::flushLayerChanges() @@ -541,7 +607,7 @@ void LayerTreeRenderer::flushLayerChanges() setAnimationsLocked(false); m_rootLayer->flushCompositingState(FloatRect()); - commitTileOperations(); + commitPendingBackingStoreOperations(); removeReleasedImageBackingsIfNeeded(); // The pending tiles state is on its way for the screen, tell the web process to render the next one. @@ -586,8 +652,6 @@ void LayerTreeRenderer::syncRemoteContent() for (size_t i = 0; i < renderQueue.size(); ++i) renderQueue[i](); - - m_renderQueue.clear(); } void LayerTreeRenderer::purgeGLResources() @@ -608,6 +672,7 @@ void LayerTreeRenderer::purgeGLResources() m_layers.clear(); m_fixedLayers.clear(); m_textureMapper.clear(); + m_pendingSyncBackingStores.clear(); m_backingStoresWithPendingBuffers.clear(); setActive(false); diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.h index b081c5e16..6f1056aac 100644 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.h +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.h @@ -41,6 +41,7 @@ namespace WebCore { class CustomFilterProgram; class CustomFilterProgramInfo; +class TextureMapperLayer; } namespace WebKit { @@ -138,14 +139,15 @@ private: void renderNextFrame(); void purgeBackingStores(); - void assignImageBackingToLayer(WebCore::GraphicsLayer*, CoordinatedImageBackingID); void removeReleasedImageBackingsIfNeeded(); void ensureRootLayer(); void ensureLayer(WebLayerID); - void commitTileOperations(); + void commitPendingBackingStoreOperations(); - PassRefPtr<CoordinatedBackingStore> getBackingStore(WebCore::GraphicsLayer*); + CoordinatedBackingStore* getBackingStore(WebCore::GraphicsLayer*); + void prepareContentBackingStore(WebCore::GraphicsLayer*); + void createBackingStoreIfNeeded(WebCore::GraphicsLayer*); void removeBackingStoreIfNeeded(WebCore::GraphicsLayer*); void resetBackingStoreSizeToLayerSize(WebCore::GraphicsLayer*); @@ -163,6 +165,9 @@ private: ImageBackingMap m_imageBackings; Vector<RefPtr<CoordinatedBackingStore> > m_releasedImageBackings; + typedef HashMap<WebCore::TextureMapperLayer*, RefPtr<CoordinatedBackingStore> > BackingStoreMap; + BackingStoreMap m_pendingSyncBackingStores; + HashSet<RefPtr<CoordinatedBackingStore> > m_backingStoresWithPendingBuffers; #if USE(GRAPHICS_SURFACE) diff --git a/Source/WebKit2/UIProcess/PageClient.h b/Source/WebKit2/UIProcess/PageClient.h index 0c7b89017..dd0cd5a1c 100644 --- a/Source/WebKit2/UIProcess/PageClient.h +++ b/Source/WebKit2/UIProcess/PageClient.h @@ -211,7 +211,7 @@ public: virtual void pluginFocusOrWindowFocusChanged(uint64_t pluginComplexTextInputIdentifier, bool pluginHasFocusAndWindowHasFocus) = 0; virtual void setPluginComplexTextInputState(uint64_t pluginComplexTextInputIdentifier, PluginComplexTextInputState) = 0; virtual CGContextRef containingWindowGraphicsContext() = 0; - virtual void didPerformDictionaryLookup(const String&, double scaleFactor, const DictionaryPopupInfo&) = 0; + virtual void didPerformDictionaryLookup(const AttributedString&, const DictionaryPopupInfo&) = 0; virtual void dismissDictionaryLookupPanel() = 0; virtual void showCorrectionPanel(WebCore::AlternativeTextType, const WebCore::FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings) = 0; virtual void dismissCorrectionPanel(WebCore::ReasonForDismissingAlternativeText) = 0; diff --git a/Source/WebKit2/UIProcess/PageViewportController.cpp b/Source/WebKit2/UIProcess/PageViewportController.cpp index 7c43a5546..ff135a2cf 100644 --- a/Source/WebKit2/UIProcess/PageViewportController.cpp +++ b/Source/WebKit2/UIProcess/PageViewportController.cpp @@ -195,8 +195,6 @@ void PageViewportController::didChangeViewportSize(const FloatSize& newSize) // Let the WebProcess know about the new viewport size, so that // it can resize the content accordingly. m_webPageProxy->setViewportSize(roundedIntSize(newSize)); - - syncVisibleContents(); } void PageViewportController::didChangeContentsVisibility(const FloatPoint& viewportPos, float viewportScale, const FloatPoint& trajectoryVector) @@ -236,6 +234,8 @@ void PageViewportController::didChangeViewportAttributes(const WebCore::Viewport if (updateMinimumScaleToFit()) m_client->didChangeViewportAttributes(); + + syncVisibleContents(); } WebCore::FloatSize PageViewportController::viewportSizeInContentsCoordinates() const diff --git a/Source/WebKit2/UIProcess/Plugins/qt/PluginProcessProxyQt.cpp b/Source/WebKit2/UIProcess/Plugins/qt/PluginProcessProxyQt.cpp index 679c6331d..8b4e3596f 100644 --- a/Source/WebKit2/UIProcess/Plugins/qt/PluginProcessProxyQt.cpp +++ b/Source/WebKit2/UIProcess/Plugins/qt/PluginProcessProxyQt.cpp @@ -207,7 +207,7 @@ bool PluginProcessProxy::scanPlugin(const String& pluginPath, RawPluginMetaData& String output(reinterpret_cast<const UChar*>(outputBytes.constData()), outputBytes.size() / sizeof(UChar)); Vector<String> lines; - output.split(UChar('\n'), lines); + output.split(UChar('\n'), true, lines); ASSERT(lines.size() == 3); result.name.swap(lines[0]); diff --git a/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp b/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp index d24c391cf..730dafeed 100644 --- a/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp +++ b/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp @@ -96,7 +96,7 @@ bool PluginProcessProxy::scanPlugin(const String& pluginPath, RawPluginMetaData& free(stdOut); Vector<String> lines; - stdOutString.split(UChar('\n'), lines); + stdOutString.split(UChar('\n'), true, lines); if (lines.size() < 3) return false; diff --git a/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h b/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h index 761c4a49c..29be36fc9 100644 --- a/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h +++ b/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h @@ -30,6 +30,10 @@ #include "WebPageGroupData.h" #include "WebPageProxy.h" +#if PLATFORM(MAC) +#include "ObjCObjectGraphCoders.h" +#endif + namespace WebKit { // Adds @@ -68,6 +72,13 @@ public: encoder << pageGroup->data(); break; } +#if PLATFORM(MAC) + case APIObject::TypeObjCObjectGraph: { + ObjCObjectGraph* objectGraph = static_cast<ObjCObjectGraph*>(m_root); + encoder << WebContextObjCObjectGraphEncoder(objectGraph); + break; + } +#endif default: ASSERT_NOT_REACHED(); break; @@ -127,6 +138,16 @@ public: coder.m_root = WebPageGroup::get(pageGroupID); break; } +#if PLATFORM(MAC) + case APIObject::TypeObjCObjectGraph: { + RefPtr<ObjCObjectGraph> objectGraph; + WebContextObjCObjectGraphDecoder objectGraphDecoder(objectGraph, coder.m_process); + if (!decoder->decode(objectGraphDecoder)) + return false; + coder.m_root = objectGraph.get(); + break; + } +#endif default: return false; } diff --git a/Source/WebKit2/UIProcess/WebPageProxy.cpp b/Source/WebKit2/UIProcess/WebPageProxy.cpp index 192c5cb7b..df416c09d 100644 --- a/Source/WebKit2/UIProcess/WebPageProxy.cpp +++ b/Source/WebKit2/UIProcess/WebPageProxy.cpp @@ -234,6 +234,7 @@ WebPageProxy::WebPageProxy(PageClient* pageClient, PassRefPtr<WebProcessProxy> p , m_shouldSendEventsSynchronously(false) , m_suppressVisibilityUpdates(false) , m_mediaVolume(1) + , m_mayStartMediaWhenInWindow(true) #if ENABLE(PAGE_VISIBILITY_API) , m_visibilityState(PageVisibilityStateVisible) #endif @@ -296,11 +297,11 @@ bool WebPageProxy::isValid() PassRefPtr<ImmutableArray> WebPageProxy::relatedPages() const { + // pages() returns a list of pages in WebProcess, so this page may or may not be among them - a client can use a reference to WebPageProxy after the page has closed. Vector<WebPageProxy*> pages = m_process->pages(); - ASSERT(pages.contains(this)); Vector<RefPtr<APIObject> > result; - result.reserveCapacity(pages.size() - 1); + result.reserveCapacity(pages.size()); for (size_t i = 0; i < pages.size(); ++i) { if (pages[i] != this) result.append(pages[i]); @@ -2782,6 +2783,19 @@ void WebPageProxy::setMediaVolume(float volume) m_process->send(Messages::WebPage::SetMediaVolume(volume), m_pageID); } +void WebPageProxy::setMayStartMediaWhenInWindow(bool mayStartMedia) +{ + if (mayStartMedia == m_mayStartMediaWhenInWindow) + return; + + m_mayStartMediaWhenInWindow = mayStartMedia; + + if (!isValid()) + return; + + process()->send(Messages::WebPage::SetMayStartMediaWhenInWindow(mayStartMedia), m_pageID); +} + #if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) void WebPageProxy::handleDownloadRequest(DownloadProxy* download) { @@ -3763,6 +3777,7 @@ WebPageCreationParameters WebPageProxy::creationParameters() const parameters.canRunModal = m_canRunModal; parameters.deviceScaleFactor = m_intrinsicDeviceScaleFactor; parameters.mediaVolume = m_mediaVolume; + parameters.mayStartMediaWhenInWindow = m_mayStartMediaWhenInWindow; #if PLATFORM(MAC) parameters.isSmartInsertDeleteEnabled = m_isSmartInsertDeleteEnabled; diff --git a/Source/WebKit2/UIProcess/WebPageProxy.h b/Source/WebKit2/UIProcess/WebPageProxy.h index 91fad303e..9139b482e 100644 --- a/Source/WebKit2/UIProcess/WebPageProxy.h +++ b/Source/WebKit2/UIProcess/WebPageProxy.h @@ -736,6 +736,7 @@ public: void printMainFrame(); void setMediaVolume(float); + void setMayStartMediaWhenInWindow(bool); // WebPopupMenuProxy::Client virtual NativeWebMouseEvent* currentlyProcessedMouseDownEvent(); @@ -754,6 +755,8 @@ public: void endColorChooser(); #endif + const WebLoaderClient& loaderClient() { return m_loaderClient; } + private: WebPageProxy(PageClient*, PassRefPtr<WebProcessProxy>, WebPageGroup*, uint64_t pageID); @@ -948,7 +951,7 @@ private: void searchWithSpotlight(const String&); // Dictionary. - void didPerformDictionaryLookup(const String&, const DictionaryPopupInfo&); + void didPerformDictionaryLookup(const AttributedString&, const DictionaryPopupInfo&); #endif // Spelling and grammar. @@ -1238,6 +1241,7 @@ private: bool m_suppressVisibilityUpdates; float m_mediaVolume; + bool m_mayStartMediaWhenInWindow; #if PLATFORM(QT) WTF::HashSet<RefPtr<QtRefCountedNetworkRequestData> > m_applicationSchemeRequests; diff --git a/Source/WebKit2/UIProcess/WebPageProxy.messages.in b/Source/WebKit2/UIProcess/WebPageProxy.messages.in index 7158d8127..f88eda49e 100644 --- a/Source/WebKit2/UIProcess/WebPageProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebPageProxy.messages.in @@ -271,7 +271,7 @@ messages -> WebPageProxy { #if PLATFORM(MAC) # Dictionary support. - DidPerformDictionaryLookup(WTF::String text, WebKit::DictionaryPopupInfo dictionaryPopupInfo) + DidPerformDictionaryLookup(WebKit::AttributedString text, WebKit::DictionaryPopupInfo dictionaryPopupInfo) # Keyboard input support messages InterpretQueuedKeyEvent(WebKit::EditorState state) -> (bool handled, Vector<WebCore::KeypressCommand> savedCommands) diff --git a/Source/WebKit2/UIProcess/efl/PageClientLegacyImpl.cpp b/Source/WebKit2/UIProcess/efl/PageClientLegacyImpl.cpp index 6f305bdd6..f62b8671a 100644 --- a/Source/WebKit2/UIProcess/efl/PageClientLegacyImpl.cpp +++ b/Source/WebKit2/UIProcess/efl/PageClientLegacyImpl.cpp @@ -49,7 +49,7 @@ void PageClientLegacyImpl::didCommitLoad() void PageClientLegacyImpl::updateViewportSize(const WebCore::IntSize& size) { #if USE(TILED_BACKING_STORE) - m_viewImpl->page()->drawingArea()->setVisibleContentsRect(IntRect(m_viewImpl->scrollPosition(), size), m_viewImpl->scaleFactor(), FloatPoint()); + m_viewImpl->page()->drawingArea()->setVisibleContentsRect(IntRect(m_viewImpl->discretePagePosition(), size), m_viewImpl->scaleFactor(), FloatPoint()); #else UNUSED_PARAM(size); #endif @@ -86,7 +86,7 @@ void PageClientLegacyImpl::didChangeContentsSize(const WebCore::IntSize& size) #if USE(TILED_BACKING_STORE) void PageClientLegacyImpl::pageDidRequestScroll(const IntPoint& position) { - m_viewImpl->setScrollPosition(position); + m_viewImpl->setPagePosition(FloatPoint(position)); m_viewImpl->update(); } diff --git a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp index cdd565008..fe2913969 100644 --- a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp @@ -40,7 +40,6 @@ namespace WebKit { PageViewportControllerClientEfl::PageViewportControllerClientEfl(EwkViewImpl* viewImpl) : m_viewImpl(viewImpl) - , m_scaleFactor(1) , m_controller(0) { ASSERT(m_viewImpl); @@ -68,15 +67,6 @@ void PageViewportControllerClientEfl::updateViewportSize(const IntSize& viewport m_controller->didChangeViewportSize(viewportSize); } -void PageViewportControllerClientEfl::setVisibleContentsRect(const IntPoint& newScrollPosition, float newScale, const FloatPoint& trajectory) -{ - m_scaleFactor = newScale; - m_scrollPosition = newScrollPosition; - - ASSERT(m_controller); - m_controller->didChangeContentsVisibility(m_scrollPosition, m_scaleFactor, trajectory); -} - void PageViewportControllerClientEfl::didChangeContentsSize(const WebCore::IntSize& contentsSize) { drawingArea()->layerTreeCoordinatorProxy()->setContentsSize(contentsSize); @@ -85,25 +75,27 @@ void PageViewportControllerClientEfl::didChangeContentsSize(const WebCore::IntSi void PageViewportControllerClientEfl::setViewportPosition(const WebCore::FloatPoint& contentsPoint) { - IntPoint position(contentsPoint.x(), contentsPoint.y()); - setVisibleContentsRect(position, m_scaleFactor, FloatPoint()); - m_viewImpl->setScrollPosition(position); + m_contentPosition = roundedIntPoint(contentsPoint); + + FloatPoint pos(contentsPoint); + pos.scale(scaleFactor(), scaleFactor()); + m_viewImpl->setPagePosition(pos); + + m_controller->didChangeContentsVisibility(m_contentPosition, scaleFactor()); } void PageViewportControllerClientEfl::setContentsScale(float newScale, bool treatAsInitialValue) { - if (treatAsInitialValue) { - m_scrollPosition = IntPoint(); - m_viewImpl->setScrollPosition(IntPoint()); - } - m_scaleFactor = newScale; + if (treatAsInitialValue) + setViewportPosition(FloatPoint(0, 0)); + m_viewImpl->setScaleFactor(newScale); } void PageViewportControllerClientEfl::didResumeContent() { ASSERT(m_controller); - m_controller->didChangeContentsVisibility(m_scrollPosition, m_scaleFactor); + m_controller->didChangeContentsVisibility(m_contentPosition, scaleFactor()); } void PageViewportControllerClientEfl::didChangeVisibleContents() diff --git a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h index ee9d37690..1ae6a541d 100644 --- a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h @@ -28,12 +28,11 @@ #if USE(TILED_BACKING_STORE) +#include "EwkViewImpl.h" #include "PageClientBase.h" #include "PageViewportControllerClient.h" #include <wtf/PassOwnPtr.h> -class EwkViewImpl; - namespace WebKit { class PageViewportControllerClientEfl : public PageViewportControllerClient { @@ -46,11 +45,10 @@ public: DrawingAreaProxy* drawingArea() const; WebCore::IntSize viewSize() { return m_viewportSize; } - float scaleFactor() const { return m_scaleFactor; } - WebCore::IntPoint scrollPosition() { return m_scrollPosition; } + float scaleFactor() const { return m_viewImpl->scaleFactor(); } + WebCore::IntPoint contentPosition() const { return m_contentPosition; } void updateViewportSize(const WebCore::IntSize& viewportSize); - void setVisibleContentsRect(const WebCore::IntPoint&, float, const WebCore::FloatPoint&); void setRendererActive(bool); virtual void setViewportPosition(const WebCore::FloatPoint& contentsPoint); @@ -68,8 +66,7 @@ private: EwkViewImpl* m_viewImpl; WebCore::IntSize m_viewportSize; - WebCore::IntPoint m_scrollPosition; - float m_scaleFactor; + WebCore::IntPoint m_contentPosition; PageViewportController* m_controller; }; diff --git a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h index 9ce88ae5a..d832ab663 100644 --- a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h +++ b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h @@ -38,13 +38,14 @@ class IntRect; } @class WKView; +@class WebCoreFullScreenPlaceholderView; @class WebWindowScaleAnimation; @class WebWindowFadeAnimation; -@interface WKFullScreenWindowController : NSWindowController { +@interface WKFullScreenWindowController : NSWindowController<NSWindowDelegate> { @private WKView *_webView; - RetainPtr<NSImageView> _webViewPlaceholder; + RetainPtr<WebCoreFullScreenPlaceholderView> _webViewPlaceholder; RetainPtr<WebWindowScaleAnimation> _scaleAnimation; RetainPtr<WebWindowFadeAnimation> _fadeAnimation; RetainPtr<NSWindow> _backgroundWindow; diff --git a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm index 238a67516..7a891cb71 100644 --- a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm +++ b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm @@ -39,6 +39,8 @@ #import <WebCore/DisplaySleepDisabler.h> #import <WebCore/FloatRect.h> #import <WebCore/IntRect.h> +#import <WebCore/LocalizedStrings.h> +#import <WebCore/WebCoreFullScreenPlaceholderView.h> #import <WebCore/WebCoreFullScreenWindow.h> #import <WebCore/WebWindowAnimation.h> #import <WebKit/WebNSWindowExtras.h> @@ -53,8 +55,12 @@ static RetainPtr<NSWindow> createBackgroundFullscreenWindow(NSRect frame); static const CFTimeInterval defaultAnimationDuration = 0.5; static const NSTimeInterval DefaultWatchdogTimerInterval = 1; +@interface NSWindow (WebNSWindowDetails) +- (void)exitFullScreenMode:(id)sender; +- (void)enterFullScreenMode:(id)sender; +@end + @interface WKFullScreenWindowController(Private)<NSAnimationDelegate> -- (void)_updateMenuAndDockForFullScreen; - (void)_replaceView:(NSView*)view with:(NSView*)otherView; - (WebPageProxy*)_page; - (WebFullScreenManagerProxy*)_manager; @@ -87,11 +93,12 @@ static NSRect convertRectToScreen(NSWindow *window, NSRect rect) #pragma mark Initialization - (id)init { - NSWindow *window = [[WebCoreFullScreenWindow alloc] initWithContentRect:NSZeroRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]; - self = [super initWithWindow:window]; - [window release]; + RetainPtr<NSWindow> window = adoptNS([[WebCoreFullScreenWindow alloc] initWithContentRect:NSZeroRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]); + self = [super initWithWindow:window.get()]; if (!self) return nil; + [window.get() setDelegate:self]; + [window.get() setCollectionBehavior:([window collectionBehavior] | NSWindowCollectionBehaviorFullScreenPrimary)]; [self windowDidLoad]; return self; @@ -100,6 +107,7 @@ static NSRect convertRectToScreen(NSWindow *window, NSRect rect) - (void)dealloc { [self setWebView:nil]; + [[self window] setDelegate:nil]; [NSObject cancelPreviousPerformRequestsWithTarget:self]; @@ -174,7 +182,6 @@ static NSRect convertRectToScreen(NSWindow *window, NSRect rect) // the Dock's size or location, or they may have changed the fullScreen screen's dimensions. // Update our presentation parameters, and ensure that the full screen window occupies the // entire screen: - [self _updateMenuAndDockForFullScreen]; NSWindow* window = [self window]; NSRect screenFrame = [[window screen] frame]; [window setFrame:screenFrame display:YES]; @@ -212,8 +219,6 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) return; _isFullScreen = YES; - [self _updateMenuAndDockForFullScreen]; - if (!screen) screen = [NSScreen mainScreen]; NSRect screenFrame = [screen frame]; @@ -246,11 +251,11 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) // Swap the webView placeholder into place. if (!_webViewPlaceholder) { - _webViewPlaceholder.adoptNS([[NSImageView alloc] init]); - [_webViewPlaceholder.get() setLayer:[CALayer layer]]; - [_webViewPlaceholder.get() setWantsLayer:YES]; + _webViewPlaceholder.adoptNS([[WebCoreFullScreenPlaceholderView alloc] initWithFrame:[_webView frame]]); + [_webViewPlaceholder.get() setTarget:self]; + [_webViewPlaceholder.get() setAction:@selector(cancelOperation:)]; } - [[_webViewPlaceholder.get() layer] setContents:(id)webViewContents.get()]; + [_webViewPlaceholder.get() setContents:(id)webViewContents.get()]; [self _replaceView:_webView with:_webViewPlaceholder.get()]; // Then insert the WebView into the full screen window @@ -273,9 +278,10 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) _initialFrame = initialFrame; _finalFrame = finalFrame; - [self _updateMenuAndDockForFullScreen]; + if (!_backgroundWindow) + _backgroundWindow = createBackgroundFullscreenWindow(NSZeroRect); - [self _startEnterFullScreenAnimationWithDuration:defaultAnimationDuration]; + [[self window] enterFullScreenMode:self]; } - (void)finishedEnterFullScreenAnimation:(bool)completed @@ -294,24 +300,14 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) windowBounds.origin = NSZeroPoint; WKWindowSetClipRect([self window], windowBounds); - NSWindow *webWindow = [_webViewPlaceholder.get() window]; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - // In Lion, NSWindow will animate into and out of orderOut operations. Suppress that - // behavior here, making sure to reset the animation behavior afterward. - NSWindowAnimationBehavior animationBehavior = [webWindow animationBehavior]; - [webWindow setAnimationBehavior:NSWindowAnimationBehaviorNone]; -#endif - [webWindow orderOut:self]; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - [webWindow setAnimationBehavior:animationBehavior]; -#endif - [_fadeAnimation.get() stopAnimation]; [_fadeAnimation.get() setWindow:nil]; _fadeAnimation = nullptr; [_backgroundWindow.get() orderOut:self]; [_backgroundWindow.get() setFrame:NSZeroRect display:YES]; + + [_webViewPlaceholder.get() setExitWarningVisible:YES]; NSEnableScreenUpdates(); } else [_scaleAnimation.get() stopAnimation]; @@ -328,7 +324,9 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) return; _isFullScreen = NO; - // Screen updates to be re-enabled in _startExitFullScreenAnimationWithDuration: + [_webViewPlaceholder.get() setExitWarningVisible:NO]; + + // Screen updates to be re-enabled in _startExitFullScreenAnimationWithDuration: or beganExitFullScreenWithInitialFrame:finalFrame: NSDisableScreenUpdates(); [[self window] setAutodisplay:NO]; @@ -349,30 +347,18 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) if (_isEnteringFullScreen) [self finishedEnterFullScreenAnimation:NO]; - [self _updateMenuAndDockForFullScreen]; - - NSWindow* webWindow = [_webViewPlaceholder.get() window]; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - // In Lion, NSWindow will animate into and out of orderOut operations. Suppress that - // behavior here, making sure to reset the animation behavior afterward. - NSWindowAnimationBehavior animationBehavior = [webWindow animationBehavior]; - [webWindow setAnimationBehavior:NSWindowAnimationBehaviorNone]; -#endif - // If the user has moved the fullScreen window into a new space, temporarily change - // the collectionBehavior of the webView's window so that it is pulled into the active space: - if (!([webWindow respondsToSelector:@selector(isOnActiveSpace)] ? [webWindow isOnActiveSpace] : YES)) { - NSWindowCollectionBehavior behavior = [webWindow collectionBehavior]; - [webWindow setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces]; - [webWindow orderWindow:NSWindowBelow relativeTo:[[self window] windowNumber]]; - [webWindow setCollectionBehavior:behavior]; - } else - [webWindow orderWindow:NSWindowBelow relativeTo:[[self window] windowNumber]]; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - [webWindow setAnimationBehavior:animationBehavior]; -#endif + if (![[self window] isOnActiveSpace]) { + // If the full screen window is not in the active space, the NSWindow full screen animation delegate methods + // will never be called. So call finishedExitFullScreenAnimation explicitly. + [self finishedExitFullScreenAnimation:YES]; - [self _startExitFullScreenAnimationWithDuration:defaultAnimationDuration]; + // Because we are breaking the normal animation pattern, re-enable screen updates + // as exitFullScreen has disabled them, but _startExitFullScreenAnimationWithDuration: + // will never be called. + NSEnableScreenUpdates(); + } + + [[self window] exitFullScreenMode:self]; } static void completeFinishExitFullScreenAnimationAfterRepaint(WKErrorRef, void*); @@ -383,8 +369,6 @@ static void completeFinishExitFullScreenAnimationAfterRepaint(WKErrorRef, void*) return; _isExitingFullScreen = NO; - [self _updateMenuAndDockForFullScreen]; - // Screen updates to be re-enabled in completeFinishExitFullScreenAnimationAfterRepaint. NSDisableScreenUpdates(); [[_webViewPlaceholder.get() window] setAutodisplay:NO]; @@ -444,46 +428,51 @@ static void completeFinishExitFullScreenAnimationAfterRepaint(WKErrorRef, void* } #pragma mark - -#pragma mark NSAnimation delegate +#pragma mark Custom NSWindow Full Screen Animation -- (void)animationDidEnd:(NSAnimation*)animation +- (NSArray *)customWindowsToEnterFullScreenForWindow:(NSWindow *)window { - if (_isFullScreen) - [self finishedEnterFullScreenAnimation:YES]; - else - [self finishedExitFullScreenAnimation:YES]; + return [NSArray arrayWithObjects:[self window], _backgroundWindow.get(), nil]; } -#pragma mark - -#pragma mark Internal Interface +- (NSArray *)customWindowsToExitFullScreenForWindow:(NSWindow *)window +{ + return [NSArray arrayWithObjects:[self window], _backgroundWindow.get(), nil]; +} -- (void)_updateMenuAndDockForFullScreen +- (void)window:(NSWindow *)window startCustomAnimationToEnterFullScreenWithDuration:(NSTimeInterval)duration { - // NSApplicationPresentationOptions is available on > 10.6 only: -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 - NSApplicationPresentationOptions options = NSApplicationPresentationDefault; - NSScreen* fullScreenScreen = [[self window] screen]; - - if (_isFullScreen) { - // Auto-hide the menu bar if the fullScreenScreen contains the menu bar: - // NOTE: if the fullScreenScreen contains the menu bar but not the dock, we must still - // auto-hide the dock, or an exception will be thrown. - if ([[NSScreen screens] objectAtIndex:0] == fullScreenScreen) - options |= (NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock); - // Check if the current screen contains the dock by comparing the screen's frame to its - // visibleFrame; if a dock is present, the visibleFrame will differ. If the current screen - // contains the dock, hide it. - else if (!NSEqualRects([fullScreenScreen frame], [fullScreenScreen visibleFrame])) - options |= NSApplicationPresentationAutoHideDock; - } - - if ([NSApp respondsToSelector:@selector(setPresentationOptions:)]) - [NSApp setPresentationOptions:options]; - else -#endif - SetSystemUIMode(_isFullScreen ? kUIModeAllHidden : kUIModeNormal, 0); + [self _startEnterFullScreenAnimationWithDuration:duration]; +} + +- (void)window:(NSWindow *)window startCustomAnimationToExitFullScreenWithDuration:(NSTimeInterval)duration +{ + [self _startExitFullScreenAnimationWithDuration:duration]; +} + +- (void)windowDidFailToEnterFullScreen:(NSWindow *)window +{ + [self finishedEnterFullScreenAnimation:NO]; +} + +- (void)windowDidEnterFullScreen:(NSNotification*)notification +{ + [self finishedEnterFullScreenAnimation:YES]; +} + +- (void)windowDidFailToExitFullScreen:(NSWindow *)window +{ + [self finishedExitFullScreenAnimation:NO]; } +- (void)windowDidExitFullScreen:(NSNotification*)notification +{ + [self finishedExitFullScreenAnimation:YES]; +} + +#pragma mark - +#pragma mark Internal Interface + - (WebPageProxy*)_page { return toImpl([_webView pageRef]); @@ -543,7 +532,6 @@ static NSRect windowFrameFromApparentFrames(NSRect screenFrame, NSRect initialFr _scaleAnimation.adoptNS([[WebWindowScaleAnimation alloc] initWithHintedDuration:duration window:[self window] initalFrame:initialWindowFrame finalFrame:screenFrame]); [_scaleAnimation.get() setAnimationBlockingMode:NSAnimationNonblocking]; - [_scaleAnimation.get() setDelegate:self]; [_scaleAnimation.get() setCurrentProgress:0]; [_scaleAnimation.get() startAnimation]; @@ -596,7 +584,6 @@ static NSRect windowFrameFromApparentFrames(NSRect screenFrame, NSRect initialFr _scaleAnimation.adoptNS([[WebWindowScaleAnimation alloc] initWithHintedDuration:duration window:[self window] initalFrame:currentFrame finalFrame:initialWindowFrame]); [_scaleAnimation.get() setAnimationBlockingMode:NSAnimationNonblocking]; - [_scaleAnimation.get() setDelegate:self]; [_scaleAnimation.get() setCurrentProgress:0]; [_scaleAnimation.get() startAnimation]; diff --git a/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm index 6f0956e6d..137c22f2c 100644 --- a/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm +++ b/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm @@ -400,9 +400,9 @@ void WebPageProxy::setSmartInsertDeleteEnabled(bool isSmartInsertDeleteEnabled) process()->send(Messages::WebPage::SetSmartInsertDeleteEnabled(isSmartInsertDeleteEnabled), m_pageID); } -void WebPageProxy::didPerformDictionaryLookup(const String& text, const DictionaryPopupInfo& dictionaryPopupInfo) +void WebPageProxy::didPerformDictionaryLookup(const AttributedString& text, const DictionaryPopupInfo& dictionaryPopupInfo) { - m_pageClient->didPerformDictionaryLookup(text, m_pageScaleFactor, dictionaryPopupInfo); + m_pageClient->didPerformDictionaryLookup(text, dictionaryPopupInfo); } void WebPageProxy::registerWebProcessAccessibilityToken(const CoreIPC::DataReference& data) diff --git a/Source/WebKit2/WebKit2.xcodeproj/project.pbxproj b/Source/WebKit2/WebKit2.xcodeproj/project.pbxproj index 76e2d2a67..f5893bff4 100644 --- a/Source/WebKit2/WebKit2.xcodeproj/project.pbxproj +++ b/Source/WebKit2/WebKit2.xcodeproj/project.pbxproj @@ -811,6 +811,10 @@ BC8699B7116AADAA002A925B /* WKViewInternal.h in Headers */ = {isa = PBXBuildFile; fileRef = BC8699B4116AADAA002A925B /* WKViewInternal.h */; }; BC8780FC1161C2B800CC2768 /* PlatformProcessIdentifier.h in Headers */ = {isa = PBXBuildFile; fileRef = BC8780FB1161C2B800CC2768 /* PlatformProcessIdentifier.h */; }; BC8A501511765F5600757573 /* WKRetainPtr.h in Headers */ = {isa = PBXBuildFile; fileRef = BC8A501411765F5600757573 /* WKRetainPtr.h */; settings = {ATTRIBUTES = (Private, ); }; }; + BC8ACA1316670D89004C1941 /* ObjCObjectGraph.h in Headers */ = {isa = PBXBuildFile; fileRef = BC8ACA0F16670D7A004C1941 /* ObjCObjectGraph.h */; }; + BC8ACA1416670D89004C1941 /* ObjCObjectGraph.mm in Sources */ = {isa = PBXBuildFile; fileRef = BC8ACA1016670D7B004C1941 /* ObjCObjectGraph.mm */; }; + BC8ACA1516670D89004C1941 /* ObjCObjectGraphCoders.h in Headers */ = {isa = PBXBuildFile; fileRef = BC8ACA1116670D7E004C1941 /* ObjCObjectGraphCoders.h */; }; + BC8ACA1616670D89004C1941 /* ObjCObjectGraphCoders.mm in Sources */ = {isa = PBXBuildFile; fileRef = BC8ACA1216670D83004C1941 /* ObjCObjectGraphCoders.mm */; }; BC8F2F2A16273A2C005FACB5 /* WKWebProcessPlugInBrowserContextController.mm in Sources */ = {isa = PBXBuildFile; fileRef = BC8F2F2816273A2B005FACB5 /* WKWebProcessPlugInBrowserContextController.mm */; }; BC8F2F2B16273A2C005FACB5 /* WKWebProcessPlugInBrowserContextController.h in Headers */ = {isa = PBXBuildFile; fileRef = BC8F2F2916273A2C005FACB5 /* WKWebProcessPlugInBrowserContextController.h */; settings = {ATTRIBUTES = (Public, ); }; }; BC8F2F2E16273ACC005FACB5 /* WKWebProcessPlugInBrowserContextControllerInternal.h in Headers */ = {isa = PBXBuildFile; fileRef = BC8F2F2D16273ACB005FACB5 /* WKWebProcessPlugInBrowserContextControllerInternal.h */; }; @@ -1591,6 +1595,7 @@ 33D3A3C61339617900709BE4 /* WebMediaCacheManagerProxyMessageReceiver.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WebMediaCacheManagerProxyMessageReceiver.cpp; sourceTree = "<group>"; }; 33D3A3C71339617900709BE4 /* WebMediaCacheManagerProxyMessages.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebMediaCacheManagerProxyMessages.h; sourceTree = "<group>"; }; 33F9D5B81312F1EE000D683F /* WebResourceCacheManagerCFNet.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; name = WebResourceCacheManagerCFNet.cpp; path = ResourceCache/cf/WebResourceCacheManagerCFNet.cpp; sourceTree = "<group>"; }; + 3574B37F1665932C00859BB7 /* PDFAnnotationTextWidgetDetails.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = PDFAnnotationTextWidgetDetails.h; path = PDF/PDFAnnotationTextWidgetDetails.h; sourceTree = "<group>"; }; 3760881C150413E900FC82C7 /* WebRenderObject.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WebRenderObject.cpp; sourceTree = "<group>"; }; 3760881D150413E900FC82C7 /* WebRenderObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebRenderObject.h; sourceTree = "<group>"; }; 37608820150414F700FC82C7 /* WKRenderObject.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WKRenderObject.cpp; sourceTree = "<group>"; }; @@ -2074,6 +2079,10 @@ BC87DFA91018101400564216 /* libicucore.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libicucore.dylib; path = /usr/lib/libicucore.dylib; sourceTree = "<absolute>"; }; BC8A501011765AF700757573 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = WebProcess/Info.plist; sourceTree = "<group>"; }; BC8A501411765F5600757573 /* WKRetainPtr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WKRetainPtr.h; sourceTree = "<group>"; }; + BC8ACA0F16670D7A004C1941 /* ObjCObjectGraph.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ObjCObjectGraph.h; sourceTree = "<group>"; }; + BC8ACA1016670D7B004C1941 /* ObjCObjectGraph.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = ObjCObjectGraph.mm; sourceTree = "<group>"; }; + BC8ACA1116670D7E004C1941 /* ObjCObjectGraphCoders.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ObjCObjectGraphCoders.h; sourceTree = "<group>"; }; + BC8ACA1216670D83004C1941 /* ObjCObjectGraphCoders.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = ObjCObjectGraphCoders.mm; sourceTree = "<group>"; }; BC8F2F2816273A2B005FACB5 /* WKWebProcessPlugInBrowserContextController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WKWebProcessPlugInBrowserContextController.mm; sourceTree = "<group>"; }; BC8F2F2916273A2C005FACB5 /* WKWebProcessPlugInBrowserContextController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WKWebProcessPlugInBrowserContextController.h; sourceTree = "<group>"; }; BC8F2F2D16273ACB005FACB5 /* WKWebProcessPlugInBrowserContextControllerInternal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WKWebProcessPlugInBrowserContextControllerInternal.h; sourceTree = "<group>"; }; @@ -3774,6 +3783,10 @@ BC111B5A112F628200337BAB /* mac */ = { isa = PBXGroup; children = ( + BC8ACA0F16670D7A004C1941 /* ObjCObjectGraph.h */, + BC8ACA1016670D7B004C1941 /* ObjCObjectGraph.mm */, + BC8ACA1116670D7E004C1941 /* ObjCObjectGraphCoders.h */, + BC8ACA1216670D83004C1941 /* ObjCObjectGraphCoders.mm */, E179FD9B134D38060015B883 /* ArgumentCodersMac.h */, E179FD9E134D38250015B883 /* ArgumentCodersMac.mm */, E1A31731134CEA6C007C9A4F /* AttributedString.h */, @@ -3788,10 +3801,10 @@ C02BFF1D1251502E009CCBEA /* NativeWebKeyboardEventMac.mm */, 31EA25D0134F78B2005B1452 /* NativeWebMouseEventMac.mm */, DF58C6351371ACA000F9A37C /* NativeWebWheelEventMac.mm */, - E19582D2153CBFD700B60875 /* PDFKitImports.h */, - E19582D4153CC05300B60875 /* PDFKitImports.mm */, C574A57F12E66681002DFE98 /* PasteboardTypes.h */, C574A58012E66681002DFE98 /* PasteboardTypes.mm */, + E19582D2153CBFD700B60875 /* PDFKitImports.h */, + E19582D4153CC05300B60875 /* PDFKitImports.mm */, BCF505E51243047B005955AE /* PlatformCertificateInfo.h */, BCF505E61243047B005955AE /* PlatformCertificateInfo.mm */, E1CC1B8F12D7EADF00625838 /* PrintInfoMac.mm */, @@ -4433,6 +4446,7 @@ 2D870D0E1622B7F9000A3F20 /* PDFPlugin.mm */, E199875C142BFC9700BB2DE7 /* SimplePDFPlugin.mm */, E199875A142BF9B800BB2DE7 /* SimplePDFPlugin.h */, + 3574B37F1665932C00859BB7 /* PDFAnnotationTextWidgetDetails.h */, ); name = PDF; sourceTree = "<group>"; @@ -5000,6 +5014,8 @@ 2984F589164BA095004BC0C6 /* CustomProtocolManagerMessages.h in Headers */, 51F060E01654317F00F3281B /* WebResourceLoaderMessages.h in Headers */, 5175944B1657080400DD771D /* NetworkResourceLoaderMessages.h in Headers */, + BC8ACA1316670D89004C1941 /* ObjCObjectGraph.h in Headers */, + BC8ACA1516670D89004C1941 /* ObjCObjectGraphCoders.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -5954,6 +5970,8 @@ 2984F588164BA095004BC0C6 /* CustomProtocolManagerMessageReceiver.cpp in Sources */, 51F060E11654318500F3281B /* WebResourceLoaderMessageReceiver.cpp in Sources */, 5175944A1657080400DD771D /* NetworkResourceLoaderMessageReceiver.cpp in Sources */, + BC8ACA1416670D89004C1941 /* ObjCObjectGraph.mm in Sources */, + BC8ACA1616670D89004C1941 /* ObjCObjectGraphCoders.mm in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Source/WebKit2/WebProcess.pro b/Source/WebKit2/WebProcess.pro index e4186952f..7f8b1cab8 100644 --- a/Source/WebKit2/WebProcess.pro +++ b/Source/WebKit2/WebProcess.pro @@ -21,7 +21,8 @@ build?(webkit1): DEFINES += HAVE_WEBKIT1 INSTALLS += target isEmpty(INSTALL_BINS) { - target.path = $$[QT_INSTALL_BINS] + use?(libexecdir): target.path = $$[QT_INSTALL_LIBEXECS] + else: target.path = $$[QT_INSTALL_BINS] } else { target.path = $$INSTALL_BINS } diff --git a/Source/WebKit2/WebProcess/InjectedBundle/API/mac/WKWebProcessPlugIn.mm b/Source/WebKit2/WebProcess/InjectedBundle/API/mac/WKWebProcessPlugIn.mm index cbcc8492e..fbf731768 100644 --- a/Source/WebKit2/WebProcess/InjectedBundle/API/mac/WKWebProcessPlugIn.mm +++ b/Source/WebKit2/WebProcess/InjectedBundle/API/mac/WKWebProcessPlugIn.mm @@ -123,6 +123,12 @@ static WKWebProcessPlugInController *sharedInstance; return self; } +- (WKWebProcessPlugInBrowserContextController *)_browserContextControllerForBundlePageRef:(WKBundlePageRef)pageRef +{ + ASSERT(_bundlePageWrapperCache.contains(pageRef)); + return _bundlePageWrapperCache.get(pageRef).get(); +} + @end @implementation WKWebProcessPlugInController diff --git a/Source/WebKit2/WebProcess/InjectedBundle/API/mac/WKWebProcessPlugInInternal.h b/Source/WebKit2/WebProcess/InjectedBundle/API/mac/WKWebProcessPlugInInternal.h index 58b3cc3f7..a125e339e 100644 --- a/Source/WebKit2/WebProcess/InjectedBundle/API/mac/WKWebProcessPlugInInternal.h +++ b/Source/WebKit2/WebProcess/InjectedBundle/API/mac/WKWebProcessPlugInInternal.h @@ -32,6 +32,8 @@ + (WKWebProcessPlugInController *)_shared; - (id)_initWithPrincipalClassInstance:(id<WKWebProcessPlugIn>)principalClassInstance bundleRef:(WKBundleRef)bundleRef; +- (WKWebProcessPlugInBrowserContextController *)_browserContextControllerForBundlePageRef:(WKBundlePageRef)pageRef; + @end #endif // defined(__LP64__) && defined(__clang__) diff --git a/Source/WebKit2/WebProcess/InjectedBundle/InjectedBundleUserMessageCoders.h b/Source/WebKit2/WebProcess/InjectedBundle/InjectedBundleUserMessageCoders.h index c3fb18d30..aa783a372 100644 --- a/Source/WebKit2/WebProcess/InjectedBundle/InjectedBundleUserMessageCoders.h +++ b/Source/WebKit2/WebProcess/InjectedBundle/InjectedBundleUserMessageCoders.h @@ -33,6 +33,10 @@ #include "WebPageGroupProxy.h" #include "WebProcess.h" +#if PLATFORM(MAC) +#include "ObjCObjectGraphCoders.h" +#endif + namespace WebKit { // Adds @@ -71,6 +75,13 @@ public: encoder << pageGroup->pageGroupID(); break; } +#if PLATFORM(MAC) + case APIObject::TypeObjCObjectGraph: { + ObjCObjectGraph* objectGraph = static_cast<ObjCObjectGraph*>(m_root); + encoder << InjectedBundleObjCObjectGraphEncoder(objectGraph); + break; + } +#endif default: ASSERT_NOT_REACHED(); break; @@ -128,6 +139,16 @@ public: coder.m_root = WebProcess::shared().webPageGroup(pageGroupData); break; } +#if PLATFORM(MAC) + case APIObject::TypeObjCObjectGraph: { + RefPtr<ObjCObjectGraph> objectGraph; + InjectedBundleObjCObjectGraphDecoder objectGraphDecoder(objectGraph, &WebProcess::shared()); + if (!decoder->decode(objectGraphDecoder)) + return false; + coder.m_root = objectGraph.get(); + break; + } +#endif default: return false; } diff --git a/Source/WebKit2/WebProcess/Plugins/Netscape/NetscapePlugin.h b/Source/WebKit2/WebProcess/Plugins/Netscape/NetscapePlugin.h index 559aadab5..2063ccee6 100644 --- a/Source/WebKit2/WebProcess/Plugins/Netscape/NetscapePlugin.h +++ b/Source/WebKit2/WebProcess/Plugins/Netscape/NetscapePlugin.h @@ -239,7 +239,7 @@ private: bool supportsSnapshotting() const; // Convert the given point from plug-in coordinates to root view coordinates. - WebCore::IntPoint convertToRootView(const WebCore::IntPoint&) const; + virtual WebCore::IntPoint convertToRootView(const WebCore::IntPoint&) const OVERRIDE; // Convert the given point from root view coordinates to plug-in coordinates. Returns false if the point can't be // converted (if the transformation matrix isn't invertible). diff --git a/Source/WebKit2/WebProcess/Plugins/PDF/PDFAnnotationTextWidgetDetails.h b/Source/WebKit2/WebProcess/Plugins/PDF/PDFAnnotationTextWidgetDetails.h new file mode 100644 index 000000000..8656ff466 --- /dev/null +++ b/Source/WebKit2/WebProcess/Plugins/PDF/PDFAnnotationTextWidgetDetails.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import <PDFKit/PDFKit.h> + +@interface PDFAnnotationTextWidget (Details) +- (BOOL)isMultiline; +- (BOOL)isReadOnly; +@end diff --git a/Source/WebKit2/WebProcess/Plugins/PDF/PDFPlugin.h b/Source/WebKit2/WebProcess/Plugins/PDF/PDFPlugin.h index a1233fabe..132c28774 100644 --- a/Source/WebKit2/WebProcess/Plugins/PDF/PDFPlugin.h +++ b/Source/WebKit2/WebProcess/Plugins/PDF/PDFPlugin.h @@ -94,11 +94,16 @@ private: virtual void setScrollOffset(const WebCore::IntPoint&) OVERRIDE; virtual void invalidateScrollbarRect(WebCore::Scrollbar*, const WebCore::IntRect&) OVERRIDE; virtual void invalidateScrollCornerRect(const WebCore::IntRect&) OVERRIDE; + virtual WebCore::IntPoint currentMousePosition() const { return m_lastMousePositionInPluginCoordinates; } NSEvent *nsEventForWebMouseEvent(const WebMouseEvent&); + WebCore::IntPoint convertFromPluginToPDFView(const WebCore::IntPoint&) const; + WebCore::IntPoint convertFromRootViewToPlugin(const WebCore::IntPoint&) const; bool supportsForms(); + void updatePageAndDeviceScaleFactors(); + RetainPtr<CALayer> m_containerLayer; RetainPtr<CALayer> m_contentLayer; RetainPtr<CALayer> m_horizontalScrollbarLayer; @@ -110,8 +115,8 @@ private: RefPtr<WebCore::Element> m_annotationContainer; WebCore::AffineTransform m_rootViewToPluginTransform; - WebCore::IntPoint m_lastMousePoint; WebMouseEvent m_lastMouseEvent; + WebCore::IntPoint m_lastMousePositionInPluginCoordinates; RetainPtr<WKPDFLayerControllerDelegate> m_pdfLayerControllerDelegate; }; diff --git a/Source/WebKit2/WebProcess/Plugins/PDF/PDFPlugin.mm b/Source/WebKit2/WebProcess/Plugins/PDF/PDFPlugin.mm index 716b24e15..f50fb8c0e 100644 --- a/Source/WebKit2/WebProcess/Plugins/PDF/PDFPlugin.mm +++ b/Source/WebKit2/WebProcess/Plugins/PDF/PDFPlugin.mm @@ -30,6 +30,7 @@ #import "ArgumentCoders.h" #import "DataReference.h" +#import "PDFAnnotationTextWidgetDetails.h" #import "PDFKitImports.h" #import "PDFLayerControllerDetails.h" #import "PDFPluginAnnotation.h" @@ -303,7 +304,7 @@ void PDFPlugin::pdfDocumentDidLoad() [m_pdfLayerController.get() setFrameSize:size()]; m_pdfLayerController.get().document = document.get(); - [m_pdfLayerController.get() setDeviceScaleFactor:controller()->contentsScaleFactor()]; + updatePageAndDeviceScaleFactors(); if (handlesPageScaleFactor()) pluginView()->setPageScaleFactor([m_pdfLayerController.get() contentScaleFactor], IntPoint()); @@ -316,9 +317,18 @@ void PDFPlugin::pdfDocumentDidLoad() runScriptsInPDFDocument(); } -void PDFPlugin::contentsScaleFactorChanged(float contentsScaleFactor) +void PDFPlugin::updatePageAndDeviceScaleFactors() { - [m_pdfLayerController.get() setDeviceScaleFactor:contentsScaleFactor]; + double newScaleFactor = controller()->contentsScaleFactor(); + if (!handlesPageScaleFactor()) + newScaleFactor *= webFrame()->page()->pageScaleFactor(); + + [m_pdfLayerController.get() setDeviceScaleFactor:newScaleFactor]; +} + +void PDFPlugin::contentsScaleFactorChanged(float) +{ + updatePageAndDeviceScaleFactors(); } void PDFPlugin::calculateSizes() @@ -405,6 +415,16 @@ PlatformLayer* PDFPlugin::pluginLayer() return m_containerLayer.get(); } +IntPoint PDFPlugin::convertFromRootViewToPlugin(const IntPoint& point) const +{ + return m_rootViewToPluginTransform.mapPoint(point); +} + +IntPoint PDFPlugin::convertFromPluginToPDFView(const IntPoint& point) const +{ + return IntPoint(point.x(), size().height() - point.y()); +} + void PDFPlugin::geometryDidChange(const IntSize& pluginSize, const IntRect&, const AffineTransform& pluginToRootViewTransform) { if (size() == pluginSize && pluginView()->pageScaleFactor() == [m_pdfLayerController.get() contentScaleFactor]) @@ -422,10 +442,14 @@ void PDFPlugin::geometryDidChange(const IntSize& pluginSize, const IntRect&, con if (handlesPageScaleFactor()) { CGFloat magnification = pluginView()->pageScaleFactor() - [m_pdfLayerController.get() contentScaleFactor]; - // FIXME: Instead of m_lastMousePoint, we should use the zoom origin from PluginView::setPageScaleFactor. + // FIXME: Instead of m_lastMousePositionInPluginCoordinates, we should use the zoom origin from PluginView::setPageScaleFactor. if (magnification) - [m_pdfLayerController.get() magnifyWithMagnification:magnification atPoint:m_lastMousePoint immediately:NO]; - } + [m_pdfLayerController.get() magnifyWithMagnification:magnification atPoint:convertFromPluginToPDFView(m_lastMousePositionInPluginCoordinates) immediately:NO]; + } else { + // If we don't handle page scale ourselves, we need to respect our parent page's + // scale, which may have changed. + updatePageAndDeviceScaleFactors(); + } calculateSizes(); updateScrollbars(); @@ -493,13 +517,9 @@ static NSEventType eventTypeFromWebEvent(const WebEvent& event) NSEvent *PDFPlugin::nsEventForWebMouseEvent(const WebMouseEvent& event) { - IntPoint mousePosition = event.position(); + m_lastMousePositionInPluginCoordinates = convertFromRootViewToPlugin(event.position()); - IntPoint positionInPDFView(mousePosition); - positionInPDFView = m_rootViewToPluginTransform.mapPoint(positionInPDFView); - positionInPDFView.setY(size().height() - positionInPDFView.y()); - - m_lastMousePoint = positionInPDFView; + IntPoint positionInPDFViewCoordinates(convertFromPluginToPDFView(m_lastMousePositionInPluginCoordinates)); NSEventType eventType = eventTypeFromWebEvent(event); @@ -508,27 +528,59 @@ NSEvent *PDFPlugin::nsEventForWebMouseEvent(const WebMouseEvent& event) NSUInteger modifierFlags = modifierFlagsFromWebEvent(event); - return [NSEvent mouseEventWithType:eventType location:positionInPDFView modifierFlags:modifierFlags timestamp:0 windowNumber:0 context:nil eventNumber:0 clickCount:event.clickCount() pressure:0]; + return [NSEvent mouseEventWithType:eventType location:positionInPDFViewCoordinates modifierFlags:modifierFlags timestamp:0 windowNumber:0 context:nil eventNumber:0 clickCount:event.clickCount() pressure:0]; } bool PDFPlugin::handleMouseEvent(const WebMouseEvent& event) { + PlatformMouseEvent platformEvent = platform(event); + IntPoint mousePosition = convertFromRootViewToPlugin(event.position()); + m_lastMouseEvent = event; - IntPoint mousePosition = event.position(); + RefPtr<Scrollbar> targetScrollbar; + RefPtr<Scrollbar> targetScrollbarForLastMousePosition; - // FIXME: Forward mouse events to the appropriate scrollbar. - if (IntRect(m_verticalScrollbarLayer.get().frame).contains(mousePosition) - || IntRect(m_horizontalScrollbarLayer.get().frame).contains(mousePosition) - || IntRect(m_scrollCornerLayer.get().frame).contains(mousePosition)) + if (m_verticalScrollbarLayer) { + IntRect verticalScrollbarFrame(m_verticalScrollbarLayer.get().frame); + if (verticalScrollbarFrame.contains(mousePosition)) + targetScrollbar = verticalScrollbar(); + if (verticalScrollbarFrame.contains(m_lastMousePositionInPluginCoordinates)) + targetScrollbarForLastMousePosition = verticalScrollbar(); + } + + if (m_horizontalScrollbarLayer) { + IntRect horizontalScrollbarFrame(m_horizontalScrollbarLayer.get().frame); + if (horizontalScrollbarFrame.contains(mousePosition)) + targetScrollbar = horizontalScrollbar(); + if (horizontalScrollbarFrame.contains(m_lastMousePositionInPluginCoordinates)) + targetScrollbarForLastMousePosition = horizontalScrollbar(); + } + + if (m_scrollCornerLayer && IntRect(m_scrollCornerLayer.get().frame).contains(mousePosition)) return false; + // Right-clicks and Control-clicks always call handleContextMenuEvent as well. + if (event.button() == WebMouseEvent::RightButton || (event.button() == WebMouseEvent::LeftButton && event.controlKey())) + return true; + NSEvent *nsEvent = nsEventForWebMouseEvent(event); switch (event.type()) { case WebEvent::MouseMove: mouseMovedInContentArea(); + if (targetScrollbar) { + if (!targetScrollbarForLastMousePosition) { + targetScrollbar->mouseEntered(); + return true; + } + return targetScrollbar->mouseMoved(platformEvent); + } + + if (!targetScrollbar && targetScrollbarForLastMousePosition) + targetScrollbarForLastMousePosition->mouseExited(); + switch (event.button()) { case WebMouseEvent::LeftButton: [m_pdfLayerController.get() mouseDragged:nsEvent]; @@ -543,6 +595,9 @@ bool PDFPlugin::handleMouseEvent(const WebMouseEvent& event) case WebEvent::MouseDown: switch (event.button()) { case WebMouseEvent::LeftButton: + if (targetScrollbar) + return targetScrollbar->mouseDown(platformEvent); + [m_pdfLayerController.get() mouseDown:nsEvent]; return true; case WebMouseEvent::RightButton: @@ -555,6 +610,9 @@ bool PDFPlugin::handleMouseEvent(const WebMouseEvent& event) case WebEvent::MouseUp: switch (event.button()) { case WebMouseEvent::LeftButton: + if (targetScrollbar) + return targetScrollbar->mouseUp(platformEvent); + [m_pdfLayerController.get() mouseUp:nsEvent]; return true; case WebMouseEvent::RightButton: @@ -574,7 +632,7 @@ bool PDFPlugin::handleContextMenuEvent(const WebMouseEvent& event) NSMenu *nsMenu = [m_pdfLayerController.get() menuForEvent:nsEventForWebMouseEvent(event)]; FrameView* frameView = webFrame()->coreFrame()->view(); - IntPoint point = frameView->contentsToScreen(IntRect(event.position(), IntSize())).location(); + IntPoint point = frameView->contentsToScreen(IntRect(frameView->windowToContents(event.position()), IntSize())).location(); if (nsMenu) { WKPopupContextMenu(nsMenu, point); return true; @@ -672,6 +730,11 @@ void PDFPlugin::setActiveAnnotation(PDFAnnotation *annotation) m_activeAnnotation->commit(); if (annotation) { + if ([annotation isKindOfClass:pdfAnnotationTextWidgetClass()] && static_cast<PDFAnnotationTextWidget *>(annotation).isReadOnly) { + m_activeAnnotation = 0; + return; + } + m_activeAnnotation = PDFPluginAnnotation::create(annotation, m_pdfLayerController.get(), this); m_activeAnnotation->attach(m_annotationContainer.get()); } else diff --git a/Source/WebKit2/WebProcess/Plugins/PDF/PDFPluginTextAnnotation.mm b/Source/WebKit2/WebProcess/Plugins/PDF/PDFPluginTextAnnotation.mm index b5df3732d..f69a5d598 100644 --- a/Source/WebKit2/WebProcess/Plugins/PDF/PDFPluginTextAnnotation.mm +++ b/Source/WebKit2/WebProcess/Plugins/PDF/PDFPluginTextAnnotation.mm @@ -28,6 +28,7 @@ #import "config.h" #import "PDFPluginTextAnnotation.h" +#import "PDFAnnotationTextWidgetDetails.h" #import "PDFKitImports.h" #import "PDFLayerControllerDetails.h" #import <PDFKit/PDFKit.h> @@ -40,10 +41,6 @@ #import <WebCore/HTMLTextAreaElement.h> #import <WebCore/Page.h> -@interface PDFAnnotationTextWidget (Details) -- (BOOL)isMultiline; -@end - using namespace WebCore; namespace WebKit { diff --git a/Source/WebKit2/WebProcess/Plugins/Plugin.cpp b/Source/WebKit2/WebProcess/Plugins/Plugin.cpp index 12e0b3d31..f2c6af46c 100644 --- a/Source/WebKit2/WebProcess/Plugins/Plugin.cpp +++ b/Source/WebKit2/WebProcess/Plugins/Plugin.cpp @@ -27,6 +27,7 @@ #include "Plugin.h" #include "WebCoreArgumentCoders.h" +#include <WebCore/IntPoint.h> using namespace WebCore; @@ -105,4 +106,10 @@ void Plugin::updateControlTints(GraphicsContext*) { } +IntPoint Plugin::convertToRootView(const IntPoint&) const +{ + ASSERT_NOT_REACHED(); + return IntPoint(); +} + } // namespace WebKit diff --git a/Source/WebKit2/WebProcess/Plugins/Plugin.h b/Source/WebKit2/WebProcess/Plugins/Plugin.h index 54f8b3ad8..d50a1764b 100644 --- a/Source/WebKit2/WebProcess/Plugins/Plugin.h +++ b/Source/WebKit2/WebProcess/Plugins/Plugin.h @@ -50,6 +50,7 @@ namespace CoreIPC { namespace WebCore { class AffineTransform; class GraphicsContext; + class IntPoint; class IntRect; class IntSize; class Scrollbar; @@ -250,6 +251,8 @@ public: virtual RetainPtr<PDFDocument> pdfDocumentForPrinting() const { return 0; } #endif + virtual WebCore::IntPoint convertToRootView(const WebCore::IntPoint& pointInLocalCoordinates) const; + protected: Plugin(); diff --git a/Source/WebKit2/WebProcess/Plugins/PluginProxy.cpp b/Source/WebKit2/WebProcess/Plugins/PluginProxy.cpp index a18834a6c..f7ead5664 100644 --- a/Source/WebKit2/WebProcess/Plugins/PluginProxy.cpp +++ b/Source/WebKit2/WebProcess/Plugins/PluginProxy.cpp @@ -665,6 +665,11 @@ void PluginProxy::update(const IntRect& paintedRect) controller()->invalidate(paintedRect); } +IntPoint PluginProxy::convertToRootView(const IntPoint& point) const +{ + return m_pluginToRootViewTransform.mapPoint(point); +} + } // namespace WebKit #endif // ENABLE(PLUGIN_PROCESS) diff --git a/Source/WebKit2/WebProcess/Plugins/PluginProxy.h b/Source/WebKit2/WebProcess/Plugins/PluginProxy.h index b1a893bdd..535c8c7fe 100644 --- a/Source/WebKit2/WebProcess/Plugins/PluginProxy.h +++ b/Source/WebKit2/WebProcess/Plugins/PluginProxy.h @@ -125,6 +125,8 @@ private: virtual WebCore::Scrollbar* horizontalScrollbar(); virtual WebCore::Scrollbar* verticalScrollbar(); + virtual WebCore::IntPoint convertToRootView(const WebCore::IntPoint&) const OVERRIDE; + float contentsScaleFactor(); bool needsBackingStore() const; bool updateBackingStore(); diff --git a/Source/WebKit2/WebProcess/Plugins/PluginView.cpp b/Source/WebKit2/WebProcess/Plugins/PluginView.cpp index 44f575ad5..6c74f4633 100644 --- a/Source/WebKit2/WebProcess/Plugins/PluginView.cpp +++ b/Source/WebKit2/WebProcess/Plugins/PluginView.cpp @@ -68,7 +68,8 @@ using namespace WebCore; namespace WebKit { -static const double pluginSnapshotTimerDelay = 1; +// This simulated mouse click delay in HTMLPlugInImageElement.cpp should generally be the same or shorter than this delay. +static const double pluginSnapshotTimerDelay = 1.1; class PluginView::URLRequest : public RefCounted<URLRequest> { public: @@ -554,13 +555,17 @@ void PluginView::didInitializePlugin() redeliverManualStream(); #if PLATFORM(MAC) - if (m_pluginElement->displayState() < HTMLPlugInElement::Playing) + if (m_pluginElement->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick) m_pluginSnapshotTimer.restart(); - else if (m_plugin->pluginLayer()) { - if (frame()) { - frame()->view()->enterCompositingMode(); - m_pluginElement->setNeedsStyleRecalc(SyntheticStyleChange); + else { + if (m_plugin->pluginLayer()) { + if (frame()) { + frame()->view()->enterCompositingMode(); + m_pluginElement->setNeedsStyleRecalc(SyntheticStyleChange); + } } + if (m_pluginElement->displayState() < HTMLPlugInElement::Playing) + m_pluginElement->dispatchPendingMouseClick(); } setWindowIsVisible(m_webPage->windowIsVisible()); @@ -686,7 +691,7 @@ void PluginView::setFrameRect(const WebCore::IntRect& rect) void PluginView::paint(GraphicsContext* context, const IntRect& /*dirtyRect*/) { - if (!m_plugin || !m_isInitialized || m_pluginElement->displayState() < HTMLPlugInElement::Playing) + if (!m_plugin || !m_isInitialized || m_pluginElement->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick) return; if (context->paintingDisabled()) { @@ -728,12 +733,62 @@ void PluginView::setParent(ScrollView* scrollView) initializePlugin(); } +PassOwnPtr<WebEvent> PluginView::createWebEvent(MouseEvent* event) const +{ + WebEvent::Type type = WebEvent::NoType; + unsigned clickCount = 1; + if (event->type() == eventNames().mousedownEvent) + type = WebEvent::MouseDown; + else if (event->type() == eventNames().mouseupEvent) + type = WebEvent::MouseUp; + else if (event->type() == eventNames().mouseoverEvent) { + type = WebEvent::MouseMove; + clickCount = 0; + } else if (event->type() == eventNames().clickEvent) + return nullptr; + else + ASSERT_NOT_REACHED(); + + WebMouseEvent::Button button = WebMouseEvent::NoButton; + switch (event->button()) { + case WebCore::LeftButton: + button = WebMouseEvent::LeftButton; + break; + case WebCore::MiddleButton: + button = WebMouseEvent::MiddleButton; + break; + case WebCore::RightButton: + button = WebMouseEvent::RightButton; + break; + default: + ASSERT_NOT_REACHED(); + break; + } + + unsigned modifiers = 0; + if (event->shiftKey()) + modifiers |= WebEvent::ShiftKey; + if (event->ctrlKey()) + modifiers |= WebEvent::ControlKey; + if (event->altKey()) + modifiers |= WebEvent::AltKey; + if (event->metaKey()) + modifiers |= WebEvent::MetaKey; + + return adoptPtr(new WebMouseEvent(type, button, m_plugin->convertToRootView(IntPoint(event->offsetX(), event->offsetY())), event->screenLocation(), 0, 0, 0, clickCount, static_cast<WebEvent::Modifiers>(modifiers), 0)); +} + void PluginView::handleEvent(Event* event) { if (!m_isInitialized || !m_plugin) return; const WebEvent* currentEvent = WebPage::currentEvent(); + OwnPtr<WebEvent> simulatedWebEvent; + if (event->isMouseEvent() && toMouseEvent(event)->isSimulated()) { + simulatedWebEvent = createWebEvent(toMouseEvent(event)); + currentEvent = simulatedWebEvent.get(); + } if (!currentEvent) return; @@ -776,16 +831,25 @@ void PluginView::handleEvent(Event* event) bool PluginView::handleEditingCommand(const String& commandName, const String& argument) { + if (!m_isInitialized || !m_plugin) + return false; + return m_plugin->handleEditingCommand(commandName, argument); } bool PluginView::isEditingCommandEnabled(const String& commandName) { + if (!m_isInitialized || !m_plugin) + return false; + return m_plugin->isEditingCommandEnabled(commandName); } bool PluginView::shouldAllowScripting() { + if (!m_isInitialized || !m_plugin) + return false; + return m_plugin->shouldAllowScripting(); } @@ -950,7 +1014,10 @@ void PluginView::performFrameLoadURLRequest(URLRequest* request) Frame* targetFrame = frame->loader()->findFrameForNavigation(request->target()); if (!targetFrame) { // We did not find a target frame. Ask our frame to load the page. This may or may not create a popup window. - frame->loader()->load(request->request(), request->target(), false); + FrameLoadRequest frameRequest(frame, request->request()); + frameRequest.setFrameName(request->target()); + frameRequest.setShouldCheckNewWindowPolicy(true); + frame->loader()->load(frameRequest); // FIXME: We don't know whether the window was successfully created here so we just assume that it worked. // It's better than not telling the plug-in anything. @@ -959,7 +1026,7 @@ void PluginView::performFrameLoadURLRequest(URLRequest* request) } // Now ask the frame to load the request. - targetFrame->loader()->load(request->request(), false); + targetFrame->loader()->load(FrameLoadRequest(targetFrame, request->request())); WebFrame* targetWebFrame = static_cast<WebFrameLoaderClient*>(targetFrame->loader()->client())->webFrame(); if (WebFrame::LoadListener* loadListener = targetWebFrame->loadListener()) { @@ -1079,7 +1146,7 @@ void PluginView::invalidateRect(const IntRect& dirtyRect) return; #endif - if (m_pluginElement->displayState() < HTMLPlugInElement::Playing) + if (m_pluginElement->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick) return; RenderBoxModelObject* renderer = toRenderBoxModelObject(m_pluginElement->renderer()); @@ -1237,7 +1304,7 @@ bool PluginView::isAcceleratedCompositingEnabled() if (!settings) return false; - if (m_pluginElement->displayState() < HTMLPlugInElement::Playing) + if (m_pluginElement->displayState() < HTMLPlugInElement::PlayingWithPendingMouseClick) return false; return settings->acceleratedCompositingEnabled(); } diff --git a/Source/WebKit2/WebProcess/Plugins/PluginView.h b/Source/WebKit2/WebProcess/Plugins/PluginView.h index 59f0f8403..cd9e35b95 100644 --- a/Source/WebKit2/WebProcess/Plugins/PluginView.h +++ b/Source/WebKit2/WebProcess/Plugins/PluginView.h @@ -44,11 +44,14 @@ namespace WebCore { class Frame; class HTMLPlugInElement; +class MouseEvent; class RenderBoxModelObject; } namespace WebKit { +class WebEvent; + class PluginView : public WebCore::PluginViewBase, public PluginController, private WebCore::MediaCanStartListener, private WebFrame::LoadListener { public: static PassRefPtr<PluginView> create(PassRefPtr<WebCore::HTMLPlugInElement>, PassRefPtr<Plugin>, const Plugin::Parameters&); @@ -201,6 +204,8 @@ private: virtual void didFinishLoad(WebFrame*); virtual void didFailLoad(WebFrame*, bool wasCancelled); + PassOwnPtr<WebEvent> createWebEvent(WebCore::MouseEvent*) const; + RefPtr<WebCore::HTMLPlugInElement> m_pluginElement; RefPtr<Plugin> m_plugin; WebPage* m_webPage; diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.cpp b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.cpp index c7808b2b2..349948e05 100644 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.cpp +++ b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.cpp @@ -107,7 +107,6 @@ void CoordinatedGraphicsLayer::didChangeGeometry() CoordinatedGraphicsLayer::CoordinatedGraphicsLayer(GraphicsLayerClient* client) : GraphicsLayer(client) - , m_maskTarget(0) , m_inUpdateMode(false) , m_shouldUpdateVisibleRect(true) , m_shouldSyncLayerState(true) @@ -269,6 +268,8 @@ void CoordinatedGraphicsLayer::setContentsVisible(bool b) if (contentsAreVisible() == b) return; GraphicsLayer::setContentsVisible(b); + if (maskLayer()) + maskLayer()->setContentsVisible(b); didChangeLayerState(); } @@ -390,8 +391,8 @@ void CoordinatedGraphicsLayer::setMaskLayer(GraphicsLayer* layer) return; layer->setSize(size()); + layer->setContentsVisible(contentsAreVisible()); CoordinatedGraphicsLayer* CoordinatedGraphicsLayer = toCoordinatedGraphicsLayer(layer); - CoordinatedGraphicsLayer->setMaskTarget(this); CoordinatedGraphicsLayer->didChangeLayerState(); didChangeLayerState(); @@ -653,8 +654,6 @@ void CoordinatedGraphicsLayer::adjustContentsScale() // No reason to save the previous backing store for non-visible areas. m_previousBackingStore->removeAllNonVisibleTiles(); - - createBackingStore(); } void CoordinatedGraphicsLayer::createBackingStore() diff --git a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.h b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.h index a903e6519..1517ae56f 100644 --- a/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.h +++ b/Source/WebKit2/WebProcess/WebPage/CoordinatedGraphics/CoordinatedGraphicsLayer.h @@ -165,7 +165,6 @@ public: private: bool fixedToViewport() const { return m_fixedToViewport; } - void setMaskTarget(GraphicsLayer* layer) { m_maskTarget = layer; } void didChangeLayerState(); void didChangeAnimations(); @@ -207,7 +206,6 @@ private: WebKit::WebLayerID m_id; WebKit::WebLayerInfo m_layerInfo; - GraphicsLayer* m_maskTarget; GraphicsLayerTransform m_layerTransform; TransformationMatrix m_cachedInverseTransform; bool m_inUpdateMode : 1; diff --git a/Source/WebKit2/WebProcess/WebPage/WebPage.cpp b/Source/WebKit2/WebProcess/WebPage/WebPage.cpp index c91c73ed1..83c0ae7fd 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebPage.cpp +++ b/Source/WebKit2/WebProcess/WebPage/WebPage.cpp @@ -325,6 +325,7 @@ WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters) #endif m_page->setCanStartMedia(false); + m_mayStartMediaWhenInWindow = parameters.mayStartMediaWhenInWindow; m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData); m_page->setGroupName(m_pageGroup->identifier()); @@ -824,7 +825,7 @@ void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtens SendStopResponsivenessTimer stopper(this); m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle); - m_mainFrame->coreFrame()->loader()->load(request, false); + m_mainFrame->coreFrame()->loader()->load(FrameLoadRequest(m_mainFrame->coreFrame(), request)); } void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL) @@ -833,7 +834,7 @@ void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIME ResourceRequest request(baseURL); SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL); - m_mainFrame->coreFrame()->loader()->load(request, substituteData, false); + m_mainFrame->coreFrame()->loader()->load(FrameLoadRequest(m_mainFrame->coreFrame(), request, substituteData)); } void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString) @@ -873,8 +874,7 @@ void WebPage::linkClicked(const String& url, const WebMouseEvent& event) if (event.type() != WebEvent::NoType) coreEvent = MouseEvent::create(eventNames().clickEvent, frame->document()->defaultView(), platform(event), 0, 0); - frame->loader()->loadFrameRequest(FrameLoadRequest(frame->document()->securityOrigin(), ResourceRequest(url)), - false, false, coreEvent.get(), 0, MaybeSendReferrer); + frame->loader()->loadFrameRequest(FrameLoadRequest(frame, ResourceRequest(url)), false, false, coreEvent.get(), 0, MaybeSendReferrer); } void WebPage::stopLoadingFrame(uint64_t frameID) @@ -1893,7 +1893,9 @@ void WebPage::setIsInWindow(bool isInWindow) // Defer the call to Page::setCanStartMedia() since it ends up sending a syncrhonous messages to the UI process // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>. - m_setCanStartMediaTimer.startOneShot(0); + if (m_mayStartMediaWhenInWindow) + m_setCanStartMediaTimer.startOneShot(0); + m_page->didMoveOnscreen(); } } @@ -2238,6 +2240,7 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) settings->setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey())); settings->setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey())); settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey())); + settings->setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey())); settings->setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey())); settings->setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey())); settings->setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey())); @@ -2293,6 +2296,10 @@ void WebPage::updatePreferences(const WebPreferencesStore& store) settings->setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey())); settings->setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey())); +#if ENABLE(TEXT_AUTOSIZING) + settings->setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey())); +#endif + platformPreferencesDidChange(store); if (m_drawingArea) @@ -3313,6 +3320,16 @@ void WebPage::setMediaVolume(float volume) m_page->setMediaVolume(volume); } +void WebPage::setMayStartMediaWhenInWindow(bool mayStartMedia) +{ + if (mayStartMedia == m_mayStartMediaWhenInWindow) + return; + + m_mayStartMediaWhenInWindow = mayStartMedia; + if (m_mayStartMediaWhenInWindow && m_page->isOnscreen()) + m_setCanStartMediaTimer.startOneShot(0); +} + void WebPage::runModal() { if (m_isClosed) diff --git a/Source/WebKit2/WebProcess/WebPage/WebPage.h b/Source/WebKit2/WebProcess/WebPage/WebPage.h index 19af39c6e..00ea81c8c 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebPage.h +++ b/Source/WebKit2/WebProcess/WebPage/WebPage.h @@ -525,6 +525,7 @@ public: #endif void setMediaVolume(float); + void setMayStartMediaWhenInWindow(bool); bool mainFrameHasCustomRepresentation() const; @@ -851,6 +852,7 @@ private: #endif WebCore::RunLoop::Timer<WebPage> m_setCanStartMediaTimer; + bool m_mayStartMediaWhenInWindow; HashMap<uint64_t, RefPtr<WebUndoStep> > m_undoStepMap; diff --git a/Source/WebKit2/WebProcess/WebPage/WebPage.messages.in b/Source/WebKit2/WebProcess/WebPage/WebPage.messages.in index bbf6a686c..ad4292b4b 100644 --- a/Source/WebKit2/WebProcess/WebPage/WebPage.messages.in +++ b/Source/WebKit2/WebProcess/WebPage/WebPage.messages.in @@ -226,6 +226,7 @@ messages -> WebPage { # Media SetMediaVolume(float volume) + SetMayStartMediaWhenInWindow(bool mayStartMedia) SetMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled) diff --git a/Source/WebKit2/WebProcess/WebPage/mac/WebPageMac.mm b/Source/WebKit2/WebProcess/WebPage/mac/WebPageMac.mm index 5f09d751b..de49bd2fe 100644 --- a/Source/WebKit2/WebProcess/WebPage/mac/WebPageMac.mm +++ b/Source/WebKit2/WebProcess/WebPage/mac/WebPageMac.mm @@ -545,39 +545,48 @@ void WebPage::performDictionaryLookupForSelection(DictionaryPopupInfo::Type type void WebPage::performDictionaryLookupForRange(DictionaryPopupInfo::Type type, Frame* frame, Range* range, NSDictionary *options) { - String rangeText = range->text(); - if (rangeText.stripWhiteSpace().isEmpty()) + if (range->text().stripWhiteSpace().isEmpty()) return; RenderObject* renderer = range->startContainer()->renderer(); RenderStyle* style = renderer->style(); - NSFont *font = style->font().primaryFont()->getNSFont(); - - // We won't be able to get an NSFont in the case that a Web Font is being used, so use - // the default system font at the same size instead. - if (!font) - font = [NSFont systemFontOfSize:style->font().primaryFont()->platformData().size()]; - - CFDictionaryRef fontDescriptorAttributes = (CFDictionaryRef)[[font fontDescriptor] fontAttributes]; - if (!fontDescriptorAttributes) - return; Vector<FloatQuad> quads; range->textQuads(quads); if (quads.isEmpty()) return; - + IntRect rangeRect = frame->view()->contentsToWindow(quads[0].enclosingBoundingBox()); DictionaryPopupInfo dictionaryPopupInfo; dictionaryPopupInfo.type = type; dictionaryPopupInfo.origin = FloatPoint(rangeRect.x(), rangeRect.y() + (style->fontMetrics().ascent() * pageScaleFactor())); - dictionaryPopupInfo.fontInfo.fontAttributeDictionary = fontDescriptorAttributes; #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 dictionaryPopupInfo.options = (CFDictionaryRef)options; #endif - send(Messages::WebPageProxy::DidPerformDictionaryLookup(rangeText, dictionaryPopupInfo)); + NSAttributedString *nsAttributedString = [WebHTMLConverter editingAttributedStringFromRange:range]; + + RetainPtr<NSMutableAttributedString> scaledNSAttributedString(AdoptNS, [[NSMutableAttributedString alloc] initWithString:[nsAttributedString string]]); + + NSFontManager *fontManager = [NSFontManager sharedFontManager]; + + [nsAttributedString enumerateAttributesInRange:NSMakeRange(0, [nsAttributedString length]) options:0 usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop) { + RetainPtr<NSMutableDictionary> scaledAttributes(AdoptNS, [attributes mutableCopy]); + + NSFont *font = [scaledAttributes objectForKey:NSFontAttributeName]; + if (font) { + font = [fontManager convertFont:font toSize:[font pointSize] * pageScaleFactor()]; + [scaledAttributes setObject:font forKey:NSFontAttributeName]; + } + + [scaledNSAttributedString.get() addAttributes:scaledAttributes.get() range:range]; + }]; + + AttributedString attributedString; + attributedString.string = scaledNSAttributedString; + + send(Messages::WebPageProxy::DidPerformDictionaryLookup(attributedString, dictionaryPopupInfo)); } bool WebPage::performNonEditingBehaviorForSelector(const String& selector) diff --git a/Source/WebKit2/win/WebKit2.def b/Source/WebKit2/win/WebKit2.def index 8416b9101..87c7f35b1 100644 --- a/Source/WebKit2/win/WebKit2.def +++ b/Source/WebKit2/win/WebKit2.def @@ -173,6 +173,7 @@ EXPORTS ?create@SerializedScriptValue@WebCore@@SA?AV?$PassRefPtr@VSerializedScriptValue@WebCore@@@WTF@@ABVString@4@@Z ?create@SerializedScriptValue@WebCore@@SA?AV?$PassRefPtr@VSerializedScriptValue@WebCore@@@WTF@@PAVExecState@JSC@@VJSValue@6@PAV?$Vector@V?$RefPtr@VMessagePort@WebCore@@@WTF@@$00@4@PAV?$Vector@V?$RefPtr@VArrayBuffer@WTF@@@WTF@@$00@4@W4SerializationErrorMode@2@@Z ?create@ShadowRoot@WebCore@@SA?AV?$PassRefPtr@VShadowRoot@WebCore@@@WTF@@PAVElement@2@AAH@Z + ?createFromWire@SerializedScriptValue@WebCore@@SA?AV?$PassRefPtr@VSerializedScriptValue@WebCore@@@WTF@@ABVString@4@@Z ?createWrapper@WebCore@@YA?AVJSValue@JSC@@PAVExecState@3@PAVJSDOMGlobalObject@1@PAVNode@1@@Z ?deserialize@SerializedScriptValue@WebCore@@QAE?AVJSValue@JSC@@PAVExecState@4@PAVJSGlobalObject@4@PAV?$Vector@V?$RefPtr@VMessagePort@WebCore@@@WTF@@$00@WTF@@W4SerializationErrorMode@2@@Z ?documentState@HistoryItem@WebCore@@QBEABV?$Vector@VString@WTF@@$0A@@WTF@@XZ @@ -193,6 +194,9 @@ EXPORTS ?getHighlight@InspectorController@WebCore@@QBEXPAUHighlight@2@@Z ?getLocationAndLengthFromRange@TextIterator@WebCore@@SA_NPAVElement@2@PBVRange@2@AAI2@Z ?getReferencedFilePaths@FormController@WebCore@@SA?AV?$Vector@VString@WTF@@$0A@@WTF@@ABV34@@Z + ?countElementShadow@ShadowRoot@WebCore@@QBEIXZ + ?hasShadowInsertionPoint@ShadowRoot@WebCore@@QBE_NXZ + ?hasContentElement@ShadowRoot@WebCore@@QBE_NXZ ?inputTag@HTMLNames@WebCore@@3VQualifiedName@2@B ?instrumentingAgentsForPage@InspectorInstrumentation@WebCore@@CAPAVInstrumentingAgents@2@PAVPage@2@@Z ?isActiveInsertionPoint@WebCore@@YA_NPBVNode@1@@Z @@ -275,6 +279,7 @@ EXPORTS ?toJS@WebCore@@YA?AVJSValue@JSC@@PAVExecState@3@PAVJSDOMGlobalObject@1@PAVNodeList@1@@Z ?toRange@WebCore@@YAPAVRange@1@VJSValue@JSC@@@Z ?toString@SerializedScriptValue@WebCore@@QAE?AVString@WTF@@XZ + ?toWireString@SerializedScriptValue@WebCore@@QBE?AVString@WTF@@XZ ?treeScope@Node@WebCore@@QBEPAVTreeScope@2@XZ ?updateLayoutIgnorePendingStylesheets@Document@WebCore@@QAEXXZ ?userPreferredLanguages@WebCore@@YA?AV?$Vector@VString@WTF@@$0A@@WTF@@XZ @@ -329,4 +334,34 @@ EXPORTS ?layerTreeAsText@Frame@WebCore@@QBE?AVString@WTF@@I@Z ?trackedRepaintRectsAsText@Frame@WebCore@@QBE?AVString@WTF@@XZ ?setTracksRepaints@FrameView@WebCore@@QAEX_N@Z - + ??1BitmapImage@WebCore@@UAE@XZ + ??0BitmapImage@WebCore@@IAE@PAVImageObserver@1@@Z + ?isBitmapImage@BitmapImage@WebCore@@UBE_NXZ + ?currentFrameHasAlpha@BitmapImage@WebCore@@UAE_NXZ + ?hasSingleSecurityOrigin@BitmapImage@WebCore@@UBE_NXZ + ?computeIntrinsicDimensions@Image@WebCore@@UAEXAAULength@2@0AAVFloatSize@2@@Z + ?size@BitmapImage@WebCore@@UBE?AVIntSize@2@XZ + ?getHotSpot@BitmapImage@WebCore@@UBE_NAAVIntPoint@2@@Z + ?dataChanged@BitmapImage@WebCore@@UAE_N_N@Z + ?filenameExtension@BitmapImage@WebCore@@UBE?AVString@WTF@@XZ + ?destroyDecodedData@BitmapImage@WebCore@@MAEX_N@Z + ?decodedSize@BitmapImage@WebCore@@UBEIXZ + ?startAnimation@BitmapImage@WebCore@@MAEX_N@Z + ?stopAnimation@BitmapImage@WebCore@@UAEXXZ + ?resetAnimation@BitmapImage@WebCore@@UAEXXZ + ?nativeImageForCurrentFrame@BitmapImage@WebCore@@UAEPAUCGImage@@XZ + ?getHBITMAP@BitmapImage@WebCore@@UAE_NPAUHBITMAP__@@@Z + ?getHBITMAPOfSize@BitmapImage@WebCore@@UAE_NPAUHBITMAP__@@PAUtagSIZE@@@Z + ?drawPattern@Image@WebCore@@UAEXPAVGraphicsContext@2@ABVFloatRect@2@ABVAffineTransform@2@ABVFloatPoint@2@W4ColorSpace@2@W4CompositeOperator@2@1@Z + ?reportMemoryUsage@BitmapImage@WebCore@@UBEXPAVMemoryObjectInfo@WTF@@@Z + ?drawFrameMatchingSourceSize@BitmapImage@WebCore@@MAEXPAVGraphicsContext@2@ABVFloatRect@2@ABVIntSize@2@W4ColorSpace@2@W4CompositeOperator@2@@Z + ?draw@Image@WebCore@@MAEXPAVGraphicsContext@2@ABVFloatRect@2@1W4ColorSpace@2@W4CompositeOperator@2@W4RespectImageOrientationEnum@2@@Z + ?draw@BitmapImage@WebCore@@MAEXPAVGraphicsContext@2@ABVFloatRect@2@1W4ColorSpace@2@W4CompositeOperator@2@@Z + ?mayFillWithSolidColor@BitmapImage@WebCore@@MAE_NXZ + ?solidColor@BitmapImage@WebCore@@MBE?AVColor@2@XZ + ?draw@BitmapImage@WebCore@@MAEXPAVGraphicsContext@2@ABVFloatRect@2@1W4ColorSpace@2@W4CompositeOperator@2@W4RespectImageOrientationEnum@2@@Z + ?frameCount@BitmapImage@WebCore@@MAEIXZ + ?getCGImageRef@BitmapImage@WebCore@@UAEPAUCGImage@@XZ + ?getFirstCGImageRefOfSize@BitmapImage@WebCore@@UAEPAUCGImage@@ABVIntSize@2@@Z + ?getCGImageArray@BitmapImage@WebCore@@UAE?AV?$RetainPtr@PBU__CFArray@@@WTF@@XZ + ?notSolidColor@BitmapImage@WebCore@@UAE_NXZ diff --git a/Source/WebKit2/win/WebKit2CFLite.def b/Source/WebKit2/win/WebKit2CFLite.def index 003fc8b6d..420ecf0f4 100644 --- a/Source/WebKit2/win/WebKit2CFLite.def +++ b/Source/WebKit2/win/WebKit2CFLite.def @@ -167,6 +167,7 @@ EXPORTS ?create@SerializedScriptValue@WebCore@@SA?AV?$PassRefPtr@VSerializedScriptValue@WebCore@@@WTF@@ABVString@4@@Z ?create@SerializedScriptValue@WebCore@@SA?AV?$PassRefPtr@VSerializedScriptValue@WebCore@@@WTF@@PAVExecState@JSC@@VJSValue@6@PAV?$Vector@V?$RefPtr@VMessagePort@WebCore@@@WTF@@$00@4@PAV?$Vector@V?$RefPtr@VArrayBuffer@WTF@@@WTF@@$00@4@W4SerializationErrorMode@2@@Z ?create@ShadowRoot@WebCore@@SA?AV?$PassRefPtr@VShadowRoot@WebCore@@@WTF@@PAVElement@2@AAH@Z + ?createFromWire@SerializedScriptValue@WebCore@@SA?AV?$PassRefPtr@VSerializedScriptValue@WebCore@@@WTF@@ABVString@4@@Z ?createWrapper@WebCore@@YA?AVJSValue@JSC@@PAVExecState@3@PAVJSDOMGlobalObject@1@PAVNode@1@@Z ?deserialize@SerializedScriptValue@WebCore@@QAE?AVJSValue@JSC@@PAVExecState@4@PAVJSGlobalObject@4@PAV?$Vector@V?$RefPtr@VMessagePort@WebCore@@@WTF@@$00@WTF@@W4SerializationErrorMode@2@@Z ?documentState@HistoryItem@WebCore@@QBEABV?$Vector@VString@WTF@@$0A@@WTF@@XZ @@ -186,6 +187,9 @@ EXPORTS ?getHighlight@InspectorController@WebCore@@QBEXPAUHighlight@2@@Z ?getLocationAndLengthFromRange@TextIterator@WebCore@@SA_NPAVElement@2@PBVRange@2@AAI2@Z ?getReferencedFilePaths@FormController@WebCore@@SA?AV?$Vector@VString@WTF@@$0A@@WTF@@ABV34@@Z + ?countElementShadow@ShadowRoot@WebCore@@QBEIXZ + ?hasShadowInsertionPoint@ShadowRoot@WebCore@@QBE_NXZ + ?hasContentElement@ShadowRoot@WebCore@@QBE_NXZ ?inputTag@HTMLNames@WebCore@@3VQualifiedName@2@B ?instrumentingAgentsForPage@InspectorInstrumentation@WebCore@@CAPAVInstrumentingAgents@2@PAVPage@2@@Z ?isActiveInsertionPoint@WebCore@@YA_NPBVNode@1@@Z @@ -270,6 +274,7 @@ EXPORTS ?toJS@WebCore@@YA?AVJSValue@JSC@@PAVExecState@3@PAVJSDOMGlobalObject@1@PAVNodeList@1@@Z ?toRange@WebCore@@YAPAVRange@1@VJSValue@JSC@@@Z ?toString@SerializedScriptValue@WebCore@@QAE?AVString@WTF@@XZ + ?toWireString@SerializedScriptValue@WebCore@@QBE?AVString@WTF@@XZ ?treeScope@Node@WebCore@@QBEPAVTreeScope@2@XZ ?updateLayoutIgnorePendingStylesheets@Document@WebCore@@QAEXXZ ?userPreferredLanguages@WebCore@@YA?AV?$Vector@VString@WTF@@$0A@@WTF@@XZ @@ -320,3 +325,32 @@ EXPORTS ?layerTreeAsText@Frame@WebCore@@QBE?AVString@WTF@@I@Z ?trackedRepaintRectsAsText@Frame@WebCore@@QBE?AVString@WTF@@XZ ?setTracksRepaints@FrameView@WebCore@@QAEX_N@Z + ??1BitmapImage@WebCore@@UAE@XZ + ??0BitmapImage@WebCore@@IAE@PAVImageObserver@1@@Z + ?isBitmapImage@BitmapImage@WebCore@@UBE_NXZ + ?currentFrameHasAlpha@BitmapImage@WebCore@@UAE_NXZ + ?hasSingleSecurityOrigin@BitmapImage@WebCore@@UBE_NXZ + ?computeIntrinsicDimensions@Image@WebCore@@UAEXAAULength@2@0AAVFloatSize@2@@Z + ?size@BitmapImage@WebCore@@UBE?AVIntSize@2@XZ + ?getHotSpot@BitmapImage@WebCore@@UBE_NAAVIntPoint@2@@Z + ?dataChanged@BitmapImage@WebCore@@UAE_N_N@Z + ?filenameExtension@BitmapImage@WebCore@@UBE?AVString@WTF@@XZ + ?destroyDecodedData@BitmapImage@WebCore@@MAEX_N@Z + ?decodedSize@BitmapImage@WebCore@@UBEIXZ + ?startAnimation@BitmapImage@WebCore@@MAEX_N@Z + ?stopAnimation@BitmapImage@WebCore@@UAEXXZ + ?resetAnimation@BitmapImage@WebCore@@UAEXXZ + ?nativeImageForCurrentFrame@BitmapImage@WebCore@@UAEPAVNativeImageCairo@2@XZ + ?getHBITMAP@BitmapImage@WebCore@@UAE_NPAUHBITMAP__@@@Z + ?getHBITMAPOfSize@BitmapImage@WebCore@@UAE_NPAUHBITMAP__@@PAUtagSIZE@@@Z + ?drawPattern@Image@WebCore@@UAEXPAVGraphicsContext@2@ABVFloatRect@2@ABVAffineTransform@2@ABVFloatPoint@2@W4ColorSpace@2@W4CompositeOperator@2@1@Z + ?reportMemoryUsage@BitmapImage@WebCore@@UBEXPAVMemoryObjectInfo@WTF@@@Z + ?drawFrameMatchingSourceSize@BitmapImage@WebCore@@MAEXPAVGraphicsContext@2@ABVFloatRect@2@ABVIntSize@2@W4ColorSpace@2@W4CompositeOperator@2@@Z + ?draw@Image@WebCore@@MAEXPAVGraphicsContext@2@ABVFloatRect@2@1W4ColorSpace@2@W4CompositeOperator@2@W4RespectImageOrientationEnum@2@@Z + ?draw@BitmapImage@WebCore@@MAEXPAVGraphicsContext@2@ABVFloatRect@2@1W4ColorSpace@2@W4CompositeOperator@2@@Z + ?mayFillWithSolidColor@BitmapImage@WebCore@@MAE_NXZ + ?solidColor@BitmapImage@WebCore@@MBE?AVColor@2@XZ + ?frameAtIndex@BitmapImage@WebCore@@IAEPAVNativeImageCairo@2@I@Z + ?draw@BitmapImage@WebCore@@MAEXPAVGraphicsContext@2@ABVFloatRect@2@1W4ColorSpace@2@W4CompositeOperator@2@W4RespectImageOrientationEnum@2@@Z + ?frameCount@BitmapImage@WebCore@@MAEIXZ + ?notSolidColor@BitmapImage@WebCore@@UAE_NXZ diff --git a/Source/autotools/symbols.filter b/Source/autotools/symbols.filter index c18745c46..8d04e6079 100644 --- a/Source/autotools/symbols.filter +++ b/Source/autotools/symbols.filter @@ -47,6 +47,9 @@ _ZN7WebCore10JSDocument6s_infoE; _ZN7WebCore10toDocumentEN3JSC7JSValueE; _ZN7WebCore10ClientRectC1Ev; _ZN7WebCore10ClientRectC1ERKNS_7IntRectE; +_ZNK7WebCore10ShadowRoot17hasContentElementEv; +_ZNK7WebCore10ShadowRoot18countElementShadowEv; +_ZNK7WebCore10ShadowRoot23hasShadowInsertionPointEv; _ZN7WebCore10ShadowRoot6createEPNS_7ElementERi; _ZN7WebCore11EventTarget17toGeneratedStreamEv; _ZN7WebCore11EventTarget8toStreamEv; @@ -217,10 +220,12 @@ _ZNK7WebCore5Frame25trackedRepaintRectsAsTextEv; _ZN7WebCore4toJSEPN3JSC9ExecStateEPNS_17JSDOMGlobalObjectEPN3WTF11ArrayBufferE; _ZN7WebCore13toArrayBufferEN3JSC7JSValueE; _ZN7WebCore21SerializedScriptValue6createEPN3JSC9ExecStateENS1_7JSValueEPN3WTF6VectorINS5_6RefPtrINS_11MessagePortEEELm1EEEPNS6_INS7_INS5_11ArrayBufferEEELm1EEENS_22SerializationErrorModeE; +_ZN7WebCore21SerializedScriptValue14createFromWireERKN3WTF6StringE; _ZN7WebCore21SerializedScriptValue6createERKN3WTF6StringE; _ZN7WebCore21SerializedScriptValue8toStringEv; _ZN7WebCore21SerializedScriptValue11deserializeEPN3JSC9ExecStateEPNS1_14JSGlobalObjectEPN3WTF6VectorINS6_6RefPtrINS_11MessagePortEEELm1EEENS_22SerializationErrorModeE; _ZN7WebCore21SerializedScriptValueD1Ev; +_ZNK7WebCore21SerializedScriptValue12toWireStringEv; local: _Z*; diff --git a/Source/cmake/OptionsEfl.cmake b/Source/cmake/OptionsEfl.cmake index 11578c27e..fe37fbf7c 100644 --- a/Source/cmake/OptionsEfl.cmake +++ b/Source/cmake/OptionsEfl.cmake @@ -40,6 +40,7 @@ FILE(MAKE_DIRECTORY ${THEME_BINARY_DIR}) SET(VERSION_SCRIPT "-Wl,--version-script,${CMAKE_MODULE_PATH}/eflsymbols.filter") WEBKIT_OPTION_BEGIN() +WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_3D_RENDERING ON) WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_ANIMATION_API ON) WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_API_TESTS ON) WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_BATTERY_STATUS ON) @@ -81,6 +82,7 @@ WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_VIDEO_TRACK ON) WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_WEB_INTENTS ON) WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_WEB_INTENTS_TAG ON) WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_WEB_TIMING ON) +WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_WEBGL ON) WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_WORKERS ON) WEBKIT_OPTION_DEFAULT_PORT_VALUE(ENABLE_XHR_TIMEOUT ON) WEBKIT_OPTION_DEFAULT_PORT_VALUE(WTF_USE_TILED_BACKING_STORE ON) diff --git a/Source/cmake/WebKitFeatures.cmake b/Source/cmake/WebKitFeatures.cmake index 0b25c2068..b938b2838 100644 --- a/Source/cmake/WebKitFeatures.cmake +++ b/Source/cmake/WebKitFeatures.cmake @@ -11,10 +11,10 @@ MACRO (WEBKIT_OPTION_DEFAULT_PORT_VALUE _name _value) ENDMACRO () MACRO (WEBKIT_OPTION_BEGIN) - WEBKIT_OPTION_DEFINE(ENABLE_API_TESTS "Enable public API unit tests" OFF) WEBKIT_OPTION_DEFINE(ENABLE_3D_RENDERING "Toggle 3D rendering support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_ACCELERATED_2D_CANVAS "Toggle accelerated 2D canvas support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_ANIMATION_API "Toggle animation API support" OFF) + WEBKIT_OPTION_DEFINE(ENABLE_API_TESTS "Enable public API unit tests" OFF) WEBKIT_OPTION_DEFINE(ENABLE_ASSEMBLER_WX_EXCLUSIVE "Toggel Assembler WX Exclusive support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_BATTERY_STATUS "Toggle battery status API support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_BLOB "Toggle Blob support" OFF) @@ -115,12 +115,12 @@ MACRO (WEBKIT_OPTION_BEGIN) WEBKIT_OPTION_DEFINE(ENABLE_VIBRATION "Toggle Vibration API support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_VIDEO "Toggle Video support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_VIDEO_TRACK "Toggle Track support for HTML5 video" OFF) - WEBKIT_OPTION_DEFINE(ENABLE_WEBGL "Toggle 3D canvas (WebGL) support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_WEB_AUDIO "Toggle Web Audio support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_WEB_INTENTS "Toggle Web Intents support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_WEB_INTENTS_TAG "Toogle HTMLIntentElement tag support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_WEB_SOCKETS "Toggle Web Sockets support" ON) WEBKIT_OPTION_DEFINE(ENABLE_WEB_TIMING "Toggle Web Timing support" OFF) + WEBKIT_OPTION_DEFINE(ENABLE_WEBGL "Toggle 3D canvas (WebGL) support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_WORKERS "Toggle Web Workers support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_XHR_TIMEOUT "Toggle XHR timeout support" OFF) WEBKIT_OPTION_DEFINE(ENABLE_XSLT "Toggle XSLT support" ON) @@ -166,11 +166,9 @@ MACRO (WEBKIT_OPTION_END) IF (${_name}) LIST(APPEND FEATURE_DEFINES ${_name}) SET(FEATURE_DEFINES_WITH_SPACE_SEPARATOR "${FEATURE_DEFINES_WITH_SPACE_SEPARATOR} ${_name}") - SET(_MESSAGE "${_MESSAGE} ON") - ELSE () - SET(_MESSAGE "${_MESSAGE} OFF") ENDIF () + SET(_MESSAGE "${_MESSAGE} ${_WEBKIT_AVAILABLE_OPTIONS_INITALVALUE_${_name}}") MESSAGE(STATUS "${_MESSAGE}") ENDFOREACH () ENDMACRO () diff --git a/Tools/BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui.js b/Tools/BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui.js index 5d3b8f366..9c3d47e5f 100644 --- a/Tools/BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui.js +++ b/Tools/BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui.js @@ -245,7 +245,7 @@ ui.StatusArea = base.extends('div', { this.appendChild(new ui.actions.List([new ui.actions.Close()])); $(this).bind('close', this.close.bind(this)); - var processing = document.createElement('div'); + var processing = document.createElement('progress'); processing.className = 'process-text'; processing.textContent = 'Processing...'; this.appendChild(processing); diff --git a/Tools/BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui_unittests.js b/Tools/BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui_unittests.js index 74de3e41c..66f7ac914 100644 --- a/Tools/BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui_unittests.js +++ b/Tools/BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui_unittests.js @@ -155,7 +155,7 @@ test("StatusArea", 3, function() { equal(statusArea.outerHTML, '<div class="status processing" style="visibility: visible; ">' + '<ul class="actions"><li><button class="action">Close</button></li></ul>' + - '<div class="process-text">Processing...</div>' + + '<progress class="process-text">Processing...</progress>' + '<div id="status-content-1" class="status-content">' + '<div class="message">First Message</div>' + '<div class="message">Second Message</div>' + @@ -169,7 +169,7 @@ test("StatusArea", 3, function() { equal(statusArea.outerHTML, '<div class="status processing" style="visibility: visible; ">' + '<ul class="actions"><li><button class="action">Close</button></li></ul>' + - '<div class="process-text">Processing...</div>' + + '<progress class="process-text">Processing...</progress>' + '<div id="status-content-1" class="status-content">' + '<div class="message">First Message</div>' + '<div class="message">Second Message</div>' + @@ -185,7 +185,7 @@ test("StatusArea", 3, function() { equal(statusArea.outerHTML, '<div class="status" style="visibility: visible; ">' + '<ul class="actions"><li><button class="action">Close</button></li></ul>' + - '<div class="process-text">Processing...</div>' + + '<progress class="process-text">Processing...</progress>' + '<div id="status-content-1" class="status-content">' + '<div class="message">First Message</div>' + '<div class="message">Second Message</div>' + diff --git a/Tools/ChangeLog b/Tools/ChangeLog index e6466f500..40be5de2c 100644 --- a/Tools/ChangeLog +++ b/Tools/ChangeLog @@ -1,3 +1,1019 @@ +2012-11-29 Sudarsana Nagineni <sudarsana.nagineni@intel.com> + + [EFL][WK2] Add support for PlatformWebView::simulateMouseMove() in TestWebKitAPI + https://bugs.webkit.org/show_bug.cgi?id=103252 + + Reviewed by Kenneth Rohde Christiansen. + + Add support for PlatformWebView::simulateMouseMove() and enable + WebKit2 API test MouseMoveAfterCrash. + + * TestWebKitAPI/PlatformEfl.cmake: Enable MouseMoveAfterCrash API + test. + * TestWebKitAPI/efl/PlatformWebView.cpp: + (TestWebKitAPI::onWebProcessCrashed): Handle 'webprocess,crashed' signal + to prevent loading an error page since the test case is reloading actual + page after web process has terminated and recovered. + (TestWebKitAPI): + (TestWebKitAPI::PlatformWebView::PlatformWebView): + (TestWebKitAPI::PlatformWebView::simulateMouseMove): Implemented. + +2012-11-29 Andras Becsi <andras.becsi@digia.com> + + [Qt] Fix installation of QtWebProcess binary + https://bugs.webkit.org/show_bug.cgi?id=101735 + + Reviewed by Simon Hausmann. + + Add config test to detect the availability of support + for "program executables" in Qt (libexec). + + This test can be removed after the Qt5 release. + + * Tools.pro: + * qmake/mkspecs/features/features.prf: + * qmake/config.tests/libexecdir/libexecdir.cpp: + * qmake/config.tests/libexecdir/libexecdir.pro: + +2012-11-29 Eric Seidel <eric@webkit.org> + + run-perf-tests does not work when the layout test directory does not exist + https://bugs.webkit.org/show_bug.cgi?id=103572 + + Reviewed by Ryosuke Niwa. + + Make sure that Profiler() calls maybe_make_directory for the output_dir + before ever using it. It's a little awkward to create the directory + from the constructor, but its simplest that way as the various subclasses + all use the directory at different times. + + Since this required having a filesystem in Profiler (and I didn't want + to grab inside Workspace to get one), I just made Profiler expect a + SystemHost instead of a separate filesystem, executive and workspace. + + * Scripts/webkitpy/common/system/profiler.py: + (ProfilerFactory.create_profiler): + (Profiler.__init__): + (SingleFileOutputProfiler.__init__): + (GooglePProf.__init__): + (GooglePProf.profile_after_exit): + (Instruments.__init__): + (Instruments.attach_to_pid): + * Scripts/webkitpy/common/system/profiler_unittest.py: + (ProfilerFactoryTest.test_basic): + +2012-11-28 Vivek Galatage <vivek.vg@samsung.com> + + Adding secondary email id + https://bugs.webkit.org/show_bug.cgi?id=103594 + + Unreviewed. Adding secondary email. + + * Scripts/webkitpy/common/config/committers.py: + +2012-11-28 Kent Tamura <tkent@chromium.org> + + garden-o-matic: Use indeterminate <progress> in the status area + https://bugs.webkit.org/show_bug.cgi?id=103494 + + Reviewed by Adam Barth. + + * BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui.js: + Wrap the "Processing..." message with an indeterminate progress bar. + We keep the message as a fallback content. + * BuildSlaveSupport/build.webkit.org-config/public_html/TestFailures/scripts/ui_unittests.js: + Follow the above change. + +2012-11-28 Nima Ghanavatian <nghanavatian@rim.com> + + Adding Nima Ghanavatian to committers.py + https://bugs.webkit.org/show_bug.cgi?id=103533 + + Reviewed by Rob Buis. + + Adding myself to committers.py as a Committer. + + * Scripts/webkitpy/common/config/committers.py: + +2012-11-28 peavo@outlook.com <peavo@outlook.com> + + [WinCairo] Crash when requesting favicon. + https://bugs.webkit.org/show_bug.cgi?id=102689 + + Reviewed by Brent Fulgham. + + * TestWebKitAPI/Tests/WebCore/win: Added. + * TestWebKitAPI/Tests/WebCore/win/BitmapImage.cpp: Added. + (TestWebKitAPI::BitmapImageTest::BitmapImageTest): Allocate frame in constructor. + (TestWebKitAPI::BitmapImageTest::frameCount): Override frameCount() method. + (TestWebKitAPI::TEST): Added new test. + * TestWebKitAPI/config.h: Make sure defines are correct for WinCairo. + * TestWebKitAPI/win/TestWebKitAPI.vcproj: Added new test. + +2012-11-28 Eric Seidel <eric@webkit.org> + + run-perf-tests should have a --profile option for easy profiling + https://bugs.webkit.org/show_bug.cgi?id=99517 + + Reviewed by Adam Barth. + + This is a very basic implementation which works on Mac and Linux + and makes it trivial for anyone to profile a PerformanceTest. + + Currently it's not "hard" to profile a PerformanceTest + but lowering the barriers to entry here allows all of us to focus + less on the tools and more on the code. + + This also paves the way for adding easy mobile-profiling (e.g. chromium-android) + which is actually "hard", and this option will make much easier. + + * Scripts/webkitpy/common/system/profiler.py: Added. + (ProfilerFactory): + (ProfilerFactory.create_profiler): + (Profiler): + (Profiler.__init__): + (Profiler.adjusted_environment): + (Profiler.attach_to_pid): + (Profiler.did_stop): + (SingleFileOutputProfiler): + (SingleFileOutputProfiler.__init__): + (GooglePProf): + (GooglePProf.__init__): + (GooglePProf.adjusted_environment): + (GooglePProf.did_stop): + (Instruments): + (Instruments.__init__): + (Instruments.attach_to_pid): + * Scripts/webkitpy/common/system/profiler_unittest.py: Added. + (ProfilerFactoryTest): + (ProfilerFactoryTest.test_basic): + * Scripts/webkitpy/layout_tests/port/driver.py: + (Driver.__init__): + (Driver._start): + (Driver.stop): + (Driver.cmd_line): + * Scripts/webkitpy/performance_tests/perftest.py: + (PerfTest.parse_output): + * Scripts/webkitpy/performance_tests/perftest_unittest.py: + (MainTest.test_parse_output): + (MainTest.test_parse_output_with_failing_line): + * Scripts/webkitpy/performance_tests/perftestsrunner.py: + (PerfTestsRunner._parse_args): + (PerfTestsRunner.run): + +2012-11-28 Zan Dobersek <zandobersek@gmail.com> + + Remove deprecated logging usage from QueueEngine + https://bugs.webkit.org/show_bug.cgi?id=103532 + + Reviewed by Dirk Pranke. + + Replace usage of deprecated logging in webkitpy.tool.bot.queueengine with + logging through the Logger object. The unit test is modified to reflect + these changes. + + After these changes the deprecated logging (i.e. logging to stderr) is not + used anymore through webkitpy and can be removed. + + * Scripts/webkitpy/tool/bot/queueengine.py: + (QueueEngine.exit_after_handled_error): + (QueueEngine.run): + (QueueEngine._stopping): + (QueueEngine._sleep): + * Scripts/webkitpy/tool/bot/queueengine_unittest.py: + (QueueEngineTest._run_engine): + +2012-11-28 Nate Chapin <japhet@chromium.org> + + Move empty loading to DocumentLoader, simplify FrameLoader::init() + https://bugs.webkit.org/show_bug.cgi?id=101512 + + Reviewed by Adam Barth. + + * DumpRenderTree/chromium/WebViewHost.cpp: + (WebViewHost::updateForCommittedLoad): This function doesn't play nicely with empty urls and incorrectly + interprets them as a non-empty load. This change is required for + http/tests/navigation/new-window-redirect-history.html to continue to pass in chromium. + * TestWebKitAPI/Tests/WebKit2/AboutBlankLoad.cpp: This test relies on a callback that no longer + is sent for about:blank loads. Hook into didFinishLoadForFrame() instead. + (TestWebKitAPI::didFinishLoadForFrame): + (TestWebKitAPI::TEST): + +2012-11-28 Sadrul Habib Chowdhury <sadrul@chromium.org> + + [chromium] Allow plugins to opt-in to receive synthetic mouse events out of touch events. + https://bugs.webkit.org/show_bug.cgi?id=103092 + + Reviewed by Tony Chang. + + Update the test web-plugin to be able to opt-in to receive synthesized mouse events created + from touch events. + + * DumpRenderTree/chromium/TestWebPlugin.cpp: + (parseTouchEventRequestType): + (TestWebPlugin::TestWebPlugin): + (TestWebPlugin::initialize): + * DumpRenderTree/chromium/TestWebPlugin.h: + (TestWebPlugin): + +2012-11-28 Sudarsana Nagineni <sudarsana.nagineni@intel.com> + + [EFL][WK2] Add support for PlatformWebView::simulateSpacebarKeyPress() in TestWebKitAPI + https://bugs.webkit.org/show_bug.cgi?id=103123 + + Reviewed by Laszlo Gombos. + + Add support for PlatformWebView::simulateSpacebarKeyPress(). + This functionality is needed by WebKit2 API test MouseMoveAfterCrash + which is going to be unskipped in bug #103252. + + * TestWebKitAPI/efl/PlatformUtilities.cpp: + (TestWebKitAPI::Util::sleep): + * TestWebKitAPI/efl/PlatformWebView.cpp: Use usleep() instead of + sleep(). + (TestWebKitAPI::PlatformWebView::simulateSpacebarKeyPress): + (TestWebKitAPI): + +2012-11-28 Yael Aharon <yael.aharon@intel.com> + + Minor cleanup in TestInvocation + https://bugs.webkit.org/show_bug.cgi?id=103512 + + Reviewed by Kenneth Rohde Christiansen. + + Remove a function declaration that is not defined and not used. + Fix spelling error in m_webProcessIsUnresponsive. + + * WebKitTestRunner/TestInvocation.cpp: + (WTR::TestInvocation::TestInvocation): + (WTR::TestInvocation::invoke): + * WebKitTestRunner/TestInvocation.h: + (TestInvocation): + * WebKitTestRunner/cairo/TestInvocationCairo.cpp: + (WTR::TestInvocation::dumpPixelsAndCompareWithExpected): + * WebKitTestRunner/qt/TestInvocationQt.cpp: + (WTR::TestInvocation::dumpPixelsAndCompareWithExpected): + +2012-11-28 Thiago Marcos P. Santos <thiago.santos@intel.com> + + Unreviewed. Use my personal email as bugzilla email. + + * Scripts/webkitpy/common/config/committers.py: + +2012-11-28 Thiago Marcos P. Santos <thiago.santos@intel.com> + + Unreviewed. Adding myself to committers.py. + + * Scripts/webkitpy/common/config/committers.py: + +2012-11-26 Andrey Adaikin <aandrey@chromium.org> + + Unreviewed. Adding myself to committers.py. + + * Scripts/webkitpy/common/config/committers.py: + +2012-11-28 Tommy Widenflycht <tommyw@google.com> + + Add basic implementation for MediaStreamAudioDestinationNode + https://bugs.webkit.org/show_bug.cgi?id=101815 + + Reviewed by Chris Rogers. + + Adds a bit of code that exercises the WebKit API. + + * DumpRenderTree/chromium/MockWebMediaStreamCenter.cpp: + (MockWebMediaStreamSourceConsumer): + (MockWebMediaStreamSourceConsumer::~MockWebMediaStreamSourceConsumer): + (MockWebMediaStreamCenter::didCreateMediaStream): + +2012-11-28 Matt Falkenhagen <falken@chromium.org> + + Unreviewed. Adding myself to committers list. + + * Scripts/webkitpy/common/config/committers.py: + +2012-11-27 Li Yin <li.yin@intel.com> + + Unreviewed. Adding myself to committers list. + + * Scripts/webkitpy/common/config/committers.py: + +2012-11-27 Christophe Dumez <christophe.dumez@intel.com> + + Unreviewed. Adding myself to committers.py. + + * Scripts/webkitpy/common/config/committers.py: + +2012-11-27 Vivek Galatage <vivek.vg@samsung.com> + + Unreviewd. Adding myself to committers list. + + * Scripts/webkitpy/common/config/committers.py: + +2012-11-27 Tony Chang <tony@chromium.org> + + Bring back partytime! + https://bugs.webkit.org/show_bug.cgi?id=103466 + + Reviewed by Adam Barth. + + "code 404, message Unknown function images/partytime_gif" since we didn't + allow .gif or .png files to be served. + + * Scripts/webkitpy/tool/servers/gardeningserver.py: + (GardeningHTTPRequestHandler): + +2012-11-27 Adam Barth <abarth@webkit.org> + + run-perf-tests fails on Android because of stderr output + https://bugs.webkit.org/show_bug.cgi?id=103462 + + Reviewed by Ryosuke Niwa. + + The chromium-android port produces some stderr output that causes + run-perf-tests to get sad and not record the results of the performance + test. This patch teaches run-perf-test to ignore this output much in + the same way that it currently ignores some stdout messages. + + * Scripts/webkitpy/performance_tests/perftest.py: + (PerfTest.run): + (PerfTest._should_ignore_line): + (PerfTest): + (PerfTest._should_ignore_line_in_stderr): + (PerfTest._filter_stderr): + (PerfTest._should_ignore_line_in_parser_test_result): + +2012-11-27 Tony Chang <tony@chromium.org> + + Fix garden-o-matic for non-chromium ports + https://bugs.webkit.org/show_bug.cgi?id=103458 + + Reviewed by Adam Barth. + + I was getting a 403 error when trying to select any non-chromium port. + + * Scripts/webkitpy/tool/servers/reflectionhandler.py: + (ReflectionHandler._handle_request): Use the path without query params. + +2012-11-27 Yael Aharon <yael.aharon@intel.com> + + [EFL][WK2] 3D pixel tests are failing + https://bugs.webkit.org/show_bug.cgi?id=102833 + + Reviewed by Kenneth Rohde Christiansen. + + Generate a snapshot of the view in the UI process instead of the web process. + We have to use Texture Mapper in order to correctly paint 3D transforms etc. + + * WebKitTestRunner/TestInvocation.h: + (TestInvocation): + * WebKitTestRunner/cairo/TestInvocationCairo.cpp: + (WTR::writeFunction): + (WTR::paintRepaintRectOverlay): + (WTR): + (WTR::TestInvocation::forceRepaintDoneCallback): + (WTR::TestInvocation::dumpPixelsAndCompareWithExpected): + * WebKitTestRunner/efl/PlatformWebViewEfl.cpp: + (WTR::PlatformWebView::windowSnapshotImage): + +2012-11-27 Adam Barth <abarth@webkit.org> + + Make it possible to run performance tests on Chromium Android + https://bugs.webkit.org/show_bug.cgi?id=103268 + + Reviewed by Ryosuke Niwa. + + Based on a patch by Peter Beverloo. + + This patch (almost) makes it possible to run WebKit performance tests + on the Chromium port for Android. There are a few things I had to do + in order to make this happen: + + 1) The worker number when creating a driver for a port is zero-based + for layout tests and elsewhere. Android uses this to determine + which device it has to run on, so make it zero based for performance + tests as well. + + 2) Tests aren't available on the Android device, so we start an HTTP + server that serves the tests to the device or emulator. + + The one shortcoming of this patch is that chromium-android produces + some stderr output that confuses run-perf-tests. I'll address that + issue in a subsequent CL. This patch also depends on + https://codereview.chromium.org/11416182 in order to work. + + * Scripts/webkitpy/layout_tests/port/chromium_android.py: + (ChromiumAndroidPort.start_http_server): + (ChromiumAndroidDriver._command_from_driver_input): + * Scripts/webkitpy/performance_tests/perftest.py: + (ReplayPerfTest.prepare): + * Scripts/webkitpy/performance_tests/perftestsrunner.py: + (PerfTestsRunner.__init__): + (PerfTestsRunner._parse_args): + (PerfTestsRunner._start_servers): + (PerfTestsRunner): + (PerfTestsRunner._stop_servers): + (PerfTestsRunner.run): + (PerfTestsRunner._run_tests_set): + +2012-11-27 Zan Dobersek <zandobersek@gmail.com> + + Remove use of deprecated logging from webkitpy.common and webkitpy.layout_tests + https://bugs.webkit.org/show_bug.cgi?id=103408 + + Reviewed by Dirk Pranke. + + Remove the use of the deprecated log and error methods by replacing them with + logging through Python's logging.Logger objects. + + This patch covers such changes in webkitpy.common and webkitpy.layout_tests and also + updates any affected unit test. + + * Scripts/webkitpy/common/checkout/changelog.py: + (ChangeLogEntry._parse_entry): + * Scripts/webkitpy/common/checkout/checkout.py: + * Scripts/webkitpy/common/checkout/checkout_unittest.py: + (CheckoutTest.test_apply_patch): + * Scripts/webkitpy/common/checkout/deps_mock.py: + (MockDEPS.write_variable): + * Scripts/webkitpy/common/checkout/scm/detection.py: + (SCMDetector.default_scm): + * Scripts/webkitpy/common/checkout/scm/detection_unittest.py: + (SCMDetectorTest.test_detect_scm_system): + * Scripts/webkitpy/common/checkout/scm/git.py: + (Git._check_git_architecture): + (Git._commit_on_branch): + * Scripts/webkitpy/common/checkout/scm/scm.py: + (SCM.ensure_clean_working_directory): + (SCM.ensure_no_local_commits): + (SCM.will.commit_locally_with_message): + * Scripts/webkitpy/common/checkout/scm/svn.py: + (SVN.apply_reverse_diff): + * Scripts/webkitpy/common/net/bugzilla/attachment.py: + (Attachment._validate_flag_value): + * Scripts/webkitpy/common/net/bugzilla/bugzilla.py: + (Bugzilla._fetch_bug_page): + (Bugzilla.bug_id_for_attachment_id): + (Bugzilla.authenticate): + (Bugzilla._commit_queue_flag): + (Bugzilla.add_attachment_to_bug): + (Bugzilla.add_patch_to_bug): + (Bugzilla.create_bug): + (Bugzilla.clear_attachment_flags): + (Bugzilla.set_flag_on_attachment): + (Bugzilla.obsolete_attachment): + (Bugzilla.add_cc_to_bug): + (Bugzilla.post_comment_to_bug): + (Bugzilla.close_bug_as_fixed): + (Bugzilla.reassign_bug): + (reopen_bug): + * Scripts/webkitpy/common/net/bugzilla/bugzilla_mock.py: + (MockBugzilla.create_bug): + (MockBugzilla.reassign_bug): + (MockBugzilla.set_flag_on_attachment): + (MockBugzilla.post_comment_to_bug): + (MockBugzilla.add_attachment_to_bug): + (MockBugzilla.add_patch_to_bug): + (MockBugzilla.reopen_bug): + * Scripts/webkitpy/common/net/bugzilla/bugzilla_unittest.py: + (test_add_cc_to_bug): + (_assert_reopen): + (test_reopen_bug): + * Scripts/webkitpy/common/net/buildbot/buildbot_mock.py: + (MockBuilder.force_build): + * Scripts/webkitpy/common/net/credentials.py: + (Credentials._run_security_tool): + * Scripts/webkitpy/common/net/credentials_unittest.py: + (_assert_security_call): + * Scripts/webkitpy/common/net/irc/irc_mock.py: + (MockIRC.post): + (MockIRC.disconnect): + * Scripts/webkitpy/common/net/irc/ircproxy.py: + (IRCProxy.__init__): + (IRCProxy.disconnect): + * Scripts/webkitpy/common/net/irc/ircproxy_unittest.py: + (IRCProxyTest.test_trivial): + * Scripts/webkitpy/common/net/layouttestresults.py: + (ORWTResultsHTMLParser._failures_from_fail_row): + * Scripts/webkitpy/common/net/layouttestresults_unittest.py: + (test_failures_from_fail_row): + * Scripts/webkitpy/common/net/networktransaction.py: + * Scripts/webkitpy/common/net/resultsjsonparser.py: + (JSONTestResult._tokenize): + (JSONTestResult._failure_types_from_actual_result): + * Scripts/webkitpy/common/net/statusserver.py: + (StatusServer.update_status): + (StatusServer.update_svn_revision): + * Scripts/webkitpy/common/net/statusserver_mock.py: + (MockStatusServer.release_work_item): + (MockStatusServer.update_work_items): + (MockStatusServer.submit_to_ews): + (MockStatusServer.update_status): + * Scripts/webkitpy/common/net/unittestresults.py: + (UnitTestResults.results_from_string): + * Scripts/webkitpy/common/system/executive_mock.py: + (MockExecutive.running_pids): + (MockExecutive.run_and_throw_if_fail): + (MockExecutive.run_command): + (MockExecutive.popen): + * Scripts/webkitpy/common/system/user_mock.py: + (MockUser.confirm): + (MockUser.open_url): + * Scripts/webkitpy/common/system/workspace_unittest.py: + (WorkspaceTest.test_create_zip): + (WorkspaceTest.test_create_zip_exception): + * Scripts/webkitpy/common/watchlist/watchlist_mock.py: + (MockWatchList.determine_cc_and_messages): + * Scripts/webkitpy/layout_tests/port/chromium_win_unittest.py: + (ChromiumWinTest.test_setup_environ_for_server_register_cygwin): + * Scripts/webkitpy/layout_tests/port/efl_unittest.py: + (EflPortTest.test_show_results_html_file): + * Scripts/webkitpy/layout_tests/port/gtk_unittest.py: + (GtkPortTest.test_show_results_html_file): + * Scripts/webkitpy/layout_tests/port/mac_unittest.py: + (test_show_results_html_file): + * Scripts/webkitpy/layout_tests/port/port_testcase.py: + (test_build_driver): + * Scripts/webkitpy/layout_tests/port/qt_unittest.py: + (QtPortTest.test_show_results_html_file): + * Scripts/webkitpy/layout_tests/port/win_unittest.py: + (WinPortTest.test_show_results_html_file): + * Scripts/webkitpy/layout_tests/port/xvfbdriver_unittest.py: + (XvfbDriverTest.assertDriverStartSuccessful): + (XvfbDriverTest.test_start_no_pixel_tests): + (XvfbDriverTest.test_start_pixel_tests): + (XvfbDriverTest.test_start_arbitrary_worker_number): + (XvfbDriverTest.test_start_next_worker): + (XvfbDriverTest.test_stop): + * Scripts/webkitpy/layout_tests/servers/apache_http_server_unittest.py: + (TestLayoutTestApacheHttpd.test_start_cmd): + * Scripts/webkitpy/performance_tests/perftestsrunner_unittest.py: + (test_run_test_pause_before_testing): + (test_run_memory_test): + (_test_run_with_json_output): + (test_run_respects_no_results): + (test_run_generates_and_show_results_page): + (test_run_respects_no_show_results): + * Scripts/webkitpy/tool/bot/feeders_unittest.py: + (FeedersTest.test_commit_queue_feeder): + * Scripts/webkitpy/tool/bot/flakytestreporter_unittest.py: + (FlakyTestReporterTest.test_create_bug_for_flaky_test): + (test_report_flaky_tests_creating_bug): + * Scripts/webkitpy/tool/bot/irc_command_unittest.py: + (IRCCommandTest.test_rollout_updates_working_copy): + * Scripts/webkitpy/tool/bot/ircbot_unittest.py: + (IRCBotTest.test_exception_during_command): + (IRCBotTest.test_hi): + (IRCBotTest.test_help): + (IRCBotTest.test_restart): + (IRCBotTest.test_rollout): + (IRCBotTest.test_revert): + (IRCBotTest.test_roll_chromium_deps): + (IRCBotTest.test_roll_chromium_deps_to_lkgr): + (IRCBotTest.test_multi_rollout): + (IRCBotTest.test_rollout_with_r_in_svn_revision): + (IRCBotTest.test_multi_rollout_with_r_in_svn_revision): + (IRCBotTest.test_rollout_bananas): + (IRCBotTest.test_rollout_invalidate_revision): + (IRCBotTest.test_rollout_invalidate_reason): + (test_multi_rollout_invalidate_reason): + (test_rollout_no_reason): + (test_multi_rollout_no_reason): + * Scripts/webkitpy/tool/bot/sheriff_unittest.py: + (SheriffTest.test_post_blame_comment_on_bug): + * Scripts/webkitpy/tool/commands/applywatchlistlocal_unittest.py: + (ApplyWatchListLocalTest.test_args_parsing): + (test_args_parsing_with_bug): + * Scripts/webkitpy/tool/commands/download_unittest.py: + (test_land_cowboy): + (test_check_style): + (test_create_rollout): + (test_create_rollout_resolved): + (test_rollout): + * Scripts/webkitpy/tool/commands/earlywarningsystem_unittest.py: + (AbstractEarlyWarningSystemTest.test_failing_tests_message): + (EarlyWarningSytemTest._default_expected_logs): + (EarlyWarningSytemTest._test_builder_ews): + (EarlyWarningSytemTest._test_testing_ews): + * Scripts/webkitpy/tool/commands/openbugs_unittest.py: + (OpenBugsTest.test_args_parsing): + * Scripts/webkitpy/tool/commands/queries_unittest.py: + (QueryCommandsTest.test_bugs_to_commit): + (QueryCommandsTest.test_patches_in_commit_queue): + * Scripts/webkitpy/tool/commands/queues_unittest.py: + (FeederQueueTest.test_feeder_queue): + (AbstractPatchQueueTest.test_next_patch): + (AbstractPatchQueueTest.test_upload_results_archive_for_patch): + (CommitQueueTest.test_commit_queue): + (test_commit_queue_failure): + (test_commit_queue_failure_with_failing_tests): + (test_rollout): + (test_rollout_lands): + (test_auto_retry): + (test_manual_reject_during_processing): + (test_report_flaky_tests): + (StyleQueueTest.test_style_queue_with_style_exception): + (test_style_queue_with_watch_list_exception): + * Scripts/webkitpy/tool/commands/queuestest.py: + (QueuesTest._default_begin_work_queue_logs): + * Scripts/webkitpy/tool/commands/roll_unittest.py: + (RollCommandsTest.test_update_chromium_deps): + * Scripts/webkitpy/tool/commands/upload_unittest.py: + (UploadCommandsTest.test_assign_to_committer): + (test_post): + (test_attach_to_bug): + (test_attach_to_bug_no_description_or_comment): + (test_land_safely): + (test_prepare): + (test_upload): + (test_mark_bug_fixed): + * Scripts/webkitpy/tool/steps/applywatchlist_unittest.py: + (ApplyWatchListTest.test_apply_watch_list_local): + * Scripts/webkitpy/tool/steps/commit_unittest.py: + (CommitTest._test_check_test_expectations): + * Scripts/webkitpy/tool/steps/runtests_unittest.py: + (RunTestsTest.test_webkit_run_unit_tests): + * Scripts/webkitpy/tool/steps/steps_unittest.py: + (StepsTest._assert_step_output_with_bug): + (StepsTest._assert_post_diff_output_for_bug): + (StepsTest.test_post_diff): + (StepsTest.test_post_diff_for_commit): + (StepsTest.test_ensure_bug_is_open_and_assigned): + (StepsTest.test_runtests_args): + * Scripts/webkitpy/tool/steps/suggestreviewers_unittest.py: + (SuggestReviewersTest.test_basic): + * Scripts/webkitpy/tool/steps/validatechangelogs_unittest.py: + (ValidateChangeLogsTest._assert_start_line_produces_output): + +2012-11-27 Pratik Solanki <psolanki@apple.com> + + objc/objc-runtime.h does not exist on all PLATFORM(MAC) + https://bugs.webkit.org/show_bug.cgi?id=101780 + + Reviewed by Brent Fulgham. + + Clean up header includes so we don't include objc/objc-runtime.h. + + * DumpRenderTree/mac/DumpRenderTree.mm: + * DumpRenderTree/mac/ObjCPlugin.m: + * TestWebKitAPI/mac/InstanceMethodSwizzler.h: + * WebKitTestRunner/InjectedBundle/mac/ActivateFonts.mm: + +2012-11-27 Marja Hölttä <marja@chromium.org> + + Add callbacks to the FrameLoaderClient when a resource is requested + https://bugs.webkit.org/show_bug.cgi?id=92761 + + Reviewed by Adam Barth. + + In Chromium, when an extension script cancels a network + request (which happens out of process), we'd like to + notify content scripts running on the current page about + which elements failed to load because the requests were + cancelled (as opposed to e.g. the network request just + didn't work). Since the resource request itself does not + carry any information what DOM element is was made for, + currently a content script has to search the DOM tree and + guess which requests will be cancelled by its counter + part. By adding these callbacks, the embedder can make + this connection explictly. + + * DumpRenderTree/chromium/DRTTestRunner.cpp: + (DRTTestRunner::DRTTestRunner): + (DRTTestRunner::dumpResourceRequestCallbacks): + (DRTTestRunner::reset): + * DumpRenderTree/chromium/DRTTestRunner.h: + (DRTTestRunner): + (DRTTestRunner::setShouldDumpResourceRequestCallbacks): + (DRTTestRunner::shouldDumpResourceRequestCallbacks): + * DumpRenderTree/chromium/TestShell.h: + (TestShell::shouldDumpResourceRequestCallbacks): + * DumpRenderTree/chromium/WebViewHost.cpp: + (WebViewHost::willRequestResource): + * DumpRenderTree/chromium/WebViewHost.h: + (WebViewHost): + +2012-11-27 VÃctor Manuel Jáquez Leal <vjaquez@igalia.com> + + [GStreamer] Verify if GStreamer was previously initialized + https://bugs.webkit.org/show_bug.cgi?id=103151 + + Reviewed by Philippe Normand. + + This patch adds the gst_init() in GtkLauncher, so we can add the + GStreamer options in the command line through + gst_init_get_option_group(). + + This approach is not valid for MiniBrowser because it uses WebKit2, + where the GStreamer backend lives in the web process, which is + different from the UI process. + + * GNUmakefile.am: + * GtkLauncher/main.c: + (main): + +2012-11-27 Andras Becsi <andras.becsi@digia.com> + + [Qt] Fix the build with new Qt5 hash + https://bugs.webkit.org/show_bug.cgi?id=103406 + + Reviewed by Csaba Osztrogonác. + + Remove references to deprecated QApplication::GuiServer which + has been removed, and use QStyleFactory::create instead of + instantiating a QWindowsStyle directly since it is about to + become an internal class. + + * DumpRenderTree/qt/DumpRenderTreeMain.cpp: + (main): + * QtTestBrowser/qttestbrowser.cpp: + (LauncherApplication::LauncherApplication): + * WebKitTestRunner/InjectedBundle/qt/InjectedBundleQt.cpp: + (WTR::InjectedBundle::platformInitialize): + +2012-11-27 Sadrul Habib Chowdhury <sadrul@chromium.org> + + [style] Add a style-check for enum-member names + https://bugs.webkit.org/show_bug.cgi?id=103157 + + Reviewed by Daniel Bates. + + * Scripts/webkitpy/style/checkers/cpp.py: + (_EnumState): + (_EnumState.__init__): + (_EnumState.process_clean_line): + (check_enum_casing): + (check_style): + (process_line): + (_process_lines): + (CppChecker): + * Scripts/webkitpy/style/checkers/cpp_unittest.py: + (NoNonVirtualDestructorsTest.test_enum_casing): + (NoNonVirtualDestructorsTest.test_internal_braces.Foo): + +2012-11-26 Ryuan Choi <ryuan.choi@gmail.com> + + [EFL][jhbuild] Disable unnecessary options of elementary module + https://bugs.webkit.org/show_bug.cgi?id=103360 + + Reviewed by Gyuyoung Kim. + + When jhbuild configures elementary, unnecessary options may be enabled by + user installed modules and it causes build break. + + * efl/jhbuild.modules: + Added --disable-emap --disable-ethumb --disable-eweather to elementary. + +2012-11-26 Varun Jain <varunjain@chromium.org> + + LongPress and LongTap gestures should start drag/drop and open context menu respectively. + https://bugs.webkit.org/show_bug.cgi?id=101545 + + Reviewed by Antonio Gomes. + + For LongPress, we simulate drag by sending a mouse down and mouse drag + events. If a drag is not started (because maybe there is no draggable + element), then we show context menu instead (which is the current + behavior for LongPress). For LongTap, we use the existing functions that + LongPress uses to summon the context menu. LongPress initiated drag and + drop can be enabled/disabled by the platform using the Setting + touchDragDropEnabled which is disabled by default. + + * DumpRenderTree/chromium/TestRunner/src/EventSender.cpp: + (WebTestRunner): + (WebTestRunner::EventSender::EventSender): + (WebTestRunner::EventSender::gestureLongTap): + (WebTestRunner::EventSender::gestureEvent): + * DumpRenderTree/chromium/TestRunner/src/EventSender.h: + (EventSender): + * DumpRenderTree/chromium/TestRunner/src/TestRunner.cpp: + (WebTestRunner::TestRunner::TestRunner): + (WebTestRunner::TestRunner::setTouchDragDropEnabled): + (WebTestRunner): + * DumpRenderTree/chromium/TestRunner/src/TestRunner.h: + (TestRunner): + +2012-11-26 Christophe Dumez <christophe.dumez@intel.com> + + [EFL][WK2] Add setting to enable / disable HTML5 local storage functionality + https://bugs.webkit.org/show_bug.cgi?id=103224 + + Reviewed by Laszlo Gombos. + + Add --local-storage command line argument to MiniBrowser to + explicitely disable HTML5 local storage functionality. This + is useful for testing purposes. + + * MiniBrowser/efl/main.c: + (window_create): + (elm_main): + +2012-11-26 Zan Dobersek <zandobersek@gmail.com> + + Remove use of deprecated logging from most of webkitpy.tool + https://bugs.webkit.org/show_bug.cgi?id=103180 + + Reviewed by Dirk Pranke. + + Remove calls to log and error methods of the deprecated_logging module, replacing them + by using Python's Logger objects. This patch covers the switch in all of webkitpy.tool + except the QueueEngine. + + Unit tests are adjusted for these changes, moving output from expected stderr to expected logs. + + * Scripts/webkitpy/tool/bot/commitqueuetask_unittest.py: + (MockCommitQueue.run_command): + (MockCommitQueue.command_passed): + (MockCommitQueue.command_failed): + (MockCommitQueue.report_flaky_tests): + (MockCommitQueue.archive_last_test_results): + (CommitQueueTaskTest._run_through_task): + (CommitQueueTaskTest.test_success_case): + (test_fast_success_case): + (test_clean_failure): + (test_update_failure): + (test_apply_failure): + (test_validate_changelog_failure): + (test_build_failure): + (test_red_build_failure): + (test_flaky_test_failure): + (test_failed_archive): + (test_double_flaky_test_failure): + (test_test_failure): + (test_red_test_failure): + (test_very_red_tree_retry): + (test_red_tree_patch_rejection): + (test_land_failure): + * Scripts/webkitpy/tool/bot/feeders.py: + (CommitQueueFeeder._update_work_items): + (EWSFeeder.feed): + * Scripts/webkitpy/tool/bot/feeders_unittest.py: + * Scripts/webkitpy/tool/bot/layouttestresultsreader.py: + (LayoutTestResultsReader.archive): + * Scripts/webkitpy/tool/bot/layouttestresultsreader_unittest.py: + (test_archive_last_layout_test_results): + * Scripts/webkitpy/tool/bot/sheriff.py: + * Scripts/webkitpy/tool/commands/abstractsequencedcommand.py: + (AbstractSequencedCommand.execute): + * Scripts/webkitpy/tool/commands/commandtest.py: + (CommandsTest.assert_execute_outputs): + * Scripts/webkitpy/tool/commands/download.py: + (AbstractPatchProcessingCommand._process_patch.execute): + (ProcessBugsMixin._fetch_list_of_patches_to_process): + (ProcessURLsMixin._fetch_list_of_patches_to_process): + (AbstractRolloutPrepCommand._commit_info): + * Scripts/webkitpy/tool/commands/download_unittest.py: + (AbstractRolloutPrepCommandTest.test_commit_info): + (DownloadCommandsTest.test_build): + (DownloadCommandsTest.test_build_and_test): + (test_apply_attachment): + (test_apply_from_bug): + (test_apply_watch_list): + (test_land): + (test_land_red_builders): + (test_check_style): + (test_build_attachment): + (test_land_attachment): + (test_land_from_bug): + (test_land_from_url): + (test_prepare_rollout): + (test_create_rollout): + (test_create_rollout_resolved): + (test_rollout): + * Scripts/webkitpy/tool/commands/earlywarningsystem.py: + (AbstractEarlyWarningSystem.handle_script_error.does): + * Scripts/webkitpy/tool/commands/earlywarningsystem_unittest.py: + (EarlyWarningSytemTest._default_expected_stderr): + (EarlyWarningSytemTest._default_expected_logs): + (EarlyWarningSytemTest._test_testing_ews): + * Scripts/webkitpy/tool/commands/openbugs.py: + (OpenBugs.execute): + * Scripts/webkitpy/tool/commands/openbugs_unittest.py: + (OpenBugsTest.test_args_parsing): + * Scripts/webkitpy/tool/commands/perfalizer.py: + (Perfalizer.handle_unexpected_error): + * Scripts/webkitpy/tool/commands/queries.py: + (PatchesInCommitQueue.execute): + (PatchesToCommitQueue._needs_commit_queue): + * Scripts/webkitpy/tool/commands/queries_unittest.py: + (QueryCommandsTest.test_bugs_to_commit): + (QueryCommandsTest.test_patches_in_commit_queue): + (QueryCommandsTest.test_patches_to_commit_queue): + * Scripts/webkitpy/tool/commands/queues.py: + (AbstractQueue._cc_watchers): + (AbstractQueue.begin_work_queue): + (FeederQueue.handle_unexpected_error): + (CommitQueue.handle_script_error): + (AbstractReviewQueue.handle_unexpected_error): + (AbstractReviewQueue.handle_script_error): + * Scripts/webkitpy/tool/commands/queues_unittest.py: + (test_auto_retry): + * Scripts/webkitpy/tool/commands/queuestest.py: + (QueuesTest.assert_outputs): + (QueuesTest._default_begin_work_queue_stderr): + (QueuesTest): + (QueuesTest._default_begin_work_queue_logs): + (QueuesTest.assert_queue_outputs): + * Scripts/webkitpy/tool/commands/roll_unittest.py: + (RollCommandsTest.test_update_chromium_deps): + (test_update_chromium_deps_older_revision): + * Scripts/webkitpy/tool/commands/sheriffbot.py: + (SheriffBot.handle_unexpected_error): + * Scripts/webkitpy/tool/commands/stepsequence.py: + (StepSequence.run_and_handle_errors): + * Scripts/webkitpy/tool/commands/upload.py: + (AssignToCommitter._assign_bug_to_last_patch_attacher): + (AbstractPatchUploadingCommand._prepare_state): + (PostCommits.execute): + (MarkBugFixed._determine_bug_id_and_svn_revision): + (MarkBugFixed.execute): + (CreateBug.create_bug_from_commit): + (CreateBug.execute): + * Scripts/webkitpy/tool/commands/upload_unittest.py: + (test_obsolete_attachments): + (test_land_safely): + (test_mark_bug_fixed): + * Scripts/webkitpy/tool/multicommandtool.py: + (Command.check_arguments_and_execute): + (MultiCommandTool.main): + * Scripts/webkitpy/tool/multicommandtool_unittest.py: + (CommandTest.test_required_arguments): + * Scripts/webkitpy/tool/steps/addsvnmimetypeforpng.py: + (AddSvnMimetypeForPng.run): + * Scripts/webkitpy/tool/steps/applypatch.py: + (ApplyPatch.run): + * Scripts/webkitpy/tool/steps/build.py: + (Build.run): + * Scripts/webkitpy/tool/steps/checkstyle.py: + * Scripts/webkitpy/tool/steps/closebug.py: + (CloseBug.run): + * Scripts/webkitpy/tool/steps/closebugforlanddiff.py: + (CloseBugForLandDiff.run): + * Scripts/webkitpy/tool/steps/closebugforlanddiff_unittest.py: + (CloseBugForLandDiffTest.test_empty_state): + * Scripts/webkitpy/tool/steps/commit.py: + (Commit.run): + * Scripts/webkitpy/tool/steps/commit_unittest.py: + (CommitTest._test_check_test_expectations): + * Scripts/webkitpy/tool/steps/ensurelocalcommitifneeded.py: + (EnsureLocalCommitIfNeeded.run): + * Scripts/webkitpy/tool/steps/obsoletepatches.py: + (ObsoletePatches.run): + * Scripts/webkitpy/tool/steps/preparechangelog.py: + (PrepareChangeLog.run): + * Scripts/webkitpy/tool/steps/reopenbugafterrollout.py: + (ReopenBugAfterRollout.run): + * Scripts/webkitpy/tool/steps/runtests.py: + (RunTests.run): + * Scripts/webkitpy/tool/steps/runtests_unittest.py: + (RunTestsTest.test_webkit_run_unit_tests): + * Scripts/webkitpy/tool/steps/steps_unittest.py: + (StepsTest.test_update_step): + (StepsTest.test_runtests_args): + * Scripts/webkitpy/tool/steps/update.py: + (Update.run): + * Scripts/webkitpy/tool/steps/updatechangelogswithreview_unittest.py: + (UpdateChangeLogsWithReviewerTest.test_guess_reviewer_from_bug): + (UpdateChangeLogsWithReviewerTest.test_guess_reviewer_from_multipatch_bug): + * Scripts/webkitpy/tool/steps/updatechangelogswithreviewer.py: + (UpdateChangeLogsWithReviewer._guess_reviewer_from_bug): + (UpdateChangeLogsWithReviewer.run): + * Scripts/webkitpy/tool/steps/updatechromiumdeps.py: + (UpdateChromiumDEPS._validate_revisions): + (UpdateChromiumDEPS.run): + * Scripts/webkitpy/tool/steps/validatechangelogs.py: + (ValidateChangeLogs._check_changelog_diff): + (ValidateChangeLogs.run): + * Scripts/webkitpy/tool/steps/validatechangelogs_unittest.py: + (ValidateChangeLogsTest._assert_start_line_produces_output): + * Scripts/webkitpy/tool/steps/validatereviewer.py: + (ValidateReviewer.run): + +2012-11-26 Zan Dobersek <zandobersek@gmail.com> + + Coverage testing in webkitpy should omit some paths + https://bugs.webkit.org/show_bug.cgi?id=103267 + + Reviewed by Dirk Pranke. + + Omit testing coverage of any file under /usr directory and any file + that is of third party origin and was autoinstalled. + + * Scripts/webkitpy/test/main.py: + (Tester._run_tests): + +2012-11-26 Jaehun Lim <ljaehun.lim@samsung.com> + + Text Autosizing: Add Text Autosizing APIs for WK2 + https://bugs.webkit.org/show_bug.cgi?id=100633 + + Reviewed by Sam Weinig. + + Add test cases for Text Autosizing in WKPreferences. + + * TestWebKitAPI/Tests/WebKit2/WKPreferences.cpp: + (TestWebKitAPI::TEST): + 2012-11-26 Pierre Rossi <pierre.rossi@gmail.com> [Qt] REGRESSION(r135575): It made all tests assert diff --git a/Tools/DumpRenderTree/chromium/DRTTestRunner.cpp b/Tools/DumpRenderTree/chromium/DRTTestRunner.cpp index 2f8397bee..e2255c793 100644 --- a/Tools/DumpRenderTree/chromium/DRTTestRunner.cpp +++ b/Tools/DumpRenderTree/chromium/DRTTestRunner.cpp @@ -139,6 +139,7 @@ DRTTestRunner::DRTTestRunner(TestShell* shell) bindMethod("dumpProgressFinishedCallback", &DRTTestRunner::dumpProgressFinishedCallback); bindMethod("dumpUserGestureInFrameLoadCallbacks", &DRTTestRunner::dumpUserGestureInFrameLoadCallbacks); bindMethod("dumpResourceLoadCallbacks", &DRTTestRunner::dumpResourceLoadCallbacks); + bindMethod("dumpResourceRequestCallbacks", &DRTTestRunner::dumpResourceRequestCallbacks); bindMethod("dumpResourceResponseMIMETypes", &DRTTestRunner::dumpResourceResponseMIMETypes); bindMethod("dumpSelectionRect", &DRTTestRunner::dumpSelectionRect); bindMethod("dumpStatusCallbacks", &DRTTestRunner::dumpWindowStatusChanges); @@ -322,6 +323,12 @@ void DRTTestRunner::dumpResourceLoadCallbacks(const CppArgumentList&, CppVariant result->setNull(); } +void DRTTestRunner::dumpResourceRequestCallbacks(const CppArgumentList&, CppVariant* result) +{ + m_dumpResourceRequestCallbacks = true; + result->setNull(); +} + void DRTTestRunner::dumpResourceResponseMIMETypes(const CppArgumentList&, CppVariant* result) { m_dumpResourceResponseMIMETypes = true; @@ -556,6 +563,7 @@ void DRTTestRunner::reset() m_dumpProgressFinishedCallback = false; m_dumpUserGestureInFrameLoadCallbacks = false; m_dumpResourceLoadCallbacks = false; + m_dumpResourceRequestCallbacks = false; m_dumpResourceResponseMIMETypes = false; m_dumpBackForwardList = false; m_dumpChildFrameScrollPositions = false; diff --git a/Tools/DumpRenderTree/chromium/DRTTestRunner.h b/Tools/DumpRenderTree/chromium/DRTTestRunner.h index 9f02e1c53..49f27c36b 100644 --- a/Tools/DumpRenderTree/chromium/DRTTestRunner.h +++ b/Tools/DumpRenderTree/chromium/DRTTestRunner.h @@ -116,7 +116,12 @@ public: // line for each resource load callback. It takes no arguments, and ignores // any that may be present. void dumpResourceLoadCallbacks(const CppArgumentList&, CppVariant*); - + + // This function sets a flag that tells the test_shell to print a line of + // descriptive text for each element that requested a resource. It takes no + // arguments, and ignores any that may be present. + void dumpResourceRequestCallbacks(const CppArgumentList&, CppVariant*); + // This function sets a flag that tells the test_shell to dump the MIME type // for each resource that was loaded. It takes no arguments, and ignores any // that may be present. @@ -318,6 +323,8 @@ public: bool shouldDumpUserGestureInFrameLoadCallbacks() { return m_dumpUserGestureInFrameLoadCallbacks; } void setShouldDumpUserGestureInFrameLoadCallbacks(bool value) { m_dumpUserGestureInFrameLoadCallbacks = value; } bool shouldDumpResourceLoadCallbacks() {return m_dumpResourceLoadCallbacks; } + void setShouldDumpResourceRequestCallbacks(bool value) { m_dumpResourceRequestCallbacks = value; } + bool shouldDumpResourceRequestCallbacks() { return m_dumpResourceRequestCallbacks; } void setShouldDumpResourceResponseMIMETypes(bool value) { m_dumpResourceResponseMIMETypes = value; } bool shouldDumpResourceResponseMIMETypes() {return m_dumpResourceResponseMIMETypes; } bool shouldDumpStatusCallbacks() { return m_dumpWindowStatusChanges; } @@ -451,7 +458,11 @@ private: // If true, the test_shell will output a descriptive line for each resource // load callback. bool m_dumpResourceLoadCallbacks; - + + // If true, the test_shell will output a descriptive line for each resource + // request callback. + bool m_dumpResourceRequestCallbacks; + // If true, the test_shell will output the MIME type for each resource that // was loaded. bool m_dumpResourceResponseMIMETypes; diff --git a/Tools/DumpRenderTree/chromium/MockWebMediaStreamCenter.cpp b/Tools/DumpRenderTree/chromium/MockWebMediaStreamCenter.cpp index b7178f099..e0f761934 100644 --- a/Tools/DumpRenderTree/chromium/MockWebMediaStreamCenter.cpp +++ b/Tools/DumpRenderTree/chromium/MockWebMediaStreamCenter.cpp @@ -33,6 +33,7 @@ #include "MockWebMediaStreamCenter.h" +#include <public/WebAudioDestinationConsumer.h> #include <public/WebMediaStreamCenterClient.h> #include <public/WebMediaStreamComponent.h> #include <public/WebMediaStreamDescriptor.h> @@ -85,8 +86,25 @@ void MockWebMediaStreamCenter::didStopLocalMediaStream(const WebMediaStreamDescr videoComponents[i].source().setReadyState(WebMediaStreamSource::ReadyStateEnded); } -void MockWebMediaStreamCenter::didCreateMediaStream(WebMediaStreamDescriptor&) +class MockWebAudioDestinationConsumer : public WebAudioDestinationConsumer { +public: + virtual ~MockWebAudioDestinationConsumer() { } + virtual void consumeAudio(const WebVector<const float*>&, size_t number_of_frames) OVERRIDE { } +}; + +void MockWebMediaStreamCenter::didCreateMediaStream(WebMediaStreamDescriptor& stream) { + WebVector<WebMediaStreamComponent> audioComponents; + stream.audioSources(audioComponents); + for (size_t i = 0; i < audioComponents.size(); ++i) { + WebMediaStreamSource source = audioComponents[i].source(); + if (source.requiresAudioConsumer()) { + MockWebAudioDestinationConsumer* consumer = new MockWebAudioDestinationConsumer(); + source.addAudioConsumer(consumer); + source.removeAudioConsumer(consumer); + delete consumer; + } + } } #endif // ENABLE(MEDIA_STREAM) diff --git a/Tools/DumpRenderTree/chromium/TestRunner/src/EventSender.cpp b/Tools/DumpRenderTree/chromium/TestRunner/src/EventSender.cpp index 171e25ddb..773a56b17 100644 --- a/Tools/DumpRenderTree/chromium/TestRunner/src/EventSender.cpp +++ b/Tools/DumpRenderTree/chromium/TestRunner/src/EventSender.cpp @@ -296,6 +296,7 @@ EventSender::EventSender() bindMethod("gestureTapDown", &EventSender::gestureTapDown); bindMethod("gestureTapCancel", &EventSender::gestureTapCancel); bindMethod("gestureLongPress", &EventSender::gestureLongPress); + bindMethod("gestureLongTap", &EventSender::gestureLongTap); bindMethod("gestureTwoFingerTap", &EventSender::gestureTwoFingerTap); bindMethod("zoomPageIn", &EventSender::zoomPageIn); bindMethod("zoomPageOut", &EventSender::zoomPageOut); @@ -1137,6 +1138,12 @@ void EventSender::gestureLongPress(const CppArgumentList& arguments, CppVariant* gestureEvent(WebInputEvent::GestureLongPress, arguments); } +void EventSender::gestureLongTap(const CppArgumentList& arguments, CppVariant* result) +{ + result->setNull(); + gestureEvent(WebInputEvent::GestureLongTap, arguments); +} + void EventSender::gestureTwoFingerTap(const CppArgumentList& arguments, CppVariant* result) { result->setNull(); @@ -1206,8 +1213,16 @@ void EventSender::gestureEvent(WebInputEvent::Type type, const CppArgumentList& event.x = point.x; event.y = point.y; if (arguments.size() >= 4) { - event.data.tapDown.width = static_cast<float>(arguments[2].toDouble()); - event.data.tapDown.height = static_cast<float>(arguments[3].toDouble()); + event.data.longPress.width = static_cast<float>(arguments[2].toDouble()); + event.data.longPress.height = static_cast<float>(arguments[3].toDouble()); + } + break; + case WebInputEvent::GestureLongTap: + event.x = point.x; + event.y = point.y; + if (arguments.size() >= 4) { + event.data.longPress.width = static_cast<float>(arguments[2].toDouble()); + event.data.longPress.height = static_cast<float>(arguments[3].toDouble()); } break; case WebInputEvent::GestureTwoFingerTap: diff --git a/Tools/DumpRenderTree/chromium/TestRunner/src/EventSender.h b/Tools/DumpRenderTree/chromium/TestRunner/src/EventSender.h index c5d742b5f..b1da68487 100644 --- a/Tools/DumpRenderTree/chromium/TestRunner/src/EventSender.h +++ b/Tools/DumpRenderTree/chromium/TestRunner/src/EventSender.h @@ -111,6 +111,7 @@ public: void gestureTapDown(const CppArgumentList&, CppVariant*); void gestureTapCancel(const CppArgumentList&, CppVariant*); void gestureLongPress(const CppArgumentList&, CppVariant*); + void gestureLongTap(const CppArgumentList&, CppVariant*); void gestureTwoFingerTap(const CppArgumentList&, CppVariant*); void gestureEvent(WebKit::WebInputEvent::Type, const CppArgumentList&); diff --git a/Tools/DumpRenderTree/chromium/TestRunner/src/TestRunner.cpp b/Tools/DumpRenderTree/chromium/TestRunner/src/TestRunner.cpp index 37078927d..8aa817a2b 100644 --- a/Tools/DumpRenderTree/chromium/TestRunner/src/TestRunner.cpp +++ b/Tools/DumpRenderTree/chromium/TestRunner/src/TestRunner.cpp @@ -98,6 +98,7 @@ TestRunner::TestRunner() bindMethod("setPageVisibility", &TestRunner::setPageVisibility); bindMethod("setTextDirection", &TestRunner::setTextDirection); bindMethod("textSurroundingNode", &TestRunner::textSurroundingNode); + bindMethod("setTouchDragDropEnabled", &TestRunner::setTouchDragDropEnabled); // Properties. bindProperty("workerThreadCount", &TestRunner::workerThreadCount); @@ -664,6 +665,15 @@ void TestRunner::textSurroundingNode(const CppArgumentList& arguments, CppVarian result->set(surroundingText.textContent().utf8()); } +void TestRunner::setTouchDragDropEnabled(const CppArgumentList& arguments, CppVariant* result) +{ + result->setNull(); + if (arguments.size() != 1 || !arguments[0].isBool()) + return; + + m_webView->settings()->setTouchDragDropEnabled(arguments[0].toBoolean()); +} + void TestRunner::workerThreadCount(CppVariant* result) { result->set(static_cast<int>(WebWorkerInfo::dedicatedWorkerCount())); diff --git a/Tools/DumpRenderTree/chromium/TestRunner/src/TestRunner.h b/Tools/DumpRenderTree/chromium/TestRunner/src/TestRunner.h index f9e9f7a24..4691e5579 100644 --- a/Tools/DumpRenderTree/chromium/TestRunner/src/TestRunner.h +++ b/Tools/DumpRenderTree/chromium/TestRunner/src/TestRunner.h @@ -147,6 +147,7 @@ private: // point coordinates relative to the node and the fourth the maximum text // length to retrieve. void textSurroundingNode(const CppArgumentList&, CppVariant*); + void setTouchDragDropEnabled(const CppArgumentList&, CppVariant*); /////////////////////////////////////////////////////////////////////////// // Properties diff --git a/Tools/DumpRenderTree/chromium/TestShell.h b/Tools/DumpRenderTree/chromium/TestShell.h index 9120121db..306f35cd1 100644 --- a/Tools/DumpRenderTree/chromium/TestShell.h +++ b/Tools/DumpRenderTree/chromium/TestShell.h @@ -112,6 +112,7 @@ public: void setFocus(WebKit::WebWidget*, bool enable); bool shouldDumpFrameLoadCallbacks() const { return (m_testIsPreparing || m_testIsPending) && testRunner()->shouldDumpFrameLoadCallbacks(); } + bool shouldDumpResourceRequestCallbacks() const { return (m_testIsPreparing || m_testIsPending) && testRunner()->shouldDumpResourceRequestCallbacks(); } bool shouldDumpUserGestureInFrameLoadCallbacks() const { return (m_testIsPreparing || m_testIsPending) && testRunner()->shouldDumpUserGestureInFrameLoadCallbacks(); } bool shouldDumpResourceLoadCallbacks() const { return (m_testIsPreparing || m_testIsPending) && testRunner()->shouldDumpResourceLoadCallbacks(); } bool shouldDumpResourceResponseMIMETypes() const { return (m_testIsPreparing || m_testIsPending) && testRunner()->shouldDumpResourceResponseMIMETypes(); } diff --git a/Tools/DumpRenderTree/chromium/TestWebPlugin.cpp b/Tools/DumpRenderTree/chromium/TestWebPlugin.cpp index 2960dc0bd..ea2fded18 100644 --- a/Tools/DumpRenderTree/chromium/TestWebPlugin.cpp +++ b/Tools/DumpRenderTree/chromium/TestWebPlugin.cpp @@ -118,12 +118,24 @@ static void printEventDetails(const WebKit::WebInputEvent& event) } } +static WebKit::WebPluginContainer::TouchEventRequestType parseTouchEventRequestType(const WebString& string) +{ + DEFINE_STATIC_LOCAL(const WebString, kPrimitiveRaw, (WebString::fromUTF8("raw"))); + DEFINE_STATIC_LOCAL(const WebString, kPrimitiveSynthetic, (WebString::fromUTF8("synthetic"))); + + if (string == kPrimitiveRaw) + return WebKit::WebPluginContainer::TouchEventRequestTypeRaw; + if (string == kPrimitiveSynthetic) + return WebKit::WebPluginContainer::TouchEventRequestTypeSynthesizedMouse; + return WebKit::WebPluginContainer::TouchEventRequestTypeNone; +} + TestWebPlugin::TestWebPlugin(WebKit::WebFrame* frame, const WebKit::WebPluginParams& params) : m_frame(frame) , m_container(0) , m_context(0) - , m_acceptsTouchEvent(false) + , m_touchEventRequest(WebKit::WebPluginContainer::TouchEventRequestTypeNone) , m_printEventDetails(false) , m_canProcessDrag(false) { @@ -150,7 +162,7 @@ TestWebPlugin::TestWebPlugin(WebKit::WebFrame* frame, else if (attributeName == kAttributeOpacity) m_scene.opacity = parseOpacity(attributeValue); else if (attributeName == kAttributeAcceptsTouch) - m_acceptsTouchEvent = parseBoolean(attributeValue); + m_touchEventRequest = parseTouchEventRequestType(attributeValue); else if (attributeName == kAttributePrintEventDetails) m_printEventDetails = parseBoolean(attributeValue); else if (attributeName == kAttributeCanProcessDrag) @@ -183,7 +195,7 @@ bool TestWebPlugin::initialize(WebPluginContainer* container) m_container = container; m_container->setBackingTextureId(m_colorTexture); - m_container->setIsAcceptingTouchEvents(m_acceptsTouchEvent); + m_container->requestTouchEventType(m_touchEventRequest); m_container->setWantsWheelEvents(true); return true; } diff --git a/Tools/DumpRenderTree/chromium/TestWebPlugin.h b/Tools/DumpRenderTree/chromium/TestWebPlugin.h index 49fde85aa..e6f5b47a4 100644 --- a/Tools/DumpRenderTree/chromium/TestWebPlugin.h +++ b/Tools/DumpRenderTree/chromium/TestWebPlugin.h @@ -27,6 +27,7 @@ #define TestWebPlugin_h #include "WebPlugin.h" +#include "WebPluginContainer.h" #include "platform/WebRect.h" namespace WebKit { @@ -131,7 +132,7 @@ private: unsigned m_framebuffer; Scene m_scene; - bool m_acceptsTouchEvent; + WebKit::WebPluginContainer::TouchEventRequestType m_touchEventRequest; bool m_printEventDetails; bool m_canProcessDrag; }; diff --git a/Tools/DumpRenderTree/chromium/WebViewHost.cpp b/Tools/DumpRenderTree/chromium/WebViewHost.cpp index baf8d0d9e..bc5f9942b 100644 --- a/Tools/DumpRenderTree/chromium/WebViewHost.cpp +++ b/Tools/DumpRenderTree/chromium/WebViewHost.cpp @@ -39,6 +39,7 @@ #include "TestNavigationController.h" #include "TestShell.h" #include "TestWebPlugin.h" +#include "WebCachedURLRequest.h" #include "WebConsoleMessage.h" #include "WebContextMenuData.h" #include "WebDOMMessageEvent.h" @@ -1139,6 +1140,23 @@ static bool hostIsUsedBySomeTestsToGenerateError(const string& host) return host == "255.255.255.255"; } +void WebViewHost::willRequestResource(WebKit::WebFrame* frame, const WebKit::WebCachedURLRequest& request) +{ + if (m_shell->shouldDumpResourceRequestCallbacks()) { + printFrameDescription(frame); + WebElement element = request.initiatorElement(); + if (!element.isNull()) { + printf(" - element with "); + if (element.hasAttribute("id")) + printf("id '%s'", element.getAttribute("id").utf8().data()); + else + printf("no id"); + } else + printf(" - %s", request.initiatorName().utf8().data()); + printf(" requested '%s'\n", URLDescription(request.urlRequest().url()).c_str()); + } +} + void WebViewHost::willSendRequest(WebFrame* frame, unsigned identifier, WebURLRequest& request, const WebURLResponse& redirectResponse) { // Need to use GURL for host() and SchemeIs() @@ -1605,7 +1623,8 @@ void WebViewHost::updateForCommittedLoad(WebFrame* frame, bool isNewNavigation) { // Code duplicated from RenderView::DidCommitLoadForFrame. TestShellExtraData* extraData = static_cast<TestShellExtraData*>(frame->dataSource()->extraData()); - bool nonBlankPageAfterReset = m_pageId == -1 && strcmp(frame->dataSource()->request().url().spec().data(), "about:blank"); + const WebURL& url = frame->dataSource()->request().url(); + bool nonBlankPageAfterReset = m_pageId == -1 && !url.isEmpty() && strcmp(url.spec().data(), "about:blank"); if (isNewNavigation || nonBlankPageAfterReset) { // New navigation. diff --git a/Tools/DumpRenderTree/chromium/WebViewHost.h b/Tools/DumpRenderTree/chromium/WebViewHost.h index eb41d54a4..97906eb26 100644 --- a/Tools/DumpRenderTree/chromium/WebViewHost.h +++ b/Tools/DumpRenderTree/chromium/WebViewHost.h @@ -260,6 +260,7 @@ class WebViewHost : public WebKit::WebViewClient, public WebKit::WebFrameClient, virtual void didChangeLocationWithinPage(WebKit::WebFrame*); virtual void assignIdentifierToRequest(WebKit::WebFrame*, unsigned identifier, const WebKit::WebURLRequest&); virtual void removeIdentifierForRequest(unsigned identifier); + virtual void willRequestResource(WebKit::WebFrame*, const WebKit::WebCachedURLRequest&); virtual void willSendRequest(WebKit::WebFrame*, unsigned identifier, WebKit::WebURLRequest&, const WebKit::WebURLResponse&); virtual void didReceiveResponse(WebKit::WebFrame*, unsigned identifier, const WebKit::WebURLResponse&); virtual void didFinishResourceLoad(WebKit::WebFrame*, unsigned identifier); diff --git a/Tools/DumpRenderTree/mac/DumpRenderTree.mm b/Tools/DumpRenderTree/mac/DumpRenderTree.mm index 908a231b9..cbcc09562 100644 --- a/Tools/DumpRenderTree/mac/DumpRenderTree.mm +++ b/Tools/DumpRenderTree/mac/DumpRenderTree.mm @@ -87,7 +87,6 @@ #import <WebKit/WebTypesInternal.h> #import <WebKit/WebViewPrivate.h> #import <getopt.h> -#import <objc/objc-runtime.h> #import <wtf/Assertions.h> #import <wtf/FastMalloc.h> #import <wtf/RetainPtr.h> diff --git a/Tools/DumpRenderTree/mac/ObjCPlugin.m b/Tools/DumpRenderTree/mac/ObjCPlugin.m index e1aa12577..ffd9968f9 100644 --- a/Tools/DumpRenderTree/mac/ObjCPlugin.m +++ b/Tools/DumpRenderTree/mac/ObjCPlugin.m @@ -28,7 +28,7 @@ #import "ObjCPlugin.h" #import <WebKit/WebKit.h> -#import <objc/objc-runtime.h> +#import <objc/runtime.h> // === NSObject category to expose almost everything to JavaScript === diff --git a/Tools/DumpRenderTree/qt/DumpRenderTreeMain.cpp b/Tools/DumpRenderTree/qt/DumpRenderTreeMain.cpp index 70b5d14e6..5026d3ca4 100644 --- a/Tools/DumpRenderTree/qt/DumpRenderTreeMain.cpp +++ b/Tools/DumpRenderTree/qt/DumpRenderTreeMain.cpp @@ -35,10 +35,11 @@ #include <qdir.h> #include <qfont.h> #include <qstringlist.h> +#include <qstylefactory.h> #include <qtimer.h> #include <qurl.h> #include <qwebdatabase.h> -#include <qwindowsstyle.h> + #include <wtf/AlwaysInline.h> #include <wtf/ExportMacros.h> @@ -116,7 +117,7 @@ int main(int argc, char* argv[]) WebKit::QtTestSupport::initializeTestFonts(); - QApplication::setStyle(new QWindowsStyle); + QApplication::setStyle(QStyleFactory::create(QLatin1String("windows"))); QApplication::setDesktopSettingsAware(false); QApplication app(argc, argv); diff --git a/Tools/GNUmakefile.am b/Tools/GNUmakefile.am index 6058be8ec..80ab04c2b 100644 --- a/Tools/GNUmakefile.am +++ b/Tools/GNUmakefile.am @@ -22,7 +22,8 @@ Programs_GtkLauncher_CFLAGS = \ -fno-strict-aliasing \ $(global_cflags) \ $(GTK_CFLAGS) \ - $(LIBSOUP_CFLAGS) + $(LIBSOUP_CFLAGS) \ + $(GSTREAMER_CFLAGS) Programs_GtkLauncher_LDADD = \ libwebkitgtk-@WEBKITGTK_API_MAJOR_VERSION@.@WEBKITGTK_API_MINOR_VERSION@.la \ @@ -30,7 +31,8 @@ Programs_GtkLauncher_LDADD = \ $(GTK_LIBS) \ $(GLIB_LIBS) \ $(LIBSOUP_LIBS) \ - $(WINMM_LIBS) + $(WINMM_LIBS) \ + $(GSTREAMER_LIBS) Programs_GtkLauncher_LDFLAGS = \ -no-fast-install \ diff --git a/Tools/GtkLauncher/main.c b/Tools/GtkLauncher/main.c index 942a20b0f..7470e1714 100644 --- a/Tools/GtkLauncher/main.c +++ b/Tools/GtkLauncher/main.c @@ -27,6 +27,7 @@ #include "LauncherInspectorWindow.h" #include <errno.h> +#include <gst/gst.h> #include <gtk/gtk.h> #include <stdlib.h> #include <string.h> @@ -483,10 +484,12 @@ int main(int argc, char* argv[]) }; gtk_init(&argc, &argv); + gst_init(&argc, &argv); GOptionContext *context = g_option_context_new(0); g_option_context_add_main_entries(context, commandLineOptions, 0); g_option_context_add_group(context, gtk_get_option_group(TRUE)); + g_option_context_add_group(context, gst_init_get_option_group()); webkitSettings = webkit_web_settings_new(); g_object_set(webkitSettings, "enable-developer-extras", TRUE, NULL); diff --git a/Tools/MiniBrowser/efl/main.c b/Tools/MiniBrowser/efl/main.c index 768e9ca33..ac38b7ec5 100644 --- a/Tools/MiniBrowser/efl/main.c +++ b/Tools/MiniBrowser/efl/main.c @@ -41,6 +41,7 @@ static Eina_List *windows = NULL; static char *evas_engine_name = NULL; static Eina_Bool encoding_detector_enabled = EINA_FALSE; static Eina_Bool frame_flattening_enabled = EINA_FALSE; +static Eina_Bool local_storage_enabled = EINA_TRUE; static int window_width = 800; static int window_height = 600; /* Default value of device_pixel_ratio is '0' so that we don't set custom device @@ -78,9 +79,9 @@ static const Ecore_Getopt options = { "MiniBrowser", "%prog [options] [url]", "0.0.1", - "(C)2012 Samsung Electronics\n", + "(C)2012 Samsung Electronics\n (C)2012 Intel Corporation\n", "", - "Test Web Browser using the Enlightenment Foundation Libraries of WebKit2", + "Test Web Browser using the Enlightenment Foundation Libraries (EFL) port of WebKit2", EINA_TRUE, { ECORE_GETOPT_STORE_STR ('e', "engine", "ecore-evas engine to use."), @@ -95,6 +96,8 @@ static const Ecore_Getopt options = { ('c', "encoding-detector", "enable/disable encoding detector", EINA_FALSE), ECORE_GETOPT_STORE_DEF_BOOL ('f', "flattening", "frame flattening.", EINA_FALSE), + ECORE_GETOPT_STORE_DEF_BOOL + ('l', "local-storage", "HTML5 local storage support (enabled by default).", EINA_TRUE), ECORE_GETOPT_VERSION ('V', "version"), ECORE_GETOPT_COPYRIGHT @@ -1063,6 +1066,8 @@ static Browser_Window *window_create(const char *url, int width, int height) ewk_settings_file_access_from_file_urls_allowed_set(settings, EINA_TRUE); ewk_settings_encoding_detector_enabled_set(settings, encoding_detector_enabled); ewk_settings_frame_flattening_enabled_set(settings, frame_flattening_enabled); + ewk_settings_local_storage_enabled_set(settings, local_storage_enabled); + info("HTML5 local storage is %s for this view.\n", local_storage_enabled ? "enabled" : "disabled"); ewk_settings_developer_extras_enabled_set(settings, EINA_TRUE); ewk_settings_preferred_minimum_contents_width_set(settings, 0); @@ -1139,6 +1144,7 @@ elm_main(int argc, char *argv[]) ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_BOOL(encoding_detector_enabled), ECORE_GETOPT_VALUE_BOOL(frame_flattening_enabled), + ECORE_GETOPT_VALUE_BOOL(local_storage_enabled), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_BOOL(quitOption), diff --git a/Tools/QtTestBrowser/qttestbrowser.cpp b/Tools/QtTestBrowser/qttestbrowser.cpp index fcd13a204..c5b6ef0ce 100644 --- a/Tools/QtTestBrowser/qttestbrowser.cpp +++ b/Tools/QtTestBrowser/qttestbrowser.cpp @@ -88,7 +88,7 @@ void LauncherApplication::applyDefaultSettings() } LauncherApplication::LauncherApplication(int& argc, char** argv) - : QApplication(argc, argv, QApplication::GuiServer) + : QApplication(argc, argv) , m_isRobotized(false) , m_robotTimeoutSeconds(0) , m_robotExtraTimeSeconds(0) diff --git a/Tools/Scripts/webkitpy/common/checkout/changelog.py b/Tools/Scripts/webkitpy/common/checkout/changelog.py index ae7b71fc0..c5cf42c79 100644 --- a/Tools/Scripts/webkitpy/common/checkout/changelog.py +++ b/Tools/Scripts/webkitpy/common/checkout/changelog.py @@ -30,13 +30,15 @@ import codecs import fileinput # inplace file editing for set_reviewer_in_changelog +import logging import re import textwrap from webkitpy.common.config.committers import CommitterList from webkitpy.common.config.committers import Account import webkitpy.common.config.urls as config_urls -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) # FIXME: parse_bug_id_from_changelog should not be a free function. @@ -162,7 +164,7 @@ class ChangeLogEntry(object): def _parse_entry(self): match = re.match(self.date_line_regexp, self._contents, re.MULTILINE) if not match: - log("WARNING: Creating invalid ChangeLogEntry:\n%s" % self._contents) + _log.warning("Creating invalid ChangeLogEntry:\n%s" % self._contents) # FIXME: group("name") does not seem to be Unicode? Probably due to self._contents not being unicode. self._author_text = match.group("authors") if match else None diff --git a/Tools/Scripts/webkitpy/common/checkout/checkout.py b/Tools/Scripts/webkitpy/common/checkout/checkout.py index 8f450249c..fb686f4d6 100644 --- a/Tools/Scripts/webkitpy/common/checkout/checkout.py +++ b/Tools/Scripts/webkitpy/common/checkout/checkout.py @@ -35,7 +35,6 @@ from webkitpy.common.checkout.scm import CommitMessage from webkitpy.common.checkout.deps import DEPS from webkitpy.common.memoized import memoized from webkitpy.common.system.executive import ScriptError -from webkitpy.common.system.deprecated_logging import log # This class represents the WebKit-specific parts of the checkout (like ChangeLogs). diff --git a/Tools/Scripts/webkitpy/common/checkout/checkout_unittest.py b/Tools/Scripts/webkitpy/common/checkout/checkout_unittest.py index e9c2cddda..a3b47c95e 100644 --- a/Tools/Scripts/webkitpy/common/checkout/checkout_unittest.py +++ b/Tools/Scripts/webkitpy/common/checkout/checkout_unittest.py @@ -259,5 +259,5 @@ class CheckoutTest(unittest.TestCase): mock_patch = Mock() mock_patch.contents = lambda: "foo" mock_patch.reviewer = lambda: None - expected_stderr = "MOCK run_command: ['svn-apply', '--force'], cwd=/mock-checkout, input=foo\n" - OutputCapture().assert_outputs(self, checkout.apply_patch, [mock_patch], expected_stderr=expected_stderr) + expected_logs = "MOCK run_command: ['svn-apply', '--force'], cwd=/mock-checkout, input=foo\n" + OutputCapture().assert_outputs(self, checkout.apply_patch, [mock_patch], expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/common/checkout/deps_mock.py b/Tools/Scripts/webkitpy/common/checkout/deps_mock.py index cb57e8b28..423debae0 100644 --- a/Tools/Scripts/webkitpy/common/checkout/deps_mock.py +++ b/Tools/Scripts/webkitpy/common/checkout/deps_mock.py @@ -26,8 +26,9 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging -from webkitpy.common.system.deprecated_logging import log +_log = logging.getLogger(__name__) class MockDEPS(object): @@ -35,4 +36,4 @@ class MockDEPS(object): return 6564 def write_variable(self, name, value): - log("MOCK: MockDEPS.write_variable(%s, %s)" % (name, value)) + _log.info("MOCK: MockDEPS.write_variable(%s, %s)" % (name, value)) diff --git a/Tools/Scripts/webkitpy/common/checkout/scm/detection.py b/Tools/Scripts/webkitpy/common/checkout/scm/detection.py index 44bc9265d..e635b4075 100644 --- a/Tools/Scripts/webkitpy/common/checkout/scm/detection.py +++ b/Tools/Scripts/webkitpy/common/checkout/scm/detection.py @@ -27,14 +27,16 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.common.system.filesystem import FileSystem from webkitpy.common.system.executive import Executive -from webkitpy.common.system.deprecated_logging import log - from .svn import SVN from .git import Git +_log = logging.getLogger(__name__) + class SCMDetector(object): def __init__(self, filesystem, executive): @@ -55,7 +57,7 @@ class SCMDetector(object): script_directory = self._filesystem.dirname(self._filesystem.path_to_module(self.__module__)) scm_system = self.detect_scm_system(script_directory, patch_directories) if scm_system: - log("The current directory (%s) is not a WebKit checkout, using %s" % (cwd, scm_system.checkout_root)) + _log.info("The current directory (%s) is not a WebKit checkout, using %s" % (cwd, scm_system.checkout_root)) else: raise Exception("FATAL: Failed to determine the SCM system for either %s or %s" % (cwd, script_directory)) return scm_system diff --git a/Tools/Scripts/webkitpy/common/checkout/scm/detection_unittest.py b/Tools/Scripts/webkitpy/common/checkout/scm/detection_unittest.py index ecd91259f..1d7484826 100644 --- a/Tools/Scripts/webkitpy/common/checkout/scm/detection_unittest.py +++ b/Tools/Scripts/webkitpy/common/checkout/scm/detection_unittest.py @@ -42,7 +42,7 @@ class SCMDetectorTest(unittest.TestCase): executive = MockExecutive(should_log=True) detector = SCMDetector(filesystem, executive) - expected_stderr = "MOCK run_command: ['svn', 'info'], cwd=/\nMOCK run_command: ['git', 'rev-parse', '--is-inside-work-tree'], cwd=/\n" - scm = OutputCapture().assert_outputs(self, detector.detect_scm_system, ["/"], expected_stderr=expected_stderr) + expected_logs = "MOCK run_command: ['svn', 'info'], cwd=/\nMOCK run_command: ['git', 'rev-parse', '--is-inside-work-tree'], cwd=/\n" + scm = OutputCapture().assert_outputs(self, detector.detect_scm_system, ["/"], expected_logs=expected_logs) self.assertEqual(scm, None) # FIXME: This should make a synthetic tree and test SVN and Git detection in that tree. diff --git a/Tools/Scripts/webkitpy/common/checkout/scm/git.py b/Tools/Scripts/webkitpy/common/checkout/scm/git.py index f68823871..6313256d8 100644 --- a/Tools/Scripts/webkitpy/common/checkout/scm/git.py +++ b/Tools/Scripts/webkitpy/common/checkout/scm/git.py @@ -32,14 +32,12 @@ import os import re from webkitpy.common.memoized import memoized -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.system.executive import Executive, ScriptError from .commitmessage import CommitMessage from .scm import AuthenticationError, SCM, commit_error_handler from .svn import SVN, SVNRepository - _log = logging.getLogger(__name__) @@ -96,7 +94,7 @@ class Git(SCM, SVNRepository): return webkit_dev_thread_url = "https://lists.webkit.org/pipermail/webkit-dev/2010-December/015287.html" - log("Warning: This machine is 64-bit, but the git binary (%s) does not support 64-bit.\nInstall a 64-bit git for better performance, see:\n%s\n" % (git_path, webkit_dev_thread_url)) + _log.warning("This machine is 64-bit, but the git binary (%s) does not support 64-bit.\nInstall a 64-bit git for better performance, see:\n%s\n" % (git_path, webkit_dev_thread_url)) def _run_git(self, command_args, **kwargs): full_command_args = [self.executable_name] + command_args @@ -403,7 +401,7 @@ class Git(SCM, SVNRepository): self._run_git(['commit', '-m', message]) output = self.push_local_commits_to_server(username=username, password=password) except Exception, e: - log("COMMIT FAILED: " + str(e)) + _log.warning("COMMIT FAILED: " + str(e)) output = "Commit failed." commit_succeeded = False finally: diff --git a/Tools/Scripts/webkitpy/common/checkout/scm/scm.py b/Tools/Scripts/webkitpy/common/checkout/scm/scm.py index ee63b7130..7d6e1804d 100644 --- a/Tools/Scripts/webkitpy/common/checkout/scm/scm.py +++ b/Tools/Scripts/webkitpy/common/checkout/scm/scm.py @@ -31,11 +31,13 @@ import logging import re +import sys -from webkitpy.common.system.deprecated_logging import error, log from webkitpy.common.system.executive import Executive, ScriptError from webkitpy.common.system.filesystem import FileSystem +_log = logging.getLogger(__name__) + class CheckoutNeedsUpdate(ScriptError): def __init__(self, script_args, exit_code, output, cwd): @@ -94,7 +96,7 @@ class SCM: if not force_clean: print self.run(self.status_command(), error_handler=Executive.ignore_error, cwd=self.checkout_root) raise ScriptError(message="Working directory has modifications, pass --force-clean or --no-clean to continue.") - log("Cleaning working directory") + _log.info("Cleaning working directory") self.clean_working_directory() def ensure_no_local_commits(self, force): @@ -104,7 +106,8 @@ class SCM: if not len(commits): return if not force: - error("Working directory has local commits, pass --force-clean to continue.") + _log.error("Working directory has local commits, pass --force-clean to continue.") + sys.exit(1) self.discard_local_commits() def run_status_and_extract_filenames(self, status_command, status_regexp): @@ -238,7 +241,8 @@ class SCM: SCM._subclass_must_implement() def commit_locally_with_message(self, message): - error("Your source control manager does not support local commits.") + _log.error("Your source control manager does not support local commits.") + sys.exit(1) def discard_local_commits(self): pass diff --git a/Tools/Scripts/webkitpy/common/checkout/scm/svn.py b/Tools/Scripts/webkitpy/common/checkout/scm/svn.py index 112be057d..1323b702c 100644 --- a/Tools/Scripts/webkitpy/common/checkout/scm/svn.py +++ b/Tools/Scripts/webkitpy/common/checkout/scm/svn.py @@ -35,12 +35,10 @@ import sys import tempfile from webkitpy.common.memoized import memoized -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.system.executive import Executive, ScriptError from .scm import AuthenticationError, SCM, commit_error_handler - _log = logging.getLogger(__name__) @@ -311,8 +309,8 @@ class SVN(SCM, SVNRepository): def apply_reverse_diff(self, revision): # '-c -revision' applies the inverse diff of 'revision' svn_merge_args = ['merge', '--non-interactive', '-c', '-%s' % revision, self._repository_url()] - log("WARNING: svn merge has been known to take more than 10 minutes to complete. It is recommended you use git for rollouts.") - log("Running 'svn %s'" % " ".join(svn_merge_args)) + _log.warning("svn merge has been known to take more than 10 minutes to complete. It is recommended you use git for rollouts.") + _log.debug("Running 'svn %s'" % " ".join(svn_merge_args)) # FIXME: Should this use cwd=self.checkout_root? self._run_svn(svn_merge_args) diff --git a/Tools/Scripts/webkitpy/common/config/committers.py b/Tools/Scripts/webkitpy/common/config/committers.py index 92a6a1ead..e49eebf52 100644 --- a/Tools/Scripts/webkitpy/common/config/committers.py +++ b/Tools/Scripts/webkitpy/common/config/committers.py @@ -201,6 +201,7 @@ committers_unable_to_review = [ Committer("Andrei Popescu", "andreip@google.com", "andreip"), Committer("Andrew Wellington", ["andrew@webkit.org", "proton@wiretapped.net"], "proton"), Committer("Andrew Scherkus", "scherkus@chromium.org", "scherkus"), + Committer("Andrey Adaykin", "aandrey@chromium.org", "aandrey"), Committer("Andrey Kosyakov", "caseq@chromium.org", "caseq"), Committer("Andras Becsi", ["abecsi@webkit.org", "andras.becsi@digia.com"], "bbandix"), Committer("Andy Wingo", "wingo@igalia.com", "wingo"), @@ -229,6 +230,7 @@ committers_unable_to_review = [ Committer("Chris Guillory", ["ctguil@chromium.org", "chris.guillory@google.com"], "ctguil"), Committer("Chris Petersen", "cpetersen@apple.com", "cpetersen"), Committer("Christian Dywan", ["christian@twotoasts.de", "christian@webkit.org", "christian@lanedo.com"]), + Committer("Christophe Dumez", ["christophe.dumez@intel.com", "dchris@gmail.com"], "chris-qBT"), Committer("Collin Jackson", "collinj@webkit.org", "collinjackson"), Committer("Cris Neckar", "cdn@chromium.org", "cneckar"), Committer("Dan Winship", "danw@gnome.org", "danw"), @@ -325,6 +327,7 @@ committers_unable_to_review = [ Committer("Leandro Gracia Gil", "leandrogracia@chromium.org", "leandrogracia"), Committer("Leandro Pereira", ["leandro@profusion.mobi", "leandro@webkit.org"], "acidx"), Committer("Leo Yang", ["leoyang@rim.com", "leoyang@webkit.org", "leoyang.webkit@gmail.com"], "leoyang"), + Committer("Li Yin", ["li.yin@intel.com"], "liyin"), Committer("Lucas De Marchi", ["demarchi@webkit.org", "lucas.demarchi@profusion.mobi"], "demarchi"), Committer("Lucas Forschler", ["lforschler@apple.com"], "lforschler"), Committer("Luciano Wolf", "luciano.wolf@openbossa.org", "luck"), @@ -336,6 +339,7 @@ committers_unable_to_review = [ Committer("Mark Lam", "mark.lam@apple.com", "mlam"), Committer("Mary Wu", ["mary.wu@torchmobile.com.cn", "wwendy2007@gmail.com"], "marywu"), Committer("Matt Delaney", "mdelaney@apple.com"), + Committer("Matt Falkenhagen", "falken@chromium.org", "falken"), Committer("Matt Lilek", ["mlilek@apple.com", "webkit@mattlilek.com", "pewtermoose@webkit.org"], "pewtermoose"), Committer("Matt Perry", "mpcomplete@chromium.org"), Committer("Maxime Britto", ["maxime.britto@gmail.com", "britto@apple.com"]), @@ -355,6 +359,7 @@ committers_unable_to_review = [ Committer("Nat Duca", ["nduca@chromium.org", "nduca@google.com"], "nduca"), Committer("Nayan Kumar K", ["nayankk@motorola.com", "nayankk@gmail.com"], "xc0ffee"), Committer("Nico Weber", ["thakis@chromium.org", "thakis@google.com"], "thakis"), + Committer("Nima Ghanavatian", ["nghanavatian@rim.com", "nima.ghanavatian@gmail.com"], "nghanavatian"), Committer("Noel Gordon", ["noel.gordon@gmail.com", "noel@chromium.org", "noel@google.com"], "noel"), Committer("Pam Greene", "pam@chromium.org", "pamg"), Committer("Patrick Gansterer", ["paroga@paroga.com", "paroga@webkit.org"], "paroga"), @@ -392,6 +397,7 @@ committers_unable_to_review = [ Committer("Takashi Sakamoto", "tasak@google.com", "tasak"), Committer("Takashi Toyoshima", "toyoshim@chromium.org", "toyoshim"), Committer("Terry Anderson", "tdanderson@chromium.org", "tdanderson"), + Committer("Thiago Marcos P. Santos", ["tmpsantos@gmail.com", "thiago.santos@intel.com"], "tmpsantos"), Committer("Thomas Sepez", "tsepez@chromium.org", "tsepez"), Committer("Tom Hudson", ["tomhudson@google.com", "tomhudson@chromium.org"], "tomhudson"), Committer("Tom Zakrajsek", "tomz@codeaurora.org", "tomz"), @@ -406,6 +412,7 @@ committers_unable_to_review = [ Committer("Vincent Scheib", "scheib@chromium.org", "scheib"), Committer("Vineet Chaudhary", "rgf748@motorola.com", "vineetc"), Committer("Vitaly Repeshko", "vitalyr@chromium.org"), + Committer("Vivek Galatage", ["vivekg@webkit.org", "vivek.vg@samsung.com"], "vivekg"), Committer("William Siegrist", "wsiegrist@apple.com", "wms"), Committer("W. James MacLean", "wjmaclean@chromium.org", "seumas"), Committer("Xianzhu Wang", ["wangxianzhu@chromium.org", "phnixwxz@gmail.com", "wangxianzhu@google.com"], "wangxianzhu"), diff --git a/Tools/Scripts/webkitpy/common/net/bugzilla/attachment.py b/Tools/Scripts/webkitpy/common/net/bugzilla/attachment.py index 6e10d65a9..c749a1512 100644 --- a/Tools/Scripts/webkitpy/common/net/bugzilla/attachment.py +++ b/Tools/Scripts/webkitpy/common/net/bugzilla/attachment.py @@ -28,8 +28,11 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.common.memoized import memoized -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class Attachment(object): @@ -102,7 +105,7 @@ class Attachment(object): "%s_by_email" % flag)(email) if committer: return committer - log("Warning, attachment %s on bug %s has invalid %s (%s)" % ( + _log.warning("Warning, attachment %s on bug %s has invalid %s (%s)" % ( self._attachment_dictionary['id'], self._attachment_dictionary['bug_id'], flag, email)) diff --git a/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla.py b/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla.py index 651e1b374..957f04dca 100644 --- a/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla.py +++ b/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla.py @@ -30,6 +30,7 @@ # # WebKit's Python module for interacting with Bugzilla +import logging import mimetypes import re import StringIO @@ -41,13 +42,14 @@ from datetime import datetime # used in timestamp() from .attachment import Attachment from .bug import Bug -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.config import committers import webkitpy.common.config.urls as config_urls from webkitpy.common.net.credentials import Credentials from webkitpy.common.system.user import User from webkitpy.thirdparty.BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, SoupStrainer +_log = logging.getLogger(__name__) + class EditUsersParser(object): def __init__(self): @@ -435,7 +437,7 @@ class Bugzilla(object): def _fetch_bug_page(self, bug_id): bug_url = self.bug_url_for_bug_id(bug_id, xml=True) - log("Fetching: %s" % bug_url) + _log.info("Fetching: %s" % bug_url) return self.browser.open(bug_url) def fetch_bug_dictionary(self, bug_id): @@ -472,7 +474,7 @@ class Bugzilla(object): self.authenticate() attachment_url = self.attachment_url_for_id(attachment_id, 'edit') - log("Fetching: %s" % attachment_url) + _log.info("Fetching: %s" % attachment_url) page = self.browser.open(attachment_url) return self._parse_bug_id_from_attachment_page(page) @@ -503,7 +505,7 @@ class Bugzilla(object): attempts += 1 username, password = credentials.read_credentials() - log("Logging in as %s..." % username) + _log.info("Logging in as %s..." % username) self.browser.open(config_urls.bug_server_url + "index.cgi?GoAheadAndLogIn=1") self.browser.select_form(name="login") @@ -519,7 +521,7 @@ class Bugzilla(object): errorMessage = "Bugzilla login failed: %s" % match.group(1) # raise an exception only if this was the last attempt if attempts < 5: - log(errorMessage) + _log.error(errorMessage) else: raise Exception(errorMessage) else: @@ -532,10 +534,10 @@ class Bugzilla(object): user = self.committers.account_by_email(self.username) mark_for_commit_queue = True if not user: - log("Your Bugzilla login is not listed in committers.py. Uploading with cq? instead of cq+") + _log.warning("Your Bugzilla login is not listed in committers.py. Uploading with cq? instead of cq+") mark_for_landing = False elif not user.can_commit: - log("You're not a committer yet or haven't updated committers.py yet. Uploading with cq? instead of cq+") + _log.warning("You're not a committer yet or haven't updated committers.py yet. Uploading with cq? instead of cq+") mark_for_landing = False if mark_for_landing: @@ -585,14 +587,14 @@ class Bugzilla(object): def add_attachment_to_bug(self, bug_id, file_or_string, description, filename=None, comment_text=None, mimetype=None): self.authenticate() - log('Adding attachment "%s" to %s' % (description, self.bug_url_for_bug_id(bug_id))) + _log.info('Adding attachment "%s" to %s' % (description, self.bug_url_for_bug_id(bug_id))) self.browser.open(self.add_attachment_url(bug_id)) self.browser.select_form(name="entryform") file_object = self._file_object_for_upload(file_or_string) filename = filename or self._filename_for_upload(file_object, bug_id) self._fill_attachment_form(description, file_object, filename=filename, mimetype=mimetype) if comment_text: - log(comment_text) + _log.info(comment_text) self.browser['comment'] = comment_text self.browser.submit() @@ -607,7 +609,7 @@ class Bugzilla(object): mark_for_commit_queue=False, mark_for_landing=False): self.authenticate() - log('Adding patch "%s" to %s' % (description, self.bug_url_for_bug_id(bug_id))) + _log.info('Adding patch "%s" to %s' % (description, self.bug_url_for_bug_id(bug_id))) self.browser.open(self.add_attachment_url(bug_id)) self.browser.select_form(name="entryform") @@ -621,7 +623,7 @@ class Bugzilla(object): is_patch=True, filename=filename) if comment_text: - log(comment_text) + _log.info(comment_text) self.browser['comment'] = comment_text self.browser.submit() @@ -658,7 +660,7 @@ class Bugzilla(object): mark_for_commit_queue=False): self.authenticate() - log('Creating bug with title "%s"' % bug_title) + _log.info('Creating bug with title "%s"' % bug_title) self.browser.open(config_urls.bug_server_url + "enter_bug.cgi?product=WebKit") self.browser.select_form(name="Create") component_items = self.browser.find_control('component').items @@ -694,8 +696,8 @@ class Bugzilla(object): response = self.browser.submit() bug_id = self._check_create_bug_response(response.read()) - log("Bug %s created." % bug_id) - log("%sshow_bug.cgi?id=%s" % (config_urls.bug_server_url, bug_id)) + _log.info("Bug %s created." % bug_id) + _log.info("%sshow_bug.cgi?id=%s" % (config_urls.bug_server_url, bug_id)) return bug_id def _find_select_element_for_flag(self, flag_name): @@ -714,7 +716,7 @@ class Bugzilla(object): comment_text = "Clearing flags on attachment: %s" % attachment_id if additional_comment_text: comment_text += "\n\n%s" % additional_comment_text - log(comment_text) + _log.info(comment_text) self.browser.open(self.attachment_url_for_id(attachment_id, 'edit')) self.browser.select_form(nr=1) @@ -737,7 +739,7 @@ class Bugzilla(object): # FIXME: additional_comment_text seems useless and should be merged into comment-text. if additional_comment_text: comment_text += "\n\n%s" % additional_comment_text - log(comment_text) + _log.info(comment_text) self.browser.open(self.attachment_url_for_id(attachment_id, 'edit')) self.browser.select_form(nr=1) @@ -754,7 +756,7 @@ class Bugzilla(object): def obsolete_attachment(self, attachment_id, comment_text=None): self.authenticate() - log("Obsoleting attachment: %s" % attachment_id) + _log.info("Obsoleting attachment: %s" % attachment_id) self.browser.open(self.attachment_url_for_id(attachment_id, 'edit')) self.browser.select_form(nr=1) self.browser.find_control('isobsolete').items[0].selected = True @@ -762,7 +764,7 @@ class Bugzilla(object): self._find_select_element_for_flag('review').value = ("X",) self._find_select_element_for_flag('commit-queue').value = ("X",) if comment_text: - log(comment_text) + _log.info(comment_text) # Bugzilla has two textareas named 'comment', one is somehow # hidden. We want the first. self.browser.set_value(comment_text, name='comment', nr=0) @@ -771,7 +773,7 @@ class Bugzilla(object): def add_cc_to_bug(self, bug_id, email_address_list): self.authenticate() - log("Adding %s to the CC list for bug %s" % (email_address_list, bug_id)) + _log.info("Adding %s to the CC list for bug %s" % (email_address_list, bug_id)) self.browser.open(self.bug_url_for_bug_id(bug_id)) self.browser.select_form(name="changeform") self.browser["newcc"] = ", ".join(email_address_list) @@ -780,7 +782,7 @@ class Bugzilla(object): def post_comment_to_bug(self, bug_id, comment_text, cc=None): self.authenticate() - log("Adding comment to bug %s" % bug_id) + _log.info("Adding comment to bug %s" % bug_id) self.browser.open(self.bug_url_for_bug_id(bug_id)) self.browser.select_form(name="changeform") self.browser["comment"] = comment_text @@ -791,7 +793,7 @@ class Bugzilla(object): def close_bug_as_fixed(self, bug_id, comment_text=None): self.authenticate() - log("Closing bug %s as fixed" % bug_id) + _log.info("Closing bug %s as fixed" % bug_id) self.browser.open(self.bug_url_for_bug_id(bug_id)) self.browser.select_form(name="changeform") if comment_text: @@ -809,12 +811,12 @@ class Bugzilla(object): if not assignee: assignee = self.username - log("Assigning bug %s to %s" % (bug_id, assignee)) + _log.info("Assigning bug %s to %s" % (bug_id, assignee)) self.browser.open(self.bug_url_for_bug_id(bug_id)) self.browser.select_form(name="changeform") if not self._has_control(self.browser, "assigned_to"): - log("""Failed to assign bug to you (can't find assigned_to) control. + _log.warning("""Failed to assign bug to you (can't find assigned_to) control. Do you have EditBugs privileges at bugs.webkit.org? https://bugs.webkit.org/userprefs.cgi?tab=permissions @@ -823,7 +825,7 @@ for someone to add EditBugs to your bugs.webkit.org account.""") return if comment_text: - log(comment_text) + _log.info(comment_text) self.browser["comment"] = comment_text self.browser["assigned_to"] = assignee self.browser.submit() @@ -831,10 +833,10 @@ for someone to add EditBugs to your bugs.webkit.org account.""") def reopen_bug(self, bug_id, comment_text): self.authenticate() - log("Re-opening bug %s" % bug_id) + _log.info("Re-opening bug %s" % bug_id) # Bugzilla requires a comment when re-opening a bug, so we know it will # never be None. - log(comment_text) + _log.info(comment_text) self.browser.open(self.bug_url_for_bug_id(bug_id)) self.browser.select_form(name="changeform") bug_status = self.browser.find_control("bug_status", type="select") @@ -851,6 +853,6 @@ for someone to add EditBugs to your bugs.webkit.org account.""") else: # FIXME: This logic is slightly backwards. We won't print this # message if the bug is already open with state "UNCONFIRMED". - log("Did not reopen bug %s, it appears to already be open with status %s." % (bug_id, bug_status.value)) + _log.info("Did not reopen bug %s, it appears to already be open with status %s." % (bug_id, bug_status.value)) self.browser['comment'] = comment_text self.browser.submit() diff --git a/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla_mock.py b/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla_mock.py index 71b080ce9..473a9fa6e 100644 --- a/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla_mock.py +++ b/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla_mock.py @@ -27,12 +27,13 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import datetime +import logging from .bug import Bug from .attachment import Attachment from webkitpy.common.config.committers import CommitterList, Reviewer -from webkitpy.common.system.deprecated_logging import log +_log = logging.getLogger(__name__) def _id_to_object_dictionary(*objects): @@ -328,15 +329,15 @@ class MockBugzilla(object): blocked=None, mark_for_review=False, mark_for_commit_queue=False): - log("MOCK create_bug") - log("bug_title: %s" % bug_title) - log("bug_description: %s" % bug_description) + _log.info("MOCK create_bug") + _log.info("bug_title: %s" % bug_title) + _log.info("bug_description: %s" % bug_description) if component: - log("component: %s" % component) + _log.info("component: %s" % component) if cc: - log("cc: %s" % cc) + _log.info("cc: %s" % cc) if blocked: - log("blocked: %s" % blocked) + _log.info("blocked: %s" % blocked) return 60001 def quips(self): @@ -374,11 +375,11 @@ class MockBugzilla(object): return "%s/%s%s" % (self.bug_server_url, attachment_id, action_param) def reassign_bug(self, bug_id, assignee=None, comment_text=None): - log("MOCK reassign_bug: bug_id=%s, assignee=%s" % (bug_id, assignee)) + _log.info("MOCK reassign_bug: bug_id=%s, assignee=%s" % (bug_id, assignee)) if comment_text: - log("-- Begin comment --") - log(comment_text) - log("-- End comment --") + _log.info("-- Begin comment --") + _log.info(comment_text) + _log.info("-- End comment --") def set_flag_on_attachment(self, attachment_id, @@ -386,20 +387,20 @@ class MockBugzilla(object): flag_value, comment_text=None, additional_comment_text=None): - log("MOCK setting flag '%s' to '%s' on attachment '%s' with comment '%s' and additional comment '%s'" % ( - flag_name, flag_value, attachment_id, comment_text, additional_comment_text)) + _log.info("MOCK setting flag '%s' to '%s' on attachment '%s' with comment '%s' and additional comment '%s'" % ( + flag_name, flag_value, attachment_id, comment_text, additional_comment_text)) def post_comment_to_bug(self, bug_id, comment_text, cc=None): - log("MOCK bug comment: bug_id=%s, cc=%s\n--- Begin comment ---\n%s\n--- End comment ---\n" % ( - bug_id, cc, comment_text)) + _log.info("MOCK bug comment: bug_id=%s, cc=%s\n--- Begin comment ---\n%s\n--- End comment ---\n" % ( + bug_id, cc, comment_text)) def add_attachment_to_bug(self, bug_id, file_or_string, description, filename=None, comment_text=None, mimetype=None): - log("MOCK add_attachment_to_bug: bug_id=%s, description=%s filename=%s mimetype=%s" % - (bug_id, description, filename, mimetype)) + _log.info("MOCK add_attachment_to_bug: bug_id=%s, description=%s filename=%s mimetype=%s" % + (bug_id, description, filename, mimetype)) if comment_text: - log("-- Begin comment --") - log(comment_text) - log("-- End comment --") + _log.info("-- Begin comment --") + _log.info(comment_text) + _log.info("-- End comment --") def add_patch_to_bug(self, bug_id, @@ -409,12 +410,12 @@ class MockBugzilla(object): mark_for_review=False, mark_for_commit_queue=False, mark_for_landing=False): - log("MOCK add_patch_to_bug: bug_id=%s, description=%s, mark_for_review=%s, mark_for_commit_queue=%s, mark_for_landing=%s" % - (bug_id, description, mark_for_review, mark_for_commit_queue, mark_for_landing)) + _log.info("MOCK add_patch_to_bug: bug_id=%s, description=%s, mark_for_review=%s, mark_for_commit_queue=%s, mark_for_landing=%s" % + (bug_id, description, mark_for_review, mark_for_commit_queue, mark_for_landing)) if comment_text: - log("-- Begin comment --") - log(comment_text) - log("-- End comment --") + _log.info("-- Begin comment --") + _log.info(comment_text) + _log.info("-- End comment --") def add_cc_to_bug(self, bug_id, ccs): pass @@ -423,7 +424,7 @@ class MockBugzilla(object): pass def reopen_bug(self, bug_id, message): - log("MOCK reopen_bug %s with comment '%s'" % (bug_id, message)) + _log.info("MOCK reopen_bug %s with comment '%s'" % (bug_id, message)) def close_bug_as_fixed(self, bug_id, message): pass diff --git a/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla_unittest.py b/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla_unittest.py index 538d39e85..90e4c83fc 100644 --- a/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla_unittest.py +++ b/Tools/Scripts/webkitpy/common/net/bugzilla/bugzilla_unittest.py @@ -250,8 +250,8 @@ Ignore this bug. Just for testing failure modes of webkit-patch and the commit- bugzilla = Bugzilla() bugzilla.browser = MockBrowser() bugzilla.authenticate = lambda: None - expected_stderr = "Adding ['adam@example.com'] to the CC list for bug 42\n" - OutputCapture().assert_outputs(self, bugzilla.add_cc_to_bug, [42, ["adam@example.com"]], expected_stderr=expected_stderr) + expected_logs = "Adding ['adam@example.com'] to the CC list for bug 42\n" + OutputCapture().assert_outputs(self, bugzilla.add_cc_to_bug, [42, ["adam@example.com"]], expected_logs=expected_logs) def _mock_control_item(self, name): mock_item = Mock() @@ -264,23 +264,23 @@ Ignore this bug. Just for testing failure modes of webkit-patch and the commit- mock_control.value = [item_names[selected_index]] if item_names else None return lambda name, type: mock_control - def _assert_reopen(self, item_names=None, selected_index=None, extra_stderr=None): + def _assert_reopen(self, item_names=None, selected_index=None, extra_logs=None): bugzilla = Bugzilla() bugzilla.browser = MockBrowser() bugzilla.authenticate = lambda: None mock_find_control = self._mock_find_control(item_names, selected_index) bugzilla.browser.find_control = mock_find_control - expected_stderr = "Re-opening bug 42\n['comment']\n" - if extra_stderr: - expected_stderr += extra_stderr - OutputCapture().assert_outputs(self, bugzilla.reopen_bug, [42, ["comment"]], expected_stderr=expected_stderr) + expected_logs = "Re-opening bug 42\n['comment']\n" + if extra_logs: + expected_logs += extra_logs + OutputCapture().assert_outputs(self, bugzilla.reopen_bug, [42, ["comment"]], expected_logs=expected_logs) def test_reopen_bug(self): self._assert_reopen(item_names=["REOPENED", "RESOLVED", "CLOSED"], selected_index=1) self._assert_reopen(item_names=["UNCONFIRMED", "RESOLVED", "CLOSED"], selected_index=1) - extra_stderr = "Did not reopen bug 42, it appears to already be open with status ['NEW'].\n" - self._assert_reopen(item_names=["NEW", "RESOLVED"], selected_index=0, extra_stderr=extra_stderr) + extra_logs = "Did not reopen bug 42, it appears to already be open with status ['NEW'].\n" + self._assert_reopen(item_names=["NEW", "RESOLVED"], selected_index=0, extra_logs=extra_logs) def test_file_object_for_upload(self): bugzilla = Bugzilla() diff --git a/Tools/Scripts/webkitpy/common/net/buildbot/buildbot_mock.py b/Tools/Scripts/webkitpy/common/net/buildbot/buildbot_mock.py index f5b6042b3..d20bdb75c 100644 --- a/Tools/Scripts/webkitpy/common/net/buildbot/buildbot_mock.py +++ b/Tools/Scripts/webkitpy/common/net/buildbot/buildbot_mock.py @@ -26,7 +26,9 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -from webkitpy.common.system.deprecated_logging import log +import logging + +_log = logging.getLogger(__name__) class MockBuild(object): @@ -55,7 +57,7 @@ class MockBuilder(object): return self.accumulated_results_url() def force_build(self, username, comments): - log("MOCK: force_build: name=%s, username=%s, comments=%s" % ( + _log.info("MOCK: force_build: name=%s, username=%s, comments=%s" % ( self._name, username, comments)) diff --git a/Tools/Scripts/webkitpy/common/net/credentials.py b/Tools/Scripts/webkitpy/common/net/credentials.py index 21aeaeafe..7038b7e3c 100644 --- a/Tools/Scripts/webkitpy/common/net/credentials.py +++ b/Tools/Scripts/webkitpy/common/net/credentials.py @@ -29,6 +29,7 @@ # # Python module for reading stored web credentials from the OS. +import logging import os import platform import re @@ -36,7 +37,6 @@ import re from webkitpy.common.checkout.scm import Git from webkitpy.common.system.executive import Executive, ScriptError from webkitpy.common.system.user import User -from webkitpy.common.system.deprecated_logging import log try: # Use keyring, a cross platform keyring interface, as a fallback: @@ -45,6 +45,8 @@ try: except ImportError: keyring = None +_log = logging.getLogger(__name__) + class Credentials(object): _environ_prefix = "webkit_bugzilla_" @@ -98,15 +100,15 @@ class Credentials(object): if username: security_command += ["-a", username] - log("Reading Keychain for %s account and password. " - "Click \"Allow\" to continue..." % self.host) + _log.info("Reading Keychain for %s account and password. " + "Click \"Allow\" to continue..." % self.host) try: return self.executive.run_command(security_command) except ScriptError: # Failed to either find a keychain entry or somekind of OS-related # error occured (for instance, couldn't find the /usr/sbin/security # command). - log("Could not find a keychain entry for %s." % self.host) + _log.error("Could not find a keychain entry for %s." % self.host) return None def _credentials_from_keychain(self, username=None): diff --git a/Tools/Scripts/webkitpy/common/net/credentials_unittest.py b/Tools/Scripts/webkitpy/common/net/credentials_unittest.py index 15682f3b8..3659d69d1 100644 --- a/Tools/Scripts/webkitpy/common/net/credentials_unittest.py +++ b/Tools/Scripts/webkitpy/common/net/credentials_unittest.py @@ -116,8 +116,8 @@ password: "SECRETSAUCE" executive_mock = Mock() credentials = MockedCredentials("example.com", executive=executive_mock) - expected_stderr = "Reading Keychain for example.com account and password. Click \"Allow\" to continue...\n" - OutputCapture().assert_outputs(self, credentials._run_security_tool, [username], expected_stderr=expected_stderr) + expected_logs = "Reading Keychain for example.com account and password. Click \"Allow\" to continue...\n" + OutputCapture().assert_outputs(self, credentials._run_security_tool, [username], expected_logs=expected_logs) security_args = ["/usr/bin/security", "find-internet-password", "-g", "-s", "example.com"] if username: diff --git a/Tools/Scripts/webkitpy/common/net/irc/irc_mock.py b/Tools/Scripts/webkitpy/common/net/irc/irc_mock.py index 734be0670..b2ae0715a 100644 --- a/Tools/Scripts/webkitpy/common/net/irc/irc_mock.py +++ b/Tools/Scripts/webkitpy/common/net/irc/irc_mock.py @@ -26,12 +26,14 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -from webkitpy.common.system.deprecated_logging import log +import logging + +_log = logging.getLogger(__name__) class MockIRC(object): def post(self, message): - log("MOCK: irc.post: %s" % message) + _log.info("MOCK: irc.post: %s" % message) def disconnect(self): - log("MOCK: irc.disconnect") + _log.info("MOCK: irc.disconnect") diff --git a/Tools/Scripts/webkitpy/common/net/irc/ircproxy.py b/Tools/Scripts/webkitpy/common/net/irc/ircproxy.py index 13348b4af..521f6f761 100644 --- a/Tools/Scripts/webkitpy/common/net/irc/ircproxy.py +++ b/Tools/Scripts/webkitpy/common/net/irc/ircproxy.py @@ -26,11 +26,13 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging import threading from webkitpy.common.net.irc.ircbot import IRCBot from webkitpy.common.thread.threadedmessagequeue import ThreadedMessageQueue -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class _IRCThread(threading.Thread): @@ -48,7 +50,7 @@ class _IRCThread(threading.Thread): class IRCProxy(object): def __init__(self, irc_delegate, irc_bot=IRCBot): - log("Connecting to IRC") + _log.info("Connecting to IRC") self._message_queue = ThreadedMessageQueue() self._child_thread = _IRCThread(self._message_queue, irc_delegate, irc_bot) self._child_thread.start() @@ -57,6 +59,6 @@ class IRCProxy(object): self._message_queue.post(message) def disconnect(self): - log("Disconnecting from IRC...") + _log.info("Disconnecting from IRC...") self._message_queue.stop() self._child_thread.join() diff --git a/Tools/Scripts/webkitpy/common/net/irc/ircproxy_unittest.py b/Tools/Scripts/webkitpy/common/net/irc/ircproxy_unittest.py index b44ce400b..bce9d855d 100644 --- a/Tools/Scripts/webkitpy/common/net/irc/ircproxy_unittest.py +++ b/Tools/Scripts/webkitpy/common/net/irc/ircproxy_unittest.py @@ -39,5 +39,5 @@ class IRCProxyTest(unittest.TestCase): proxy.post("hello") proxy.disconnect() - expected_stderr = "Connecting to IRC\nDisconnecting from IRC...\n" - OutputCapture().assert_outputs(self, fun, expected_stderr=expected_stderr) + expected_logs = "Connecting to IRC\nDisconnecting from IRC...\n" + OutputCapture().assert_outputs(self, fun, expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/common/net/layouttestresults.py b/Tools/Scripts/webkitpy/common/net/layouttestresults.py index f0d807edc..74322c757 100644 --- a/Tools/Scripts/webkitpy/common/net/layouttestresults.py +++ b/Tools/Scripts/webkitpy/common/net/layouttestresults.py @@ -29,12 +29,15 @@ # A module for parsing results.html files generated by old-run-webkit-tests # This class is one big hack and only needs to exist until we transition to new-run-webkit-tests. +import logging + from webkitpy.common.net.resultsjsonparser import ResultsJSONParser -from webkitpy.common.system.deprecated_logging import log from webkitpy.thirdparty.BeautifulSoup import BeautifulSoup, SoupStrainer from webkitpy.layout_tests.models import test_results from webkitpy.layout_tests.models import test_failures +_log = logging.getLogger(__name__) + # FIXME: This should be unified with all the layout test results code in the layout_tests package # This doesn't belong in common.net, but we don't have a better place for it yet. @@ -78,7 +81,7 @@ class ORWTResultsHTMLParser(object): elif anchor_text in ["expected", "actual", "diff", "pretty diff"]: failures.add(test_failures.FailureTextMismatch()) else: - log("Unhandled link text in results.html parsing: %s. Please file a bug against webkitpy." % anchor_text) + _log.warning("Unhandled link text in results.html parsing: %s. Please file a bug against webkitpy." % anchor_text) # FIXME: Its possible the row contained no links due to ORWT brokeness. # We should probably assume some type of failure anyway. return failures diff --git a/Tools/Scripts/webkitpy/common/net/layouttestresults_unittest.py b/Tools/Scripts/webkitpy/common/net/layouttestresults_unittest.py index 462a88c66..4131bdf85 100644 --- a/Tools/Scripts/webkitpy/common/net/layouttestresults_unittest.py +++ b/Tools/Scripts/webkitpy/common/net/layouttestresults_unittest.py @@ -122,8 +122,8 @@ class ORWTResultsHTMLParserTest(unittest.TestCase): self.assertEqual(type(sorted(failures)[0]), test_failures.FailureImageHashMismatch) row = BeautifulSoup("<tr><td><a>test.hml</a><a>foo</a></td></tr>") - expected_stderr = "Unhandled link text in results.html parsing: foo. Please file a bug against webkitpy.\n" - OutputCapture().assert_outputs(self, ORWTResultsHTMLParser._failures_from_fail_row, [row], expected_stderr=expected_stderr) + expected_logs = "Unhandled link text in results.html parsing: foo. Please file a bug against webkitpy.\n" + OutputCapture().assert_outputs(self, ORWTResultsHTMLParser._failures_from_fail_row, [row], expected_logs=expected_logs) class LayoutTestResultsTest(unittest.TestCase): diff --git a/Tools/Scripts/webkitpy/common/net/networktransaction.py b/Tools/Scripts/webkitpy/common/net/networktransaction.py index 03b143267..60acaaba3 100644 --- a/Tools/Scripts/webkitpy/common/net/networktransaction.py +++ b/Tools/Scripts/webkitpy/common/net/networktransaction.py @@ -30,9 +30,6 @@ import logging import time import urllib2 -from webkitpy.common.system.deprecated_logging import log - - _log = logging.getLogger(__name__) diff --git a/Tools/Scripts/webkitpy/common/net/resultsjsonparser.py b/Tools/Scripts/webkitpy/common/net/resultsjsonparser.py index 42ce56a17..1a2a70f4b 100644 --- a/Tools/Scripts/webkitpy/common/net/resultsjsonparser.py +++ b/Tools/Scripts/webkitpy/common/net/resultsjsonparser.py @@ -26,16 +26,17 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - import json +import logging from webkitpy.common.memoized import memoized -from webkitpy.common.system.deprecated_logging import log # FIXME: common should never import from new-run-webkit-tests, one of these files needs to move. from webkitpy.layout_tests.layout_package import json_results_generator from webkitpy.layout_tests.models import test_expectations, test_results, test_failures from webkitpy.layout_tests.models.test_expectations import TestExpectations +_log = logging.getLogger(__name__) + # These are helper functions for navigating the results json structure. def for_each_test(tree, handler, prefix=''): @@ -83,7 +84,7 @@ class JSONTestResult(object): def _tokenize(self, results_string): tokens = map(TestExpectations.expectation_from_string, results_string.split(' ')) if None in tokens: - log("Unrecognized result in %s" % results_string) + _log.warning("Unrecognized result in %s" % results_string) return set(tokens) @memoized @@ -123,7 +124,7 @@ class JSONTestResult(object): elif actual == test_expectations.MISSING: return [test_failures.FailureMissingResult(), test_failures.FailureMissingImageHash(), test_failures.FailureMissingImage()] else: - log("Failed to handle: %s" % self._result_dict['actual']) + _log.warning("Failed to handle: %s" % self._result_dict['actual']) return [] def _failures(self): diff --git a/Tools/Scripts/webkitpy/common/net/statusserver.py b/Tools/Scripts/webkitpy/common/net/statusserver.py index 2bda1ce88..99850f55d 100644 --- a/Tools/Scripts/webkitpy/common/net/statusserver.py +++ b/Tools/Scripts/webkitpy/common/net/statusserver.py @@ -29,7 +29,6 @@ # This the client designed to talk to Tools/QueueStatusServer. from webkitpy.common.net.networktransaction import NetworkTransaction -from webkitpy.common.system.deprecated_logging import log from webkitpy.thirdparty.BeautifulSoup import BeautifulSoup import logging @@ -145,11 +144,11 @@ class StatusServer: return NetworkTransaction().run(lambda: self._post_work_items_to_server(queue_name, work_items)) def update_status(self, queue_name, status, patch=None, results_file=None): - log(status) + _log.info(status) return NetworkTransaction().run(lambda: self._post_status_to_server(queue_name, status, patch, results_file)) def update_svn_revision(self, svn_revision_number, broken_bot): - log("SVN revision: %s broke %s" % (svn_revision_number, broken_bot)) + _log.info("SVN revision: %s broke %s" % (svn_revision_number, broken_bot)) return NetworkTransaction().run(lambda: self._post_svn_revision_to_server(svn_revision_number, broken_bot)) def _fetch_url(self, url): diff --git a/Tools/Scripts/webkitpy/common/net/statusserver_mock.py b/Tools/Scripts/webkitpy/common/net/statusserver_mock.py index 69d1ae807..22fa12f13 100644 --- a/Tools/Scripts/webkitpy/common/net/statusserver_mock.py +++ b/Tools/Scripts/webkitpy/common/net/statusserver_mock.py @@ -26,7 +26,9 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -from webkitpy.common.system.deprecated_logging import log +import logging + +_log = logging.getLogger(__name__) class MockStatusServer(object): @@ -48,17 +50,17 @@ class MockStatusServer(object): return self._work_items.pop(0) def release_work_item(self, queue_name, patch): - log("MOCK: release_work_item: %s %s" % (queue_name, patch.id())) + _log.info("MOCK: release_work_item: %s %s" % (queue_name, patch.id())) def update_work_items(self, queue_name, work_items): self._work_items = work_items - log("MOCK: update_work_items: %s %s" % (queue_name, work_items)) + _log.info("MOCK: update_work_items: %s %s" % (queue_name, work_items)) def submit_to_ews(self, patch_id): - log("MOCK: submit_to_ews: %s" % (patch_id)) + _log.info("MOCK: submit_to_ews: %s" % (patch_id)) def update_status(self, queue_name, status, patch=None, results_file=None): - log("MOCK: update_status: %s %s" % (queue_name, status)) + _log.info("MOCK: update_status: %s %s" % (queue_name, status)) return 187 def update_svn_revision(self, svn_revision, broken_bot): diff --git a/Tools/Scripts/webkitpy/common/net/unittestresults.py b/Tools/Scripts/webkitpy/common/net/unittestresults.py index bb82b0503..b616c0946 100644 --- a/Tools/Scripts/webkitpy/common/net/unittestresults.py +++ b/Tools/Scripts/webkitpy/common/net/unittestresults.py @@ -26,9 +26,10 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging import xml.dom.minidom -from webkitpy.common.system.deprecated_logging import log +_log = logging.getLogger(__name__) class UnitTestResults(object): @@ -46,5 +47,5 @@ class UnitTestResults(object): failures.append("%s.%s" % (classname, testname)) return failures except xml.parsers.expat.ExpatError, e: - log("XML error %s parsing unit test output" % str(e)) + _log.error("XML error %s parsing unit test output" % str(e)) return None diff --git a/Tools/Scripts/webkitpy/common/system/executive_mock.py b/Tools/Scripts/webkitpy/common/system/executive_mock.py index 47eddea8b..a83f5b245 100644 --- a/Tools/Scripts/webkitpy/common/system/executive_mock.py +++ b/Tools/Scripts/webkitpy/common/system/executive_mock.py @@ -26,12 +26,14 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging import os import StringIO -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.system.executive import ScriptError +_log = logging.getLogger(__name__) + class MockProcess(object): def __init__(self, stdout='MOCK STDOUT\n', stderr=''): @@ -71,7 +73,7 @@ class MockExecutive(object): if process_name_filter(process_name): running_pids.append(process_pid) - log("MOCK running_pids: %s" % running_pids) + _log.info("MOCK running_pids: %s" % running_pids) return running_pids def run_and_throw_if_fail(self, args, quiet=False, cwd=None, env=None): @@ -79,7 +81,7 @@ class MockExecutive(object): env_string = "" if env: env_string = ", env=%s" % env - log("MOCK run_and_throw_if_fail: %s, cwd=%s%s" % (args, cwd, env_string)) + _log.info("MOCK run_and_throw_if_fail: %s, cwd=%s%s" % (args, cwd, env_string)) if self._should_throw_when_run.intersection(args): raise ScriptError("Exception for %s" % args, output="MOCK command output") return "MOCK output of child process" @@ -104,7 +106,7 @@ class MockExecutive(object): input_string = "" if input: input_string = ", input=%s" % input - log("MOCK run_command: %s, cwd=%s%s%s" % (args, cwd, env_string, input_string)) + _log.info("MOCK run_command: %s, cwd=%s%s%s" % (args, cwd, env_string, input_string)) output = "MOCK output of child process" if self._should_throw: raise ScriptError("MOCK ScriptError", output=output) @@ -128,7 +130,7 @@ class MockExecutive(object): env_string = "" if env: env_string = ", env=%s" % env - log("MOCK popen: %s%s%s" % (args, cwd_string, env_string)) + _log.info("MOCK popen: %s%s%s" % (args, cwd_string, env_string)) if not self._proc: self._proc = MockProcess() return self._proc diff --git a/Tools/Scripts/webkitpy/common/system/profiler.py b/Tools/Scripts/webkitpy/common/system/profiler.py new file mode 100644 index 000000000..264a4e238 --- /dev/null +++ b/Tools/Scripts/webkitpy/common/system/profiler.py @@ -0,0 +1,99 @@ +# Copyright (C) 2012 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the Google name nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import logging +import re + +_log = logging.getLogger(__name__) + + +class ProfilerFactory(object): + @classmethod + def create_profiler(cls, host, executable_path, output_dir, identifier=None): + if host.platform.is_mac(): + return Instruments(host, executable_path, output_dir, identifier) + return GooglePProf(host, executable_path, output_dir, identifier) + + +class Profiler(object): + def __init__(self, host, executable_path, output_dir, identifier=None): + self._host = host + self._executable_path = executable_path + self._output_dir = output_dir + self._identifier = "test" + self._host.filesystem.maybe_make_directory(self._output_dir) + + def adjusted_environment(self, env): + return env + + def attach_to_pid(self, pid): + pass + + def profile_after_exit(self): + pass + + +class SingleFileOutputProfiler(Profiler): + def __init__(self, host, executable_path, output_dir, output_suffix, identifier=None): + super(SingleFileOutputProfiler, self).__init__(host, executable_path, output_dir, identifier) + self._output_path = self._host.workspace.find_unused_filename(self._output_dir, self._identifier, output_suffix) + + +class GooglePProf(SingleFileOutputProfiler): + def __init__(self, host, executable_path, output_dir, identifier=None): + super(GooglePProf, self).__init__(host, executable_path, output_dir, "pprof", identifier) + + def adjusted_environment(self, env): + env['CPUPROFILE'] = self._output_path + return env + + def _first_ten_lines_of_profile(self, pprof_output): + match = re.search("^Total:[^\n]*\n((?:[^\n]*\n){0,10})", pprof_output, re.MULTILINE) + return match.group(1) if match else None + + def profile_after_exit(self): + # FIXME: We should have code to find the right google-pprof executable, some Googlers have + # google-pprof installed as "pprof" on their machines for them. + # FIXME: Similarly we should find the right perl! + pprof_args = ['/usr/bin/perl', '/usr/bin/google-pprof', '--text', self._executable_path, self._output_path] + profile_text = self._host.executive.run_command(pprof_args) + print self._first_ten_lines_of_profile(profile_text) + + +# FIXME: iprofile is a newer commandline interface to replace /usr/bin/instruments. +class Instruments(SingleFileOutputProfiler): + def __init__(self, host, executable_path, output_dir, identifier=None): + super(Instruments, self).__init__(host, executable_path, output_dir, "trace", identifier) + + # FIXME: We may need a way to find this tracetemplate on the disk + _time_profile = "/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/Resources/templates/Time Profiler.tracetemplate" + + def attach_to_pid(self, pid): + cmd = ["instruments", "-t", self._time_profile, "-D", self._output_path, "-p", pid] + cmd = map(unicode, cmd) + self._host.executive.popen(cmd) diff --git a/Tools/Scripts/webkitpy/common/system/profiler_unittest.py b/Tools/Scripts/webkitpy/common/system/profiler_unittest.py new file mode 100644 index 000000000..059b7cfa1 --- /dev/null +++ b/Tools/Scripts/webkitpy/common/system/profiler_unittest.py @@ -0,0 +1,87 @@ +# Copyright (C) 2012 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import unittest + +from webkitpy.common.system.systemhost_mock import MockSystemHost + +from .profiler import ProfilerFactory, Instruments, GooglePProf + + +class ProfilerFactoryTest(unittest.TestCase): + def test_basic(self): + host = MockSystemHost() + self.assertFalse(host.filesystem.exists("/tmp/output")) + profiler = ProfilerFactory.create_profiler(host, '/bin/executable', '/tmp/output') + self.assertTrue(host.filesystem.exists("/tmp/output")) + self.assertEquals(profiler._output_path, "/tmp/output/test.trace") + + host.platform.os_name = 'linux' + profiler = ProfilerFactory.create_profiler(host, '/bin/executable', '/tmp/output') + self.assertEquals(profiler._output_path, "/tmp/output/test.pprof") + + def test_pprof_output_regexp(self): + pprof_output = """ +sometimes +there +is +junk before the total line + + +Total: 3770 samples + 76 2.0% 2.0% 104 2.8% lookup (inline) + 60 1.6% 3.6% 60 1.6% FL_SetPrevious (inline) + 56 1.5% 5.1% 56 1.5% MaskPtr (inline) + 51 1.4% 6.4% 222 5.9% WebCore::HTMLTokenizer::nextToken + 42 1.1% 7.6% 47 1.2% WTF::Vector::shrinkCapacity + 35 0.9% 8.5% 35 0.9% WTF::RefPtr::get (inline) + 33 0.9% 9.4% 43 1.1% append (inline) + 29 0.8% 10.1% 67 1.8% WTF::StringImpl::deref (inline) + 29 0.8% 10.9% 100 2.7% add (inline) + 28 0.7% 11.6% 28 0.7% WebCore::QualifiedName::localName (inline) + 25 0.7% 12.3% 27 0.7% WebCore::Private::addChildNodesToDeletionQueue + 24 0.6% 12.9% 24 0.6% __memcpy_ssse3_back + 23 0.6% 13.6% 23 0.6% intHash (inline) + 23 0.6% 14.2% 76 2.0% tcmalloc::FL_Next + 23 0.6% 14.8% 95 2.5% tcmalloc::FL_Push + 22 0.6% 15.4% 22 0.6% WebCore::MarkupTokenizerBase::InputStreamPreprocessor::peek (inline) +""" + expected_first_ten_lines = """ 76 2.0% 2.0% 104 2.8% lookup (inline) + 60 1.6% 3.6% 60 1.6% FL_SetPrevious (inline) + 56 1.5% 5.1% 56 1.5% MaskPtr (inline) + 51 1.4% 6.4% 222 5.9% WebCore::HTMLTokenizer::nextToken + 42 1.1% 7.6% 47 1.2% WTF::Vector::shrinkCapacity + 35 0.9% 8.5% 35 0.9% WTF::RefPtr::get (inline) + 33 0.9% 9.4% 43 1.1% append (inline) + 29 0.8% 10.1% 67 1.8% WTF::StringImpl::deref (inline) + 29 0.8% 10.9% 100 2.7% add (inline) + 28 0.7% 11.6% 28 0.7% WebCore::QualifiedName::localName (inline) +""" + host = MockSystemHost() + profiler = GooglePProf(host, '/bin/executable', '/tmp/output') + self.assertEquals(profiler._first_ten_lines_of_profile(pprof_output), expected_first_ten_lines) diff --git a/Tools/Scripts/webkitpy/common/system/user_mock.py b/Tools/Scripts/webkitpy/common/system/user_mock.py index 16f79a0c4..d17ea9a90 100644 --- a/Tools/Scripts/webkitpy/common/system/user_mock.py +++ b/Tools/Scripts/webkitpy/common/system/user_mock.py @@ -26,7 +26,9 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -from webkitpy.common.system.deprecated_logging import log +import logging + +_log = logging.getLogger(__name__) class MockUser(object): @@ -52,7 +54,7 @@ class MockUser(object): pass def confirm(self, message=None, default='y'): - log(message) + _log.info(message) return default == 'y' def can_open_url(self): @@ -61,6 +63,6 @@ class MockUser(object): def open_url(self, url): self.opened_urls.append(url) if url.startswith("file://"): - log("MOCK: user.open_url: file://...") + _log.info("MOCK: user.open_url: file://...") return - log("MOCK: user.open_url: %s" % url) + _log.info("MOCK: user.open_url: %s" % url) diff --git a/Tools/Scripts/webkitpy/common/system/workspace_unittest.py b/Tools/Scripts/webkitpy/common/system/workspace_unittest.py index 49094ac63..eca386ac3 100644 --- a/Tools/Scripts/webkitpy/common/system/workspace_unittest.py +++ b/Tools/Scripts/webkitpy/common/system/workspace_unittest.py @@ -50,18 +50,23 @@ class WorkspaceTest(unittest.TestCase): def test_create_zip(self): workspace = Workspace(None, MockExecutive(should_log=True)) - expected_stderr = "MOCK run_command: ['zip', '-9', '-r', '/zip/path', '.'], cwd=/source/path\n" + expected_logs = "MOCK run_command: ['zip', '-9', '-r', '/zip/path', '.'], cwd=/source/path\n" class MockZipFile(object): def __init__(self, path): self.filename = path - archive = OutputCapture().assert_outputs(self, workspace.create_zip, ["/zip/path", "/source/path", MockZipFile], expected_stderr=expected_stderr) + archive = OutputCapture().assert_outputs(self, workspace.create_zip, ["/zip/path", "/source/path", MockZipFile], expected_logs=expected_logs) self.assertEqual(archive.filename, "/zip/path") def test_create_zip_exception(self): workspace = Workspace(None, MockExecutive(should_log=True, should_throw=True)) - expected_stderr = "MOCK run_command: ['zip', '-9', '-r', '/zip/path', '.'], cwd=/source/path\n" + expected_logs = """MOCK run_command: ['zip', '-9', '-r', '/zip/path', '.'], cwd=/source/path +Workspace.create_zip failed: +MOCK ScriptError + +MOCK output of child process +""" class MockZipFile(object): def __init__(self, path): self.filename = path - archive = OutputCapture().assert_outputs(self, workspace.create_zip, ["/zip/path", "/source/path", MockZipFile], expected_stderr=expected_stderr) + archive = OutputCapture().assert_outputs(self, workspace.create_zip, ["/zip/path", "/source/path", MockZipFile], expected_logs=expected_logs) self.assertEqual(archive, None) diff --git a/Tools/Scripts/webkitpy/common/watchlist/watchlist_mock.py b/Tools/Scripts/webkitpy/common/watchlist/watchlist_mock.py index 2fd2f880f..cbbf0718a 100644 --- a/Tools/Scripts/webkitpy/common/watchlist/watchlist_mock.py +++ b/Tools/Scripts/webkitpy/common/watchlist/watchlist_mock.py @@ -26,10 +26,12 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -from webkitpy.common.system.deprecated_logging import log +import logging + +_log = logging.getLogger(__name__) class MockWatchList(object): def determine_cc_and_messages(self, diff): - log("MockWatchList: determine_cc_and_messages") + _log.info("MockWatchList: determine_cc_and_messages") return {'cc_list': ['abarth@webkit.org', 'eric@webkit.org', 'levin@chromium.org'], 'messages': ['Message1.', 'Message2.'], } diff --git a/Tools/Scripts/webkitpy/layout_tests/port/chromium_android.py b/Tools/Scripts/webkitpy/layout_tests/port/chromium_android.py index a077dc92e..c18cd0941 100644 --- a/Tools/Scripts/webkitpy/layout_tests/port/chromium_android.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/chromium_android.py @@ -68,7 +68,9 @@ SCALING_GOVERNORS_PATTERN = "/sys/devices/system/cpu/cpu*/cpufreq/scaling_govern # All the test cases are still served to DumpRenderTree through file protocol, # but we use a file-to-http feature to bridge the file request to host's http # server to get the real test files and corresponding resources. -TEST_PATH_PREFIX = '/all-tests' +# See webkit/support/platform_support_android.cc for the other side of this bridge. +PERF_TEST_PATH_PREFIX = '/all-perf-tests' +LAYOUT_TEST_PATH_PREFIX = '/all-tests' # All ports the Android forwarder to forward. # 8000, 8080 and 8443 are for http/https tests. @@ -129,7 +131,8 @@ DEVICE_FONTS_DIR = DEVICE_DRT_DIR + 'fonts/' # 1. as a virtual path in file urls that will be bridged to HTTP. # 2. pointing to some files that are pushed to the device for tests that # don't work on file-over-http (e.g. blob protocol tests). -DEVICE_LAYOUT_TESTS_DIR = DEVICE_SOURCE_ROOT_DIR + 'third_party/WebKit/LayoutTests/' +DEVICE_WEBKIT_BASE_DIR = DEVICE_SOURCE_ROOT_DIR + 'third_party/WebKit/' +DEVICE_LAYOUT_TESTS_DIR = DEVICE_WEBKIT_BASE_DIR + 'LayoutTests/' # Test resources that need to be accessed as files directly. # Each item can be the relative path of a directory or a file. @@ -242,7 +245,8 @@ class ChromiumAndroidPort(chromium.ChromiumPort): def start_http_server(self, additional_dirs=None, number_of_servers=0): if not additional_dirs: additional_dirs = {} - additional_dirs[TEST_PATH_PREFIX] = self.layout_tests_dir() + additional_dirs[PERF_TEST_PATH_PREFIX] = self.perf_tests_dir() + additional_dirs[LAYOUT_TEST_PATH_PREFIX] = self.layout_tests_dir() super(ChromiumAndroidPort, self).start_http_server(additional_dirs, number_of_servers) def create_driver(self, worker_number, no_timeout=False): @@ -665,10 +669,10 @@ class ChromiumAndroidDriver(driver.Driver): def _command_from_driver_input(self, driver_input): command = super(ChromiumAndroidDriver, self)._command_from_driver_input(driver_input) if command.startswith('/'): - # Convert the host file path to a device file path. See comment of - # DEVICE_LAYOUT_TESTS_DIR for details. + fs = self._port._filesystem # FIXME: what happens if command lies outside of the layout_tests_dir on the host? - command = DEVICE_LAYOUT_TESTS_DIR + self._port.relative_test_filename(command) + relative_test_filename = fs.relpath(command, fs.dirname(self._port.layout_tests_dir())) + command = DEVICE_WEBKIT_BASE_DIR + relative_test_filename return command def _read_prompt(self, deadline): diff --git a/Tools/Scripts/webkitpy/layout_tests/port/chromium_win_unittest.py b/Tools/Scripts/webkitpy/layout_tests/port/chromium_win_unittest.py index 1c0ddc1fe..a84b5ee15 100644 --- a/Tools/Scripts/webkitpy/layout_tests/port/chromium_win_unittest.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/chromium_win_unittest.py @@ -64,9 +64,9 @@ class ChromiumWinTest(chromium_port_testcase.ChromiumPortTestCase): def test_setup_environ_for_server_register_cygwin(self): port = self.make_port(options=MockOptions(register_cygwin=True, results_directory='/')) port._executive = MockExecutive(should_log=True) - expected_stderr = "MOCK run_command: ['/mock-checkout/Source/WebKit/chromium/third_party/cygwin/setup_mount.bat'], cwd=None\n" + expected_logs = "MOCK run_command: ['/mock-checkout/Source/WebKit/chromium/third_party/cygwin/setup_mount.bat'], cwd=None\n" output = outputcapture.OutputCapture() - output.assert_outputs(self, port.setup_environ_for_server, expected_stderr=expected_stderr) + output.assert_outputs(self, port.setup_environ_for_server, expected_logs=expected_logs) def assert_name(self, port_name, os_version_string, expected): port = self.make_port(port_name=port_name, os_version=os_version_string) diff --git a/Tools/Scripts/webkitpy/layout_tests/port/driver.py b/Tools/Scripts/webkitpy/layout_tests/port/driver.py index 7993d0577..e883590cf 100644 --- a/Tools/Scripts/webkitpy/layout_tests/port/driver.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/driver.py @@ -36,6 +36,7 @@ import time import os from webkitpy.common.system import path +from webkitpy.common.system.profiler import ProfilerFactory _log = logging.getLogger(__name__) @@ -140,6 +141,10 @@ class Driver(object): self._server_process = None self._measurements = {} + if self._port.get_option("profile"): + self._profiler = ProfilerFactory.create_profiler(self._port.host, self._port._path_to_driver(), self._port.results_directory()) + else: + self._profiler = None def __del__(self): self.stop() @@ -282,15 +287,21 @@ class Driver(object): environment['LOCAL_RESOURCE_ROOT'] = self._port.layout_tests_dir() if 'WEBKITOUTPUTDIR' in os.environ: environment['WEBKITOUTPUTDIR'] = os.environ['WEBKITOUTPUTDIR'] + if self._profiler: + environment = self._profiler.adjusted_environment(environment) self._crashed_process_name = None self._crashed_pid = None self._server_process = self._port._server_process_constructor(self._port, server_name, self.cmd_line(pixel_tests, per_test_args), environment) self._server_process.start() + if self._profiler: + self._profiler.attach_to_pid(self._server_process.pid()) def stop(self): if self._server_process: self._server_process.stop(self._port.driver_stop_timeout()) self._server_process = None + if self._profiler: + self._profiler.profile_after_exit() if self._driver_tempdir: self._port._filesystem.rmtree(str(self._driver_tempdir)) diff --git a/Tools/Scripts/webkitpy/layout_tests/port/efl_unittest.py b/Tools/Scripts/webkitpy/layout_tests/port/efl_unittest.py index d9851b32e..1ac687b18 100644 --- a/Tools/Scripts/webkitpy/layout_tests/port/efl_unittest.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/efl_unittest.py @@ -39,5 +39,5 @@ class EflPortTest(port_testcase.PortTestCase): def test_show_results_html_file(self): port = self.make_port() port._executive = MockExecutive(should_log=True) - expected_stderr = "MOCK run_command: ['Tools/Scripts/run-launcher', '--release', '--efl', 'file://test.html'], cwd=/mock-checkout\n" - OutputCapture().assert_outputs(self, port.show_results_html_file, ["test.html"], expected_stderr=expected_stderr) + expected_logs = "MOCK run_command: ['Tools/Scripts/run-launcher', '--release', '--efl', 'file://test.html'], cwd=/mock-checkout\n" + OutputCapture().assert_outputs(self, port.show_results_html_file, ["test.html"], expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/layout_tests/port/gtk_unittest.py b/Tools/Scripts/webkitpy/layout_tests/port/gtk_unittest.py index 6f5fae68d..7002495a4 100644 --- a/Tools/Scripts/webkitpy/layout_tests/port/gtk_unittest.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/gtk_unittest.py @@ -46,8 +46,8 @@ class GtkPortTest(port_testcase.PortTestCase): def test_show_results_html_file(self): port = self.make_port() port._executive = MockExecutive(should_log=True) - expected_stderr = "MOCK run_command: ['Tools/Scripts/run-launcher', '--release', '--gtk', 'file://test.html'], cwd=/mock-checkout\n" - OutputCapture().assert_outputs(self, port.show_results_html_file, ["test.html"], expected_stderr=expected_stderr) + expected_logs = "MOCK run_command: ['Tools/Scripts/run-launcher', '--release', '--gtk', 'file://test.html'], cwd=/mock-checkout\n" + OutputCapture().assert_outputs(self, port.show_results_html_file, ["test.html"], expected_logs=expected_logs) def test_default_timeout_ms(self): self.assertEqual(self.make_port(options=MockOptions(configuration='Release')).default_timeout_ms(), 6000) diff --git a/Tools/Scripts/webkitpy/layout_tests/port/mac_unittest.py b/Tools/Scripts/webkitpy/layout_tests/port/mac_unittest.py index 511201464..831fbf7c9 100644 --- a/Tools/Scripts/webkitpy/layout_tests/port/mac_unittest.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/mac_unittest.py @@ -139,8 +139,8 @@ java/ port = self.make_port() # Delay setting a should_log executive to avoid logging from MacPort.__init__. port._executive = MockExecutive(should_log=True) - expected_stderr = "MOCK popen: ['Tools/Scripts/run-safari', '--release', '--no-saved-state', '-NSOpen', 'test.html'], cwd=/mock-checkout\n" - OutputCapture().assert_outputs(self, port.show_results_html_file, ["test.html"], expected_stderr=expected_stderr) + expected_logs = "MOCK popen: ['Tools/Scripts/run-safari', '--release', '--no-saved-state', '-NSOpen', 'test.html'], cwd=/mock-checkout\n" + OutputCapture().assert_outputs(self, port.show_results_html_file, ["test.html"], expected_logs=expected_logs) def test_operating_system(self): self.assertEqual('mac', self.make_port().operating_system()) diff --git a/Tools/Scripts/webkitpy/layout_tests/port/port_testcase.py b/Tools/Scripts/webkitpy/layout_tests/port/port_testcase.py index e7cd76c92..8ea108ba0 100755 --- a/Tools/Scripts/webkitpy/layout_tests/port/port_testcase.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/port_testcase.py @@ -535,28 +535,33 @@ class PortTestCase(unittest.TestCase): # Delay setting _executive to avoid logging during construction port._executive = MockExecutive(should_log=True) port._options = MockOptions(configuration="Release") # This should not be necessary, but I think TestWebKitPort is actually reading from disk (and thus detects the current configuration). - expected_stderr = "MOCK run_command: ['Tools/Scripts/build-dumprendertree', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'}\n" - self.assertTrue(output.assert_outputs(self, port._build_driver, expected_stderr=expected_stderr, expected_logs='')) + expected_logs = "MOCK run_command: ['Tools/Scripts/build-dumprendertree', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'}\n" + self.assertTrue(output.assert_outputs(self, port._build_driver, expected_logs=expected_logs)) # Make sure when passed --webkit-test-runner we build the right tool. port._options = MockOptions(webkit_test_runner=True, configuration="Release") - expected_stderr = "MOCK run_command: ['Tools/Scripts/build-dumprendertree', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'}\nMOCK run_command: ['Tools/Scripts/build-webkittestrunner', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'}\n" - self.assertTrue(output.assert_outputs(self, port._build_driver, expected_stderr=expected_stderr, expected_logs='')) + expected_logs = "MOCK run_command: ['Tools/Scripts/build-dumprendertree', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'}\nMOCK run_command: ['Tools/Scripts/build-webkittestrunner', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'}\n" + self.assertTrue(output.assert_outputs(self, port._build_driver, expected_logs=expected_logs)) # Make sure we show the build log when --verbose is passed, which we simulate by setting the logging level to DEBUG. output.set_log_level(logging.DEBUG) port._options = MockOptions(configuration="Release") - expected_stderr = "MOCK run_command: ['Tools/Scripts/build-dumprendertree', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'}\n" - expected_logs = "Output of ['Tools/Scripts/build-dumprendertree', '--release']:\nMOCK output of child process\n" - self.assertTrue(output.assert_outputs(self, port._build_driver, expected_stderr=expected_stderr, expected_logs=expected_logs)) + expected_logs = """MOCK run_command: ['Tools/Scripts/build-dumprendertree', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'} +Output of ['Tools/Scripts/build-dumprendertree', '--release']: +MOCK output of child process +""" + self.assertTrue(output.assert_outputs(self, port._build_driver, expected_logs=expected_logs)) output.set_log_level(logging.INFO) # Make sure that failure to build returns False. port._executive = MockExecutive(should_log=True, should_throw=True) # Because WK2 currently has to build both webkittestrunner and DRT, if DRT fails, that's the only one it tries. - expected_stderr = "MOCK run_command: ['Tools/Scripts/build-dumprendertree', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'}\n" - expected_logs = "MOCK ScriptError\n\nMOCK output of child process\n" - self.assertFalse(output.assert_outputs(self, port._build_driver, expected_stderr=expected_stderr, expected_logs=expected_logs)) + expected_logs = """MOCK run_command: ['Tools/Scripts/build-dumprendertree', '--release'], cwd=/mock-checkout, env={'LC_ALL': 'C', 'MOCK_ENVIRON_COPY': '1'} +MOCK ScriptError + +MOCK output of child process +""" + self.assertFalse(output.assert_outputs(self, port._build_driver, expected_logs=expected_logs)) def _assert_config_file_for_platform(self, port, platform, config_file): self.assertEqual(port._apache_config_file_name_for_platform(platform), config_file) diff --git a/Tools/Scripts/webkitpy/layout_tests/port/qt_unittest.py b/Tools/Scripts/webkitpy/layout_tests/port/qt_unittest.py index 4a558f8dd..d6ef8d85e 100644 --- a/Tools/Scripts/webkitpy/layout_tests/port/qt_unittest.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/qt_unittest.py @@ -104,8 +104,8 @@ class QtPortTest(port_testcase.PortTestCase): def test_show_results_html_file(self): port = self.make_port() port._executive = MockExecutive(should_log=True) - expected_stderr = "MOCK run_command: ['Tools/Scripts/run-launcher', '--release', '--qt', 'file://test.html'], cwd=/mock-checkout\n" - OutputCapture().assert_outputs(self, port.show_results_html_file, ["test.html"], expected_stderr=expected_stderr) + expected_logs = "MOCK run_command: ['Tools/Scripts/run-launcher', '--release', '--qt', 'file://test.html'], cwd=/mock-checkout\n" + OutputCapture().assert_outputs(self, port.show_results_html_file, ["test.html"], expected_logs=expected_logs) def test_setup_environ_for_server(self): port = self.make_port() diff --git a/Tools/Scripts/webkitpy/layout_tests/port/win_unittest.py b/Tools/Scripts/webkitpy/layout_tests/port/win_unittest.py index 668685f56..9def7246a 100644 --- a/Tools/Scripts/webkitpy/layout_tests/port/win_unittest.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/win_unittest.py @@ -51,11 +51,11 @@ class WinPortTest(port_testcase.PortTestCase): capture = OutputCapture() capture.capture_output() port.show_results_html_file('test.html') - _, stderr, _ = capture.restore_output() + _, _, logs = capture.restore_output() # We can't know for sure what path will be produced by cygpath, but we can assert about # everything else. - self.assertTrue(stderr.startswith("MOCK run_command: ['Tools/Scripts/run-safari', '--release', '")) - self.assertTrue(stderr.endswith("test.html'], cwd=/mock-checkout\n")) + self.assertTrue(logs.startswith("MOCK run_command: ['Tools/Scripts/run-safari', '--release', '")) + self.assertTrue(logs.endswith("test.html'], cwd=/mock-checkout\n")) def _assert_search_path(self, expected_search_paths, version, use_webkit2=False): port = self.make_port(port_name='win', os_version=version, options=MockOptions(webkit_test_runner=use_webkit2)) diff --git a/Tools/Scripts/webkitpy/layout_tests/port/xvfbdriver_unittest.py b/Tools/Scripts/webkitpy/layout_tests/port/xvfbdriver_unittest.py index 367131039..241b37c1f 100644 --- a/Tools/Scripts/webkitpy/layout_tests/port/xvfbdriver_unittest.py +++ b/Tools/Scripts/webkitpy/layout_tests/port/xvfbdriver_unittest.py @@ -26,9 +26,9 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging import unittest -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.system.filesystem_mock import MockFileSystem from webkitpy.common.system.executive_mock import MockExecutive2 from webkitpy.common.system.outputcapture import OutputCapture @@ -38,6 +38,8 @@ from webkitpy.layout_tests.port.server_process_mock import MockServerProcess from webkitpy.layout_tests.port.xvfbdriver import XvfbDriver from webkitpy.tool.mocktool import MockOptions +_log = logging.getLogger(__name__) + class XvfbDriverTest(unittest.TestCase): def make_driver(self, worker_number=0, xorg_running=False, executive=None): @@ -57,27 +59,27 @@ class XvfbDriverTest(unittest.TestCase): # intend to test the behavior of XvfbDriver.stop. driver._xvfb_process = None - def assertDriverStartSuccessful(self, driver, expected_stderr, expected_display, pixel_tests=False): - OutputCapture().assert_outputs(self, driver.start, [pixel_tests, []], expected_stderr=expected_stderr) + def assertDriverStartSuccessful(self, driver, expected_logs, expected_display, pixel_tests=False): + OutputCapture().assert_outputs(self, driver.start, [pixel_tests, []], expected_logs=expected_logs) self.assertTrue(driver._server_process.started) self.assertEqual(driver._server_process.env["DISPLAY"], expected_display) def test_start_no_pixel_tests(self): driver = self.make_driver() - expected_stderr = "MOCK run_command: ['ps', '-eo', 'comm,command'], cwd=None\nMOCK popen: ['Xvfb', ':0', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" - self.assertDriverStartSuccessful(driver, expected_stderr=expected_stderr, expected_display=":0") + expected_logs = "MOCK run_command: ['ps', '-eo', 'comm,command'], cwd=None\nMOCK popen: ['Xvfb', ':0', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" + self.assertDriverStartSuccessful(driver, expected_logs=expected_logs, expected_display=":0") self.cleanup_driver(driver) def test_start_pixel_tests(self): driver = self.make_driver() - expected_stderr = "MOCK run_command: ['ps', '-eo', 'comm,command'], cwd=None\nMOCK popen: ['Xvfb', ':0', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" - self.assertDriverStartSuccessful(driver, expected_stderr=expected_stderr, expected_display=":0", pixel_tests=True) + expected_logs = "MOCK run_command: ['ps', '-eo', 'comm,command'], cwd=None\nMOCK popen: ['Xvfb', ':0', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" + self.assertDriverStartSuccessful(driver, expected_logs=expected_logs, expected_display=":0", pixel_tests=True) self.cleanup_driver(driver) def test_start_arbitrary_worker_number(self): driver = self.make_driver(worker_number=17) - expected_stderr = "MOCK run_command: ['ps', '-eo', 'comm,command'], cwd=None\nMOCK popen: ['Xvfb', ':0', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" - self.assertDriverStartSuccessful(driver, expected_stderr=expected_stderr, expected_display=":0", pixel_tests=True) + expected_logs = "MOCK run_command: ['ps', '-eo', 'comm,command'], cwd=None\nMOCK popen: ['Xvfb', ':0', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" + self.assertDriverStartSuccessful(driver, expected_logs=expected_logs, expected_display=":0", pixel_tests=True) self.cleanup_driver(driver) def disabled_test_next_free_display(self): @@ -105,19 +107,19 @@ class XvfbDriverTest(unittest.TestCase): def test_start_next_worker(self): driver = self.make_driver() driver._next_free_display = lambda: 0 - expected_stderr = "MOCK popen: ['Xvfb', ':0', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" - self.assertDriverStartSuccessful(driver, expected_stderr=expected_stderr, expected_display=":0", pixel_tests=True) + expected_logs = "MOCK popen: ['Xvfb', ':0', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" + self.assertDriverStartSuccessful(driver, expected_logs=expected_logs, expected_display=":0", pixel_tests=True) self.cleanup_driver(driver) driver = self.make_driver() driver._next_free_display = lambda: 3 - expected_stderr = "MOCK popen: ['Xvfb', ':3', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" - self.assertDriverStartSuccessful(driver, expected_stderr=expected_stderr, expected_display=":3", pixel_tests=True) + expected_logs = "MOCK popen: ['Xvfb', ':3', '-screen', '0', '800x600x24', '-nolisten', 'tcp']\n" + self.assertDriverStartSuccessful(driver, expected_logs=expected_logs, expected_display=":3", pixel_tests=True) self.cleanup_driver(driver) def test_stop(self): filesystem = MockFileSystem(files={'/tmp/.X42-lock': '1234\n'}) port = Port(host=MockSystemHost(log_executive=True, filesystem=filesystem), options=MockOptions(configuration='Release')) - port._executive.kill_process = lambda x: log("MOCK kill_process pid: " + str(x)) + port._executive.kill_process = lambda x: _log.info("MOCK kill_process pid: " + str(x)) driver = XvfbDriver(port, worker_number=0, pixel_tests=True) class FakeXvfbProcess(object): @@ -126,8 +128,8 @@ class XvfbDriverTest(unittest.TestCase): driver._xvfb_process = FakeXvfbProcess() driver._lock_file = '/tmp/.X42-lock' - expected_stderr = "MOCK kill_process pid: 1234\n" - OutputCapture().assert_outputs(self, driver.stop, [], expected_stderr=expected_stderr) + expected_logs = "MOCK kill_process pid: 1234\n" + OutputCapture().assert_outputs(self, driver.stop, [], expected_logs=expected_logs) self.assertEqual(driver._xvfb_process, None) self.assertFalse(port._filesystem.exists(driver._lock_file)) diff --git a/Tools/Scripts/webkitpy/layout_tests/servers/apache_http_server_unittest.py b/Tools/Scripts/webkitpy/layout_tests/servers/apache_http_server_unittest.py index 34ab97b40..f3ca6a1a8 100644 --- a/Tools/Scripts/webkitpy/layout_tests/servers/apache_http_server_unittest.py +++ b/Tools/Scripts/webkitpy/layout_tests/servers/apache_http_server_unittest.py @@ -63,8 +63,8 @@ class TestLayoutTestApacheHttpd(unittest.TestCase): server.start() server.stop() finally: - out, err, logs = oc.restore_output() - self.assertTrue("StartServers 4" in err) - self.assertTrue("MinSpareServers 4" in err) - self.assertTrue("MaxSpareServers 4" in err) + _, _, logs = oc.restore_output() + self.assertTrue("StartServers 4" in logs) + self.assertTrue("MinSpareServers 4" in logs) + self.assertTrue("MaxSpareServers 4" in logs) self.assertTrue(host.filesystem.exists("/mock/output_dir/httpd.conf")) diff --git a/Tools/Scripts/webkitpy/performance_tests/perftest.py b/Tools/Scripts/webkitpy/performance_tests/perftest.py index 9e2f87d47..623aef341 100644 --- a/Tools/Scripts/webkitpy/performance_tests/perftest.py +++ b/Tools/Scripts/webkitpy/performance_tests/perftest.py @@ -70,6 +70,7 @@ class PerfTest(object): def run(self, driver, time_out_ms): output = self.run_single(driver, self.path_or_url(), time_out_ms) + self._filter_stderr(output) if self.run_failed(output): return None return self.parse_output(output) @@ -92,6 +93,27 @@ class PerfTest(object): return True + def _should_ignore_line(self, regexps, line): + if not line: + return True + for regexp in regexps: + if regexp.search(line): + return True + return False + + _lines_to_ignore_in_stderr = [ + re.compile(r'^Unknown option:'), + re.compile(r'^\[WARNING:proxy_service.cc')] + + def _should_ignore_line_in_stderr(self, line): + return self._should_ignore_line(self._lines_to_ignore_in_stderr, line) + + def _filter_stderr(self, output): + if not output.error: + return + filtered_error = '\n'.join([line for line in re.split('\n', output.error) if not self._should_ignore_line_in_stderr(line)]) + output.error = filtered_error if filtered_error else None + _lines_to_ignore_in_parser_result = [ re.compile(r'^Running \d+ times$'), re.compile(r'^Ignoring warm-up '), @@ -105,12 +127,7 @@ class PerfTest(object): re.compile(re.escape("""Blocked access to external URL http://www.whatwg.org/specs/web-apps/current-work/"""))] def _should_ignore_line_in_parser_test_result(self, line): - if not line: - return True - for regex in self._lines_to_ignore_in_parser_result: - if regex.search(line): - return True - return False + return self._should_ignore_line(self._lines_to_ignore_in_parser_result, line) _description_regex = re.compile(r'^Description: (?P<description>.*)$', re.IGNORECASE) _result_classes = ['Time', 'JS Heap', 'Malloc'] @@ -166,11 +183,12 @@ class PerfTest(object): _log.error("The test didn't report all statistics.") return None - for result_name in ordered_results_keys: - if result_name == test_name: - self.output_statistics(result_name, results[result_name], description_string) - else: - self.output_statistics(result_name, results[result_name]) + if not self._port.get_option('profile'): + for result_name in ordered_results_keys: + if result_name == test_name: + self.output_statistics(result_name, results[result_name], description_string) + else: + self.output_statistics(result_name, results[result_name]) return results def output_statistics(self, test_name, results, description_string=None): @@ -327,7 +345,7 @@ class ReplayPerfTest(PageLoadingPerfTest): _log.info("Preparing replay for %s" % self.test_name()) - driver = self._port.create_driver(worker_number=1, no_timeout=True) + driver = self._port.create_driver(worker_number=0, no_timeout=True) try: output = self.run_single(driver, self._archive_path, time_out_ms, record=True) finally: diff --git a/Tools/Scripts/webkitpy/performance_tests/perftest_unittest.py b/Tools/Scripts/webkitpy/performance_tests/perftest_unittest.py index 259fc7854..9e275b635 100755 --- a/Tools/Scripts/webkitpy/performance_tests/perftest_unittest.py +++ b/Tools/Scripts/webkitpy/performance_tests/perftest_unittest.py @@ -63,7 +63,7 @@ class MainTest(unittest.TestCase): output_capture = OutputCapture() output_capture.capture_output() try: - test = PerfTest(None, 'some-test', '/path/some-dir/some-test') + test = PerfTest(MockPort(), 'some-test', '/path/some-dir/some-test') self.assertEqual(test.parse_output(output), {'some-test': {'avg': 1100.0, 'median': 1101.0, 'min': 1080.0, 'max': 1120.0, 'stdev': 11.0, 'unit': 'ms', 'values': [i for i in range(1, 20)]}}) @@ -91,7 +91,7 @@ class MainTest(unittest.TestCase): output_capture = OutputCapture() output_capture.capture_output() try: - test = PerfTest(None, 'some-test', '/path/some-dir/some-test') + test = PerfTest(MockPort(), 'some-test', '/path/some-dir/some-test') self.assertEqual(test.parse_output(output), None) finally: actual_stdout, actual_stderr, actual_logs = output_capture.restore_output() diff --git a/Tools/Scripts/webkitpy/performance_tests/perftestsrunner.py b/Tools/Scripts/webkitpy/performance_tests/perftestsrunner.py index 42e0d96e1..6dc4742b7 100755 --- a/Tools/Scripts/webkitpy/performance_tests/perftestsrunner.py +++ b/Tools/Scripts/webkitpy/performance_tests/perftestsrunner.py @@ -68,6 +68,8 @@ class PerfTestsRunner(object): self._base_path = self._port.perf_tests_dir() self._results = {} self._timestamp = time.time() + self._needs_http = None + self._has_http_lock = False @staticmethod def _parse_args(args=None): @@ -83,6 +85,8 @@ class PerfTestsRunner(object): help="Specify port/platform being tested (i.e. chromium-mac)"), optparse.make_option("--chromium", action="store_const", const='chromium', dest='platform', help='Alias for --platform=chromium'), + optparse.make_option("--chromium-android", + action="store_const", const='chromium-android', dest='platform', help='Alias for --platform=chromium-android'), optparse.make_option("--builder-name", help=("The name of the builder shown on the waterfall running this script e.g. google-mac-2.")), optparse.make_option("--build-number", @@ -117,6 +121,8 @@ class PerfTestsRunner(object): help="Run replay tests."), optparse.make_option("--force", dest="skipped", action="store_true", default=False, help="Run all tests, including the ones in the Skipped list."), + optparse.make_option("--profile", action="store_true", + help="Output per-test profile information."), ] return optparse.OptionParser(option_list=(perf_option_list)).parse_args(args) @@ -151,8 +157,21 @@ class PerfTestsRunner(object): return tests + def _start_servers(self): + if self._needs_http: + self._port.acquire_http_lock() + self._port.start_http_server(number_of_servers=2) + self._has_http_lock = True + + def _stop_servers(self): + if self._has_http_lock: + self._port.stop_http_server() + self._port.release_http_lock() + def run(self): - if not self._port.check_build(needs_http=False): + self._needs_http = self._port.requires_http_server() + + if not self._port.check_build(needs_http=self._needs_http): _log.error("Build not up to date for %s" % self._port._path_to_driver()) return self.EXIT_CODE_BAD_BUILD @@ -163,8 +182,14 @@ class PerfTestsRunner(object): if not test.prepare(self._options.time_out_ms): return self.EXIT_CODE_BAD_PREPARATION - unexpected = self._run_tests_set(sorted(list(tests), key=lambda test: test.test_name()), self._port) - if self._options.generate_results: + try: + self._start_servers() + unexpected = self._run_tests_set(sorted(list(tests), key=lambda test: test.test_name()), self._port) + + finally: + self._stop_servers() + + if self._options.generate_results and not self._options.profile: exit_code = self._generate_and_show_results() if exit_code: return exit_code @@ -290,7 +315,7 @@ class PerfTestsRunner(object): driver = None for test in tests: - driver = port.create_driver(worker_number=1, no_timeout=True) + driver = port.create_driver(worker_number=0, no_timeout=True) if self._options.pause_before_testing: driver.start() diff --git a/Tools/Scripts/webkitpy/performance_tests/perftestsrunner_unittest.py b/Tools/Scripts/webkitpy/performance_tests/perftestsrunner_unittest.py index 62e7353df..16a05599c 100755 --- a/Tools/Scripts/webkitpy/performance_tests/perftestsrunner_unittest.py +++ b/Tools/Scripts/webkitpy/performance_tests/perftestsrunner_unittest.py @@ -242,9 +242,8 @@ max 548000 bytes self.assertEqual(TestDriverWithStartCount.start_count, 1) finally: stdout, stderr, log = output.restore_output() - self.assertEqual(stderr, "Ready to run test?\n") self.assertEqual(self.normalizeFinishedTime(log), - "Running inspector/pass.html (1 of 1)\nRESULT group_name: test_name= 42 ms\nFinished: 0.1 s\n\n") + "Ready to run test?\nRunning inspector/pass.html (1 of 1)\nRESULT group_name: test_name= 42 ms\nFinished: 0.1 s\n\n") def test_run_test_set_for_parser_tests(self): runner, port = self.create_runner() @@ -289,14 +288,16 @@ max 548000 bytes 'RESULT Parser: memory-test: Malloc= 532000.0 bytes', 'median= 529000.0 bytes, stdev= 13000.0 bytes, min= 511000.0 bytes, max= 548000.0 bytes', 'Finished: 0.1 s', - '', ''])) + '', + 'MOCK: user.open_url: file://...', + ''])) results = runner.load_output_json()[0]['results'] values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] self.assertEqual(results['Parser/memory-test'], {'min': 1080.0, 'max': 1120.0, 'median': 1101.0, 'stdev': 11.0, 'avg': 1100.0, 'unit': 'ms', 'values': values}) self.assertEqual(results['Parser/memory-test:JSHeap'], {'min': 811000.0, 'max': 848000.0, 'median': 829000.0, 'stdev': 15000.0, 'avg': 832000.0, 'unit': 'bytes', 'values': values}) self.assertEqual(results['Parser/memory-test:Malloc'], {'min': 511000.0, 'max': 548000.0, 'median': 529000.0, 'stdev': 13000.0, 'avg': 532000.0, 'unit': 'bytes', 'values': values}) - def _test_run_with_json_output(self, runner, filesystem, upload_suceeds=False, expected_exit_code=0): + def _test_run_with_json_output(self, runner, filesystem, upload_suceeds=False, results_shown=True, expected_exit_code=0): filesystem.write_text_file(runner._base_path + '/inspector/pass.html', 'some content') filesystem.write_text_file(runner._base_path + '/Bindings/event-target-wrapper.html', 'some content') @@ -318,18 +319,19 @@ max 548000 bytes stdout, stderr, logs = output_capture.restore_output() if not expected_exit_code: - self.assertEqual(self.normalizeFinishedTime(logs), - '\n'.join(['Running 2 tests', - 'Running Bindings/event-target-wrapper.html (1 of 2)', - 'RESULT Bindings: event-target-wrapper= 1489.05 ms', - 'median= 1487.0 ms, stdev= 14.46 ms, min= 1471.0 ms, max= 1510.0 ms', - 'Finished: 0.1 s', - '', - 'Running inspector/pass.html (2 of 2)', - 'RESULT group_name: test_name= 42 ms', - 'Finished: 0.1 s', - '', - ''])) + expected_logs = '\n'.join(['Running 2 tests', + 'Running Bindings/event-target-wrapper.html (1 of 2)', + 'RESULT Bindings: event-target-wrapper= 1489.05 ms', + 'median= 1487.0 ms, stdev= 14.46 ms, min= 1471.0 ms, max= 1510.0 ms', + 'Finished: 0.1 s', + '', + 'Running inspector/pass.html (2 of 2)', + 'RESULT group_name: test_name= 42 ms', + 'Finished: 0.1 s', + '', '']) + if results_shown: + expected_logs += 'MOCK: user.open_url: file://...\n' + self.assertEqual(self.normalizeFinishedTime(logs), expected_logs) self.assertEqual(uploaded[0], upload_suceeds) @@ -373,7 +375,7 @@ max 548000 bytes def test_run_respects_no_results(self): runner, port = self.create_runner(args=['--output-json-path=/mock-checkout/output.json', '--test-results-server=some.host', '--no-results']) - self._test_run_with_json_output(runner, port.host.filesystem, upload_suceeds=False) + self._test_run_with_json_output(runner, port.host.filesystem, upload_suceeds=False, results_shown=False) self.assertFalse(port.host.filesystem.isfile('/mock-checkout/output.json')) def test_run_generates_json_by_default(self): @@ -428,7 +430,7 @@ max 548000 bytes page_shown = [] port.show_results_html_file = lambda path: page_shown.append(path) filesystem = port.host.filesystem - self._test_run_with_json_output(runner, filesystem) + self._test_run_with_json_output(runner, filesystem, results_shown=False) expected_entry = {"timestamp": 123456789, "results": self._event_target_wrapper_and_inspector_results, "webkit-revision": "5678", "branch": "webkit-trunk"} @@ -441,7 +443,7 @@ max 548000 bytes '<script>%s</script>END' % json_output) self.assertEqual(page_shown[0], '/mock-checkout/output.html') - self._test_run_with_json_output(runner, filesystem) + self._test_run_with_json_output(runner, filesystem, results_shown=False) json_output = port.host.filesystem.read_text_file('/mock-checkout/output.json') self.assertEqual(json.loads(json_output), [expected_entry, expected_entry]) self.assertEqual(filesystem.read_text_file('/mock-checkout/output.html'), @@ -454,14 +456,14 @@ max 548000 bytes runner, port = self.create_runner_and_setup_results_template(args=['--output-json-path=/mock-checkout/output.json']) page_shown = [] port.show_results_html_file = show_results_html_file - self._test_run_with_json_output(runner, port.host.filesystem) + self._test_run_with_json_output(runner, port.host.filesystem, results_shown=False) self.assertEqual(page_shown[0], '/mock-checkout/output.html') runner, port = self.create_runner_and_setup_results_template(args=['--output-json-path=/mock-checkout/output.json', '--no-show-results']) page_shown = [] port.show_results_html_file = show_results_html_file - self._test_run_with_json_output(runner, port.host.filesystem) + self._test_run_with_json_output(runner, port.host.filesystem, results_shown=False) self.assertEqual(page_shown, []) def test_run_with_bad_output_json(self): diff --git a/Tools/Scripts/webkitpy/style/checkers/cpp.py b/Tools/Scripts/webkitpy/style/checkers/cpp.py index f9d534b8c..c99cbea3d 100644 --- a/Tools/Scripts/webkitpy/style/checkers/cpp.py +++ b/Tools/Scripts/webkitpy/style/checkers/cpp.py @@ -1210,6 +1210,44 @@ class _FileState(object): return self.is_c() or self.is_objective_c() +class _EnumState(object): + """Maintains whether currently in an enum declaration, and checks whether + enum declarations follow the style guide. + """ + + def __init__(self): + self.in_enum_decl = False + + def process_clean_line(self, line): + # FIXME: The regular expressions for expr_all_uppercase and expr_enum_end only accept integers + # and identifiers for the value of the enumerator, but do not accept any other constant + # expressions. However, this is sufficient for now (11/27/2012). + expr_all_uppercase = r'\s*[A-Z0-9_]+\s*(?:=\s*[a-zA-Z0-9]+\s*)?,?\s*$' + expr_starts_lowercase = r'\s*[a-z]' + expr_enum_end = r'}\s*(?:[a-zA-Z0-9]+\s*(?:=\s*[a-zA-Z0-9]+)?)?\s*;\s*' + expr_enum_start = r'\s*enum(?:\s+[a-zA-Z0-9]+)?\s*\{?\s*' + if self.in_enum_decl: + if match(r'\s*' + expr_enum_end + r'$', line): + self.in_enum_decl = False + elif match(expr_all_uppercase, line): + return False + elif match(expr_starts_lowercase, line): + return False + else: + if match(expr_enum_start + r'$', line): + self.in_enum_decl = True + else: + matched = match(expr_enum_start + r'(?P<members>.*)' + expr_enum_end + r'$', line) + if matched: + members = matched.group('members').split(',') + for member in members: + if match(expr_all_uppercase, member): + return False + if match(expr_starts_lowercase, member): + return False + return True + return True + def check_for_non_standard_constructs(clean_lines, line_number, class_state, error): """Logs an error if we see certain non-ANSI constructs ignored by gcc-2. @@ -2040,6 +2078,21 @@ def check_namespace_indentation(clean_lines, line_number, file_extension, file_s break; +def check_enum_casing(clean_lines, line_number, enum_state, error): + """Looks for incorrectly named enum values. + + Args: + clean_lines: A CleansedLines instance containing the file. + line_number: The number of the line to check. + enum_state: A _EnumState instance which maintains enum declaration state. + error: The function to call with any errors found. + """ + + line = clean_lines.elided[line_number] # Get rid of comments and strings. + if not enum_state.process_clean_line(line): + error(line_number, 'readability/enum_casing', 4, + 'enum members should use InterCaps with an initial capital letter.') + def check_directive_indentation(clean_lines, line_number, file_state, error): """Looks for indentation of preprocessor directives. @@ -2535,7 +2588,7 @@ def get_line_width(line): return len(line) -def check_style(clean_lines, line_number, file_extension, class_state, file_state, error): +def check_style(clean_lines, line_number, file_extension, class_state, file_state, enum_state, error): """Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we @@ -2550,6 +2603,7 @@ def check_style(clean_lines, line_number, file_extension, class_state, file_stat the current stack of nested class declarations being parsed. file_state: A _FileState instance which maintains information about the state of things in the file. + enum_state: A _EnumState instance which maintains the current enum state. error: The function to call with any errors found. """ @@ -2604,6 +2658,7 @@ def check_style(clean_lines, line_number, file_extension, class_state, file_stat check_for_comparisons_to_zero(clean_lines, line_number, error) check_for_null(clean_lines, line_number, file_state, error) check_indentation_amount(clean_lines, line_number, error) + check_enum_casing(clean_lines, line_number, enum_state, error) _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"') @@ -3478,7 +3533,7 @@ def check_for_include_what_you_use(filename, clean_lines, include_state, error): def process_line(filename, file_extension, clean_lines, line, include_state, function_state, - class_state, file_state, error): + class_state, file_state, enum_state, error): """Processes a single line in the file. Args: @@ -3493,6 +3548,8 @@ def process_line(filename, file_extension, the current stack of nested class declarations being parsed. file_state: A _FileState instance which maintains information about the state of things in the file. + enum_state: A _EnumState instance which maintains an enum declaration + state. error: A callable to which errors are reported, which takes arguments: line number, error level, and message @@ -3508,7 +3565,7 @@ def process_line(filename, file_extension, check_pass_ptr_usage(clean_lines, line, function_state, error) check_for_leaky_patterns(clean_lines, line, function_state, error) check_for_multiline_comments_and_strings(clean_lines, line, error) - check_style(clean_lines, line, file_extension, class_state, file_state, error) + check_style(clean_lines, line, file_extension, class_state, file_state, enum_state, error) check_language(filename, clean_lines, line, file_extension, include_state, file_state, error) check_for_non_standard_constructs(clean_lines, line, class_state, error) @@ -3541,9 +3598,11 @@ def _process_lines(filename, file_extension, lines, error, min_confidence): remove_multi_line_comments(lines, error) clean_lines = CleansedLines(lines) file_state = _FileState(clean_lines, file_extension) + enum_state = _EnumState() for line in xrange(clean_lines.num_lines()): process_line(filename, file_extension, clean_lines, line, - include_state, function_state, class_state, file_state, error) + include_state, function_state, class_state, file_state, + enum_state, error) class_state.check_finished(error) check_for_include_what_you_use(filename, clean_lines, include_state, error) @@ -3585,6 +3644,7 @@ class CppChecker(object): 'readability/comparison_to_zero', 'readability/constructors', 'readability/control_flow', + 'readability/enum_casing', 'readability/fn_size', 'readability/function', 'readability/multiline_comment', diff --git a/Tools/Scripts/webkitpy/style/checkers/cpp_unittest.py b/Tools/Scripts/webkitpy/style/checkers/cpp_unittest.py index 6de7df619..822ed77c9 100644 --- a/Tools/Scripts/webkitpy/style/checkers/cpp_unittest.py +++ b/Tools/Scripts/webkitpy/style/checkers/cpp_unittest.py @@ -3258,6 +3258,43 @@ class NoNonVirtualDestructorsTest(CppStyleTestBase): };''', 'The class Foo probably needs a virtual destructor') + def test_enum_casing(self): + self.assert_multi_line_lint( + '''\ + enum Foo { + FOO_ONE = 1, + FOO_TWO + }; + enum { FOO_ONE }; + enum {FooOne, fooTwo}; + enum { + FOO_ONE + };''', + ['enum members should use InterCaps with an initial capital letter. [readability/enum_casing] [4]'] * 5) + + self.assert_multi_line_lint( + '''\ + enum Foo { + fooOne = 1, + FooTwo = 2 + };''', + 'enum members should use InterCaps with an initial capital letter. [readability/enum_casing] [4]') + + self.assert_multi_line_lint( + '''\ + enum Foo { + FooOne = 1, + FooTwo + } fooVar = FooOne; + enum { FooOne, FooTwo }; + enum { FooOne, FooTwo } fooVar = FooTwo; + enum { FooOne= FooTwo } foo; + enum Enum123 { + FooOne, + FooTwo = FooOne, + };''', + '') + def test_destructor_non_virtual_when_virtual_needed(self): self.assert_multi_line_lint_re( '''\ @@ -3280,7 +3317,7 @@ class NoNonVirtualDestructorsTest(CppStyleTestBase): '''\ class Foo { enum Goo { - GOO + Goo }; virtual void foo(); };''', diff --git a/Tools/Scripts/webkitpy/test/main.py b/Tools/Scripts/webkitpy/test/main.py index d8f997805..5f16beca6 100644 --- a/Tools/Scripts/webkitpy/test/main.py +++ b/Tools/Scripts/webkitpy/test/main.py @@ -139,7 +139,7 @@ class Tester(object): self._options.child_processes = 1 import webkitpy.thirdparty.autoinstalled.coverage as coverage - cov = coverage.coverage() + cov = coverage.coverage(omit=["/usr/*", "*/webkitpy/thirdparty/autoinstalled/*"]) cov.start() self.printer.write_update("Checking imports ...") diff --git a/Tools/Scripts/webkitpy/tool/bot/commitqueuetask_unittest.py b/Tools/Scripts/webkitpy/tool/bot/commitqueuetask_unittest.py index 2958c6cc1..2211b1de0 100644 --- a/Tools/Scripts/webkitpy/tool/bot/commitqueuetask_unittest.py +++ b/Tools/Scripts/webkitpy/tool/bot/commitqueuetask_unittest.py @@ -27,11 +27,11 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from datetime import datetime +import logging import unittest from webkitpy.common.net import bugzilla from webkitpy.common.net.layouttestresults import LayoutTestResults -from webkitpy.common.system.deprecated_logging import error, log from webkitpy.common.system.executive import ScriptError from webkitpy.common.system.outputcapture import OutputCapture from webkitpy.layout_tests.models import test_results @@ -41,6 +41,8 @@ from webkitpy.tool.bot.commitqueuetask import * from webkitpy.tool.bot.expectedfailures import ExpectedFailures from webkitpy.tool.mocktool import MockTool +_log = logging.getLogger(__name__) + class MockCommitQueue(CommitQueueTaskDelegate): def __init__(self, error_plan): @@ -48,18 +50,18 @@ class MockCommitQueue(CommitQueueTaskDelegate): self._failure_status_id = 0 def run_command(self, command): - log("run_webkit_patch: %s" % command) + _log.info("run_webkit_patch: %s" % command) if self._error_plan: error = self._error_plan.pop(0) if error: raise error def command_passed(self, success_message, patch): - log("command_passed: success_message='%s' patch='%s'" % ( + _log.info("command_passed: success_message='%s' patch='%s'" % ( success_message, patch.id())) def command_failed(self, failure_message, script_error, patch): - log("command_failed: failure_message='%s' script_error='%s' patch='%s'" % ( + _log.info("command_failed: failure_message='%s' script_error='%s' patch='%s'" % ( failure_message, script_error, patch.id())) self._failure_status_id += 1 return self._failure_status_id @@ -75,10 +77,10 @@ class MockCommitQueue(CommitQueueTaskDelegate): def report_flaky_tests(self, patch, flaky_results, results_archive): flaky_tests = [result.filename for result in flaky_results] - log("report_flaky_tests: patch='%s' flaky_tests='%s' archive='%s'" % (patch.id(), flaky_tests, results_archive.filename)) + _log.info("report_flaky_tests: patch='%s' flaky_tests='%s' archive='%s'" % (patch.id(), flaky_tests, results_archive.filename)) def archive_last_test_results(self, patch): - log("archive_last_test_results: patch='%s'" % patch.id()) + _log.info("archive_last_test_results: patch='%s'" % patch.id()) archive = Mock() archive.filename = "mock-archive-%s.zip" % patch.id() return archive @@ -121,18 +123,18 @@ class GoldenScriptError(ScriptError): class CommitQueueTaskTest(unittest.TestCase): - def _run_through_task(self, commit_queue, expected_stderr, expected_exception=None, expect_retry=False): + def _run_through_task(self, commit_queue, expected_logs, expected_exception=None, expect_retry=False): tool = MockTool(log_executive=True) patch = tool.bugs.fetch_attachment(10000) task = CommitQueueTask(commit_queue, patch) - success = OutputCapture().assert_outputs(self, task.run, expected_stderr=expected_stderr, expected_exception=expected_exception) + success = OutputCapture().assert_outputs(self, task.run, expected_logs=expected_logs, expected_exception=expected_exception) if not expected_exception: self.assertEqual(success, not expect_retry) return task def test_success_case(self): commit_queue = MockCommitQueue([]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -147,12 +149,12 @@ command_passed: success_message='Passed tests' patch='10000' run_webkit_patch: ['land-attachment', '--force-clean', '--non-interactive', '--parent-command=commit-queue', 10000] command_passed: success_message='Landed patch' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr) + self._run_through_task(commit_queue, expected_logs) def test_fast_success_case(self): commit_queue = MockCommitQueue([]) commit_queue.did_pass_testing_ews = lambda patch: True - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -165,28 +167,28 @@ command_passed: success_message='Built patch' patch='10000' run_webkit_patch: ['land-attachment', '--force-clean', '--non-interactive', '--parent-command=commit-queue', 10000] command_passed: success_message='Landed patch' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr) + self._run_through_task(commit_queue, expected_logs) def test_clean_failure(self): commit_queue = MockCommitQueue([ ScriptError("MOCK clean failure"), ]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_failed: failure_message='Unable to clean working directory' script_error='MOCK clean failure' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr, expect_retry=True) + self._run_through_task(commit_queue, expected_logs, expect_retry=True) def test_update_failure(self): commit_queue = MockCommitQueue([ None, ScriptError("MOCK update failure"), ]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_failed: failure_message='Unable to update working directory' script_error='MOCK update failure' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr, expect_retry=True) + self._run_through_task(commit_queue, expected_logs, expect_retry=True) def test_apply_failure(self): commit_queue = MockCommitQueue([ @@ -194,14 +196,14 @@ command_failed: failure_message='Unable to update working directory' script_erro None, GoldenScriptError("MOCK apply failure"), ]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' run_webkit_patch: ['apply-attachment', '--no-update', '--non-interactive', 10000] command_failed: failure_message='Patch does not apply' script_error='MOCK apply failure' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr, GoldenScriptError) + self._run_through_task(commit_queue, expected_logs, GoldenScriptError) def test_validate_changelog_failure(self): commit_queue = MockCommitQueue([ @@ -210,7 +212,7 @@ command_failed: failure_message='Patch does not apply' script_error='MOCK apply None, GoldenScriptError("MOCK validate failure"), ]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -219,7 +221,7 @@ command_passed: success_message='Applied patch' patch='10000' run_webkit_patch: ['validate-changelog', '--non-interactive', 10000] command_failed: failure_message='ChangeLog did not pass validation' script_error='MOCK validate failure' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr, GoldenScriptError) + self._run_through_task(commit_queue, expected_logs, GoldenScriptError) def test_build_failure(self): commit_queue = MockCommitQueue([ @@ -229,7 +231,7 @@ command_failed: failure_message='ChangeLog did not pass validation' script_error None, GoldenScriptError("MOCK build failure"), ]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -242,7 +244,7 @@ command_failed: failure_message='Patch does not build' script_error='MOCK build run_webkit_patch: ['build', '--force-clean', '--no-update', '--build-style=both'] command_passed: success_message='Able to build without patch' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr, GoldenScriptError) + self._run_through_task(commit_queue, expected_logs, GoldenScriptError) def test_red_build_failure(self): commit_queue = MockCommitQueue([ @@ -253,7 +255,7 @@ command_passed: success_message='Able to build without patch' patch='10000' ScriptError("MOCK build failure"), ScriptError("MOCK clean build failure"), ]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -266,7 +268,7 @@ command_failed: failure_message='Patch does not build' script_error='MOCK build run_webkit_patch: ['build', '--force-clean', '--no-update', '--build-style=both'] command_failed: failure_message='Unable to build without patch' script_error='MOCK clean build failure' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr, expect_retry=True) + self._run_through_task(commit_queue, expected_logs, expect_retry=True) def test_flaky_test_failure(self): commit_queue = MockCommitQueue([ @@ -280,7 +282,7 @@ command_failed: failure_message='Unable to build without patch' script_error='MO # CommitQueueTask will only report flaky tests if we successfully parsed # results.html and returned a LayoutTestResults object, so we fake one. commit_queue.test_results = lambda: LayoutTestResults([]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -299,7 +301,7 @@ report_flaky_tests: patch='10000' flaky_tests='[]' archive='mock-archive-10000.z run_webkit_patch: ['land-attachment', '--force-clean', '--non-interactive', '--parent-command=commit-queue', 10000] command_passed: success_message='Landed patch' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr) + self._run_through_task(commit_queue, expected_logs) def test_failed_archive(self): commit_queue = MockCommitQueue([ @@ -314,7 +316,7 @@ command_passed: success_message='Landed patch' patch='10000' # It's possible delegate to fail to archive layout tests, don't try to report # flaky tests when that happens. commit_queue.archive_last_test_results = lambda patch: None - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -331,7 +333,7 @@ command_passed: success_message='Passed tests' patch='10000' run_webkit_patch: ['land-attachment', '--force-clean', '--non-interactive', '--parent-command=commit-queue', 10000] command_passed: success_message='Landed patch' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr) + self._run_through_task(commit_queue, expected_logs) def test_double_flaky_test_failure(self): commit_queue = FailingTestCommitQueue([ @@ -348,9 +350,9 @@ command_passed: success_message='Landed patch' patch='10000' "foo.html", ]) # The (subtle) point of this test is that report_flaky_tests does not appear - # in the expected_stderr for this run. + # in the expected_logs for this run. # Note also that there is no attempt to run the tests w/o the patch. - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -369,7 +371,7 @@ command_failed: failure_message='Patch does not pass tests' script_error='MOCK t tool = MockTool(log_executive=True) patch = tool.bugs.fetch_attachment(10000) task = CommitQueueTask(commit_queue, patch) - success = OutputCapture().assert_outputs(self, task.run, expected_stderr=expected_stderr) + success = OutputCapture().assert_outputs(self, task.run, expected_logs=expected_logs) self.assertEqual(success, False) def test_test_failure(self): @@ -382,7 +384,7 @@ command_failed: failure_message='Patch does not pass tests' script_error='MOCK t GoldenScriptError("MOCK test failure"), ScriptError("MOCK test failure again"), ]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -401,7 +403,7 @@ archive_last_test_results: patch='10000' run_webkit_patch: ['build-and-test', '--force-clean', '--no-update', '--build', '--test', '--non-interactive'] command_passed: success_message='Able to pass tests without patch' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr, GoldenScriptError) + self._run_through_task(commit_queue, expected_logs, GoldenScriptError) def test_red_test_failure(self): commit_queue = FailingTestCommitQueue([ @@ -421,7 +423,7 @@ command_passed: success_message='Able to pass tests without patch' patch='10000' # Tests always fail, and always return the same results, but we # should still be able to land in this case! - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -442,7 +444,7 @@ command_failed: failure_message='Unable to pass tests without patch (tree is red run_webkit_patch: ['land-attachment', '--force-clean', '--non-interactive', '--parent-command=commit-queue', 10000] command_passed: success_message='Landed patch' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr) + self._run_through_task(commit_queue, expected_logs) def test_very_red_tree_retry(self): lots_of_failing_tests = map(lambda num: "test-%s.html" % num, range(0, 100)) @@ -464,7 +466,7 @@ command_passed: success_message='Landed patch' patch='10000' # Tests always fail, and return so many failures that we do not # trust the results (see ExpectedFailures._can_trust_results) so we # just give up and retry the patch. - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -483,7 +485,7 @@ archive_last_test_results: patch='10000' run_webkit_patch: ['build-and-test', '--force-clean', '--no-update', '--build', '--test', '--non-interactive'] command_failed: failure_message='Unable to pass tests without patch (tree is red?)' script_error='MOCK clean test failure' patch='10000' """ - self._run_through_task(commit_queue, expected_stderr, expect_retry=True) + self._run_through_task(commit_queue, expected_logs, expect_retry=True) def test_red_tree_patch_rejection(self): commit_queue = FailingTestCommitQueue([ @@ -503,7 +505,7 @@ command_failed: failure_message='Unable to pass tests without patch (tree is red # Tests always fail, but the clean tree only fails one test # while the patch fails two. So we should reject the patch! - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -522,7 +524,7 @@ archive_last_test_results: patch='10000' run_webkit_patch: ['build-and-test', '--force-clean', '--no-update', '--build', '--test', '--non-interactive'] command_failed: failure_message='Unable to pass tests without patch (tree is red?)' script_error='MOCK clean test failure' patch='10000' """ - task = self._run_through_task(commit_queue, expected_stderr, GoldenScriptError) + task = self._run_through_task(commit_queue, expected_logs, GoldenScriptError) self.assertEqual(task.results_from_patch_test_run(task._patch).failing_tests(), ["foo.html", "bar.html"]) # failure_status_id should be of the test with patch (1), not the test without patch (2). self.assertEqual(task.failure_status_id, 1) @@ -537,7 +539,7 @@ command_failed: failure_message='Unable to pass tests without patch (tree is red None, GoldenScriptError("MOCK land failure"), ]) - expected_stderr = """run_webkit_patch: ['clean'] + expected_logs = """run_webkit_patch: ['clean'] command_passed: success_message='Cleaned working directory' patch='10000' run_webkit_patch: ['update'] command_passed: success_message='Updated working directory' patch='10000' @@ -553,7 +555,7 @@ run_webkit_patch: ['land-attachment', '--force-clean', '--non-interactive', '--p command_failed: failure_message='Unable to land patch' script_error='MOCK land failure' patch='10000' """ # FIXME: This should really be expect_retry=True for a better user experiance. - self._run_through_task(commit_queue, expected_stderr, GoldenScriptError) + self._run_through_task(commit_queue, expected_logs, GoldenScriptError) def _expect_validate(self, patch, is_valid): class MockDelegate(object): diff --git a/Tools/Scripts/webkitpy/tool/bot/feeders.py b/Tools/Scripts/webkitpy/tool/bot/feeders.py index 4ba2f0485..f4bc4b927 100644 --- a/Tools/Scripts/webkitpy/tool/bot/feeders.py +++ b/Tools/Scripts/webkitpy/tool/bot/feeders.py @@ -26,10 +26,13 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.common.config.committervalidator import CommitterValidator -from webkitpy.common.system.deprecated_logging import log from webkitpy.tool.grammar import pluralize +_log = logging.getLogger(__name__) + class AbstractFeeder(object): def __init__(self, tool): @@ -50,7 +53,7 @@ class CommitQueueFeeder(AbstractFeeder): # FIXME: This is the last use of update_work_items, the commit-queue # should move to feeding patches one at a time like the EWS does. self._tool.status_server.update_work_items(self.queue_name, item_ids) - log("Feeding %s items %s" % (self.queue_name, item_ids)) + _log.info("Feeding %s items %s" % (self.queue_name, item_ids)) def feed(self): patches = self._validate_patches() @@ -89,7 +92,7 @@ class EWSFeeder(AbstractFeeder): def feed(self): ids_needing_review = set(self._tool.bugs.queries.fetch_attachment_ids_from_review_queue()) new_ids = ids_needing_review.difference(self._ids_sent_to_server) - log("Feeding EWS (%s, %s new)" % (pluralize("r? patch", len(ids_needing_review)), len(new_ids))) + _log.info("Feeding EWS (%s, %s new)" % (pluralize("r? patch", len(ids_needing_review)), len(new_ids))) for attachment_id in new_ids: # Order doesn't really matter for the EWS. self._tool.status_server.submit_to_ews(attachment_id) self._ids_sent_to_server.add(attachment_id) diff --git a/Tools/Scripts/webkitpy/tool/bot/feeders_unittest.py b/Tools/Scripts/webkitpy/tool/bot/feeders_unittest.py index 060a5c85b..9d0b71408 100644 --- a/Tools/Scripts/webkitpy/tool/bot/feeders_unittest.py +++ b/Tools/Scripts/webkitpy/tool/bot/feeders_unittest.py @@ -38,7 +38,7 @@ from webkitpy.tool.mocktool import MockTool class FeedersTest(unittest.TestCase): def test_commit_queue_feeder(self): feeder = CommitQueueFeeder(MockTool()) - expected_stderr = u"""Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com) + expected_logs = """Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com) Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com) MOCK setting flag 'commit-queue' to '-' on attachment '10001' with comment 'Rejecting attachment 10001 from commit-queue.' and additional comment 'non-committer@example.com does not have committer permissions according to http://trac.webkit.org/browser/trunk/Tools/Scripts/webkitpy/common/config/committers.py. @@ -48,7 +48,7 @@ MOCK setting flag 'commit-queue' to '-' on attachment '10001' with comment 'Reje MOCK: update_work_items: commit-queue [10005, 10000] Feeding commit-queue items [10005, 10000] """ - OutputCapture().assert_outputs(self, feeder.feed, expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, feeder.feed, expected_logs=expected_logs) def _mock_attachment(self, is_rollout, attach_date): attachment = Mock() diff --git a/Tools/Scripts/webkitpy/tool/bot/flakytestreporter_unittest.py b/Tools/Scripts/webkitpy/tool/bot/flakytestreporter_unittest.py index eeb06c3af..48c511281 100644 --- a/Tools/Scripts/webkitpy/tool/bot/flakytestreporter_unittest.py +++ b/Tools/Scripts/webkitpy/tool/bot/flakytestreporter_unittest.py @@ -70,7 +70,7 @@ class FlakyTestReporterTest(unittest.TestCase): def test_create_bug_for_flaky_test(self): reporter = FlakyTestReporter(MockTool(), 'dummy-queue') - expected_stderr = """MOCK create_bug + expected_logs = """MOCK create_bug bug_title: Flaky Test: foo/bar.html bug_description: This is an automatically generated bug from the dummy-queue. foo/bar.html has been flaky on the dummy-queue. @@ -90,7 +90,7 @@ component: Tools / Tests cc: test@test.com blocked: 50856 """ - OutputCapture().assert_outputs(self, reporter._create_bug_for_flaky_test, ['foo/bar.html', ['test@test.com'], 'FLAKE_MESSAGE'], expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, reporter._create_bug_for_flaky_test, ['foo/bar.html', ['test@test.com'], 'FLAKE_MESSAGE'], expected_logs=expected_logs) def test_follow_duplicate_chain(self): tool = MockTool() @@ -105,7 +105,8 @@ blocked: 50856 reporter = FlakyTestReporter(tool, 'dummy-queue') reporter._lookup_bug_for_flaky_test = lambda bug_id: None patch = tool.bugs.fetch_attachment(10000) - expected_stderr = """MOCK create_bug + expected_logs = """Bug does not already exist for foo/bar.html, creating. +MOCK create_bug bug_title: Flaky Test: foo/bar.html bug_description: This is an automatically generated bug from the dummy-queue. foo/bar.html has been flaky on the dummy-queue. @@ -144,7 +145,7 @@ The dummy-queue is continuing to process your patch. def namelist(self): return ['foo/bar-diffs.txt'] - OutputCapture().assert_outputs(self, reporter.report_flaky_tests, [patch, test_results, MockZipFile()], expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, reporter.report_flaky_tests, [patch, test_results, MockZipFile()], expected_logs=expected_logs) def test_optional_author_string(self): reporter = FlakyTestReporter(MockTool(), 'dummy-queue') diff --git a/Tools/Scripts/webkitpy/tool/bot/irc_command_unittest.py b/Tools/Scripts/webkitpy/tool/bot/irc_command_unittest.py index 4abee6678..e307e6ea9 100644 --- a/Tools/Scripts/webkitpy/tool/bot/irc_command_unittest.py +++ b/Tools/Scripts/webkitpy/tool/bot/irc_command_unittest.py @@ -86,8 +86,8 @@ class IRCCommandTest(unittest.TestCase): rollout = Rollout() tool = MockTool() tool.executive = MockExecutive(should_log=True) - expected_stderr = "MOCK run_and_throw_if_fail: ['mock-update-webkit'], cwd=/mock-checkout\n" - OutputCapture().assert_outputs(self, rollout._update_working_copy, [tool], expected_stderr=expected_stderr) + expected_logs = "MOCK run_and_throw_if_fail: ['mock-update-webkit'], cwd=/mock-checkout\n" + OutputCapture().assert_outputs(self, rollout._update_working_copy, [tool], expected_logs=expected_logs) def test_rollout(self): rollout = Rollout() diff --git a/Tools/Scripts/webkitpy/tool/bot/ircbot_unittest.py b/Tools/Scripts/webkitpy/tool/bot/ircbot_unittest.py index ce9a76bda..f96b7b6b5 100644 --- a/Tools/Scripts/webkitpy/tool/bot/ircbot_unittest.py +++ b/Tools/Scripts/webkitpy/tool/bot/ircbot_unittest.py @@ -71,8 +71,8 @@ class IRCBotTest(unittest.TestCase): raise Exception("mock_exception") bot._parse_command_and_args = lambda request: (CommandWithException, []) - expected_stderr = 'MOCK: irc.post: Exception executing command: mock_exception\n' - OutputCapture().assert_outputs(self, bot.process_message, args=["mock_nick", "ignored message"], expected_stderr=expected_stderr) + expected_logs = 'MOCK: irc.post: Exception executing command: mock_exception\n' + OutputCapture().assert_outputs(self, bot.process_message, args=["mock_nick", "ignored message"], expected_logs=expected_logs) class CommandWithException(object): def execute(self, nick, args, tool, sheriff): @@ -84,80 +84,80 @@ class IRCBotTest(unittest.TestCase): def test_hi(self): random.seed(23324) - expected_stderr = 'MOCK: irc.post: "Only you can prevent forest fires." -- Smokey the Bear\n' - OutputCapture().assert_outputs(self, run, args=["hi"], expected_stderr=expected_stderr) + expected_logs = 'MOCK: irc.post: "Only you can prevent forest fires." -- Smokey the Bear\n' + OutputCapture().assert_outputs(self, run, args=["hi"], expected_logs=expected_logs) def test_help(self): - expected_stderr = "MOCK: irc.post: mock_nick: Available commands: create-bug, help, hi, restart, roll-chromium-deps, rollout, whois\n" - OutputCapture().assert_outputs(self, run, args=["help"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Available commands: create-bug, help, hi, restart, roll-chromium-deps, rollout, whois\n" + OutputCapture().assert_outputs(self, run, args=["help"], expected_logs=expected_logs) def test_restart(self): - expected_stderr = "MOCK: irc.post: Restarting...\n" - OutputCapture().assert_outputs(self, run, args=["restart"], expected_stderr=expected_stderr, expected_exception=TerminateQueue) + expected_logs = "MOCK: irc.post: Restarting...\n" + OutputCapture().assert_outputs(self, run, args=["restart"], expected_logs=expected_logs, expected_exception=TerminateQueue) def test_rollout(self): - expected_stderr = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" - OutputCapture().assert_outputs(self, run, args=["rollout 21654 This patch broke the world"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" + OutputCapture().assert_outputs(self, run, args=["rollout 21654 This patch broke the world"], expected_logs=expected_logs) def test_revert(self): - expected_stderr = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" - OutputCapture().assert_outputs(self, run, args=["revert 21654 This patch broke the world"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" + OutputCapture().assert_outputs(self, run, args=["revert 21654 This patch broke the world"], expected_logs=expected_logs) def test_roll_chromium_deps(self): - expected_stderr = "MOCK: irc.post: mock_nick: Rolling Chromium DEPS to r21654\nMOCK: irc.post: mock_nick: Created DEPS roll: http://example.com/36936\n" - OutputCapture().assert_outputs(self, run, args=["roll-chromium-deps 21654"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Rolling Chromium DEPS to r21654\nMOCK: irc.post: mock_nick: Created DEPS roll: http://example.com/36936\n" + OutputCapture().assert_outputs(self, run, args=["roll-chromium-deps 21654"], expected_logs=expected_logs) def test_roll_chromium_deps_to_lkgr(self): - expected_stderr = "MOCK: irc.post: mock_nick: Rolling Chromium DEPS to last-known good revision\nMOCK: irc.post: mock_nick: Created DEPS roll: http://example.com/36936\n" - OutputCapture().assert_outputs(self, run, args=["roll-chromium-deps"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Rolling Chromium DEPS to last-known good revision\nMOCK: irc.post: mock_nick: Created DEPS roll: http://example.com/36936\n" + OutputCapture().assert_outputs(self, run, args=["roll-chromium-deps"], expected_logs=expected_logs) def test_multi_rollout(self): - expected_stderr = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654, http://trac.webkit.org/changeset/21655, and http://trac.webkit.org/changeset/21656 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" - OutputCapture().assert_outputs(self, run, args=["rollout 21654 21655 21656 This 21654 patch broke the world"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654, http://trac.webkit.org/changeset/21655, and http://trac.webkit.org/changeset/21656 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" + OutputCapture().assert_outputs(self, run, args=["rollout 21654 21655 21656 This 21654 patch broke the world"], expected_logs=expected_logs) def test_rollout_with_r_in_svn_revision(self): - expected_stderr = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" - OutputCapture().assert_outputs(self, run, args=["rollout r21654 This patch broke the world"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" + OutputCapture().assert_outputs(self, run, args=["rollout r21654 This patch broke the world"], expected_logs=expected_logs) def test_multi_rollout_with_r_in_svn_revision(self): - expected_stderr = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654, http://trac.webkit.org/changeset/21655, and http://trac.webkit.org/changeset/21656 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" - OutputCapture().assert_outputs(self, run, args=["rollout r21654 21655 r21656 This r21654 patch broke the world"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654, http://trac.webkit.org/changeset/21655, and http://trac.webkit.org/changeset/21656 ...\nMOCK: irc.post: mock_nick, abarth, darin, eseidel: Created rollout: http://example.com/36936\n" + OutputCapture().assert_outputs(self, run, args=["rollout r21654 21655 r21656 This r21654 patch broke the world"], expected_logs=expected_logs) def test_rollout_bananas(self): - expected_stderr = "MOCK: irc.post: mock_nick: Usage: rollout SVN_REVISION [SVN_REVISIONS] REASON\n" - OutputCapture().assert_outputs(self, run, args=["rollout bananas"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Usage: rollout SVN_REVISION [SVN_REVISIONS] REASON\n" + OutputCapture().assert_outputs(self, run, args=["rollout bananas"], expected_logs=expected_logs) def test_rollout_invalidate_revision(self): # When folks pass junk arguments, we should just spit the usage back at them. - expected_stderr = "MOCK: irc.post: mock_nick: Usage: rollout SVN_REVISION [SVN_REVISIONS] REASON\n" + expected_logs = "MOCK: irc.post: mock_nick: Usage: rollout SVN_REVISION [SVN_REVISIONS] REASON\n" OutputCapture().assert_outputs(self, run, args=["rollout --component=Tools 21654"], - expected_stderr=expected_stderr) + expected_logs=expected_logs) def test_rollout_invalidate_reason(self): # FIXME: I'm slightly confused as to why this doesn't return the USAGE message. - expected_stderr = """MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654 ... + expected_logs = """MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654 ... MOCK: irc.post: mock_nick, abarth, darin, eseidel: Failed to create rollout patch: MOCK: irc.post: The rollout reason may not begin with - (\"-bad (Requested by mock_nick on #webkit).\"). """ OutputCapture().assert_outputs(self, run, args=["rollout 21654 -bad"], - expected_stderr=expected_stderr) + expected_logs=expected_logs) def test_multi_rollout_invalidate_reason(self): - expected_stderr = """MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654, http://trac.webkit.org/changeset/21655, and http://trac.webkit.org/changeset/21656 ... + expected_logs = """MOCK: irc.post: mock_nick: Preparing rollout for http://trac.webkit.org/changeset/21654, http://trac.webkit.org/changeset/21655, and http://trac.webkit.org/changeset/21656 ... MOCK: irc.post: mock_nick, abarth, darin, eseidel: Failed to create rollout patch: MOCK: irc.post: The rollout reason may not begin with - (\"-bad (Requested by mock_nick on #webkit).\"). """ OutputCapture().assert_outputs(self, run, args=["rollout " "21654 21655 r21656 -bad"], - expected_stderr=expected_stderr) + expected_logs=expected_logs) def test_rollout_no_reason(self): - expected_stderr = "MOCK: irc.post: mock_nick: Usage: rollout SVN_REVISION [SVN_REVISIONS] REASON\n" - OutputCapture().assert_outputs(self, run, args=["rollout 21654"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Usage: rollout SVN_REVISION [SVN_REVISIONS] REASON\n" + OutputCapture().assert_outputs(self, run, args=["rollout 21654"], expected_logs=expected_logs) def test_multi_rollout_no_reason(self): - expected_stderr = "MOCK: irc.post: mock_nick: Usage: rollout SVN_REVISION [SVN_REVISIONS] REASON\n" - OutputCapture().assert_outputs(self, run, args=["rollout 21654 21655 r21656"], expected_stderr=expected_stderr) + expected_logs = "MOCK: irc.post: mock_nick: Usage: rollout SVN_REVISION [SVN_REVISIONS] REASON\n" + OutputCapture().assert_outputs(self, run, args=["rollout 21654 21655 r21656"], expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/bot/layouttestresultsreader.py b/Tools/Scripts/webkitpy/tool/bot/layouttestresultsreader.py index 94a70b2bc..4e09f896f 100644 --- a/Tools/Scripts/webkitpy/tool/bot/layouttestresultsreader.py +++ b/Tools/Scripts/webkitpy/tool/bot/layouttestresultsreader.py @@ -26,11 +26,14 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.common.net.layouttestresults import LayoutTestResults from webkitpy.common.net.unittestresults import UnitTestResults -from webkitpy.common.system.deprecated_logging import error, log from webkitpy.tool.steps.runtests import RunTests +_log = logging.getLogger(__name__) + class LayoutTestResultsReader(object): def __init__(self, tool, archive_directory): @@ -92,7 +95,7 @@ class LayoutTestResultsReader(object): if not zip_path: return None if not self._tool.filesystem.isdir(results_directory): - log("%s does not exist, not archiving." % results_directory) + _log.info("%s does not exist, not archiving." % results_directory) return None archive = self._tool.workspace.create_zip(zip_path, results_directory) # Remove the results directory to prevent http logs, etc. from getting huge between runs. diff --git a/Tools/Scripts/webkitpy/tool/bot/layouttestresultsreader_unittest.py b/Tools/Scripts/webkitpy/tool/bot/layouttestresultsreader_unittest.py index 96e2e4eef..6079632bd 100644 --- a/Tools/Scripts/webkitpy/tool/bot/layouttestresultsreader_unittest.py +++ b/Tools/Scripts/webkitpy/tool/bot/layouttestresultsreader_unittest.py @@ -91,8 +91,8 @@ class LayoutTestResultsReaderTest(unittest.TestCase): patch = tool.bugs.fetch_attachment(10001) tool.filesystem = MockFileSystem() # Should fail because the results_directory does not exist. - expected_stderr = "/mock-results does not exist, not archiving.\n" - archive = OutputCapture().assert_outputs(self, reader.archive, [patch], expected_stderr=expected_stderr) + expected_logs = "/mock-results does not exist, not archiving.\n" + archive = OutputCapture().assert_outputs(self, reader.archive, [patch], expected_logs=expected_logs) self.assertEqual(archive, None) results_directory = "/mock-results" diff --git a/Tools/Scripts/webkitpy/tool/bot/queueengine.py b/Tools/Scripts/webkitpy/tool/bot/queueengine.py index 1d7535967..0d2c97820 100644 --- a/Tools/Scripts/webkitpy/tool/bot/queueengine.py +++ b/Tools/Scripts/webkitpy/tool/bot/queueengine.py @@ -27,13 +27,16 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging import sys import traceback from datetime import datetime, timedelta from webkitpy.common.system.executive import ScriptError -from webkitpy.common.system.deprecated_logging import log, OutputTee +from webkitpy.common.system.deprecated_logging import OutputTee + +_log = logging.getLogger(__name__) # FIXME: This will be caught by "except Exception:" blocks, we should consider @@ -80,7 +83,7 @@ class QueueEngine: # Child processes exit with a special code to the parent queue process can detect the error was handled. @classmethod def exit_after_handled_error(cls, error): - log(error) + _log.error(error) sys.exit(cls.handled_error_code) def run(self): @@ -100,7 +103,7 @@ class QueueEngine: self._open_work_log(work_item) try: if not self._delegate.process_work_item(work_item): - log("Unable to process work item.") + _log.warning("Unable to process work item.") continue except ScriptError, e: # Use a special exit code to indicate that the error was already @@ -123,7 +126,7 @@ class QueueEngine: return 0 def _stopping(self, message): - log("\n%s" % message) + _log.info("\n%s" % message) self._delegate.stop_work_queue(message) # Be careful to shut down our OutputTee or the unit tests will be unhappy. self._ensure_work_log_closed() @@ -154,6 +157,6 @@ class QueueEngine: return "%s Sleeping until %s (%s)." % (message, wake_time.strftime(self.log_date_format), self.sleep_duration_text) def _sleep(self, message): - log(self._sleep_message(message)) + _log.info(self._sleep_message(message)) self._wakeup_event.wait(self.seconds_to_sleep) self._wakeup_event.clear() diff --git a/Tools/Scripts/webkitpy/tool/bot/queueengine_unittest.py b/Tools/Scripts/webkitpy/tool/bot/queueengine_unittest.py index 26789ef05..0ee8b5ad8 100644 --- a/Tools/Scripts/webkitpy/tool/bot/queueengine_unittest.py +++ b/Tools/Scripts/webkitpy/tool/bot/queueengine_unittest.py @@ -145,8 +145,8 @@ class QueueEngineTest(unittest.TestCase): engine = QueueEngine("test-queue", delegate, threading.Event()) if not termination_message: termination_message = "Delegate terminated queue." - expected_stderr = "\n%s\n" % termination_message - OutputCapture().assert_outputs(self, engine.run, expected_stderr=expected_stderr) + expected_logs = "\n%s\n" % termination_message + OutputCapture().assert_outputs(self, engine.run, expected_logs=expected_logs) def _test_terminating_queue(self, exception, termination_message): work_item_index = LoggingDelegate.expected_callbacks.index('process_work_item') diff --git a/Tools/Scripts/webkitpy/tool/bot/sheriff.py b/Tools/Scripts/webkitpy/tool/bot/sheriff.py index a8c928c9b..b4e95aec0 100644 --- a/Tools/Scripts/webkitpy/tool/bot/sheriff.py +++ b/Tools/Scripts/webkitpy/tool/bot/sheriff.py @@ -27,7 +27,6 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from webkitpy.common.config import urls -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.system.executive import ScriptError from webkitpy.tool.grammar import join_with_separators diff --git a/Tools/Scripts/webkitpy/tool/bot/sheriff_unittest.py b/Tools/Scripts/webkitpy/tool/bot/sheriff_unittest.py index 3ff5082f6..02fc03608 100644 --- a/Tools/Scripts/webkitpy/tool/bot/sheriff_unittest.py +++ b/Tools/Scripts/webkitpy/tool/bot/sheriff_unittest.py @@ -65,7 +65,7 @@ class SheriffTest(unittest.TestCase): sheriff.post_blame_comment_on_bug(commit_info, builders, ["mock-test-1"]) sheriff.post_blame_comment_on_bug(commit_info, builders, ["mock-test-1", "mock-test-2"]) - expected_stderr = u"""MOCK bug comment: bug_id=1234, cc=['watcher@example.com'] + expected_logs = u"""MOCK bug comment: bug_id=1234, cc=['watcher@example.com'] --- Begin comment --- http://trac.webkit.org/changeset/4321 might have broken Foo and Bar --- End comment --- @@ -86,4 +86,4 @@ mock-test-2 --- End comment --- """ - OutputCapture().assert_outputs(self, run, expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, run, expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/commands/abstractsequencedcommand.py b/Tools/Scripts/webkitpy/tool/commands/abstractsequencedcommand.py index 5eaf249c5..0593f2cfc 100644 --- a/Tools/Scripts/webkitpy/tool/commands/abstractsequencedcommand.py +++ b/Tools/Scripts/webkitpy/tool/commands/abstractsequencedcommand.py @@ -26,11 +26,14 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.common.system.executive import ScriptError -from webkitpy.common.system.deprecated_logging import log from webkitpy.tool.commands.stepsequence import StepSequence from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand +_log = logging.getLogger(__name__) + class AbstractSequencedCommand(AbstractDeclarativeCommand): steps = None @@ -45,7 +48,7 @@ class AbstractSequencedCommand(AbstractDeclarativeCommand): try: state = self._prepare_state(options, args, tool) except ScriptError, e: - log(e.message_with_output()) + _log.error(e.message_with_output()) self._exit(e.exit_code or 2) self._sequence.run_and_handle_errors(tool, options, state) diff --git a/Tools/Scripts/webkitpy/tool/commands/applywatchlistlocal_unittest.py b/Tools/Scripts/webkitpy/tool/commands/applywatchlistlocal_unittest.py index 91818d1c2..e88a86fa5 100644 --- a/Tools/Scripts/webkitpy/tool/commands/applywatchlistlocal_unittest.py +++ b/Tools/Scripts/webkitpy/tool/commands/applywatchlistlocal_unittest.py @@ -33,18 +33,23 @@ from webkitpy.tool.commands.applywatchlistlocal import ApplyWatchListLocal class ApplyWatchListLocalTest(CommandsTest): def test_args_parsing(self): - expected_stderr = 'MockWatchList: determine_cc_and_messages\n' - self.assert_execute_outputs(ApplyWatchListLocal(), [''], expected_stderr=expected_stderr) + expected_logs = """MockWatchList: determine_cc_and_messages +No bug was updated because no id was given. +Result of watchlist: cc "abarth@webkit.org, eric@webkit.org, levin@chromium.org" messages "Message1. + +Message2." +""" + self.assert_execute_outputs(ApplyWatchListLocal(), [''], expected_logs=expected_logs) def test_args_parsing_with_bug(self): - expected_stderr = """MockWatchList: determine_cc_and_messages + expected_logs = """MockWatchList: determine_cc_and_messages MOCK bug comment: bug_id=50002, cc=set(['eric@webkit.org', 'levin@chromium.org', 'abarth@webkit.org']) --- Begin comment --- Message1. Message2. --- End comment ---\n\n""" - self.assert_execute_outputs(ApplyWatchListLocal(), ['50002'], expected_stderr=expected_stderr) + self.assert_execute_outputs(ApplyWatchListLocal(), ['50002'], expected_logs=expected_logs) def test_args_parsing_with_two_bugs(self): self._assertRaisesRegexp(Exception, 'Too many arguments given: 1234 5678', self.assert_execute_outputs, ApplyWatchListLocal(), ['1234', '5678']) diff --git a/Tools/Scripts/webkitpy/tool/commands/commandtest.py b/Tools/Scripts/webkitpy/tool/commands/commandtest.py index eea0a6156..65f45b58f 100644 --- a/Tools/Scripts/webkitpy/tool/commands/commandtest.py +++ b/Tools/Scripts/webkitpy/tool/commands/commandtest.py @@ -32,7 +32,7 @@ from webkitpy.tool.mocktool import MockOptions, MockTool class CommandsTest(TestCase): - def assert_execute_outputs(self, command, args=[], expected_stdout="", expected_stderr="", expected_exception=None, options=MockOptions(), tool=MockTool()): + def assert_execute_outputs(self, command, args=[], expected_stdout="", expected_stderr="", expected_exception=None, expected_logs=None, options=MockOptions(), tool=MockTool()): options.blocks = None options.cc = 'MOCK cc' options.component = 'MOCK component' @@ -45,4 +45,4 @@ class CommandsTest(TestCase): options.quiet = True options.reviewer = 'MOCK reviewer' command.bind_to_tool(tool) - OutputCapture().assert_outputs(self, command.execute, [options, args, tool], expected_stdout=expected_stdout, expected_stderr=expected_stderr, expected_exception=expected_exception) + OutputCapture().assert_outputs(self, command.execute, [options, args, tool], expected_stdout=expected_stdout, expected_stderr=expected_stderr, expected_exception=expected_exception, expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/commands/download.py b/Tools/Scripts/webkitpy/tool/commands/download.py index b3ee1239c..bdd780d2c 100644 --- a/Tools/Scripts/webkitpy/tool/commands/download.py +++ b/Tools/Scripts/webkitpy/tool/commands/download.py @@ -27,6 +27,8 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool import steps from webkitpy.common.checkout.changelog import ChangeLog @@ -37,7 +39,8 @@ from webkitpy.tool.commands.stepsequence import StepSequence from webkitpy.tool.comments import bug_comment_from_commit_text from webkitpy.tool.grammar import pluralize from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand -from webkitpy.common.system.deprecated_logging import error, log + +_log = logging.getLogger(__name__) class Clean(AbstractSequencedCommand): @@ -164,7 +167,7 @@ class AbstractPatchProcessingCommand(AbstractDeclarativeCommand): # It's nice to print out total statistics. bugs_to_patches = self._collect_patches_by_bug(patches) - log("Processing %s from %s." % (pluralize("patch", len(patches)), pluralize("bug", len(bugs_to_patches)))) + _log.info("Processing %s from %s." % (pluralize("patch", len(patches)), pluralize("bug", len(bugs_to_patches)))) for patch in patches: self._process_patch(patch, options, args, tool) @@ -199,13 +202,13 @@ class ProcessBugsMixin(object): all_patches = [] for bug_id in args: patches = tool.bugs.fetch_bug(bug_id).reviewed_patches() - log("%s found on bug %s." % (pluralize("reviewed patch", len(patches)), bug_id)) + _log.info("%s found on bug %s." % (pluralize("reviewed patch", len(patches)), bug_id)) all_patches += patches if not all_patches: - log("No reviewed patches found, looking for unreviewed patches.") + _log.info("No reviewed patches found, looking for unreviewed patches.") for bug_id in args: patches = tool.bugs.fetch_bug(bug_id).patches() - log("%s found on bug %s." % (pluralize("patch", len(patches)), bug_id)) + _log.info("%s found on bug %s." % (pluralize("patch", len(patches)), bug_id)) all_patches += patches return all_patches @@ -217,7 +220,7 @@ class ProcessURLsMixin(object): bug_id = urls.parse_bug_id(url) if bug_id: patches = tool.bugs.fetch_bug(bug_id).patches() - log("%s found on bug %s." % (pluralize("patch", len(patches)), bug_id)) + _log.info("%s found on bug %s." % (pluralize("patch", len(patches)), bug_id)) all_patches += patches attachment_id = urls.parse_attachment_id(url) @@ -370,9 +373,9 @@ class AbstractRolloutPrepCommand(AbstractSequencedCommand): # SheriffBot because the SheriffBot just greps the output # of create-rollout for bug URLs. It should do better # parsing instead. - log("Preparing rollout for bug %s." % commit_info.bug_id()) + _log.info("Preparing rollout for bug %s." % commit_info.bug_id()) else: - log("Unable to parse bug number from diff.") + _log.info("Unable to parse bug number from diff.") return commit_info def _prepare_state(self, options, args, tool): diff --git a/Tools/Scripts/webkitpy/tool/commands/download_unittest.py b/Tools/Scripts/webkitpy/tool/commands/download_unittest.py index b71f3daaf..14bf2ce5e 100644 --- a/Tools/Scripts/webkitpy/tool/commands/download_unittest.py +++ b/Tools/Scripts/webkitpy/tool/commands/download_unittest.py @@ -43,15 +43,15 @@ class AbstractRolloutPrepCommandTest(unittest.TestCase): command.bind_to_tool(tool) output = OutputCapture() - expected_stderr = "Preparing rollout for bug 50000.\n" - commit_info = output.assert_outputs(self, command._commit_info, [1234], expected_stderr=expected_stderr) + expected_logs = "Preparing rollout for bug 50000.\n" + commit_info = output.assert_outputs(self, command._commit_info, [1234], expected_logs=expected_logs) self.assertTrue(commit_info) mock_commit_info = Mock() mock_commit_info.bug_id = lambda: None tool._checkout.commit_info_for_revision = lambda revision: mock_commit_info - expected_stderr = "Unable to parse bug number from diff.\n" - commit_info = output.assert_outputs(self, command._commit_info, [1234], expected_stderr=expected_stderr) + expected_logs = "Unable to parse bug number from diff.\n" + commit_info = output.assert_outputs(self, command._commit_info, [1234], expected_logs=expected_logs) self.assertEqual(commit_info, mock_commit_info) def test_prepare_state(self): @@ -90,51 +90,71 @@ class DownloadCommandsTest(CommandsTest): return options def test_build(self): - expected_stderr = "Updating working directory\nBuilding WebKit\n" - self.assert_execute_outputs(Build(), [], options=self._default_options(), expected_stderr=expected_stderr) + expected_logs = "Updating working directory\nBuilding WebKit\n" + self.assert_execute_outputs(Build(), [], options=self._default_options(), expected_logs=expected_logs) def test_build_and_test(self): - expected_stderr = "Updating working directory\nBuilding WebKit\nRunning Python unit tests\nRunning Perl unit tests\nRunning JavaScriptCore tests\nRunning WebKit unit tests\nRunning run-webkit-tests\n" - self.assert_execute_outputs(BuildAndTest(), [], options=self._default_options(), expected_stderr=expected_stderr) + expected_logs = """Updating working directory +Building WebKit +Running Python unit tests +Running Perl unit tests +Running JavaScriptCore tests +Running WebKit unit tests +Running run-webkit-tests +""" + self.assert_execute_outputs(BuildAndTest(), [], options=self._default_options(), expected_logs=expected_logs) def test_apply_attachment(self): options = self._default_options() options.update = True options.local_commit = True - expected_stderr = "Updating working directory\nProcessing 1 patch from 1 bug.\nProcessing patch 10000 from bug 50000.\n" - self.assert_execute_outputs(ApplyAttachment(), [10000], options=options, expected_stderr=expected_stderr) + expected_logs = "Updating working directory\nProcessing 1 patch from 1 bug.\nProcessing patch 10000 from bug 50000.\n" + self.assert_execute_outputs(ApplyAttachment(), [10000], options=options, expected_logs=expected_logs) def test_apply_from_bug(self): options = self._default_options() options.update = True options.local_commit = True - expected_stderr = "Updating working directory\n0 reviewed patches found on bug 50001.\nNo reviewed patches found, looking for unreviewed patches.\n1 patch found on bug 50001.\nProcessing 1 patch from 1 bug.\nProcessing patch 10002 from bug 50001.\n" - self.assert_execute_outputs(ApplyFromBug(), [50001], options=options, expected_stderr=expected_stderr) + expected_logs = "Updating working directory\n0 reviewed patches found on bug 50001.\nNo reviewed patches found, looking for unreviewed patches.\n1 patch found on bug 50001.\nProcessing 1 patch from 1 bug.\nProcessing patch 10002 from bug 50001.\n" + self.assert_execute_outputs(ApplyFromBug(), [50001], options=options, expected_logs=expected_logs) - expected_stderr = "Updating working directory\n2 reviewed patches found on bug 50000.\nProcessing 2 patches from 1 bug.\nProcessing patch 10000 from bug 50000.\nProcessing patch 10001 from bug 50000.\n" - self.assert_execute_outputs(ApplyFromBug(), [50000], options=options, expected_stderr=expected_stderr) + expected_logs = "Updating working directory\n2 reviewed patches found on bug 50000.\nProcessing 2 patches from 1 bug.\nProcessing patch 10000 from bug 50000.\nProcessing patch 10001 from bug 50000.\n" + self.assert_execute_outputs(ApplyFromBug(), [50000], options=options, expected_logs=expected_logs) def test_apply_watch_list(self): - expected_stderr = """Processing 1 patch from 1 bug. + expected_logs = """Processing 1 patch from 1 bug. Updating working directory -MOCK run_and_throw_if_fail: ['mock-update-webkit'], cwd=/mock-checkout\nProcessing patch 10000 from bug 50000. +MOCK run_and_throw_if_fail: ['mock-update-webkit'], cwd=/mock-checkout +Processing patch 10000 from bug 50000. MockWatchList: determine_cc_and_messages +No bug was updated because no id was given. +Result of watchlist: cc "abarth@webkit.org, eric@webkit.org, levin@chromium.org" messages "Message1. + +Message2." """ - self.assert_execute_outputs(ApplyWatchList(), [10000], options=self._default_options(), expected_stderr=expected_stderr, tool=MockTool(log_executive=True)) + self.assert_execute_outputs(ApplyWatchList(), [10000], options=self._default_options(), expected_logs=expected_logs, tool=MockTool(log_executive=True)) def test_land(self): - expected_stderr = "Building WebKit\nRunning Python unit tests\nRunning Perl unit tests\nRunning JavaScriptCore tests\nRunning WebKit unit tests\nRunning run-webkit-tests\nCommitted r49824: <http://trac.webkit.org/changeset/49824>\nUpdating bug 50000\n" + expected_logs = """Building WebKit +Running Python unit tests +Running Perl unit tests +Running JavaScriptCore tests +Running WebKit unit tests +Running run-webkit-tests +Committed r49824: <http://trac.webkit.org/changeset/49824> +Updating bug 50000 +""" mock_tool = MockTool() mock_tool.scm().create_patch = Mock(return_value="Patch1\nMockPatch\n") mock_tool.checkout().modified_changelogs = Mock(return_value=[]) - self.assert_execute_outputs(Land(), [50000], options=self._default_options(), expected_stderr=expected_stderr, tool=mock_tool) + self.assert_execute_outputs(Land(), [50000], options=self._default_options(), expected_logs=expected_logs, tool=mock_tool) # Make sure we're not calling expensive calls too often. self.assertEqual(mock_tool.scm().create_patch.call_count, 0) self.assertEqual(mock_tool.checkout().modified_changelogs.call_count, 1) def test_land_cowboy(self): - expected_stderr = """MOCK run_and_throw_if_fail: ['mock-prepare-ChangeLog', '--email=MOCK email', '--merge-base=None', 'MockFile1'], cwd=/mock-checkout + expected_logs = """MOCK run_and_throw_if_fail: ['mock-prepare-ChangeLog', '--email=MOCK email', '--merge-base=None', 'MockFile1'], cwd=/mock-checkout MOCK run_and_throw_if_fail: ['mock-check-webkit-style', '--git-commit', 'MOCK git commit', '--diff-files', 'MockFile1', '--filter', '-changelog'], cwd=/mock-checkout MOCK run_command: ['ruby', '-I', '/mock-checkout/Websites/bugs.webkit.org/PrettyPatch', '/mock-checkout/Websites/bugs.webkit.org/PrettyPatch/prettify.rb'], cwd=None, input=Patch1 MOCK: user.open_url: file://... @@ -156,30 +176,38 @@ Committed r49824: <http://trac.webkit.org/changeset/49824> No bug id provided. """ mock_tool = MockTool(log_executive=True) - self.assert_execute_outputs(LandCowboy(), [50000], options=self._default_options(), expected_stderr=expected_stderr, tool=mock_tool) + self.assert_execute_outputs(LandCowboy(), [50000], options=self._default_options(), expected_logs=expected_logs, tool=mock_tool) def test_land_red_builders(self): - expected_stderr = 'Building WebKit\nRunning Python unit tests\nRunning Perl unit tests\nRunning JavaScriptCore tests\nRunning WebKit unit tests\nRunning run-webkit-tests\nCommitted r49824: <http://trac.webkit.org/changeset/49824>\nUpdating bug 50000\n' + expected_logs = """Building WebKit +Running Python unit tests +Running Perl unit tests +Running JavaScriptCore tests +Running WebKit unit tests +Running run-webkit-tests +Committed r49824: <http://trac.webkit.org/changeset/49824> +Updating bug 50000 +""" mock_tool = MockTool() mock_tool.buildbot.light_tree_on_fire() - self.assert_execute_outputs(Land(), [50000], options=self._default_options(), expected_stderr=expected_stderr, tool=mock_tool) + self.assert_execute_outputs(Land(), [50000], options=self._default_options(), expected_logs=expected_logs, tool=mock_tool) def test_check_style(self): - expected_stderr = """Processing 1 patch from 1 bug. + expected_logs = """Processing 1 patch from 1 bug. Updating working directory MOCK run_and_throw_if_fail: ['mock-update-webkit'], cwd=/mock-checkout Processing patch 10000 from bug 50000. MOCK run_and_throw_if_fail: ['mock-check-webkit-style', '--git-commit', 'MOCK git commit', '--diff-files', 'MockFile1'], cwd=/mock-checkout """ - self.assert_execute_outputs(CheckStyle(), [10000], options=self._default_options(), expected_stderr=expected_stderr, tool=MockTool(log_executive=True)) + self.assert_execute_outputs(CheckStyle(), [10000], options=self._default_options(), expected_logs=expected_logs, tool=MockTool(log_executive=True)) def test_build_attachment(self): - expected_stderr = "Processing 1 patch from 1 bug.\nUpdating working directory\nProcessing patch 10000 from bug 50000.\nBuilding WebKit\n" - self.assert_execute_outputs(BuildAttachment(), [10000], options=self._default_options(), expected_stderr=expected_stderr) + expected_logs = "Processing 1 patch from 1 bug.\nUpdating working directory\nProcessing patch 10000 from bug 50000.\nBuilding WebKit\n" + self.assert_execute_outputs(BuildAttachment(), [10000], options=self._default_options(), expected_logs=expected_logs) def test_land_attachment(self): # FIXME: This expected result is imperfect, notice how it's seeing the same patch as still there after it thought it would have cleared the flags. - expected_stderr = """Processing 1 patch from 1 bug. + expected_logs = """Processing 1 patch from 1 bug. Updating working directory Processing patch 10000 from bug 50000. Building WebKit @@ -191,11 +219,11 @@ Running run-webkit-tests Committed r49824: <http://trac.webkit.org/changeset/49824> Not closing bug 50000 as attachment 10000 has review=+. Assuming there are more patches to land from this bug. """ - self.assert_execute_outputs(LandAttachment(), [10000], options=self._default_options(), expected_stderr=expected_stderr) + self.assert_execute_outputs(LandAttachment(), [10000], options=self._default_options(), expected_logs=expected_logs) def test_land_from_bug(self): # FIXME: This expected result is imperfect, notice how it's seeing the same patch as still there after it thought it would have cleared the flags. - expected_stderr = """2 reviewed patches found on bug 50000. + expected_logs = """2 reviewed patches found on bug 50000. Processing 2 patches from 1 bug. Updating working directory Processing patch 10000 from bug 50000. @@ -218,11 +246,11 @@ Running run-webkit-tests Committed r49824: <http://trac.webkit.org/changeset/49824> Not closing bug 50000 as attachment 10000 has review=+. Assuming there are more patches to land from this bug. """ - self.assert_execute_outputs(LandFromBug(), [50000], options=self._default_options(), expected_stderr=expected_stderr) + self.assert_execute_outputs(LandFromBug(), [50000], options=self._default_options(), expected_logs=expected_logs) def test_land_from_url(self): # FIXME: This expected result is imperfect, notice how it's seeing the same patch as still there after it thought it would have cleared the flags. - expected_stderr = """2 patches found on bug 50000. + expected_logs = """2 patches found on bug 50000. Processing 2 patches from 1 bug. Updating working directory Processing patch 10000 from bug 50000. @@ -245,14 +273,14 @@ Running run-webkit-tests Committed r49824: <http://trac.webkit.org/changeset/49824> Not closing bug 50000 as attachment 10000 has review=+. Assuming there are more patches to land from this bug. """ - self.assert_execute_outputs(LandFromURL(), ["https://bugs.webkit.org/show_bug.cgi?id=50000"], options=self._default_options(), expected_stderr=expected_stderr) + self.assert_execute_outputs(LandFromURL(), ["https://bugs.webkit.org/show_bug.cgi?id=50000"], options=self._default_options(), expected_logs=expected_logs) def test_prepare_rollout(self): - expected_stderr = "Preparing rollout for bug 50000.\nUpdating working directory\n" - self.assert_execute_outputs(PrepareRollout(), [852, "Reason"], options=self._default_options(), expected_stderr=expected_stderr) + expected_logs = "Preparing rollout for bug 50000.\nUpdating working directory\n" + self.assert_execute_outputs(PrepareRollout(), [852, "Reason"], options=self._default_options(), expected_logs=expected_logs) def test_create_rollout(self): - expected_stderr = """Preparing rollout for bug 50000. + expected_logs = """Preparing rollout for bug 50000. Updating working directory MOCK create_bug bug_title: REGRESSION(r852): Reason @@ -272,11 +300,11 @@ If you would like to land the rollout faster, you can use the following command: where ATTACHMENT_ID is the ID of this attachment. -- End comment -- """ - self.assert_execute_outputs(CreateRollout(), [852, "Reason"], options=self._default_options(), expected_stderr=expected_stderr) - self.assert_execute_outputs(CreateRollout(), ["855 852 854", "Reason"], options=self._default_options(), expected_stderr=expected_stderr) + self.assert_execute_outputs(CreateRollout(), [852, "Reason"], options=self._default_options(), expected_logs=expected_logs) + self.assert_execute_outputs(CreateRollout(), ["855 852 854", "Reason"], options=self._default_options(), expected_logs=expected_logs) def test_create_rollout_resolved(self): - expected_stderr = """Preparing rollout for bug 50004. + expected_logs = """Preparing rollout for bug 50004. Updating working directory MOCK create_bug bug_title: REGRESSION(r3001): Reason @@ -297,10 +325,10 @@ If you would like to land the rollout faster, you can use the following command: where ATTACHMENT_ID is the ID of this attachment. -- End comment -- """ - self.assert_execute_outputs(CreateRollout(), [3001, "Reason"], options=self._default_options(), expected_stderr=expected_stderr) + self.assert_execute_outputs(CreateRollout(), [3001, "Reason"], options=self._default_options(), expected_logs=expected_logs) def test_rollout(self): - expected_stderr = """Preparing rollout for bug 50000. + expected_logs = """Preparing rollout for bug 50000. Updating working directory MOCK: user.open_url: file://... Was that diff correct? @@ -312,5 +340,5 @@ Reason Committed r49824: <http://trac.webkit.org/changeset/49824>' """ - self.assert_execute_outputs(Rollout(), [852, "Reason"], options=self._default_options(), expected_stderr=expected_stderr) + self.assert_execute_outputs(Rollout(), [852, "Reason"], options=self._default_options(), expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/commands/earlywarningsystem.py b/Tools/Scripts/webkitpy/tool/commands/earlywarningsystem.py index 3ebdf390a..98a9a36ed 100644 --- a/Tools/Scripts/webkitpy/tool/commands/earlywarningsystem.py +++ b/Tools/Scripts/webkitpy/tool/commands/earlywarningsystem.py @@ -26,11 +26,11 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging from optparse import make_option from webkitpy.common.config.committers import CommitterList from webkitpy.common.config.ports import DeprecatedPort -from webkitpy.common.system.deprecated_logging import error, log from webkitpy.common.system.executive import ScriptError from webkitpy.tool.bot.earlywarningsystemtask import EarlyWarningSystemTask, EarlyWarningSystemTaskDelegate from webkitpy.tool.bot.expectedfailures import ExpectedFailures @@ -39,6 +39,8 @@ from webkitpy.tool.bot.patchanalysistask import UnableToApplyPatch from webkitpy.tool.bot.queueengine import QueueEngine from webkitpy.tool.commands.queues import AbstractReviewQueue +_log = logging.getLogger(__name__) + class AbstractEarlyWarningSystem(AbstractReviewQueue, EarlyWarningSystemTaskDelegate): _build_style = "release" @@ -135,7 +137,7 @@ class AbstractEarlyWarningSystem(AbstractReviewQueue, EarlyWarningSystemTaskDele @classmethod def handle_script_error(cls, tool, state, script_error): # FIXME: Why does this not exit(1) like the superclass does? - log(script_error.message_with_output()) + _log.error(script_error.message_with_output()) class GtkEWS(AbstractEarlyWarningSystem): diff --git a/Tools/Scripts/webkitpy/tool/commands/earlywarningsystem_unittest.py b/Tools/Scripts/webkitpy/tool/commands/earlywarningsystem_unittest.py index 7feff0d62..b33129a20 100644 --- a/Tools/Scripts/webkitpy/tool/commands/earlywarningsystem_unittest.py +++ b/Tools/Scripts/webkitpy/tool/commands/earlywarningsystem_unittest.py @@ -43,7 +43,7 @@ class AbstractEarlyWarningSystemTest(QueuesTest): ews = TestEWS() ews.bind_to_tool(MockTool()) ews._options = MockOptions(port=None, confirm=False) - OutputCapture().assert_outputs(self, ews.begin_work_queue, expected_stderr=self._default_begin_work_queue_stderr(ews.name)) + OutputCapture().assert_outputs(self, ews.begin_work_queue, expected_logs=self._default_begin_work_queue_logs(ews.name)) ews._expected_failures.unexpected_failures_observed = lambda results: set(["foo.html", "bar.html"]) task = Mock() patch = ews._tool.bugs.fetch_attachment(10000) @@ -51,33 +51,31 @@ class AbstractEarlyWarningSystemTest(QueuesTest): class EarlyWarningSytemTest(QueuesTest): - def _default_expected_stderr(self, ews): + def _default_expected_logs(self, ews): string_replacemnts = { "name": ews.name, "port": ews.port_name, } - expected_stderr = { - "begin_work_queue": self._default_begin_work_queue_stderr(ews.name), - "handle_unexpected_error": "Mock error message\n", - "next_work_item": "", + expected_logs = { + "begin_work_queue": self._default_begin_work_queue_logs(ews.name), "process_work_item": "MOCK: update_status: %(name)s Pass\nMOCK: release_work_item: %(name)s 10000\n" % string_replacemnts, + "handle_unexpected_error": "Mock error message\n", "handle_script_error": "ScriptError error message\n\nMOCK output\n", } - return expected_stderr + return expected_logs def _test_builder_ews(self, ews): ews.bind_to_tool(MockTool()) options = Mock() options.port = None options.run_tests = ews._default_run_tests - self.assert_queue_outputs(ews, expected_stderr=self._default_expected_stderr(ews), options=options) + self.assert_queue_outputs(ews, expected_logs=self._default_expected_logs(ews), options=options) def _test_testing_ews(self, ews): ews.test_results = lambda: None ews.bind_to_tool(MockTool()) - expected_stderr = self._default_expected_stderr(ews) - expected_stderr["handle_script_error"] = "ScriptError error message\n\nMOCK output\n" - self.assert_queue_outputs(ews, expected_stderr=expected_stderr) + expected_logs = self._default_expected_logs(ews) + self.assert_queue_outputs(ews, expected_logs=expected_logs) def test_builder_ewses(self): self._test_builder_ews(MacEWS()) diff --git a/Tools/Scripts/webkitpy/tool/commands/openbugs.py b/Tools/Scripts/webkitpy/tool/commands/openbugs.py index 1b51c9ff6..8c55aba14 100644 --- a/Tools/Scripts/webkitpy/tool/commands/openbugs.py +++ b/Tools/Scripts/webkitpy/tool/commands/openbugs.py @@ -26,11 +26,13 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging import re import sys from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class OpenBugs(AbstractDeclarativeCommand): @@ -58,6 +60,6 @@ class OpenBugs(AbstractDeclarativeCommand): # This won't open bugs until stdin is closed but could be made to easily. That would just make unit testing slightly harder. bug_ids = self._find_bugs_in_iterable(sys.stdin) - log("%s bugs found in input." % len(bug_ids)) + _log.info("%s bugs found in input." % len(bug_ids)) self._open_bugs(bug_ids) diff --git a/Tools/Scripts/webkitpy/tool/commands/openbugs_unittest.py b/Tools/Scripts/webkitpy/tool/commands/openbugs_unittest.py index 06dac1fd6..680e5142e 100644 --- a/Tools/Scripts/webkitpy/tool/commands/openbugs_unittest.py +++ b/Tools/Scripts/webkitpy/tool/commands/openbugs_unittest.py @@ -46,5 +46,5 @@ class OpenBugsTest(CommandsTest): self.assertEqual(openbugs._find_bugs_in_string(expectation[0]), expectation[1]) def test_args_parsing(self): - expected_stderr = "2 bugs found in input.\nMOCK: user.open_url: http://example.com/12345\nMOCK: user.open_url: http://example.com/23456\n" - self.assert_execute_outputs(OpenBugs(), ["12345\n23456"], expected_stderr=expected_stderr) + expected_logs = "2 bugs found in input.\nMOCK: user.open_url: http://example.com/12345\nMOCK: user.open_url: http://example.com/23456\n" + self.assert_execute_outputs(OpenBugs(), ["12345\n23456"], expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/commands/perfalizer.py b/Tools/Scripts/webkitpy/tool/commands/perfalizer.py index ae9f63a65..ed0e01548 100644 --- a/Tools/Scripts/webkitpy/tool/commands/perfalizer.py +++ b/Tools/Scripts/webkitpy/tool/commands/perfalizer.py @@ -26,7 +26,8 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -from webkitpy.common.system.deprecated_logging import log +import logging + from webkitpy.tool.bot.expectedfailures import ExpectedFailures from webkitpy.tool.bot.irc_command import IRCCommand from webkitpy.tool.bot.irc_command import Help @@ -38,6 +39,8 @@ from webkitpy.tool.bot.sheriff import Sheriff from webkitpy.tool.commands.queues import AbstractQueue from webkitpy.tool.commands.stepsequence import StepSequenceErrorHandler +_log = logging.getLogger(__name__) + class PerfalizerTask(PatchAnalysisTask): def __init__(self, tool, patch, logger): @@ -204,7 +207,7 @@ class Perfalizer(AbstractQueue, StepSequenceErrorHandler): return True def handle_unexpected_error(self, failure_map, message): - log(message) + _log.error(message) # StepSequenceErrorHandler methods diff --git a/Tools/Scripts/webkitpy/tool/commands/queries.py b/Tools/Scripts/webkitpy/tool/commands/queries.py index cbdb903ee..7cc846715 100644 --- a/Tools/Scripts/webkitpy/tool/commands/queries.py +++ b/Tools/Scripts/webkitpy/tool/commands/queries.py @@ -29,6 +29,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import fnmatch +import logging import re from datetime import datetime @@ -45,10 +46,11 @@ from webkitpy.common.system.crashlogs import CrashLogs from webkitpy.common.system.user import User from webkitpy.tool.grammar import pluralize from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand -from webkitpy.common.system.deprecated_logging import log from webkitpy.layout_tests.models.test_expectations import TestExpectations from webkitpy.layout_tests.port import platform_options, configuration_options +_log = logging.getLogger(__name__) + class SuggestReviewers(AbstractDeclarativeCommand): name = "suggest-reviewers" @@ -82,7 +84,7 @@ class PatchesInCommitQueue(AbstractDeclarativeCommand): def execute(self, options, args, tool): patches = tool.bugs.queries.fetch_patches_from_commit_queue() - log("Patches in commit queue:") + _log.info("Patches in commit queue:") for patch in patches: print patch.url() @@ -99,13 +101,13 @@ class PatchesToCommitQueue(AbstractDeclarativeCommand): @staticmethod def _needs_commit_queue(patch): if patch.commit_queue() == "+": # If it's already cq+, ignore the patch. - log("%s already has cq=%s" % (patch.id(), patch.commit_queue())) + _log.info("%s already has cq=%s" % (patch.id(), patch.commit_queue())) return False # We only need to worry about patches from contributers who are not yet committers. committer_record = CommitterList().committer_by_email(patch.attacher_email()) if committer_record: - log("%s committer = %s" % (patch.id(), committer_record)) + _log.info("%s committer = %s" % (patch.id(), committer_record)) return not committer_record def execute(self, options, args, tool): diff --git a/Tools/Scripts/webkitpy/tool/commands/queries_unittest.py b/Tools/Scripts/webkitpy/tool/commands/queries_unittest.py index ef1e0b387..b252c0b0e 100644 --- a/Tools/Scripts/webkitpy/tool/commands/queries_unittest.py +++ b/Tools/Scripts/webkitpy/tool/commands/queries_unittest.py @@ -65,24 +65,24 @@ class MockPortFactory(object): class QueryCommandsTest(CommandsTest): def test_bugs_to_commit(self): - expected_stderr = "Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com)\n" - self.assert_execute_outputs(BugsToCommit(), None, "50000\n50003\n", expected_stderr) + expected_logs = "Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com)\n" + self.assert_execute_outputs(BugsToCommit(), None, "50000\n50003\n", expected_logs=expected_logs) def test_patches_in_commit_queue(self): expected_stdout = "http://example.com/10000\nhttp://example.com/10002\n" - expected_stderr = "Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com)\nPatches in commit queue:\n" - self.assert_execute_outputs(PatchesInCommitQueue(), None, expected_stdout, expected_stderr) + expected_logs = "Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com)\nPatches in commit queue:\n" + self.assert_execute_outputs(PatchesInCommitQueue(), None, expected_stdout, expected_logs=expected_logs) def test_patches_to_commit_queue(self): expected_stdout = "http://example.com/10003&action=edit\n" - expected_stderr = "10000 already has cq=+\n10001 already has cq=+\n10004 committer = \"Eric Seidel\" <eric@webkit.org>\n" + expected_logs = "10000 already has cq=+\n10001 already has cq=+\n10004 committer = \"Eric Seidel\" <eric@webkit.org>\n" options = Mock() options.bugs = False - self.assert_execute_outputs(PatchesToCommitQueue(), None, expected_stdout, expected_stderr, options=options) + self.assert_execute_outputs(PatchesToCommitQueue(), None, expected_stdout, expected_logs=expected_logs, options=options) expected_stdout = "http://example.com/50003\n" options.bugs = True - self.assert_execute_outputs(PatchesToCommitQueue(), None, expected_stdout, expected_stderr, options=options) + self.assert_execute_outputs(PatchesToCommitQueue(), None, expected_stdout, expected_logs=expected_logs, options=options) def test_patches_to_review(self): options = Mock() diff --git a/Tools/Scripts/webkitpy/tool/commands/queues.py b/Tools/Scripts/webkitpy/tool/commands/queues.py index 62d429d88..edfbee402 100644 --- a/Tools/Scripts/webkitpy/tool/commands/queues.py +++ b/Tools/Scripts/webkitpy/tool/commands/queues.py @@ -28,6 +28,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import codecs +import logging import os import sys import time @@ -41,7 +42,6 @@ from webkitpy.common.config.committervalidator import CommitterValidator from webkitpy.common.config.ports import DeprecatedPort from webkitpy.common.net.bugzilla import Attachment from webkitpy.common.net.statusserver import StatusServer -from webkitpy.common.system.deprecated_logging import error, log from webkitpy.common.system.executive import ScriptError from webkitpy.tool.bot.botinfo import BotInfo from webkitpy.tool.bot.commitqueuetask import CommitQueueTask, CommitQueueTaskDelegate @@ -55,6 +55,8 @@ from webkitpy.tool.bot.stylequeuetask import StyleQueueTask, StyleQueueTaskDeleg from webkitpy.tool.commands.stepsequence import StepSequenceErrorHandler from webkitpy.tool.multicommandtool import Command, TryAgain +_log = logging.getLogger(__name__) + class AbstractQueue(Command, QueueEngineDelegate): watchers = [ @@ -78,7 +80,7 @@ class AbstractQueue(Command, QueueEngineDelegate): self._tool.bugs.add_cc_to_bug(bug_id, self.watchers) except Exception, e: traceback.print_exc() - log("Failed to CC watchers.") + _log.error("Failed to CC watchers.") def run_webkit_patch(self, args): webkit_patch_args = [self._tool.path()] @@ -111,12 +113,13 @@ class AbstractQueue(Command, QueueEngineDelegate): raise NotImplementedError, "subclasses must implement" def begin_work_queue(self): - log("CAUTION: %s will discard all local changes in \"%s\"" % (self.name, self._tool.scm().checkout_root)) + _log.info("CAUTION: %s will discard all local changes in \"%s\"" % (self.name, self._tool.scm().checkout_root)) if self._options.confirm: response = self._tool.user.prompt("Are you sure? Type \"yes\" to continue: ") if (response != "yes"): - error("User declined.") - log("Running WebKit %s." % self.name) + _log.error("User declined.") + sys.exit(1) + _log.info("Running WebKit %s." % self.name) self._tool.status_server.update_status(self.name, "Starting Queue") def stop_work_queue(self, reason): @@ -193,7 +196,7 @@ class FeederQueue(AbstractQueue): return None def handle_unexpected_error(self, work_item, message): - log(message) + _log.error(message) class AbstractPatchQueue(AbstractQueue): @@ -357,7 +360,7 @@ class CommitQueue(AbstractPatchQueue, StepSequenceErrorHandler, CommitQueueTaskD # Hitting this error handler should be pretty rare. It does occur, # however, when a patch no longer applies to top-of-tree in the final # land step. - log(script_error.message_with_output()) + _log.error(script_error.message_with_output()) @classmethod def handle_checkout_needs_update(cls, tool, state, options, error): @@ -405,13 +408,13 @@ class AbstractReviewQueue(AbstractPatchQueue, StepSequenceErrorHandler): raise e def handle_unexpected_error(self, patch, message): - log(message) + _log.error(message) # StepSequenceErrorHandler methods @classmethod def handle_script_error(cls, tool, state, script_error): - log(script_error.output) + _log.error(script_error.output) class StyleQueue(AbstractReviewQueue, StyleQueueTaskDelegate): diff --git a/Tools/Scripts/webkitpy/tool/commands/queues_unittest.py b/Tools/Scripts/webkitpy/tool/commands/queues_unittest.py index 88ab3de06..0a32f29be 100644 --- a/Tools/Scripts/webkitpy/tool/commands/queues_unittest.py +++ b/Tools/Scripts/webkitpy/tool/commands/queues_unittest.py @@ -130,9 +130,8 @@ class FeederQueueTest(QueuesTest): def test_feeder_queue(self): queue = TestFeederQueue() tool = MockTool(log_executive=True) - expected_stderr = { - "begin_work_queue": self._default_begin_work_queue_stderr("feeder-queue"), - "next_work_item": "", + expected_logs = { + "begin_work_queue": self._default_begin_work_queue_logs("feeder-queue"), "process_work_item": """Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com) Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com) MOCK setting flag 'commit-queue' to '-' on attachment '10001' with comment 'Rejecting attachment 10001 from commit-queue.' and additional comment 'non-committer@example.com does not have committer permissions according to http://trac.webkit.org/browser/trunk/Tools/Scripts/webkitpy/common/config/committers.py. @@ -147,7 +146,7 @@ MOCK: submit_to_ews: 10002 """, "handle_unexpected_error": "Mock error message\n", } - self.assert_queue_outputs(queue, tool=tool, expected_stderr=expected_stderr) + self.assert_queue_outputs(queue, tool=tool, expected_logs=expected_logs) class AbstractPatchQueueTest(CommandsTest): @@ -160,8 +159,8 @@ class AbstractPatchQueueTest(CommandsTest): self.assertEqual(queue._next_patch(), None) tool.status_server = MockStatusServer(work_items=[2, 10000, 10001]) expected_stdout = "MOCK: fetch_attachment: 2 is not a known attachment id\n" # A mock-only message to prevent us from making mistakes. - expected_stderr = "MOCK: release_work_item: None 2\n" - patch = OutputCapture().assert_outputs(self, queue._next_patch, expected_stdout=expected_stdout, expected_stderr=expected_stderr) + expected_logs = "MOCK: release_work_item: None 2\n" + patch = OutputCapture().assert_outputs(self, queue._next_patch, expected_stdout=expected_stdout, expected_logs=expected_logs) # The patch.id() == 2 is ignored because it doesn't exist. self.assertEqual(patch.id(), 10000) self.assertEqual(queue._next_patch().id(), 10001) @@ -175,13 +174,13 @@ class AbstractPatchQueueTest(CommandsTest): queue._options = Mock() queue._options.port = None patch = queue._tool.bugs.fetch_attachment(10001) - expected_stderr = """MOCK add_attachment_to_bug: bug_id=50000, description=Archive of layout-test-results from bot filename=layout-test-results.zip mimetype=None + expected_logs = """MOCK add_attachment_to_bug: bug_id=50000, description=Archive of layout-test-results from bot filename=layout-test-results.zip mimetype=None -- Begin comment -- The attached test failures were seen while running run-webkit-tests on the mock-queue. Port: MockPort Platform: MockPlatform 1.0 -- End comment -- """ - OutputCapture().assert_outputs(self, queue._upload_results_archive_for_patch, [patch, Mock()], expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, queue._upload_results_archive_for_patch, [patch, Mock()], expected_logs=expected_logs) class NeedsUpdateSequence(StepSequence): @@ -235,9 +234,8 @@ class CommitQueueTest(QueuesTest): tool = MockTool() tool.filesystem.write_text_file('/tmp/layout-test-results/full_results.json', '') # Otherwise the commit-queue will hit a KeyError trying to read the results from the MockFileSystem. tool.filesystem.write_text_file('/tmp/layout-test-results/webkit_unit_tests_output.xml', '') - expected_stderr = { - "begin_work_queue": self._default_begin_work_queue_stderr("commit-queue"), - "next_work_item": "", + expected_logs = { + "begin_work_queue": self._default_begin_work_queue_logs("commit-queue"), "process_work_item": """MOCK: update_status: commit-queue Cleaned working directory MOCK: update_status: commit-queue Updated working directory MOCK: update_status: commit-queue Applied patch @@ -248,15 +246,14 @@ MOCK: update_status: commit-queue Landed patch MOCK: update_status: commit-queue Pass MOCK: release_work_item: commit-queue 10000 """, - "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.' and additional comment 'Mock error message'\n", "handle_script_error": "ScriptError error message\n\nMOCK output\n", + "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.' and additional comment 'Mock error message'\n", } - self.assert_queue_outputs(CommitQueue(), tool=tool, expected_stderr=expected_stderr) + self.assert_queue_outputs(CommitQueue(), tool=tool, expected_logs=expected_logs) def test_commit_queue_failure(self): - expected_stderr = { - "begin_work_queue": self._default_begin_work_queue_stderr("commit-queue"), - "next_work_item": "", + expected_logs = { + "begin_work_queue": self._default_begin_work_queue_logs("commit-queue"), "process_work_item": """MOCK: update_status: commit-queue Cleaned working directory MOCK: update_status: commit-queue Updated working directory MOCK: update_status: commit-queue Patch does not apply @@ -265,8 +262,8 @@ Full output: http://dummy_url' MOCK: update_status: commit-queue Fail MOCK: release_work_item: commit-queue 10000 """, - "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.' and additional comment 'Mock error message'\n", "handle_script_error": "ScriptError error message\n\nMOCK output\n", + "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.' and additional comment 'Mock error message'\n", } queue = CommitQueue() @@ -278,12 +275,11 @@ MOCK: release_work_item: commit-queue 10000 raise ScriptError('MOCK script error') queue.run_webkit_patch = mock_run_webkit_patch - self.assert_queue_outputs(queue, expected_stderr=expected_stderr) + self.assert_queue_outputs(queue, expected_logs=expected_logs) def test_commit_queue_failure_with_failing_tests(self): - expected_stderr = { - "begin_work_queue": self._default_begin_work_queue_stderr("commit-queue"), - "next_work_item": "", + expected_logs = { + "begin_work_queue": self._default_begin_work_queue_logs("commit-queue"), "process_work_item": """MOCK: update_status: commit-queue Cleaned working directory MOCK: update_status: commit-queue Updated working directory MOCK: update_status: commit-queue Patch does not apply @@ -294,8 +290,8 @@ Full output: http://dummy_url' MOCK: update_status: commit-queue Fail MOCK: release_work_item: commit-queue 10000 """, - "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.' and additional comment 'Mock error message'\n", "handle_script_error": "ScriptError error message\n\nMOCK output\n", + "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.' and additional comment 'Mock error message'\n", } queue = CommitQueue() @@ -308,16 +304,15 @@ MOCK: release_work_item: commit-queue 10000 raise ScriptError('MOCK script error') queue.run_webkit_patch = mock_run_webkit_patch - self.assert_queue_outputs(queue, expected_stderr=expected_stderr) + self.assert_queue_outputs(queue, expected_logs=expected_logs) def test_rollout(self): tool = MockTool(log_executive=True) tool.filesystem.write_text_file('/tmp/layout-test-results/full_results.json', '') # Otherwise the commit-queue will hit a KeyError trying to read the results from the MockFileSystem. tool.filesystem.write_text_file('/tmp/layout-test-results/webkit_unit_tests_output.xml', '') tool.buildbot.light_tree_on_fire() - expected_stderr = { - "begin_work_queue": self._default_begin_work_queue_stderr("commit-queue"), - "next_work_item": "", + expected_logs = { + "begin_work_queue": self._default_begin_work_queue_logs("commit-queue"), "process_work_item": """MOCK run_and_throw_if_fail: ['echo', '--status-host=example.com', 'clean', '--port=%(port_name)s'], cwd=/mock-checkout MOCK: update_status: commit-queue Cleaned working directory MOCK run_and_throw_if_fail: ['echo', '--status-host=example.com', 'update', '--port=%(port_name)s'], cwd=/mock-checkout @@ -335,19 +330,18 @@ MOCK: update_status: commit-queue Landed patch MOCK: update_status: commit-queue Pass MOCK: release_work_item: commit-queue 10000 """ % {"port_name": CommitQueue.port_name}, - "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.' and additional comment 'Mock error message'\n", "handle_script_error": "ScriptError error message\n\nMOCK output\n", + "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10000' with comment 'Rejecting attachment 10000 from commit-queue.' and additional comment 'Mock error message'\n", } - self.assert_queue_outputs(CommitQueue(), tool=tool, expected_stderr=expected_stderr) + self.assert_queue_outputs(CommitQueue(), tool=tool, expected_logs=expected_logs) def test_rollout_lands(self): tool = MockTool(log_executive=True) tool.buildbot.light_tree_on_fire() rollout_patch = tool.bugs.fetch_attachment(10005) # _patch6, a rollout patch. assert(rollout_patch.is_rollout()) - expected_stderr = { - "begin_work_queue": self._default_begin_work_queue_stderr("commit-queue"), - "next_work_item": "", + expected_logs = { + "begin_work_queue": self._default_begin_work_queue_logs("commit-queue"), "process_work_item": """MOCK run_and_throw_if_fail: ['echo', '--status-host=example.com', 'clean', '--port=%(port_name)s'], cwd=/mock-checkout MOCK: update_status: commit-queue Cleaned working directory MOCK run_and_throw_if_fail: ['echo', '--status-host=example.com', 'update', '--port=%(port_name)s'], cwd=/mock-checkout @@ -361,10 +355,10 @@ MOCK: update_status: commit-queue Landed patch MOCK: update_status: commit-queue Pass MOCK: release_work_item: commit-queue 10005 """ % {"port_name": CommitQueue.port_name}, - "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10005' with comment 'Rejecting attachment 10005 from commit-queue.' and additional comment 'Mock error message'\n", "handle_script_error": "ScriptError error message\n\nMOCK output\n", + "handle_unexpected_error": "MOCK setting flag 'commit-queue' to '-' on attachment '10005' with comment 'Rejecting attachment 10005 from commit-queue.' and additional comment 'Mock error message'\n", } - self.assert_queue_outputs(CommitQueue(), tool=tool, work_item=rollout_patch, expected_stderr=expected_stderr) + self.assert_queue_outputs(CommitQueue(), tool=tool, work_item=rollout_patch, expected_logs=expected_logs) def test_auto_retry(self): queue = CommitQueue() @@ -373,9 +367,11 @@ MOCK: release_work_item: commit-queue 10005 tool = AlwaysCommitQueueTool() sequence = NeedsUpdateSequence(None) - expected_stderr = "Commit failed because the checkout is out of date. Please update and try again.\nMOCK: update_status: commit-queue Tests passed, but commit failed (checkout out of date). Updating, then landing without building or re-running tests.\n" + expected_logs = """Commit failed because the checkout is out of date. Please update and try again. +MOCK: update_status: commit-queue Tests passed, but commit failed (checkout out of date). Updating, then landing without building or re-running tests. +""" state = {'patch': None} - OutputCapture().assert_outputs(self, sequence.run_and_handle_errors, [tool, options, state], expected_exception=TryAgain, expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, sequence.run_and_handle_errors, [tool, options, state], expected_exception=TryAgain, expected_logs=expected_logs) self.assertEqual(options.update, True) self.assertEqual(options.build, False) @@ -388,7 +384,7 @@ MOCK: release_work_item: commit-queue 10005 queue._tool.filesystem.write_text_file('/tmp/layout-test-results/webkit_unit_tests_output.xml', '') queue._options = Mock() queue._options.port = None - expected_stderr = """MOCK: update_status: commit-queue Cleaned working directory + expected_logs = """MOCK: update_status: commit-queue Cleaned working directory MOCK: update_status: commit-queue Updated working directory MOCK: update_status: commit-queue Applied patch MOCK: update_status: commit-queue ChangeLog validated @@ -397,11 +393,11 @@ MOCK: update_status: commit-queue Passed tests MOCK: update_status: commit-queue Retry MOCK: release_work_item: commit-queue 10000 """ - OutputCapture().assert_outputs(self, queue.process_work_item, [QueuesTest.mock_work_item], expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, queue.process_work_item, [QueuesTest.mock_work_item], expected_logs=expected_logs) def test_report_flaky_tests(self): queue = TestCommitQueue(MockTool()) - expected_stderr = """MOCK bug comment: bug_id=50002, cc=None + expected_logs = """MOCK bug comment: bug_id=50002, cc=None --- Begin comment --- The commit-queue just saw foo/bar.html flake (text diff) while processing attachment 10000 on bug 50000. Port: MockPort Platform: MockPlatform 1.0 @@ -414,6 +410,7 @@ The commit-queue just saw bar/baz.html flake (text diff) while processing attach Port: MockPort Platform: MockPlatform 1.0 --- End comment --- +bar/baz-diffs.txt does not exist in results archive, uploading entire archive. MOCK add_attachment_to_bug: bug_id=50002, description=Archive of layout-test-results from bot filename=layout-test-results.zip mimetype=None MOCK bug comment: bug_id=50000, cc=None --- Begin comment --- @@ -439,7 +436,7 @@ The commit-queue is continuing to process your patch. # This is intentionally missing one diffs.txt to exercise the "upload the whole zip" codepath. return ['foo/bar-diffs.txt'] - OutputCapture().assert_outputs(self, queue.report_flaky_tests, [QueuesTest.mock_work_item, test_results, MockZipFile()], expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, queue.report_flaky_tests, [QueuesTest.mock_work_item, test_results, MockZipFile()], expected_logs=expected_logs) def test_did_pass_testing_ews(self): tool = MockTool() @@ -450,9 +447,8 @@ The commit-queue is continuing to process your patch. class StyleQueueTest(QueuesTest): def test_style_queue_with_style_exception(self): - expected_stderr = { - "begin_work_queue": self._default_begin_work_queue_stderr("style-queue"), - "next_work_item": "", + expected_logs = { + "begin_work_queue": self._default_begin_work_queue_logs("style-queue"), "process_work_item": """MOCK run_and_throw_if_fail: ['echo', '--status-host=example.com', 'clean'], cwd=/mock-checkout MOCK: update_status: style-queue Cleaned working directory MOCK run_and_throw_if_fail: ['echo', '--status-host=example.com', 'update'], cwd=/mock-checkout @@ -470,12 +466,11 @@ MOCK: release_work_item: style-queue 10000 "handle_script_error": "MOCK output\n", } tool = MockTool(log_executive=True, executive_throws_when_run=set(['check-style'])) - self.assert_queue_outputs(StyleQueue(), expected_stderr=expected_stderr, tool=tool) + self.assert_queue_outputs(StyleQueue(), expected_logs=expected_logs, tool=tool) def test_style_queue_with_watch_list_exception(self): - expected_stderr = { - "begin_work_queue": self._default_begin_work_queue_stderr("style-queue"), - "next_work_item": "", + expected_logs = { + "begin_work_queue": self._default_begin_work_queue_logs("style-queue"), "process_work_item": """MOCK run_and_throw_if_fail: ['echo', '--status-host=example.com', 'clean'], cwd=/mock-checkout MOCK: update_status: style-queue Cleaned working directory MOCK run_and_throw_if_fail: ['echo', '--status-host=example.com', 'update'], cwd=/mock-checkout @@ -493,4 +488,4 @@ MOCK: release_work_item: style-queue 10000 "handle_script_error": "MOCK output\n", } tool = MockTool(log_executive=True, executive_throws_when_run=set(['apply-watchlist-local'])) - self.assert_queue_outputs(StyleQueue(), expected_stderr=expected_stderr, tool=tool) + self.assert_queue_outputs(StyleQueue(), expected_logs=expected_logs, tool=tool) diff --git a/Tools/Scripts/webkitpy/tool/commands/queuestest.py b/Tools/Scripts/webkitpy/tool/commands/queuestest.py index b99302c8d..314a64021 100644 --- a/Tools/Scripts/webkitpy/tool/commands/queuestest.py +++ b/Tools/Scripts/webkitpy/tool/commands/queuestest.py @@ -48,24 +48,33 @@ class QueuesTest(unittest.TestCase): # This is _patch1 in mocktool.py mock_work_item = MockTool().bugs.fetch_attachment(10000) - def assert_outputs(self, func, func_name, args, expected_stdout, expected_stderr, expected_exceptions): + def assert_outputs(self, func, func_name, args, expected_stdout, expected_stderr, expected_exceptions, expected_logs): exception = None if expected_exceptions and func_name in expected_exceptions: exception = expected_exceptions[func_name] + logs = None + if expected_logs and func_name in expected_logs: + logs = expected_logs[func_name] + OutputCapture().assert_outputs(self, func, args=args, expected_stdout=expected_stdout.get(func_name, ""), expected_stderr=expected_stderr.get(func_name, ""), - expected_exception=exception) + expected_exception=exception, + expected_logs=logs) def _default_begin_work_queue_stderr(self, name): + string_replacements = {"name": name} + return "MOCK: update_status: %(name)s Starting Queue\n" % string_replacements + + def _default_begin_work_queue_logs(self, name): checkout_dir = '/mock-checkout' string_replacements = {"name": name, 'checkout_dir': checkout_dir} return "CAUTION: %(name)s will discard all local changes in \"%(checkout_dir)s\"\nRunning WebKit %(name)s.\nMOCK: update_status: %(name)s Starting Queue\n" % string_replacements - def assert_queue_outputs(self, queue, args=None, work_item=None, expected_stdout=None, expected_stderr=None, expected_exceptions=None, options=None, tool=None): + def assert_queue_outputs(self, queue, args=None, work_item=None, expected_stdout=None, expected_stderr=None, expected_exceptions=None, expected_logs=None, options=None, tool=None): if not tool: tool = MockTool() # This is a hack to make it easy for callers to not have to setup a custom MockFileSystem just to test the commit-queue @@ -86,13 +95,13 @@ class QueuesTest(unittest.TestCase): queue.execute(options, args, tool, engine=MockQueueEngine) - self.assert_outputs(queue.queue_log_path, "queue_log_path", [], expected_stdout, expected_stderr, expected_exceptions) - self.assert_outputs(queue.work_item_log_path, "work_item_log_path", [work_item], expected_stdout, expected_stderr, expected_exceptions) - self.assert_outputs(queue.begin_work_queue, "begin_work_queue", [], expected_stdout, expected_stderr, expected_exceptions) - self.assert_outputs(queue.should_continue_work_queue, "should_continue_work_queue", [], expected_stdout, expected_stderr, expected_exceptions) - self.assert_outputs(queue.next_work_item, "next_work_item", [], expected_stdout, expected_stderr, expected_exceptions) - self.assert_outputs(queue.process_work_item, "process_work_item", [work_item], expected_stdout, expected_stderr, expected_exceptions) - self.assert_outputs(queue.handle_unexpected_error, "handle_unexpected_error", [work_item, "Mock error message"], expected_stdout, expected_stderr, expected_exceptions) + self.assert_outputs(queue.queue_log_path, "queue_log_path", [], expected_stdout, expected_stderr, expected_exceptions, expected_logs) + self.assert_outputs(queue.work_item_log_path, "work_item_log_path", [work_item], expected_stdout, expected_stderr, expected_exceptions, expected_logs) + self.assert_outputs(queue.begin_work_queue, "begin_work_queue", [], expected_stdout, expected_stderr, expected_exceptions, expected_logs) + self.assert_outputs(queue.should_continue_work_queue, "should_continue_work_queue", [], expected_stdout, expected_stderr, expected_exceptions, expected_logs) + self.assert_outputs(queue.next_work_item, "next_work_item", [], expected_stdout, expected_stderr, expected_exceptions, expected_logs) + self.assert_outputs(queue.process_work_item, "process_work_item", [work_item], expected_stdout, expected_stderr, expected_exceptions, expected_logs) + self.assert_outputs(queue.handle_unexpected_error, "handle_unexpected_error", [work_item, "Mock error message"], expected_stdout, expected_stderr, expected_exceptions, expected_logs) # Should we have a different function for testing StepSequenceErrorHandlers? if isinstance(queue, StepSequenceErrorHandler): - self.assert_outputs(queue.handle_script_error, "handle_script_error", [tool, {"patch": self.mock_work_item}, ScriptError(message="ScriptError error message", script_args="MockErrorCommand", output="MOCK output")], expected_stdout, expected_stderr, expected_exceptions) + self.assert_outputs(queue.handle_script_error, "handle_script_error", [tool, {"patch": self.mock_work_item}, ScriptError(message="ScriptError error message", script_args="MockErrorCommand", output="MOCK output")], expected_stdout, expected_stderr, expected_exceptions, expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/commands/roll_unittest.py b/Tools/Scripts/webkitpy/tool/commands/roll_unittest.py index 237a1c94f..1dae497bc 100644 --- a/Tools/Scripts/webkitpy/tool/commands/roll_unittest.py +++ b/Tools/Scripts/webkitpy/tool/commands/roll_unittest.py @@ -34,20 +34,20 @@ from webkitpy.tool.mocktool import MockOptions, MockTool class RollCommandsTest(CommandsTest): def test_update_chromium_deps(self): - expected_stderr = """Updating Chromium DEPS to 6764 + expected_logs = """Updating Chromium DEPS to 6764 MOCK: MockDEPS.write_variable(chromium_rev, 6764) MOCK: user.open_url: file://... Was that diff correct? Committed r49824: <http://trac.webkit.org/changeset/49824> """ - self.assert_execute_outputs(RollChromiumDEPS(), [6764], expected_stderr=expected_stderr) + self.assert_execute_outputs(RollChromiumDEPS(), [6764], expected_logs=expected_logs) def test_update_chromium_deps_older_revision(self): options = MockOptions(non_interactive=False) - expected_stderr = """Current Chromium DEPS revision 6564 is newer than 5764. -ERROR: Unable to update Chromium DEPS + expected_logs = """Current Chromium DEPS revision 6564 is newer than 5764. +Unable to update Chromium DEPS """ - self.assert_execute_outputs(RollChromiumDEPS(), [5764], options=options, expected_stderr=expected_stderr, expected_exception=SystemExit) + self.assert_execute_outputs(RollChromiumDEPS(), [5764], options=options, expected_logs=expected_logs, expected_exception=SystemExit) class PostRollCommandsTest(CommandsTest): diff --git a/Tools/Scripts/webkitpy/tool/commands/sheriffbot.py b/Tools/Scripts/webkitpy/tool/commands/sheriffbot.py index d30da395b..0f91be3ef 100644 --- a/Tools/Scripts/webkitpy/tool/commands/sheriffbot.py +++ b/Tools/Scripts/webkitpy/tool/commands/sheriffbot.py @@ -26,13 +26,16 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -from webkitpy.common.system.deprecated_logging import log +import logging + from webkitpy.tool.bot.sheriff import Sheriff from webkitpy.tool.bot.irc_command import commands as irc_commands from webkitpy.tool.bot.ircbot import IRCBot from webkitpy.tool.commands.queues import AbstractQueue from webkitpy.tool.commands.stepsequence import StepSequenceErrorHandler +_log = logging.getLogger(__name__) + class SheriffBot(AbstractQueue, StepSequenceErrorHandler): name = "sheriff-bot" @@ -63,7 +66,7 @@ class SheriffBot(AbstractQueue, StepSequenceErrorHandler): return True def handle_unexpected_error(self, failure_map, message): - log(message) + _log.error(message) # StepSequenceErrorHandler methods diff --git a/Tools/Scripts/webkitpy/tool/commands/stepsequence.py b/Tools/Scripts/webkitpy/tool/commands/stepsequence.py index b66655446..1668cdb63 100644 --- a/Tools/Scripts/webkitpy/tool/commands/stepsequence.py +++ b/Tools/Scripts/webkitpy/tool/commands/stepsequence.py @@ -26,13 +26,16 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool import steps from webkitpy.common.checkout.scm import CheckoutNeedsUpdate -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.system.executive import ScriptError from webkitpy.tool.bot.queueengine import QueueEngine +_log = logging.getLogger(__name__) + class StepSequenceErrorHandler(): @classmethod @@ -69,14 +72,14 @@ class StepSequence(object): try: self._run(tool, options, state) except CheckoutNeedsUpdate, e: - log("Commit failed because the checkout is out of date. Please update and try again.") + _log.info("Commit failed because the checkout is out of date. Please update and try again.") if options.parent_command: command = tool.command_by_name(options.parent_command) command.handle_checkout_needs_update(tool, state, options, e) QueueEngine.exit_after_handled_error(e) except ScriptError, e: if not options.quiet: - log(e.message_with_output()) + _log.error(e.message_with_output()) if options.parent_command: command = tool.command_by_name(options.parent_command) command.handle_script_error(tool, state, e) diff --git a/Tools/Scripts/webkitpy/tool/commands/upload.py b/Tools/Scripts/webkitpy/tool/commands/upload.py index 6b52e6c83..5cd0de9e0 100644 --- a/Tools/Scripts/webkitpy/tool/commands/upload.py +++ b/Tools/Scripts/webkitpy/tool/commands/upload.py @@ -28,6 +28,7 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging import os import re import sys @@ -38,7 +39,6 @@ from webkitpy.tool import steps from webkitpy.common.checkout.changelog import parse_bug_id_from_changelog from webkitpy.common.config.committers import CommitterList -from webkitpy.common.system.deprecated_logging import error, log from webkitpy.common.system.user import User from webkitpy.thirdparty.mock import Mock from webkitpy.tool.commands.abstractsequencedcommand import AbstractSequencedCommand @@ -46,6 +46,8 @@ from webkitpy.tool.comments import bug_comment_from_svn_revision from webkitpy.tool.grammar import pluralize, join_with_separators from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand +_log = logging.getLogger(__name__) + class CommitMessageForCurrentDiff(AbstractDeclarativeCommand): name = "commit-message" @@ -133,24 +135,24 @@ class AssignToCommitter(AbstractDeclarativeCommand): bug = self._tool.bugs.fetch_bug(bug_id) if not bug.is_unassigned(): assigned_to_email = bug.assigned_to_email() - log(u"Bug %s is already assigned to %s (%s)." % (bug_id, assigned_to_email, committers.committer_by_email(assigned_to_email))) + _log.info(u"Bug %s is already assigned to %s (%s)." % (bug_id, assigned_to_email, committers.committer_by_email(assigned_to_email))) return reviewed_patches = bug.reviewed_patches() if not reviewed_patches: - log("Bug %s has no non-obsolete patches, ignoring." % bug_id) + _log.info("Bug %s has no non-obsolete patches, ignoring." % bug_id) return # We only need to do anything with this bug if one of the r+'d patches does not have a valid committer (cq+ set). if self._patches_have_commiters(reviewed_patches): - log("All reviewed patches on bug %s already have commit-queue+, ignoring." % bug_id) + _log.info("All reviewed patches on bug %s already have commit-queue+, ignoring." % bug_id) return latest_patch = reviewed_patches[-1] attacher_email = latest_patch.attacher_email() committer = committers.committer_by_email(attacher_email) if not committer: - log("Attacher %s is not a committer. Bug %s likely needs commit-queue+." % (attacher_email, bug_id)) + _log.info("Attacher %s is not a committer. Bug %s likely needs commit-queue+." % (attacher_email, bug_id)) return reassign_message = u"Attachment %s was posted by a committer and has review+, assigning to %s for commit." % (latest_patch.id(), committer.full_name) @@ -202,7 +204,8 @@ class AbstractPatchUploadingCommand(AbstractSequencedCommand): state = {} state["bug_id"] = self._bug_id(options, args, tool, state) if not state["bug_id"]: - error("No bug id passed and no bug url found in ChangeLogs.") + _log.error("No bug id passed and no bug url found in ChangeLogs.") + sys.exit(1) return state @@ -322,7 +325,8 @@ class PostCommits(AbstractDeclarativeCommand): def execute(self, options, args, tool): commit_ids = tool.scm().commit_ids_from_commitish_arguments(args) if len(commit_ids) > 10: # We could lower this limit, 10 is too many for one bug as-is. - error("webkit-patch does not support attaching %s at once. Are you sure you passed the right commit range?" % (pluralize("patch", len(commit_ids)))) + _log.error("webkit-patch does not support attaching %s at once. Are you sure you passed the right commit range?" % (pluralize("patch", len(commit_ids)))) + sys.exit(1) have_obsoleted_patches = set() for commit_id in commit_ids: @@ -331,7 +335,7 @@ class PostCommits(AbstractDeclarativeCommand): # Prefer --bug-id=, then a bug url in the commit message, then a bug url in the entire commit diff (i.e. ChangeLogs). bug_id = options.bug_id or parse_bug_id_from_changelog(commit_message.message()) or parse_bug_id_from_changelog(tool.scm().create_patch(git_commit=commit_id)) if not bug_id: - log("Skipping %s: No bug id found in commit or specified with --bug-id." % commit_id) + _log.info("Skipping %s: No bug id found in commit or specified with --bug-id." % commit_id) continue if options.obsolete_patches and bug_id not in have_obsoleted_patches: @@ -382,8 +386,9 @@ class MarkBugFixed(AbstractDeclarativeCommand): not_found.append("bug id") if not svn_revision: not_found.append("svn revision") - error("Could not find %s on command-line or in %s." + _log.error("Could not find %s on command-line or in %s." % (" or ".join(not_found), "r%s" % svn_revision if svn_revision else "last commit")) + sys.exit(1) return (bug_id, svn_revision) @@ -395,15 +400,16 @@ class MarkBugFixed(AbstractDeclarativeCommand): if re.match("^r[0-9]+$", svn_revision, re.IGNORECASE): svn_revision = svn_revision[1:] if not re.match("^[0-9]+$", svn_revision): - error("Invalid svn revision: '%s'" % svn_revision) + _log.error("Invalid svn revision: '%s'" % svn_revision) + sys.exit(1) needs_prompt = False if not bug_id or not svn_revision: needs_prompt = True (bug_id, svn_revision) = self._determine_bug_id_and_svn_revision(tool, bug_id, svn_revision) - log("Bug: <%s> %s" % (tool.bugs.bug_url_for_bug_id(bug_id), tool.bugs.fetch_bug_dictionary(bug_id)["title"])) - log("Revision: %s" % svn_revision) + _log.info("Bug: <%s> %s" % (tool.bugs.bug_url_for_bug_id(bug_id), tool.bugs.fetch_bug_dictionary(bug_id)["title"])) + _log.info("Revision: %s" % svn_revision) if options.open_bug: tool.user.open_url(tool.bugs.bug_url_for_bug_id(bug_id)) @@ -417,10 +423,10 @@ class MarkBugFixed(AbstractDeclarativeCommand): bug_comment = "%s\n\n%s" % (options.comment, bug_comment) if options.update_only: - log("Adding comment to Bug %s." % bug_id) + _log.info("Adding comment to Bug %s." % bug_id) tool.bugs.post_comment_to_bug(bug_id, bug_comment) else: - log("Adding comment to Bug %s and marking as Resolved/Fixed." % bug_id) + _log.info("Adding comment to Bug %s and marking as Resolved/Fixed." % bug_id) tool.bugs.close_bug_as_fixed(bug_id, bug_comment) @@ -443,7 +449,8 @@ class CreateBug(AbstractDeclarativeCommand): def create_bug_from_commit(self, options, args, tool): commit_ids = tool.scm().commit_ids_from_commitish_arguments(args) if len(commit_ids) > 3: - error("Are you sure you want to create one bug with %s patches?" % len(commit_ids)) + _log.error("Are you sure you want to create one bug with %s patches?" % len(commit_ids)) + sys.exit(1) commit_id = commit_ids[0] @@ -499,7 +506,8 @@ class CreateBug(AbstractDeclarativeCommand): def execute(self, options, args, tool): if len(args): if (not tool.scm().supports_local_commits()): - error("Extra arguments not supported; patch is taken from working directory.") + _log.error("Extra arguments not supported; patch is taken from working directory.") + sys.exit(1) self.create_bug_from_commit(options, args, tool) else: self.create_bug_from_patch(options, args, tool) diff --git a/Tools/Scripts/webkitpy/tool/commands/upload_unittest.py b/Tools/Scripts/webkitpy/tool/commands/upload_unittest.py index 185bb97f3..ad1b591e0 100644 --- a/Tools/Scripts/webkitpy/tool/commands/upload_unittest.py +++ b/Tools/Scripts/webkitpy/tool/commands/upload_unittest.py @@ -42,7 +42,7 @@ class UploadCommandsTest(CommandsTest): def test_assign_to_committer(self): tool = MockTool() - expected_stderr = """Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com) + expected_logs = """Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com) MOCK reassign_bug: bug_id=50000, assignee=eric@webkit.org -- Begin comment -- Attachment 10001 was posted by a committer and has review+, assigning to Eric Seidel for commit. @@ -50,11 +50,11 @@ Attachment 10001 was posted by a committer and has review+, assigning to Eric Se Bug 50003 is already assigned to foo@foo.com (None). Bug 50002 has no non-obsolete patches, ignoring. """ - self.assert_execute_outputs(AssignToCommitter(), [], expected_stderr=expected_stderr, tool=tool) + self.assert_execute_outputs(AssignToCommitter(), [], expected_logs=expected_logs, tool=tool) def test_obsolete_attachments(self): - expected_stderr = "Obsoleting 2 old patches on bug 50000\n" - self.assert_execute_outputs(ObsoleteAttachments(), [50000], expected_stderr=expected_stderr) + expected_logs = "Obsoleting 2 old patches on bug 50000\n" + self.assert_execute_outputs(ObsoleteAttachments(), [50000], expected_logs=expected_logs) def test_post(self): options = MockOptions() @@ -66,44 +66,46 @@ Bug 50002 has no non-obsolete patches, ignoring. options.request_commit = False options.review = True options.suggest_reviewers = False - expected_stderr = """MOCK: user.open_url: file://... + expected_logs = """MOCK: user.open_url: file://... Was that diff correct? Obsoleting 2 old patches on bug 50000 MOCK reassign_bug: bug_id=50000, assignee=None MOCK add_patch_to_bug: bug_id=50000, description=MOCK description, mark_for_review=True, mark_for_commit_queue=False, mark_for_landing=False MOCK: user.open_url: http://example.com/50000 """ - self.assert_execute_outputs(Post(), [50000], options=options, expected_stderr=expected_stderr) + self.assert_execute_outputs(Post(), [50000], options=options, expected_logs=expected_logs) def test_attach_to_bug(self): options = MockOptions() options.comment = "extra comment" options.description = "file description" - expected_stderr = """MOCK add_attachment_to_bug: bug_id=50000, description=file description filename=None mimetype=None + expected_logs = """MOCK add_attachment_to_bug: bug_id=50000, description=file description filename=None mimetype=None -- Begin comment -- extra comment -- End comment -- """ - self.assert_execute_outputs(AttachToBug(), [50000, "path/to/file.txt", "file description"], options=options, expected_stderr=expected_stderr) + self.assert_execute_outputs(AttachToBug(), [50000, "path/to/file.txt", "file description"], options=options, expected_logs=expected_logs) def test_attach_to_bug_no_description_or_comment(self): options = MockOptions() options.comment = None options.description = None - expected_stderr = """MOCK add_attachment_to_bug: bug_id=50000, description=file.txt filename=None mimetype=None -""" - self.assert_execute_outputs(AttachToBug(), [50000, "path/to/file.txt"], options=options, expected_stderr=expected_stderr) + expected_logs = "MOCK add_attachment_to_bug: bug_id=50000, description=file.txt filename=None mimetype=None\n" + self.assert_execute_outputs(AttachToBug(), [50000, "path/to/file.txt"], options=options, expected_logs=expected_logs) def test_land_safely(self): - expected_stderr = "Obsoleting 2 old patches on bug 50000\nMOCK reassign_bug: bug_id=50000, assignee=None\nMOCK add_patch_to_bug: bug_id=50000, description=Patch for landing, mark_for_review=False, mark_for_commit_queue=False, mark_for_landing=True\n" - self.assert_execute_outputs(LandSafely(), [50000], expected_stderr=expected_stderr) + expected_logs = """Obsoleting 2 old patches on bug 50000 +MOCK reassign_bug: bug_id=50000, assignee=None +MOCK add_patch_to_bug: bug_id=50000, description=Patch for landing, mark_for_review=False, mark_for_commit_queue=False, mark_for_landing=True +""" + self.assert_execute_outputs(LandSafely(), [50000], expected_logs=expected_logs) def test_prepare_diff_with_arg(self): self.assert_execute_outputs(Prepare(), [50000]) def test_prepare(self): - expected_stderr = "MOCK create_bug\nbug_title: Mock user response\nbug_description: Mock user response\ncomponent: MOCK component\ncc: MOCK cc\n" - self.assert_execute_outputs(Prepare(), [], expected_stderr=expected_stderr) + expected_logs = "MOCK create_bug\nbug_title: Mock user response\nbug_description: Mock user response\ncomponent: MOCK component\ncc: MOCK cc\n" + self.assert_execute_outputs(Prepare(), [], expected_logs=expected_logs) def test_upload(self): options = MockOptions() @@ -115,14 +117,14 @@ extra comment options.request_commit = False options.review = True options.suggest_reviewers = False - expected_stderr = """MOCK: user.open_url: file://... + expected_logs = """MOCK: user.open_url: file://... Was that diff correct? Obsoleting 2 old patches on bug 50000 MOCK reassign_bug: bug_id=50000, assignee=None MOCK add_patch_to_bug: bug_id=50000, description=MOCK description, mark_for_review=True, mark_for_commit_queue=False, mark_for_landing=False MOCK: user.open_url: http://example.com/50000 """ - self.assert_execute_outputs(Upload(), [50000], options=options, expected_stderr=expected_stderr) + self.assert_execute_outputs(Upload(), [50000], options=options, expected_logs=expected_logs) def test_mark_bug_fixed(self): tool = MockTool() @@ -130,7 +132,7 @@ MOCK: user.open_url: http://example.com/50000 options = Mock() options.bug_id = 50000 options.comment = "MOCK comment" - expected_stderr = """Bug: <http://example.com/50000> Bug with two r+'d and cq+'d patches, one of which has an invalid commit-queue setter. + expected_logs = """Bug: <http://example.com/50000> Bug with two r+'d and cq+'d patches, one of which has an invalid commit-queue setter. Revision: 9876 MOCK: user.open_url: http://example.com/50000 Is this correct? @@ -143,7 +145,7 @@ Committed r9876: <http://trac.webkit.org/changeset/9876> --- End comment --- """ - self.assert_execute_outputs(MarkBugFixed(), [], expected_stderr=expected_stderr, tool=tool, options=options) + self.assert_execute_outputs(MarkBugFixed(), [], expected_logs=expected_logs, tool=tool, options=options) def test_edit_changelog(self): self.assert_execute_outputs(EditChangeLogs(), []) diff --git a/Tools/Scripts/webkitpy/tool/multicommandtool.py b/Tools/Scripts/webkitpy/tool/multicommandtool.py index 38c410cf8..e2f91a7da 100644 --- a/Tools/Scripts/webkitpy/tool/multicommandtool.py +++ b/Tools/Scripts/webkitpy/tool/multicommandtool.py @@ -31,12 +31,14 @@ # which are called with the following format: # tool-name [global options] command-name [command options] +import logging import sys from optparse import OptionParser, IndentedHelpFormatter, SUPPRESS_USAGE, make_option from webkitpy.tool.grammar import pluralize -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class TryAgain(Exception): @@ -109,13 +111,13 @@ class Command(object): def check_arguments_and_execute(self, options, args, tool=None): if len(args) < len(self.required_arguments): - log("%s required, %s provided. Provided: %s Required: %s\nSee '%s help %s' for usage." % ( - pluralize("argument", len(self.required_arguments)), - pluralize("argument", len(args)), - "'%s'" % " ".join(args), - " ".join(self.required_arguments), - tool.name(), - self.name)) + _log.error("%s required, %s provided. Provided: %s Required: %s\nSee '%s help %s' for usage." % ( + pluralize("argument", len(self.required_arguments)), + pluralize("argument", len(args)), + "'%s'" % " ".join(args), + " ".join(self.required_arguments), + tool.name(), + self.name)) return 1 return self.execute(options, args, tool) or 0 @@ -303,7 +305,7 @@ class MultiCommandTool(object): (should_execute, failure_reason) = self.should_execute_command(command) if not should_execute: - log(failure_reason) + _log.error(failure_reason) return 0 # FIXME: Should this really be 0? while True: diff --git a/Tools/Scripts/webkitpy/tool/multicommandtool_unittest.py b/Tools/Scripts/webkitpy/tool/multicommandtool_unittest.py index c19095c3e..ecb1df007 100644 --- a/Tools/Scripts/webkitpy/tool/multicommandtool_unittest.py +++ b/Tools/Scripts/webkitpy/tool/multicommandtool_unittest.py @@ -81,8 +81,8 @@ class CommandTest(unittest.TestCase): def test_required_arguments(self): two_required_arguments = TrivialCommand(argument_names="ARG1 ARG2 [ARG3]") - expected_missing_args_error = "2 arguments required, 1 argument provided. Provided: 'foo' Required: ARG1 ARG2\nSee 'trivial-tool help trivial' for usage.\n" - exit_code = OutputCapture().assert_outputs(self, two_required_arguments.check_arguments_and_execute, [None, ["foo"], TrivialTool()], expected_stderr=expected_missing_args_error) + expected_logs = "2 arguments required, 1 argument provided. Provided: 'foo' Required: ARG1 ARG2\nSee 'trivial-tool help trivial' for usage.\n" + exit_code = OutputCapture().assert_outputs(self, two_required_arguments.check_arguments_and_execute, [None, ["foo"], TrivialTool()], expected_logs=expected_logs) self.assertEqual(exit_code, 1) diff --git a/Tools/Scripts/webkitpy/tool/servers/gardeningserver.py b/Tools/Scripts/webkitpy/tool/servers/gardeningserver.py index 41b81663e..77068acf4 100644 --- a/Tools/Scripts/webkitpy/tool/servers/gardeningserver.py +++ b/Tools/Scripts/webkitpy/tool/servers/gardeningserver.py @@ -54,6 +54,8 @@ class GardeningHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer class GardeningHTTPRequestHandler(ReflectionHandler): STATIC_FILE_NAMES = frozenset() + STATIC_FILE_EXTENSIONS = ('.js', '.css', '.html', '.gif', '.png') + STATIC_FILE_DIRECTORY = os.path.join( os.path.dirname(__file__), '..', diff --git a/Tools/Scripts/webkitpy/tool/servers/reflectionhandler.py b/Tools/Scripts/webkitpy/tool/servers/reflectionhandler.py index 2148b4eb2..954fb56a9 100644 --- a/Tools/Scripts/webkitpy/tool/servers/reflectionhandler.py +++ b/Tools/Scripts/webkitpy/tool/servers/reflectionhandler.py @@ -78,7 +78,7 @@ class ReflectionHandler(BaseHTTPServer.BaseHTTPRequestHandler): self.query = {} function_or_file_name = path[1:] or "index.html" - _, extension = os.path.splitext(self.path) + _, extension = os.path.splitext(function_or_file_name) if extension in self.STATIC_FILE_EXTENSIONS: self._serve_static_file(function_or_file_name) return diff --git a/Tools/Scripts/webkitpy/tool/steps/addsvnmimetypeforpng.py b/Tools/Scripts/webkitpy/tool/steps/addsvnmimetypeforpng.py index 73bec15db..0ef0fed46 100644 --- a/Tools/Scripts/webkitpy/tool/steps/addsvnmimetypeforpng.py +++ b/Tools/Scripts/webkitpy/tool/steps/addsvnmimetypeforpng.py @@ -21,12 +21,15 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.common import checksvnconfigfile -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.checkout.scm.detection import SCMDetector from webkitpy.common.system.systemhost import SystemHost +_log = logging.getLogger(__name__) + class AddSvnMimetypeForPng(AbstractStep): def __init__(self, tool, options, host=None, scm=None): @@ -47,19 +50,19 @@ class AddSvnMimetypeForPng(AbstractStep): config_file_path = checksvnconfigfile.config_file_path(self._host, self._fs) if file_missing: - log("There is no SVN config file. The svn:mime-type of pngs won't set.") + _log.info("There is no SVN config file. The svn:mime-type of pngs won't set.") if not self._tool.user.confirm("Are you sure you want to continue?", default="n"): self._exit(1) elif autoprop_missing and png_missing: - log(checksvnconfigfile.errorstr_autoprop(config_file_path) + checksvnconfigfile.errorstr_png(config_file_path)) + _log.info(checksvnconfigfile.errorstr_autoprop(config_file_path) + checksvnconfigfile.errorstr_png(config_file_path)) if not self._tool.user.confirm("Do you want to continue?", default="n"): self._exit(1) elif autoprop_missing: - log(checksvnconfigfile.errorstr_autoprop(config_file_path)) + _log.info(checksvnconfigfile.errorstr_autoprop(config_file_path)) if not self._tool.user.confirm("Do you want to continue?", default="n"): self._exit(1) elif png_missing: - log(checksvnconfigfile.errorstr_png(config_file_path)) + _log.info(checksvnconfigfile.errorstr_png(config_file_path)) if not self._tool.user.confirm("Do you want to continue?", default="n"): self._exit(1) diff --git a/Tools/Scripts/webkitpy/tool/steps/applypatch.py b/Tools/Scripts/webkitpy/tool/steps/applypatch.py index 5c36169fd..50ee1f7ed 100644 --- a/Tools/Scripts/webkitpy/tool/steps/applypatch.py +++ b/Tools/Scripts/webkitpy/tool/steps/applypatch.py @@ -26,9 +26,13 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) + class ApplyPatch(AbstractStep): @classmethod @@ -38,5 +42,5 @@ class ApplyPatch(AbstractStep): ] def run(self, state): - log("Processing patch %s from bug %s." % (state["patch"].id(), state["patch"].bug_id())) + _log.info("Processing patch %s from bug %s." % (state["patch"].id(), state["patch"].bug_id())) self._tool.checkout().apply_patch(state["patch"]) diff --git a/Tools/Scripts/webkitpy/tool/steps/applywatchlist_unittest.py b/Tools/Scripts/webkitpy/tool/steps/applywatchlist_unittest.py index bdaaf758a..a978f4164 100644 --- a/Tools/Scripts/webkitpy/tool/steps/applywatchlist_unittest.py +++ b/Tools/Scripts/webkitpy/tool/steps/applywatchlist_unittest.py @@ -41,11 +41,11 @@ class ApplyWatchListTest(unittest.TestCase): 'bug_id': '50001', 'diff': 'The diff', } - expected_stderr = """MockWatchList: determine_cc_and_messages + expected_logs = """MockWatchList: determine_cc_and_messages MOCK bug comment: bug_id=50001, cc=set(['levin@chromium.org']) --- Begin comment --- Message2. --- End comment --- """ - capture.assert_outputs(self, step.run, [state], expected_stderr=expected_stderr) + capture.assert_outputs(self, step.run, [state], expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/steps/build.py b/Tools/Scripts/webkitpy/tool/steps/build.py index 7f7dd9f36..a2a627229 100644 --- a/Tools/Scripts/webkitpy/tool/steps/build.py +++ b/Tools/Scripts/webkitpy/tool/steps/build.py @@ -26,9 +26,12 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class Build(AbstractStep): @@ -52,7 +55,7 @@ class Build(AbstractStep): def run(self, state): if not self._options.build: return - log("Building WebKit") + _log.info("Building WebKit") if self._options.build_style == "both": self.build("debug") self.build("release") diff --git a/Tools/Scripts/webkitpy/tool/steps/checkstyle.py b/Tools/Scripts/webkitpy/tool/steps/checkstyle.py index 3304f016f..0cb15f4c1 100644 --- a/Tools/Scripts/webkitpy/tool/steps/checkstyle.py +++ b/Tools/Scripts/webkitpy/tool/steps/checkstyle.py @@ -29,7 +29,6 @@ from webkitpy.common.system.executive import ScriptError from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import error class CheckStyle(AbstractStep): @classmethod diff --git a/Tools/Scripts/webkitpy/tool/steps/closebug.py b/Tools/Scripts/webkitpy/tool/steps/closebug.py index b33e373bf..e58be5468 100644 --- a/Tools/Scripts/webkitpy/tool/steps/closebug.py +++ b/Tools/Scripts/webkitpy/tool/steps/closebug.py @@ -26,9 +26,12 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class CloseBug(AbstractStep): @@ -48,6 +51,6 @@ class CloseBug(AbstractStep): patches = self._tool.bugs.fetch_bug(state["patch"].bug_id()).patches() for patch in patches: if patch.review() == "?" or patch.review() == "+": - log("Not closing bug %s as attachment %s has review=%s. Assuming there are more patches to land from this bug." % (patch.bug_id(), patch.id(), patch.review())) + _log.info("Not closing bug %s as attachment %s has review=%s. Assuming there are more patches to land from this bug." % (patch.bug_id(), patch.id(), patch.review())) return self._tool.bugs.close_bug_as_fixed(state["patch"].bug_id(), "All reviewed patches have been landed. Closing bug.") diff --git a/Tools/Scripts/webkitpy/tool/steps/closebugforlanddiff.py b/Tools/Scripts/webkitpy/tool/steps/closebugforlanddiff.py index e5a68dbf1..1662d6a5d 100644 --- a/Tools/Scripts/webkitpy/tool/steps/closebugforlanddiff.py +++ b/Tools/Scripts/webkitpy/tool/steps/closebugforlanddiff.py @@ -26,10 +26,13 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool.comments import bug_comment_from_commit_text from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class CloseBugForLandDiff(AbstractStep): @@ -46,7 +49,7 @@ class CloseBugForLandDiff(AbstractStep): bug_id = state.get("patch").bug_id() if bug_id: - log("Updating bug %s" % bug_id) + _log.info("Updating bug %s" % bug_id) if self._options.close_bug: self._tool.bugs.close_bug_as_fixed(bug_id, comment_text) else: @@ -54,5 +57,5 @@ class CloseBugForLandDiff(AbstractStep): # to the bug, and if so obsolete it. self._tool.bugs.post_comment_to_bug(bug_id, comment_text) else: - log(comment_text) - log("No bug id provided.") + _log.info(comment_text) + _log.info("No bug id provided.") diff --git a/Tools/Scripts/webkitpy/tool/steps/closebugforlanddiff_unittest.py b/Tools/Scripts/webkitpy/tool/steps/closebugforlanddiff_unittest.py index 0a56564dd..6969c4e9a 100644 --- a/Tools/Scripts/webkitpy/tool/steps/closebugforlanddiff_unittest.py +++ b/Tools/Scripts/webkitpy/tool/steps/closebugforlanddiff_unittest.py @@ -36,5 +36,5 @@ class CloseBugForLandDiffTest(unittest.TestCase): def test_empty_state(self): capture = OutputCapture() step = CloseBugForLandDiff(MockTool(), MockOptions()) - expected_stderr = "Committed r49824: <http://trac.webkit.org/changeset/49824>\nNo bug id provided.\n" - capture.assert_outputs(self, step.run, [{"commit_text" : "Mock commit text"}], expected_stderr=expected_stderr) + expected_logs = "Committed r49824: <http://trac.webkit.org/changeset/49824>\nNo bug id provided.\n" + capture.assert_outputs(self, step.run, [{"commit_text": "Mock commit text"}], expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/steps/commit.py b/Tools/Scripts/webkitpy/tool/steps/commit.py index 0e5ca9157..2bffa4c2a 100644 --- a/Tools/Scripts/webkitpy/tool/steps/commit.py +++ b/Tools/Scripts/webkitpy/tool/steps/commit.py @@ -26,16 +26,18 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging import sys from webkitpy.common.checkout.scm import AuthenticationError, AmbiguousCommitError from webkitpy.common.config import urls -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.system.executive import ScriptError from webkitpy.common.system.user import User from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options +_log = logging.getLogger(__name__) + class Commit(AbstractStep): # FIXME: This option exists only to make sure we don't break scripts which include --ignore-builders @@ -89,7 +91,7 @@ class Commit(AbstractStep): scm = self._tool.scm() commit_text = scm.commit_with_message(self._commit_message, git_commit=self._options.git_commit, username=username, password=password, force_squash=force_squash, changed_files=self._changed_files(state)) svn_revision = scm.svn_revision_from_commit_text(commit_text) - log("Committed r%s: <%s>" % (svn_revision, urls.view_revision_url(svn_revision))) + _log.info("Committed r%s: <%s>" % (svn_revision, urls.view_revision_url(svn_revision))) self._state["commit_text"] = commit_text break; except AmbiguousCommitError, e: diff --git a/Tools/Scripts/webkitpy/tool/steps/commit_unittest.py b/Tools/Scripts/webkitpy/tool/steps/commit_unittest.py index 25d9b61a1..936e3ebab 100644 --- a/Tools/Scripts/webkitpy/tool/steps/commit_unittest.py +++ b/Tools/Scripts/webkitpy/tool/steps/commit_unittest.py @@ -50,13 +50,16 @@ class CommitTest(unittest.TestCase): } tool.executive = MockExecutive(should_log=True, should_throw_when_run=False) - capture.assert_outputs(self, step.run, [state], expected_stderr="Committed r49824: <http://trac.webkit.org/changeset/49824>\n") + expected_logs = "Committed r49824: <http://trac.webkit.org/changeset/49824>\n" + capture.assert_outputs(self, step.run, [state], expected_logs=expected_logs) state = { "changed_files": ["platform/chromium/" + filename], } - capture.assert_outputs(self, step.run, [state], expected_stderr="MOCK run_and_throw_if_fail: ['mock-check-webkit-style', '--diff-files', 'platform/chromium/" - + filename + "'], cwd=/mock-checkout\nCommitted r49824: <http://trac.webkit.org/changeset/49824>\n") + expected_logs = """MOCK run_and_throw_if_fail: ['mock-check-webkit-style', '--diff-files', 'platform/chromium/%s'], cwd=/mock-checkout +Committed r49824: <http://trac.webkit.org/changeset/49824> +""" % filename + capture.assert_outputs(self, step.run, [state], expected_logs=expected_logs) tool.executive = MockExecutive(should_log=True, should_throw_when_run=set(["platform/chromium/" + filename])) self.assertRaises(ScriptError, capture.assert_outputs, self, step.run, [state]) diff --git a/Tools/Scripts/webkitpy/tool/steps/ensurelocalcommitifneeded.py b/Tools/Scripts/webkitpy/tool/steps/ensurelocalcommitifneeded.py index 2167351e2..778d7ae56 100644 --- a/Tools/Scripts/webkitpy/tool/steps/ensurelocalcommitifneeded.py +++ b/Tools/Scripts/webkitpy/tool/steps/ensurelocalcommitifneeded.py @@ -26,9 +26,13 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging +import sys + from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import error + +_log = logging.getLogger(__name__) class EnsureLocalCommitIfNeeded(AbstractStep): @@ -40,4 +44,5 @@ class EnsureLocalCommitIfNeeded(AbstractStep): def run(self, state): if self._options.local_commit and not self._tool.scm().supports_local_commits(): - error("--local-commit passed, but %s does not support local commits" % self._tool.scm().display_name()) + _log.error("--local-commit passed, but %s does not support local commits" % self._tool.scm().display_name()) + sys.exit(1) diff --git a/Tools/Scripts/webkitpy/tool/steps/obsoletepatches.py b/Tools/Scripts/webkitpy/tool/steps/obsoletepatches.py index de508c6cc..dfed959cb 100644 --- a/Tools/Scripts/webkitpy/tool/steps/obsoletepatches.py +++ b/Tools/Scripts/webkitpy/tool/steps/obsoletepatches.py @@ -26,10 +26,13 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool.grammar import pluralize from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class ObsoletePatches(AbstractStep): @@ -46,6 +49,6 @@ class ObsoletePatches(AbstractStep): patches = self._tool.bugs.fetch_bug(bug_id).patches() if not patches: return - log("Obsoleting %s on bug %s" % (pluralize("old patch", len(patches)), bug_id)) + _log.info("Obsoleting %s on bug %s" % (pluralize("old patch", len(patches)), bug_id)) for patch in patches: self._tool.bugs.obsolete_attachment(patch.id()) diff --git a/Tools/Scripts/webkitpy/tool/steps/preparechangelog.py b/Tools/Scripts/webkitpy/tool/steps/preparechangelog.py index 19caace01..4d80ab61f 100644 --- a/Tools/Scripts/webkitpy/tool/steps/preparechangelog.py +++ b/Tools/Scripts/webkitpy/tool/steps/preparechangelog.py @@ -26,11 +26,15 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging +import sys + from webkitpy.common.checkout.changelog import ChangeLog from webkitpy.common.system.executive import ScriptError from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import error + +_log = logging.getLogger(__name__) class PrepareChangeLog(AbstractStep): @@ -73,5 +77,6 @@ class PrepareChangeLog(AbstractStep): try: self._tool.executive.run_and_throw_if_fail(args, self._options.quiet, cwd=self._tool.scm().checkout_root) except ScriptError, e: - error("Unable to prepare ChangeLogs.") + _log.error("Unable to prepare ChangeLogs.") + sys.exit(1) self.did_modify_checkout(state) diff --git a/Tools/Scripts/webkitpy/tool/steps/reopenbugafterrollout.py b/Tools/Scripts/webkitpy/tool/steps/reopenbugafterrollout.py index f369ca925..39388f62e 100644 --- a/Tools/Scripts/webkitpy/tool/steps/reopenbugafterrollout.py +++ b/Tools/Scripts/webkitpy/tool/steps/reopenbugafterrollout.py @@ -26,9 +26,12 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool.comments import bug_comment_from_commit_text from webkitpy.tool.steps.abstractstep import AbstractStep -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class ReopenBugAfterRollout(AbstractStep): @@ -38,7 +41,7 @@ class ReopenBugAfterRollout(AbstractStep): bug_id = state["bug_id"] if not bug_id: - log(comment_text) - log("No bugs were updated.") + _log.info(comment_text) + _log.info("No bugs were updated.") return self._tool.bugs.reopen_bug(bug_id, comment_text) diff --git a/Tools/Scripts/webkitpy/tool/steps/runtests.py b/Tools/Scripts/webkitpy/tool/steps/runtests.py index aa8729123..6dc90f92c 100644 --- a/Tools/Scripts/webkitpy/tool/steps/runtests.py +++ b/Tools/Scripts/webkitpy/tool/steps/runtests.py @@ -26,11 +26,14 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import log from webkitpy.common.system.executive import ScriptError +_log = logging.getLogger(__name__) + class RunTests(AbstractStep): # FIXME: This knowledge really belongs in the commit-queue. NON_INTERACTIVE_FAILURE_LIMIT_COUNT = 30 @@ -52,31 +55,31 @@ class RunTests(AbstractStep): python_unittests_command = self._tool.port().run_python_unittests_command() if python_unittests_command: - log("Running Python unit tests") + _log.info("Running Python unit tests") self._tool.executive.run_and_throw_if_fail(python_unittests_command, cwd=self._tool.scm().checkout_root) perl_unittests_command = self._tool.port().run_perl_unittests_command() if perl_unittests_command: - log("Running Perl unit tests") + _log.info("Running Perl unit tests") self._tool.executive.run_and_throw_if_fail(perl_unittests_command, cwd=self._tool.scm().checkout_root) javascriptcore_tests_command = self._tool.port().run_javascriptcore_tests_command() if javascriptcore_tests_command: - log("Running JavaScriptCore tests") + _log.info("Running JavaScriptCore tests") self._tool.executive.run_and_throw_if_fail(javascriptcore_tests_command, quiet=True, cwd=self._tool.scm().checkout_root) webkit_unit_tests_command = self._tool.port().run_webkit_unit_tests_command() if webkit_unit_tests_command: - log("Running WebKit unit tests") + _log.info("Running WebKit unit tests") args = webkit_unit_tests_command if self._options.non_interactive: args.append("--gtest_output=xml:%s/webkit_unit_tests_output.xml" % self._tool.port().results_directory) try: self._tool.executive.run_and_throw_if_fail(args, cwd=self._tool.scm().checkout_root) except ScriptError, e: - log("Error running webkit_unit_tests: %s" % e.message_with_output()) + _log.info("Error running webkit_unit_tests: %s" % e.message_with_output()) - log("Running run-webkit-tests") + _log.info("Running run-webkit-tests") args = self._tool.port().run_webkit_tests_command() if self._options.non_interactive: args.extend([ diff --git a/Tools/Scripts/webkitpy/tool/steps/runtests_unittest.py b/Tools/Scripts/webkitpy/tool/steps/runtests_unittest.py index bf888e505..78a867b36 100644 --- a/Tools/Scripts/webkitpy/tool/steps/runtests_unittest.py +++ b/Tools/Scripts/webkitpy/tool/steps/runtests_unittest.py @@ -38,9 +38,9 @@ class RunTestsTest(unittest.TestCase): tool._deprecated_port.run_python_unittests_command = lambda: None tool._deprecated_port.run_perl_unittests_command = lambda: None step = RunTests(tool, MockOptions(test=True, non_interactive=True, quiet=False)) - expected_stderr = """Running WebKit unit tests + expected_logs = """Running WebKit unit tests MOCK run_and_throw_if_fail: ['mock-run-webkit-unit-tests', '--gtest_output=xml:/mock-results/webkit_unit_tests_output.xml'], cwd=/mock-checkout Running run-webkit-tests MOCK run_and_throw_if_fail: ['mock-run-webkit-tests', '--no-new-test-results', '--no-launch-safari', '--skip-failing-tests', '--exit-after-n-failures=30', '--results-directory=/mock-results', '--quiet'], cwd=/mock-checkout """ - OutputCapture().assert_outputs(self, step.run, [{}], expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, step.run, [{}], expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/steps/steps_unittest.py b/Tools/Scripts/webkitpy/tool/steps/steps_unittest.py index 99f174932..c4ea47b4d 100644 --- a/Tools/Scripts/webkitpy/tool/steps/steps_unittest.py +++ b/Tools/Scripts/webkitpy/tool/steps/steps_unittest.py @@ -56,8 +56,8 @@ class StepsTest(unittest.TestCase): tool = MockTool() options = self._step_options() options.update = True - expected_stderr = "Updating working directory\n" - OutputCapture().assert_outputs(self, self._run_step, [steps.Update, tool, options], expected_stderr=expected_stderr) + expected_logs = "Updating working directory\n" + OutputCapture().assert_outputs(self, self._run_step, [steps.Update, tool, options], expected_logs=expected_logs) def test_prompt_for_bug_or_title_step(self): tool = MockTool() @@ -74,26 +74,26 @@ class StepsTest(unittest.TestCase): options.open_bug = True return options - def _assert_step_output_with_bug(self, step, bug_id, expected_stderr, options=None): + def _assert_step_output_with_bug(self, step, bug_id, expected_logs, options=None): state = {'bug_id': bug_id} - OutputCapture().assert_outputs(self, self._run_step, [step, MockTool(), options, state], expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, self._run_step, [step, MockTool(), options, state], expected_logs=expected_logs) - def _assert_post_diff_output_for_bug(self, step, bug_id, expected_stderr): - self._assert_step_output_with_bug(step, bug_id, expected_stderr, self._post_diff_options()) + def _assert_post_diff_output_for_bug(self, step, bug_id, expected_logs): + self._assert_step_output_with_bug(step, bug_id, expected_logs, self._post_diff_options()) def test_post_diff(self): - expected_stderr = "MOCK add_patch_to_bug: bug_id=78, description=Patch, mark_for_review=True, mark_for_commit_queue=False, mark_for_landing=False\nMOCK: user.open_url: http://example.com/78\n" - self._assert_post_diff_output_for_bug(steps.PostDiff, 78, expected_stderr) + expected_logs = "MOCK add_patch_to_bug: bug_id=78, description=Patch, mark_for_review=True, mark_for_commit_queue=False, mark_for_landing=False\nMOCK: user.open_url: http://example.com/78\n" + self._assert_post_diff_output_for_bug(steps.PostDiff, 78, expected_logs) def test_post_diff_for_commit(self): - expected_stderr = "MOCK add_patch_to_bug: bug_id=78, description=Patch for landing, mark_for_review=False, mark_for_commit_queue=False, mark_for_landing=True\n" - self._assert_post_diff_output_for_bug(steps.PostDiffForCommit, 78, expected_stderr) + expected_logs = "MOCK add_patch_to_bug: bug_id=78, description=Patch for landing, mark_for_review=False, mark_for_commit_queue=False, mark_for_landing=True\n" + self._assert_post_diff_output_for_bug(steps.PostDiffForCommit, 78, expected_logs) def test_ensure_bug_is_open_and_assigned(self): - expected_stderr = "MOCK reopen_bug 50004 with comment 'Reopening to attach new patch.'\n" - self._assert_step_output_with_bug(steps.EnsureBugIsOpenAndAssigned, 50004, expected_stderr) - expected_stderr = "MOCK reassign_bug: bug_id=50002, assignee=None\n" - self._assert_step_output_with_bug(steps.EnsureBugIsOpenAndAssigned, 50002, expected_stderr) + expected_logs = "MOCK reopen_bug 50004 with comment 'Reopening to attach new patch.'\n" + self._assert_step_output_with_bug(steps.EnsureBugIsOpenAndAssigned, 50004, expected_logs) + expected_logs = "MOCK reassign_bug: bug_id=50002, assignee=None\n" + self._assert_step_output_with_bug(steps.EnsureBugIsOpenAndAssigned, 50002, expected_logs) def test_runtests_args(self): mock_options = self._step_options() @@ -104,7 +104,7 @@ class StepsTest(unittest.TestCase): tool = MockTool(log_executive=True) tool.port = lambda: mock_port step = steps.RunTests(tool, mock_options) - expected_stderr = """Running Python unit tests + expected_logs = """Running Python unit tests MOCK run_and_throw_if_fail: ['Tools/Scripts/test-webkitpy'], cwd=/mock-checkout Running Perl unit tests MOCK run_and_throw_if_fail: ['Tools/Scripts/test-webkitperl'], cwd=/mock-checkout @@ -113,4 +113,4 @@ MOCK run_and_throw_if_fail: ['Tools/Scripts/run-javascriptcore-tests'], cwd=/moc Running run-webkit-tests MOCK run_and_throw_if_fail: ['Tools/Scripts/run-webkit-tests', '--quiet'], cwd=/mock-checkout """ - OutputCapture().assert_outputs(self, step.run, [{}], expected_stderr=expected_stderr) + OutputCapture().assert_outputs(self, step.run, [{}], expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/steps/suggestreviewers_unittest.py b/Tools/Scripts/webkitpy/tool/steps/suggestreviewers_unittest.py index e99566326..42254c86b 100644 --- a/Tools/Scripts/webkitpy/tool/steps/suggestreviewers_unittest.py +++ b/Tools/Scripts/webkitpy/tool/steps/suggestreviewers_unittest.py @@ -42,5 +42,5 @@ class SuggestReviewersTest(unittest.TestCase): capture = OutputCapture() step = SuggestReviewers(MockTool(), MockOptions(suggest_reviewers=True, git_commit=None)) expected_stdout = "The following reviewers have recently modified files in your patch:\nFoo Bar\n" - expected_stderr = "Would you like to CC them?\n" - capture.assert_outputs(self, step.run, [{"bug_id": "123"}], expected_stdout=expected_stdout, expected_stderr=expected_stderr) + expected_logs = "Would you like to CC them?\n" + capture.assert_outputs(self, step.run, [{"bug_id": "123"}], expected_stdout=expected_stdout, expected_logs=expected_logs) diff --git a/Tools/Scripts/webkitpy/tool/steps/update.py b/Tools/Scripts/webkitpy/tool/steps/update.py index cae2bbd8d..0737ebcd0 100644 --- a/Tools/Scripts/webkitpy/tool/steps/update.py +++ b/Tools/Scripts/webkitpy/tool/steps/update.py @@ -26,9 +26,12 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import log + +_log = logging.getLogger(__name__) class Update(AbstractStep): @@ -43,7 +46,7 @@ class Update(AbstractStep): def run(self, state): if not self._options.update: return - log("Updating working directory") + _log.info("Updating working directory") self._tool.executive.run_and_throw_if_fail(self._update_command(), quiet=self._options.quiet, cwd=self._tool.scm().checkout_root) def _update_command(self): diff --git a/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreview_unittest.py b/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreview_unittest.py index 8ec8891f9..3182cf3ab 100644 --- a/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreview_unittest.py +++ b/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreview_unittest.py @@ -36,14 +36,14 @@ class UpdateChangeLogsWithReviewerTest(unittest.TestCase): def test_guess_reviewer_from_bug(self): capture = OutputCapture() step = UpdateChangeLogsWithReviewer(MockTool(), MockOptions()) - expected_stderr = "No reviewed patches on bug 50001, cannot infer reviewer.\n" - capture.assert_outputs(self, step._guess_reviewer_from_bug, [50001], expected_stderr=expected_stderr) + expected_logs = "No reviewed patches on bug 50001, cannot infer reviewer.\n" + capture.assert_outputs(self, step._guess_reviewer_from_bug, [50001], expected_logs=expected_logs) def test_guess_reviewer_from_multipatch_bug(self): capture = OutputCapture() step = UpdateChangeLogsWithReviewer(MockTool(), MockOptions()) - expected_stderr = "Guessing \"Reviewer2\" as reviewer from attachment 10001 on bug 50000.\n" - capture.assert_outputs(self, step._guess_reviewer_from_bug, [50000], expected_stderr=expected_stderr) + expected_logs = "Guessing \"Reviewer2\" as reviewer from attachment 10001 on bug 50000.\n" + capture.assert_outputs(self, step._guess_reviewer_from_bug, [50000], expected_logs=expected_logs) def test_empty_state(self): capture = OutputCapture() diff --git a/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreviewer.py b/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreviewer.py index cc3e96525..ef210a02f 100644 --- a/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreviewer.py +++ b/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreviewer.py @@ -26,11 +26,15 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging + from webkitpy.common.checkout.changelog import ChangeLog from webkitpy.tool.grammar import pluralize from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import log, error + +_log = logging.getLogger(__name__) + class UpdateChangeLogsWithReviewer(AbstractStep): @classmethod @@ -45,10 +49,10 @@ class UpdateChangeLogsWithReviewer(AbstractStep): # here as we don't currently have a way to invalidate a bug after making changes (like ObsoletePatches does). patches = self._tool.bugs.fetch_bug(bug_id).reviewed_patches() if not patches: - log("%s on bug %s, cannot infer reviewer." % ("No reviewed patches", bug_id)) + _log.info("%s on bug %s, cannot infer reviewer." % ("No reviewed patches", bug_id)) return None patch = patches[-1] - log("Guessing \"%s\" as reviewer from attachment %s on bug %s." % (patch.reviewer().full_name, patch.id(), bug_id)) + _log.info("Guessing \"%s\" as reviewer from attachment %s on bug %s." % (patch.reviewer().full_name, patch.id(), bug_id)) return patch.reviewer().full_name def run(self, state): @@ -59,12 +63,12 @@ class UpdateChangeLogsWithReviewer(AbstractStep): reviewer = self._options.reviewer if not reviewer: if not bug_id: - log("No bug id provided and --reviewer= not provided. Not updating ChangeLogs with reviewer.") + _log.info("No bug id provided and --reviewer= not provided. Not updating ChangeLogs with reviewer.") return reviewer = self._guess_reviewer_from_bug(bug_id) if not reviewer: - log("Failed to guess reviewer from bug %s and --reviewer= not provided. Not updating ChangeLogs with reviewer." % bug_id) + _log.info("Failed to guess reviewer from bug %s and --reviewer= not provided. Not updating ChangeLogs with reviewer." % bug_id) return # cached_lookup("changelogs") is always absolute paths. diff --git a/Tools/Scripts/webkitpy/tool/steps/updatechromiumdeps.py b/Tools/Scripts/webkitpy/tool/steps/updatechromiumdeps.py index c9fc63179..23d861bfc 100644 --- a/Tools/Scripts/webkitpy/tool/steps/updatechromiumdeps.py +++ b/Tools/Scripts/webkitpy/tool/steps/updatechromiumdeps.py @@ -26,12 +26,15 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging +import sys import urllib2 from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options from webkitpy.common.config import urls -from webkitpy.common.system.deprecated_logging import log, error + +_log = logging.getLogger(__name__) class UpdateChromiumDEPS(AbstractStep): @@ -49,16 +52,17 @@ class UpdateChromiumDEPS(AbstractStep): if new_chromium_revision < current_chromium_revision: message = "Current Chromium DEPS revision %s is newer than %s." % (current_chromium_revision, new_chromium_revision) if self._options.non_interactive: - error(message) # Causes the process to terminate. - log(message) + _log.error(message) + sys.exit(1) + _log.info(message) new_chromium_revision = self._tool.user.prompt("Enter new chromium revision (enter nothing to cancel):\n") try: new_chromium_revision = int(new_chromium_revision) except ValueError, TypeError: new_chromium_revision = None if not new_chromium_revision: - error("Unable to update Chromium DEPS") - + _log.error("Unable to update Chromium DEPS") + sys.exit(1) def run(self, state): # Note that state["chromium_revision"] must be defined, but can be None. @@ -69,5 +73,5 @@ class UpdateChromiumDEPS(AbstractStep): deps = self._tool.checkout().chromium_deps() current_chromium_revision = deps.read_variable("chromium_rev") self._validate_revisions(current_chromium_revision, new_chromium_revision) - log("Updating Chromium DEPS to %s" % new_chromium_revision) + _log.info("Updating Chromium DEPS to %s" % new_chromium_revision) deps.write_variable("chromium_rev", new_chromium_revision) diff --git a/Tools/Scripts/webkitpy/tool/steps/validatechangelogs.py b/Tools/Scripts/webkitpy/tool/steps/validatechangelogs.py index b6b33c0b6..061baa5ec 100644 --- a/Tools/Scripts/webkitpy/tool/steps/validatechangelogs.py +++ b/Tools/Scripts/webkitpy/tool/steps/validatechangelogs.py @@ -26,10 +26,14 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging +import sys + from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options from webkitpy.common.checkout.diff_parser import DiffParser -from webkitpy.common.system.deprecated_logging import error, log + +_log = logging.getLogger(__name__) # This is closely related to the ValidateReviewer step and the CommitterValidator class. @@ -53,7 +57,7 @@ class ValidateChangeLogs(AbstractStep): if self._options.non_interactive: return False - log("The diff to %s looks wrong. Are you sure your ChangeLog entry is at the top of the file?" % (diff_file.filename)) + _log.info("The diff to %s looks wrong. Are you sure your ChangeLog entry is at the top of the file?" % (diff_file.filename)) # FIXME: Do we need to make the file path absolute? self._tool.scm().diff_for_file(diff_file.filename) if self._tool.user.confirm("OK to continue?", default='n'): @@ -73,4 +77,5 @@ class ValidateChangeLogs(AbstractStep): parsed_diff = DiffParser(diff.splitlines()) for filename, diff_file in parsed_diff.files.items(): if not self._check_changelog_diff(diff_file): - error("ChangeLog entry in %s is not at the top of the file." % diff_file.filename) + _log.error("ChangeLog entry in %s is not at the top of the file." % diff_file.filename) + sys.exit(1) diff --git a/Tools/Scripts/webkitpy/tool/steps/validatechangelogs_unittest.py b/Tools/Scripts/webkitpy/tool/steps/validatechangelogs_unittest.py index 96bae9fa8..c3b723ed1 100644 --- a/Tools/Scripts/webkitpy/tool/steps/validatechangelogs_unittest.py +++ b/Tools/Scripts/webkitpy/tool/steps/validatechangelogs_unittest.py @@ -43,10 +43,10 @@ class ValidateChangeLogsTest(unittest.TestCase): diff_file = Mock() diff_file.filename = "mock/ChangeLog" diff_file.lines = [(start_line, start_line, "foo")] - expected_stdout = expected_stderr = "" + expected_stdout = expected_stderr = expected_logs = "" if should_fail and not non_interactive: - expected_stderr = "The diff to mock/ChangeLog looks wrong. Are you sure your ChangeLog entry is at the top of the file?\nOK to continue?\n" - result = OutputCapture().assert_outputs(self, step._check_changelog_diff, [diff_file], expected_stderr=expected_stderr) + expected_logs = "The diff to mock/ChangeLog looks wrong. Are you sure your ChangeLog entry is at the top of the file?\nOK to continue?\n" + result = OutputCapture().assert_outputs(self, step._check_changelog_diff, [diff_file], expected_logs=expected_logs) self.assertEqual(not result, should_fail) def test_check_changelog_diff(self): diff --git a/Tools/Scripts/webkitpy/tool/steps/validatereviewer.py b/Tools/Scripts/webkitpy/tool/steps/validatereviewer.py index 5e93821ce..90ddf5be3 100644 --- a/Tools/Scripts/webkitpy/tool/steps/validatereviewer.py +++ b/Tools/Scripts/webkitpy/tool/steps/validatereviewer.py @@ -26,10 +26,14 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import logging +import sys + from webkitpy.common.checkout.changelog import ChangeLog from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options -from webkitpy.common.system.deprecated_logging import error, log + +_log = logging.getLogger(__name__) # FIXME: Some of this logic should probably be unified with CommitterValidator? @@ -51,5 +55,6 @@ class ValidateReviewer(AbstractStep): continue reviewer_text = changelog_entry.reviewer_text() if reviewer_text: - log("%s found in %s does not appear to be a valid reviewer according to committers.py." % (reviewer_text, changelog_path)) - error('%s neither lists a valid reviewer nor contains the string "Unreviewed" or "Rubber stamp" (case insensitive).' % changelog_path) + _log.info("%s found in %s does not appear to be a valid reviewer according to committers.py." % (reviewer_text, changelog_path)) + _log.error('%s neither lists a valid reviewer nor contains the string "Unreviewed" or "Rubber stamp" (case insensitive).' % changelog_path) + sys.exit(1) diff --git a/Tools/TestWebKitAPI/PlatformEfl.cmake b/Tools/TestWebKitAPI/PlatformEfl.cmake index 88f424e66..e301968fe 100644 --- a/Tools/TestWebKitAPI/PlatformEfl.cmake +++ b/Tools/TestWebKitAPI/PlatformEfl.cmake @@ -59,6 +59,7 @@ SET(test_webkit2_api_BINARIES InjectedBundleInitializationUserDataCallbackWins LoadAlternateHTMLStringWithNonDirectoryURL LoadCanceledNoServerRedirectCallback + MouseMoveAfterCrash NewFirstVisuallyNonEmptyLayout NewFirstVisuallyNonEmptyLayoutFails PageLoadBasic @@ -90,7 +91,6 @@ ADD_DEFINITIONS(-DTHEME_DIR="${THEME_BINARY_DIR}") # Tests disabled because of missing features on the test harness: # # HitTestResultNodeHandle -# MouseMoveAfterCrash # ResponsivenessTimerDoesntFireEarly # SpacebarScrolling # diff --git a/Tools/TestWebKitAPI/Tests/WebCore/win/BitmapImage.cpp b/Tools/TestWebKitAPI/Tests/WebCore/win/BitmapImage.cpp new file mode 100644 index 000000000..d0d1bf29e --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebCore/win/BitmapImage.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * Copyright (C) 2012 peavo@outlook.com All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <WebCore/BitmapImage.h> + +using namespace WebCore; + +namespace TestWebKitAPI { + +// Test that there is no crash when BitmapImage::getHBITMAPOfSize() is called +// for an image with empty frames (BitmapImage::frameAtIndex(i) return null), WebKit Bug 102689. + +class BitmapImageTest : public WebCore::BitmapImage { +public: + BitmapImageTest() + { + m_frames.grow(1); + } + + virtual size_t frameCount() + { + return 1; + } +}; + +TEST(WebCore, BitmapImageEmptyFrameTest) +{ + SIZE sz = {16, 16}; + BitmapImageTest bitmapImageTest; + int bits[256]; + HBITMAP hBitmap = CreateBitmap(16, 16, 1, 32, bits); + bitmapImageTest.getHBITMAPOfSize(hBitmap, &sz); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/AboutBlankLoad.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/AboutBlankLoad.cpp index ff36a0b18..42939dd2d 100644 --- a/Tools/TestWebKitAPI/Tests/WebKit2/AboutBlankLoad.cpp +++ b/Tools/TestWebKitAPI/Tests/WebKit2/AboutBlankLoad.cpp @@ -31,11 +31,10 @@ namespace TestWebKitAPI { static bool done; -static void decidePolicyForResponse(WKPageRef, WKFrameRef, WKURLResponseRef response, WKURLRequestRef, WKFramePolicyListenerRef listener, WKTypeRef, const void*) +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) { - EXPECT_WK_STREQ("text/html", Util::MIMETypeForWKURLResponse(response)); - - WKFramePolicyListenerUse(listener); + WKRetainPtr<WKStringRef> mimeType = adoptWK(WKFrameCopyMIMEType(frame)); + EXPECT_WK_STREQ("text/html", mimeType); done = true; } @@ -44,11 +43,10 @@ TEST(WebKit2, AboutBlankLoad) WKRetainPtr<WKContextRef> context = adoptWK(WKContextCreate()); PlatformWebView webView(context.get()); - WKPagePolicyClient policyClient; - memset(&policyClient, 0, sizeof(policyClient)); - - policyClient.decidePolicyForResponse = decidePolicyForResponse; - WKPageSetPagePolicyClient(webView.page(), &policyClient); + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0 , sizeof(loaderClient)); + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); WKPageLoadURL(webView.page(), adoptWK(WKURLCreateWithUTF8CString("about:blank")).get()); diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/WKPreferences.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/WKPreferences.cpp index 3c4bedaf4..976e7041b 100644 --- a/Tools/TestWebKitAPI/Tests/WebKit2/WKPreferences.cpp +++ b/Tools/TestWebKitAPI/Tests/WebKit2/WKPreferences.cpp @@ -102,6 +102,7 @@ TEST(WebKit2, WKPreferencesDefaults) EXPECT_FALSE(WKPreferencesGetCompositingRepaintCountersVisible(preference)); EXPECT_FALSE(WKPreferencesGetNeedsSiteSpecificQuirks(preference)); EXPECT_EQ(kWKAllowAllStorage, WKPreferencesGetStorageBlockingPolicy(preference)); + EXPECT_FALSE(WKPreferencesGetTextAutosizingEnabled(preference)); WKRelease(preference); } diff --git a/Tools/TestWebKitAPI/config.h b/Tools/TestWebKitAPI/config.h index e796ebc98..dd240a585 100644 --- a/Tools/TestWebKitAPI/config.h +++ b/Tools/TestWebKitAPI/config.h @@ -47,6 +47,19 @@ #define NOMINMAX #endif +#if PLATFORM(WIN_CAIRO) +#undef WTF_USE_CG +#define WTF_USE_CAIRO 1 +#define WTF_USE_CURL 1 +#ifndef _WINSOCKAPI_ +#define _WINSOCKAPI_ // Prevent inclusion of winsock.h in windows.h +#endif +#elif !OS(WINCE) +#define WTF_USE_CG 1 +#undef WTF_USE_CAIRO +#undef WTF_USE_CURL +#endif + #endif #include <stdint.h> diff --git a/Tools/TestWebKitAPI/efl/PlatformUtilities.cpp b/Tools/TestWebKitAPI/efl/PlatformUtilities.cpp index 50f586d60..65c54e1a7 100644 --- a/Tools/TestWebKitAPI/efl/PlatformUtilities.cpp +++ b/Tools/TestWebKitAPI/efl/PlatformUtilities.cpp @@ -42,7 +42,7 @@ void run(bool* done) void sleep(double seconds) { - sleep(seconds); + usleep(seconds * 1000000); } WKURLRef createURLForResource(const char* resource, const char* extension) diff --git a/Tools/TestWebKitAPI/efl/PlatformWebView.cpp b/Tools/TestWebKitAPI/efl/PlatformWebView.cpp index 2e87f7087..cdc97bd13 100644 --- a/Tools/TestWebKitAPI/efl/PlatformWebView.cpp +++ b/Tools/TestWebKitAPI/efl/PlatformWebView.cpp @@ -54,12 +54,19 @@ static Ecore_Evas* initEcoreEvas() return ecoreEvas; } +static void onWebProcessCrashed(void*, Evas_Object*, void* eventInfo) +{ + bool* handled = static_cast<bool*>(eventInfo); + *handled = true; +} + PlatformWebView::PlatformWebView(WKContextRef contextRef, WKPageGroupRef pageGroupRef) { m_window = initEcoreEvas(); Evas* evas = ecore_evas_get(m_window); m_view = toImpl(WKViewCreate(evas, contextRef, pageGroupRef)); ewk_view_theme_set(m_view, THEME_DIR"/default.edj"); + evas_object_smart_callback_add(m_view, "webprocess,crashed", onWebProcessCrashed, 0); resizeTo(600, 800); } @@ -80,4 +87,19 @@ WKPageRef PlatformWebView::page() const return WKViewGetPage(toAPI(m_view)); } +void PlatformWebView::simulateSpacebarKeyPress() +{ + Evas* evas = ecore_evas_get(m_window); + evas_object_focus_set(m_view, true); + evas_event_feed_key_down(evas, "space", "space", " ", 0, 0, 0); + evas_event_feed_key_up(evas, "space", "space", " ", 0, 1, 0); +} + +void PlatformWebView::simulateMouseMove(unsigned x, unsigned y) +{ + Evas* evas = ecore_evas_get(m_window); + evas_object_show(m_view); + evas_event_feed_mouse_move(evas, x, y, 0, 0); +} + } // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/mac/InstanceMethodSwizzler.h b/Tools/TestWebKitAPI/mac/InstanceMethodSwizzler.h index 20d9f0afa..fe31a8aa9 100644 --- a/Tools/TestWebKitAPI/mac/InstanceMethodSwizzler.h +++ b/Tools/TestWebKitAPI/mac/InstanceMethodSwizzler.h @@ -26,7 +26,7 @@ #ifndef InstanceMethodSwizzler_h #define InstanceMethodSwizzler_h -#include <objc/objc-runtime.h> +#include <objc/runtime.h> #include <wtf/Noncopyable.h> namespace TestWebKitAPI { diff --git a/Tools/TestWebKitAPI/win/TestWebKitAPI.vcproj b/Tools/TestWebKitAPI/win/TestWebKitAPI.vcproj index a2a90f4f2..96b2d256e 100644 --- a/Tools/TestWebKitAPI/win/TestWebKitAPI.vcproj +++ b/Tools/TestWebKitAPI/win/TestWebKitAPI.vcproj @@ -421,6 +421,18 @@ Name="Tests"
>
<Filter
+ Name="WebCore"
+ >
+ <Filter
+ Name="win"
+ >
+ <File
+ RelativePath="..\Tests\WebCore\win\BitmapImage.cpp"
+ >
+ </File>
+ </Filter>
+ </Filter>
+ <Filter
Name="WebKit2"
>
<File
diff --git a/Tools/Tools.pro b/Tools/Tools.pro index dcc365b6f..2868f8c9d 100644 --- a/Tools/Tools.pro +++ b/Tools/Tools.pro @@ -34,6 +34,7 @@ OTHER_FILES = \ qmake/config.tests/README \ qmake/config.tests/fontconfig/* \ qmake/config.tests/gccdepends/* \ + qmake/config.tests/libexecdir/* \ qmake/mkspecs/modules/* \ qmake/mkspecs/features/*.prf \ qmake/mkspecs/features/*.pri \ diff --git a/Tools/WebKitTestRunner/InjectedBundle/mac/ActivateFonts.mm b/Tools/WebKitTestRunner/InjectedBundle/mac/ActivateFonts.mm index f13dd9dab..c2768db34 100644 --- a/Tools/WebKitTestRunner/InjectedBundle/mac/ActivateFonts.mm +++ b/Tools/WebKitTestRunner/InjectedBundle/mac/ActivateFonts.mm @@ -28,7 +28,6 @@ #import <AppKit/AppKit.h> #import <CoreFoundation/CoreFoundation.h> -#import <objc/objc-runtime.h> #import <wtf/ObjcRuntimeExtras.h> #import <wtf/RetainPtr.h> diff --git a/Tools/WebKitTestRunner/InjectedBundle/qt/InjectedBundleQt.cpp b/Tools/WebKitTestRunner/InjectedBundle/qt/InjectedBundleQt.cpp index 845097307..d14dd87b5 100644 --- a/Tools/WebKitTestRunner/InjectedBundle/qt/InjectedBundleQt.cpp +++ b/Tools/WebKitTestRunner/InjectedBundle/qt/InjectedBundleQt.cpp @@ -28,7 +28,8 @@ #include "InjectedBundle.h" #include <QApplication> #include <QByteArray> -#include <QWindowsStyle> +#include <QStyle> +#include <QStyleFactory> #include <stdio.h> #include <stdlib.h> #include <wtf/AlwaysInline.h> @@ -38,7 +39,7 @@ namespace WTR { void InjectedBundle::platformInitialize(WKTypeRef) { - QWindowsStyle* styleForTests = new QWindowsStyle; + QStyle* styleForTests = QStyleFactory::create(QLatin1String("windows")); QApplication::setStyle(styleForTests); // Force Qt to use the style's standard palette, instead of platform default palette. This is needed // because we are setting the style after QApplication is instantiated. diff --git a/Tools/WebKitTestRunner/TestInvocation.cpp b/Tools/WebKitTestRunner/TestInvocation.cpp index bad24fa61..8f66cc0dd 100644 --- a/Tools/WebKitTestRunner/TestInvocation.cpp +++ b/Tools/WebKitTestRunner/TestInvocation.cpp @@ -105,7 +105,7 @@ TestInvocation::TestInvocation(const std::string& pathOrURL) , m_gotFinalMessage(false) , m_gotRepaint(false) , m_error(false) - , m_webProcessIsUnrensponsive(false) + , m_webProcessIsUnresponsive(false) { } @@ -213,7 +213,7 @@ void TestInvocation::invoke() TestController::shared().runUntil(m_gotInitialResponse, TestController::ShortTimeout); if (!m_gotInitialResponse) { m_errorMessage = "Timed out waiting for initial response from web process\n"; - m_webProcessIsUnrensponsive = true; + m_webProcessIsUnresponsive = true; goto end; } if (m_error) @@ -229,7 +229,7 @@ void TestInvocation::invoke() TestController::shared().runUntil(m_gotFinalMessage, TestController::shared().useWaitToDumpWatchdogTimer() ? TestController::LongTimeout : TestController::NoTimeout); if (!m_gotFinalMessage) { m_errorMessage = "Timed out waiting for final message from web process\n"; - m_webProcessIsUnrensponsive = true; + m_webProcessIsUnresponsive = true; goto end; } if (m_error) @@ -243,7 +243,7 @@ end: WKInspectorClose(WKPageGetInspector(TestController::shared().mainWebView()->page())); #endif // ENABLE(INSPECTOR) - if (m_webProcessIsUnrensponsive) + if (m_webProcessIsUnresponsive) dumpWebProcessUnresponsiveness(); else if (!TestController::shared().resetStateToConsistentValues()) { m_errorMessage = "Timed out loading about:blank before the next test"; diff --git a/Tools/WebKitTestRunner/TestInvocation.h b/Tools/WebKitTestRunner/TestInvocation.h index c14b060a3..e49d9fd0d 100644 --- a/Tools/WebKitTestRunner/TestInvocation.h +++ b/Tools/WebKitTestRunner/TestInvocation.h @@ -51,9 +51,8 @@ private: void dumpPixelsAndCompareWithExpected(WKImageRef, WKArrayRef repaintRects); bool compareActualHashToExpectedAndDumpResults(const char[33]); -#if PLATFORM(QT) +#if PLATFORM(QT) || PLATFORM(EFL) static void forceRepaintDoneCallback(WKErrorRef, void* context); - void forceRepaintDone(); #endif WKRetainPtr<WKURLRef> m_url; @@ -72,7 +71,7 @@ private: WKRetainPtr<WKImageRef> m_pixelResult; WKRetainPtr<WKArrayRef> m_repaintRects; std::string m_errorMessage; - bool m_webProcessIsUnrensponsive; + bool m_webProcessIsUnresponsive; }; diff --git a/Tools/WebKitTestRunner/cairo/TestInvocationCairo.cpp b/Tools/WebKitTestRunner/cairo/TestInvocationCairo.cpp index 498be14e4..eb3a0d3a2 100644 --- a/Tools/WebKitTestRunner/cairo/TestInvocationCairo.cpp +++ b/Tools/WebKitTestRunner/cairo/TestInvocationCairo.cpp @@ -30,6 +30,8 @@ #include "TestInvocation.h" #include "PixelDumpSupport.h" +#include "PlatformWebView.h" +#include "TestController.h" #include <WebKit2/WKImageCairo.h> #include <cairo/cairo.h> #include <cstdio> @@ -61,7 +63,7 @@ void computeMD5HashStringForCairoSurface(cairo_surface_t* surface, char hashStri hash[8], hash[9], hash[10], hash[11], hash[12], hash[13], hash[14], hash[15]); } -static cairo_status_t writeFunction(void* closure, const unsigned char* data, unsigned int length) +static cairo_status_t writeFunction(void* closure, const unsigned char* data, unsigned length) { Vector<unsigned char>* in = reinterpret_cast<Vector<unsigned char>*>(closure); in->append(data, length); @@ -104,9 +106,37 @@ static void paintRepaintRectOverlay(cairo_surface_t* surface, WKArrayRef repaint cairo_destroy(context); } +#if PLATFORM(EFL) +void TestInvocation::forceRepaintDoneCallback(WKErrorRef, void *context) +{ + static_cast<TestInvocation*>(context)->m_gotRepaint = true; + TestController::shared().notifyDone(); +} +#endif + void TestInvocation::dumpPixelsAndCompareWithExpected(WKImageRef wkImage, WKArrayRef repaintRects) { +#if USE(ACCELERATED_COMPOSITING) && PLATFORM(EFL) + UNUSED_PARAM(wkImage); + + cairo_surface_t* surface; + + WKPageRef page = TestController::shared().mainWebView()->page(); + WKPageForceRepaint(page, this, &forceRepaintDoneCallback); + + TestController::shared().runUntil(m_gotRepaint, TestController::ShortTimeout); + + if (!m_gotRepaint) { + m_error = true; + m_errorMessage = "Timed out waiting for repaint\n"; + m_webProcessIsUnresponsive = true; + return; + } + + surface = WKImageCreateCairoSurface(TestController::shared().mainWebView()->windowSnapshotImage().get()); +#else cairo_surface_t* surface = WKImageCreateCairoSurface(wkImage); +#endif if (repaintRects) paintRepaintRectOverlay(surface, repaintRects); diff --git a/Tools/WebKitTestRunner/efl/PlatformWebViewEfl.cpp b/Tools/WebKitTestRunner/efl/PlatformWebViewEfl.cpp index a55242dc1..c7501a998 100644 --- a/Tools/WebKitTestRunner/efl/PlatformWebViewEfl.cpp +++ b/Tools/WebKitTestRunner/efl/PlatformWebViewEfl.cpp @@ -24,6 +24,9 @@ #include "EWebKit2.h" #include "WebKit2/WKAPICast.h" #include <Ecore_Evas.h> +#include <WebCore/RefPtrCairo.h> +#include <WebKit2/WKImageCairo.h> +#include <cairo.h> using namespace WebKit; @@ -124,9 +127,15 @@ void PlatformWebView::makeWebViewFirstResponder() WKRetainPtr<WKImageRef> PlatformWebView::windowSnapshotImage() { - // FIXME: implement to capture pixels in the UI process, - // which may be necessary to capture things like 3D transforms. - return 0; + Ecore_Evas* ee = ecore_evas_ecore_evas_get(evas_object_evas_get(m_view)); + ASSERT(ee); + + int width; + int height; + ecore_evas_geometry_get(ee, 0, 0, &width, &height); + ASSERT(width > 0 && height > 0); + + return adoptWK(WKViewGetSnapshot(toAPI(m_view))); } bool PlatformWebView::viewSupportsOptions(WKDictionaryRef options) const diff --git a/Tools/WebKitTestRunner/qt/TestInvocationQt.cpp b/Tools/WebKitTestRunner/qt/TestInvocationQt.cpp index 682a6377f..99d5d0e2b 100644 --- a/Tools/WebKitTestRunner/qt/TestInvocationQt.cpp +++ b/Tools/WebKitTestRunner/qt/TestInvocationQt.cpp @@ -85,7 +85,7 @@ void TestInvocation::dumpPixelsAndCompareWithExpected(WKImageRef imageRef, WKArr else { m_error = true; m_errorMessage = "Timed out waiting for repaint\n"; - m_webProcessIsUnrensponsive = true; + m_webProcessIsUnresponsive = true; return; } } else diff --git a/Tools/efl/jhbuild.modules b/Tools/efl/jhbuild.modules index 04de528ba..07a248e97 100644 --- a/Tools/efl/jhbuild.modules +++ b/Tools/efl/jhbuild.modules @@ -274,7 +274,7 @@ </autotools> <autotools id="elementary" - autogenargs="--disable-web"> + autogenargs="--disable-emap --disable-ethumb --disable-eweather --disable-web"> <branch module="releases/elementary-1.7.1.tar.bz2" version="1.7.1" checkoutdir="elementary-1.7.1" repo="download.enlightenment.org" diff --git a/Tools/qmake/config.tests/libexecdir/libexecdir.cpp b/Tools/qmake/config.tests/libexecdir/libexecdir.cpp new file mode 100644 index 000000000..a8be6a606 --- /dev/null +++ b/Tools/qmake/config.tests/libexecdir/libexecdir.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include <qlibraryinfo.h> + +int main(int, char**) +{ + QLibraryInfo::location(QLibraryInfo::LibraryExecutablesPath); + return 0; +} diff --git a/Tools/qmake/config.tests/libexecdir/libexecdir.pro b/Tools/qmake/config.tests/libexecdir/libexecdir.pro new file mode 100644 index 000000000..0db56971b --- /dev/null +++ b/Tools/qmake/config.tests/libexecdir/libexecdir.pro @@ -0,0 +1,4 @@ +SOURCES = libexecdir.cpp +OBJECTS_DIR = obj +CONFIG += qt +QT -= gui diff --git a/Tools/qmake/mkspecs/features/features.prf b/Tools/qmake/mkspecs/features/features.prf index 0212e7969..884902568 100644 --- a/Tools/qmake/mkspecs/features/features.prf +++ b/Tools/qmake/mkspecs/features/features.prf @@ -37,6 +37,7 @@ defineTest(detectFeatures) { haveQtModule(widgets): WEBKIT_CONFIG += have_qstyle haveQtModule(testlib): WEBKIT_CONFIG += have_qttestlib + config_libexecdir: WEBKIT_CONFIG += use_libexecdir config_libxml2: WEBKIT_CONFIG += use_libxml2 config_libxslt: WEBKIT_CONFIG += xslt config_libzlib: WEBKIT_CONFIG += use_zlib @@ -1,9 +1,9 @@ This is a snapshot of WebKit. It is based on the upstream trunk subversion -revision 135701 +revision 136119 You can browse the base of this snapshot at - http://trac.webkit.org/browser/trunk?rev=135701 + http://trac.webkit.org/browser/trunk?rev=136119 Additional patches may have been applied on top and files not required by the Qt port may have been removed. diff --git a/WebKitLibraries/ChangeLog b/WebKitLibraries/ChangeLog index 5a5b1d002..bc819602c 100644 --- a/WebKitLibraries/ChangeLog +++ b/WebKitLibraries/ChangeLog @@ -1,3 +1,15 @@ +2012-11-26 Roger Fong <roger_fong@apple.com> + + Unreviewed. ENABLE_ACCELERATED_OVERFLOW_SCROLLING not enabled on Windows. + Add a feature flag and skip some failing tests. + https://bugs.webkit.org/show_bug.cgi?id=103294 + + Tests skipped: + compositing/overflow/scrolling-without-painting.html + compositing/overflow/updating-scrolling-content.html + + * win/tools/vsprops/FeatureDefines.vsprops: + 2012-11-23 Alexis Menard <alexis@webkit.org> [CSS3 Backgrounds and Borders] Implement new CSS3 background-position parsing. diff --git a/WebKitLibraries/win/tools/vsprops/FeatureDefines.vsprops b/WebKitLibraries/win/tools/vsprops/FeatureDefines.vsprops index 33e2f1ceb..17079c877 100644 --- a/WebKitLibraries/win/tools/vsprops/FeatureDefines.vsprops +++ b/WebKitLibraries/win/tools/vsprops/FeatureDefines.vsprops @@ -9,7 +9,7 @@ >
<Tool
Name="VCCLCompilerTool"
- PreprocessorDefinitions="$(ENABLE_IFRAME_SEAMLESS);$(ENABLE_REQUEST_ANIMATION_FRAME);$(ENABLE_3D_RENDERING);$(ENABLE_ACCELERATED_2D_CANVAS);$(ENABLE_BLOB);$(ENABLE_CHANNEL_MESSAGING);$(ENABLE_CSS3_BACKGROUND);$(ENABLE_CSS3_CONDITIONAL_RULES);$(ENABLE_CSS3_TEXT);$(ENABLE_CSS_BOX_DECORATION_BREAK);$(ENABLE_CSS_FILTERS);$(ENABLE_CSS_GRID_LAYOUT);$(ENABLE_CSS_SHADERS);$(ENABLE_CSS_COMPOSITING);$(ENABLE_CSS_REGIONS);$(ENABLE_CSS_EXCLUSIONS);$(ENABLE_CSS_STICKY_POSITION);$(ENABLE_CUSTOM_SCHEME_HANDLER);$(ENABLE_SQL_DATABASE);$(ENABLE_DATAGRID);$(ENABLE_DATALIST_ELEMENT);$(ENABLE_DATA_TRANSFER_ITEMS);$(ENABLE_DETAILS_ELEMENT);$(ENABLE_DEVICE_ORIENTATION);$(ENABLE_DIRECTORY_UPLOAD);$(ENABLE_FILTERS);$(ENABLE_FILE_SYSTEM);$(ENABLE_FULLSCREEN_API);$(ENABLE_GAMEPAD);$(ENABLE_GEOLOCATION);$(ENABLE_HIDDEN_PAGE_DOM_TIMER_THROTTLING);$(ENABLE_HIGH_DPI_CANVAS);$(ENABLE_ICONDATABASE);$(ENABLE_INDEXED_DATABASE);$(ENABLE_INPUT_TYPE_COLOR);$(ENABLE_INPUT_SPEECH);$(ENABLE_INPUT_TYPE_DATE);$(ENABLE_INPUT_TYPE_DATETIME);$(ENABLE_INPUT_TYPE_DATETIMELOCAL);$(ENABLE_INPUT_TYPE_MONTH);$(ENABLE_INPUT_TYPE_TIME);$(ENABLE_INPUT_TYPE_WEEK);$(ENABLE_JAVASCRIPT_DEBUGGER);$(ENABLE_LEGACY_CSS_VENDOR_PREFIXES);$(ENABLE_LEGACY_NOTIFICATIONS);$(ENABLE_LINK_PREFETCH);$(ENABLE_LINK_PRERENDER);$(ENABLE_MATHML);$(ENABLE_METER_ELEMENT);$(ENABLE_MICRODATA);$(ENABLE_MUTATION_OBSERVERS);$(ENABLE_NOTIFICATIONS);$(ENABLE_PAGE_VISIBILITY_API);$(ENABLE_PROGRESS_ELEMENT);$(ENABLE_PROXIMITY_EVENTS);$(ENABLE_QUOTA);$(ENABLE_REGISTER_PROTOCOL_HANDLER);$(ENABLE_SCRIPTED_SPEECH);$(ENABLE_SHADOW_DOM);$(ENABLE_SHARED_WORKERS);$(ENABLE_STYLE_SCOPED);$(ENABLE_SVG);$(ENABLE_SVG_DOM_OBJC_BINDINGS);$(ENABLE_SVG_FONTS);$(ENABLE_SUBPIXEL_LAYOUT);$(ENABLE_TEXT_AUTOSIZING);$(ENABLE_UNDO_MANAGER);$(ENABLE_VIDEO);$(ENABLE_MEDIA_SOURCE);$(ENABLE_MEDIA_STATISTICS);$(ENABLE_WEB_SOCKETS);$(ENABLE_WEB_TIMING);$(ENABLE_WORKERS);$(ENABLE_XSLT)"
+ PreprocessorDefinitions="$(ENABLE_IFRAME_SEAMLESS);$(ENABLE_REQUEST_ANIMATION_FRAME);$(ENABLE_3D_RENDERING);$(ENABLE_ACCELERATED_2D_CANVAS);$(ENABLE_ACCELERATED_OVERFLOW_SCROLLING);$(ENABLE_BLOB);$(ENABLE_CHANNEL_MESSAGING);$(ENABLE_CSS3_BACKGROUND);$(ENABLE_CSS3_CONDITIONAL_RULES);$(ENABLE_CSS3_TEXT);$(ENABLE_CSS_BOX_DECORATION_BREAK);$(ENABLE_CSS_FILTERS);$(ENABLE_CSS_GRID_LAYOUT);$(ENABLE_CSS_SHADERS);$(ENABLE_CSS_COMPOSITING);$(ENABLE_CSS_REGIONS);$(ENABLE_CSS_EXCLUSIONS);$(ENABLE_CSS_STICKY_POSITION);$(ENABLE_CUSTOM_SCHEME_HANDLER);$(ENABLE_SQL_DATABASE);$(ENABLE_DATAGRID);$(ENABLE_DATALIST_ELEMENT);$(ENABLE_DATA_TRANSFER_ITEMS);$(ENABLE_DETAILS_ELEMENT);$(ENABLE_DEVICE_ORIENTATION);$(ENABLE_DIRECTORY_UPLOAD);$(ENABLE_FILTERS);$(ENABLE_FILE_SYSTEM);$(ENABLE_FULLSCREEN_API);$(ENABLE_GAMEPAD);$(ENABLE_GEOLOCATION);$(ENABLE_HIDDEN_PAGE_DOM_TIMER_THROTTLING);$(ENABLE_HIGH_DPI_CANVAS);$(ENABLE_ICONDATABASE);$(ENABLE_INDEXED_DATABASE);$(ENABLE_INPUT_TYPE_COLOR);$(ENABLE_INPUT_SPEECH);$(ENABLE_INPUT_TYPE_DATE);$(ENABLE_INPUT_TYPE_DATETIME);$(ENABLE_INPUT_TYPE_DATETIMELOCAL);$(ENABLE_INPUT_TYPE_MONTH);$(ENABLE_INPUT_TYPE_TIME);$(ENABLE_INPUT_TYPE_WEEK);$(ENABLE_JAVASCRIPT_DEBUGGER);$(ENABLE_LEGACY_CSS_VENDOR_PREFIXES);$(ENABLE_LEGACY_NOTIFICATIONS);$(ENABLE_LINK_PREFETCH);$(ENABLE_LINK_PRERENDER);$(ENABLE_MATHML);$(ENABLE_METER_ELEMENT);$(ENABLE_MICRODATA);$(ENABLE_MUTATION_OBSERVERS);$(ENABLE_NOTIFICATIONS);$(ENABLE_PAGE_VISIBILITY_API);$(ENABLE_PROGRESS_ELEMENT);$(ENABLE_PROXIMITY_EVENTS);$(ENABLE_QUOTA);$(ENABLE_REGISTER_PROTOCOL_HANDLER);$(ENABLE_SCRIPTED_SPEECH);$(ENABLE_SHADOW_DOM);$(ENABLE_SHARED_WORKERS);$(ENABLE_STYLE_SCOPED);$(ENABLE_SVG);$(ENABLE_SVG_DOM_OBJC_BINDINGS);$(ENABLE_SVG_FONTS);$(ENABLE_SUBPIXEL_LAYOUT);$(ENABLE_TEXT_AUTOSIZING);$(ENABLE_UNDO_MANAGER);$(ENABLE_VIDEO);$(ENABLE_MEDIA_SOURCE);$(ENABLE_MEDIA_STATISTICS);$(ENABLE_WEB_SOCKETS);$(ENABLE_WEB_TIMING);$(ENABLE_WORKERS);$(ENABLE_XSLT)"
/>
<UserMacro
Name="ENABLE_3D_RENDERING"
@@ -22,6 +22,11 @@ PerformEnvironmentSet="true"
/>
<UserMacro
+ Name="ENABLE_ACCELERATED_OVERFLOW_SCROLLING"
+ Value=""
+ PerformEnvironmentSet="true"
+ />
+ <UserMacro
Name="ENABLE_BLOB"
Value=""
PerformEnvironmentSet="true"
diff --git a/configure.ac b/configure.ac index 4e1f0e80c..97980e4d0 100644 --- a/configure.ac +++ b/configure.ac @@ -1118,6 +1118,13 @@ if test "$enable_webkit2" = "yes"; then if test "$have_gtk_unix_printing" = "yes"; then AC_DEFINE([HAVE_GTK_UNIX_PRINTING], [1], [Define if GTK+ UNIX Printing is available]) fi + + # On some Linux/Unix platforms, shm_* may only be available if linking + # against librt + if test "$os_win32" = "no"; then + AC_SEARCH_LIBS([shm_open], [rt], [SHM_LIBS="-lrt"]) + AC_SUBST(SHM_LIBS) + fi fi # Plugin Process |