Files
palemoon27/dom/base/nsRange.cpp
T
roytam1 c6e1bfdcf2 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1261578 - Part 1. Correct text color in selection range; r=jfkthame (6895ebe313)
- Bug 1261578 - Part 2. Correct text decoration color; r=jfkthame (348ba5a946)
- Bug 1261578 - Part 3. Correct MathML text color; r=jfkthame (99dfb99af4)
- Bug 1261578 - Part 4. Correct text overflow color; r=jfkthame (96318becf6)
- Bug 1261578 - Part 5. web-platform-test reftest; r=jfkthame (781bba0317)
- Bug 1110460, part 1 - Add operator= to nsCSSValuePair. r=dholbert (7d836b786b)
- Bug 1110460, part 2 - Move AddPositions() further up StyleAnimationValue.cpp and add asserts. r=dholbert (5f00295917)
- Bug 1110460, part 3 - Factor out a AddCSSValuePair helper in StyleAnimationValue.cpp. r=dholbert (9947835334)
- Bug 1110460, part 4 - Fix MOZ_ASSERT bug in nsComputedDOMStyle.cpp. r=dholbert (5403c0c377)
- Bug 1110460, part 5 - Factor out a nsStyleBasicShape::GetShapeTypeName method. r=dholbert (d27623d42f)
- Bug 1110460, part 6 - Make StyleAnimationValue support css::URLValue backed nsCSSValue objects. r=dholbert (dc006d1cae)
- Bug 1110460, part 7 - Factor out code for adding two nsCSSValuePairList lists. r=dholbert (f27f780005)
- Bug 1260655 - Allow StyleAnimationValue::UncomputeValue to produce values whose storage is independent of the passed-in computed value; r=heycam (abcc77ede5)
- Bug 1110460, part 8 - Support CSS animation of clip-path basic shapes. r=dholbert (cfe5bf883b)
- Bug 1238243 - Reftests involving possibly-ignorable hangul choseong filler. r=xidorn Bug 1238243 followup - Mark test 1238243-2.html as random on OS X 10.6, due to dependency on available fonts. Bug 1239564 - Add reftest for mask layer composition. r=roc (bb3bf56d52)
- Bug 1260543 - Treat currentcolor as computed value which is not interpolatable with actual color for text-emphasis-color and -webkit-text-fill-color. r=birtles (7b90f37e2f)
- Bug 1260543 followup - Fix the function name in test_transitions_per_property.html. DONTBUILD (1362d30c6a)
- Bug 1248708 - Part1: parse and compute -webkit-text-stroke property. r=heycam (c77332031d)
- Bug 1248708 - Part2.1: use mfbt/TypedEnumBits.h for DrawMode. r=jwatt (55bfbdf5dd)
- Bug 1266101, part 1 - Remove various bits of dead code related to painting SVG text. r=heycam (c5140a911c)
- Bug 1266101, part 2 - Remove most of the GLYPH_STROKE/GLYPH_STROKE_UNDERNEATH checking code. r=heycam (6d8f17bc19)
- Bug 1248708 - Part2.2: render -webkit-text-stroke property. r=jfkthame (bccc308ddc)
- Bug 1248708 - Part3: add reftests. r=jfkthame (0fc0864749)
- Bug 1248708 followup: Use MOZ_ARRAY_LENGTH instead of ArrayLength for expression used at compile time, to fix MSVC 2013 bustage. (trivial/bustage-fix, no review) (25cecd7585)
- Bug 1266341 - Pass the right kind of enum constants for script codes. r=masayuki (723e784a37)
- Bug 1245866 - A better buffer size check in nsIDNService::IDNA2008ToUnicode, r=jfkthame (683db7d93c)
- Bug 1233610 - IDN service should return NS_ERROR_MALFORMED_URI instead of NS_ERROR_FAILURE r=mcmanus (d70d4425ca)
- Bug 1266391 - Introduce an enum class mozilla::unicode::Script, and use this instead of bare integers to specify script codes for better type checking. r=masayuki (363a23049f)
- fix 1389436 backport (a8f96f6b33)
- Bug 1258228 - create special child accessibles in owner's constructor, part1, r=marcoz (2bbb819f76)
- Bug 1258228 - create special child accessibles in owner's constructor, part2, r=marcoz (5e20a7761a)
- Bug 1258228 - create special child accessibles in owner's constructor, part3, r=marcoz (6574efb1e7)
- Bug 1258228 - create special child accessibles in owner's constructor, part4, r=marcoz (15420c5a12)
- Bug 1188818 - DataTransfer must deal with nsIFile of directories, r=jwatt (715a857dd1)
- Bug 1126295 - Move TestAtoms.cpp to gtest and enable it; r=froydnj (9275ebeb3c)
- Bug 1257128 (part 1) - Remove nsIAtom.equalsUTF8. r=froydnj. (17238a04e6)
- Bug 1257128 (part 2) - Remove nsIAtomService.get{,Permanent}AtomUTF8. r=froydnj. (f4131f1024)
- Bug 1257128 (part 3) - Remove unused createAtom() function in a test. r=tbsaunde. (e082c1bc17)
- Bug 1257128 (part 4) - Remove unused nsIAtomService references in toolkit/. r=froydnj. (5ddae71ae8)
- Bug 1257402 - Remove NS_NewPermanentAtom() and nsIAtomService.getPermanentAtom(). r=froydnj,kmag. (4b9ad7894e)
- Bug 1145395 - Pass Element& to nsHTMLEditor::RemoveElementIfNoStyleOrIdOrClass; r=ehsan (83080cb024)
- Bug 1140105 - Can't query for a specific font face when the selection is collapsed. r=ehsan (b534c04e7f)
- Bug 1145395 - Introduce an overload of nsHTMLEditor::RemoveStyleInside that takes nsIContent&; r=ehsan (c5cb3bfb1d)
- Bug 1170326 - nsHTMLCSSUtils::ParseLength should check if the input is an empty string, r=ehsan (1950f67c9f)
- Bug 1260871 - Remove do_GetAtom() and rename NS_NewAtom() as NS_Atomize(). r=erahm. (984bc596bf)
- Bug 1254128 - Make the Mozilla .lldbinit use the full path for topsrcdir. r=sparky (20856a94b4)
- Bug 1259659 - rename from InternalUIEvent.detail to InternalUIEvent.mDetail. r=masayuki (37165bd487)
- Bug 1249664 - Make stateful frames responsible for their own keys r=dbaron (03a4365aa1)
- Bug 1232338 - part 1, Add better mouse support to InputData MouseInput r=kats (8be234631e)
- Bug 1259655 - part 1 Rename WidgetEventTime::time to WidgetEventTime::mTime r=masayuki (cd679b408e)
- Bug 1235908 - measure total event wait and process time. r=smaug (4364242809)
- Bug 1259655 - part 2 Rename WidgetEventTime::timeStamp to WidgetEventTime::mTimeStamp r=masayuki (94a507904d)
- Bug 1263785 - Kill off the deprecated nsINode::GetCurrentDoc. r=baku (670e175017)
- Bug 1245748 - Remove no-longer-needed code for directly setting up properties in KeyframeEffect(ReadOnly) constructor; r=heycam (166ed7697c)
- Bug 1259285 - Part1 - Move CSS/Web Animations-specific visibility handling. r=birtles (13a4ac2b94)
- Bug 1259285 - Part2 - Add web-platform test for visibility handling. r=birtles (b7cee58cf7)
- Bug 1260655 - Add KeyframeEffectReadOnly::SetFrames; r=heycam (7da27828da)
- Bug 1260655 - Wrap lines in keyframe-effect/constructor.html to 80 chars; r=whitespace-only (32b6412db2)
- Bug 1260655 - Update keyframe-effect/constructor.html to no longer refer to PropertyIndexedKeyframes or Keyframe; r=heycam (dbe0acf873)
- Bug 1260655 - Return the stored Keyframe objects from GetFrames, when available ; r=heycam (5b8cbc1773)
- Bug 1245748 - Add a Move constructor to Keyframe; r=heycam (eeabc9396a)
- Bug 1260655 - Add an assignment operator to Keyframe that takes an rvalue reference; r=heycam (e81f1f6d7c)
- Bug 1260655 - Add methods to CSSAnimationBuilder to build a set of Keyframe objects; r=heycam (93e2a7b3aa)
- Bug 1260655 - Use CSSAnimationBuilder::BuildAnimationFrames to set up CSS animations using Keyframe objects; r=heycam (4df3ad20cd)
- Bug 1260655 - Drop some no-longer-needed code for setting up CSS animations using AnimationProperty objects; r=heycam (e1d8e020aa)
- Bug 1260655 - Add a copy constructor and copy assignment operator to Keyframe; r=heycam (d9a1ca5d24)
- Bug 1249564 - Part 1: Assign the parent object of AnimationEffectTiming(ReadOnly). r=birtles,bz (298bdcf084)
- Bug 1249564 - Part 2: Cycle collect AnimationEffectTimingReadOnly. r=birtles (25d959d057)
- Bug 1263063 - Part 1: Remove unnecessary clamping of TimingParams::mIterationStart, since it's guaranteed to be nonnegative. r=dholbert (35362749d7)
- Bug 1263063 - Part 2: Add an assertion to ensure that iteration count is nonnegative and finite. r=dholbert (7df13df139)
- Bug 1263063 - Part 3: Change logic in KeyFrameEffect to assume that TimingParams' iteration-count has already been validated as nonnegative & finite. r=dholbert (6dd3f0d984)
- Bug 1263063 - Part 4: Move ActiveDuration() into TimingParams. r=dholbert (6760bdeaa7)
- Bug 1263063 - Part 5: Introduce TimingParams::EndTime(). r=dholbert (af9a4ddd95)
- Bug 1260983 - Allow creating animations with a target element not bound to a document; r=heycam (7d71619cfb)
- Bug 1244591 - Part 1: Implement KeyframeEffect.setFrames r=birtles,smaug (e090fa68b6)
- Bug 1244591 - Part 2: Extract useful keyframes tests to a new file r=birtles (780797fe53)
- Bug 1244591 - Part 3: Add web-platform tests for KeyframeEffect.setFrames r=birtles (997d26427b)
- Bug 1259878 - remove unnecessary isSome(). r=birtles (cb21268a0a)
- Bug 1248532 - Part 1: steps-start does not produce correct value at the beginning of the interval. r=birtles (9131923815)
- Bug 1248532 - Part 2: Add tests for step-start. r=birtles (04ae44375d)
- Bug 1248532 - Part 3: add a test for step-end with iterationStart. r=birtles (769827746b)
- Bug 1266257 - Revise timing model calculations to use fraction-based approach; r=hiro (c1de969ef0)
- Bug 1260572 - Replace AnimValuesStyleRule::AddEmptyValue with an overload of AddValue that takes an rvalue reference; r=heycam (08e01a4cdc)
- Bug 1260572 - Use 50% switch behavior if StyleAnimationValue::Interpolate fails; r=heycam (e67754e770)
- Bug 1260976 - Remove the old AnimationProperty-based GetFrames; r=heycam (efc88117e6)
- Bug 1259248. Add an ArrayView class. r=botond (5bb9e22500)
- Bug 1265648 - Remove the global nsTextFrameTextRunCache, as it no longer serves any useful purpose. r=mats (3ffbf42634)
- Bug 1238243 - Don't filter out Hangul jamo fillers as 'ignorable', because the font may require them to provide advance width. r=xidorn (9fc2f82853)
- Bug 1265648 followup - Use an array of UniquePtr<> for mTextRunsToDelete. r=mats (8745a7566e)
- Bug 1263956 - Adopt the new harfbuzz API for char-to-glyph mapping functions. r=jrmuizel (1f061d7b0f)
- Bug 1265568 - Don't require component alpha layers for text with -moz-osx-font-smoothing:grayscale. r=jfkthame,mattwoodrow (f819591273)
- Bug 1199547 - Backout workaround from bug 722676 as it causes issues on at least OSX 10.10 and 10.11. r=mstange (c96fb3a69d)
- Bug 1265953, part 1 - Convert most of the cocoa widget code from nsAutoPtr to UniquePtr. r=mstange (74aa93eaf9)
- Bug 1249915 - Add ability to synthesize native touch events on GTK for mochitests. r=karlt (b734a366fb)
- Bug 1259670 Rename WidgetPluginEvent::retargetToFocusedDocument to WidgetPluginEvent::mRetargetToFocusedDocument r=smaug (24c12b3bb4)
- Bug 1249915 - Fix synthesized touch injection code on Windows to not apply the scale factor twice. r=jimm (b590300aa3)
- Bug 1250505 - Convert SynthesizeNativeTouchPoint and SynthesizeNativeTouchTap to take a LayoutDeviceIntPoint instead of a ScreenPoint. r=njn (8ddd066519)
- Bug 1256731 - patch 1 - Don't apply theme-dpi scaling to metrics of window border elements, because Windows doesn't respect per-monitor dpi scaling when it draws them. r=emk (582676e33e)
- Bug 1247935 - Part 1: double-buffer nsShmImage. r=jrmuizel (2392a1e916)
- Bug 1247935 - Part 2: use shared pixmaps with XShm for nsShmImage. r=jrmuizel (b3dd105fcc)
- Bug 1265953, part 2 - Convert much of the rest of the widget code from nsAutoPtr to UniquePtr. r=mstange (e0c1c49ef8)
- Bug 1265953, part 3 - Convert more widget code from nsAutoPtr to UniquePtr. r=mstange (17e1be57d2)
- Bug 1265953, part 4 - Convert nsMenuX::LoadSubMenu and nsMenuX::AddMenu to UniquePtr. r=mstange (f4ea50b802)
- Bug 1259664 part.1 Rename WidgetWheelEvent::deltaX to WidgetWheelEvent::mDeltaX r=smaug (8c7ef861eb)
- Bug 1259664 part.2 Rename WidgetWheelEvent::deltaY to WidgetWheelEvent::mDeltaY r=smaug (03529452fb)
- Bug 1259664 part.3 Rename WidgetWheelEvent::deltaZ to WidgetWheelEvent::mDeltaZ r=smaug (0d664b2900)
- Bug 1259664 part.4 Rename WidgetWheelEvent::deltaMode to WidgetWheelEvent::mDeltaMode r=smaug (dc8283ee70)
- Bug 1253041 - Don't apply user wheel prefs more than once. r=smaug (2386a9da14)
- Bug 1259664 part.5 Rename WidgetWheelEvent::customizedByUserPrefs to WidgetWheelEvent::mCustomizedByUserPrefs r=smaug (3b16757c1e)
- Bug 1258820 - making root scrollable element not scroll if mouse wheel is used on xul dropdown r=masayuki (58ab750981)
- Bug 1250050 Add a pref to disable supporting mouse wheel of windowless plugins on Windows r=smaug (1560cfcb35)
- Bug 1256162, use last drag target for dragexit event when comparing to a remote browser, r=smaug (2d03394037)
- Bug 1110030 - part1 - add flags:IsSynthesizedByTIP and InputMethodAppState in WidgetKeyboardEvent. r=masayuki (c8f7802ee0)
- Bug 1110030 - part2 - Prevent PostHandleKeyboardEvent if it's handling by IME. r=masayuki (29fab0d4fe)
- Bug 1110030 - part3 - Interface between PresShell and HardwareKeyHandler. r=masayuki, r=smaug (cb152d6b4b)
- Bug 1110030 - part4 - HardwareKeyHandler component. r=masayuki, r=smaug (9e372e8f19)
- Bug 1110030 - part5 - Expose KeyboardEventInit dictionary. r=masayuki, r=smaug (3c38bf2f37)
- Bug 1110030 - part6 - Expose DefaultPreventedBy*. r=masayuki, r=smaug (5c94c067be)
- Bug 1110030 - part7 - Interface between HardwareKeyHandler and Input Method App. r=masayuki, r=smaug (f33b7f5ad5)
- Bug 1244546 part 1 - Apply proper unit conversion for SynthesizeNativeMouseEvent. r=karlt (8596ff8068)
- Bug 1244546 part 2 - Align the center point for pointerlock to meet widget's requirement. r=smaug (c447b8c770)
- Bug 1259664 part.6 Rename WidgetWheelEvent::mayHaveMomentum to WidgetWheelEvent::mMayHaveMomentum r=smaug (ef95784e26)
- Bug 1259664 part.7 Rename WidgetWheelEvent::isMomentum to WidgetWheelEvent::mIsMomentum r=smaug (983c8dc9e3)
- Bug 1259664 part.8 Rename WidgetWheelEvent::scrollType to WidgetWheelEvent::mScrollType r=smaug (c6731aee2d)
- Bug 1259664 part.9 Rename WidgetWheelEvent::lineOrPageDeltaX to WidgetWheelEvent::mLineOrPageDeltaX r=smaug (9c6d3d7f6b)
- Bug 1259664 part.10 Rename WidgetWheelEvent::lineOrPageDeltaY to WidgetWheelEvent::mLineOrPageDeltaY r=smaug (8a0d549eee)
- Bug 1259664 part.11 Rename WidgetWheelEvent::overflowDeltaX to WidgetWheelEvent::mOverflowDeltaX r=smaug (6200509b12)
- Bug 1259664 part.12 Rename WidgetWheelEvent::overflowDeltaY to Widget¦WheelEvent::mOverflowDeltaY r=smaug (3827fc7cef)
- Bug 1259664 part.13 Reorder the definition of members of WidgetWheelEvent r=smaug (ea69305e49)
- Bug 1243628 - Allow for presshell to have been destroyed and disconnected from prescontext during event dispatch. r=dholbert (b98e7ed1a2)
- Bug 1256952, send a dragexit at remote process when leaving the remote frame, r=smaug (1037c6a425)
- Bug 1261818 - don't pass nsAutoCStrings into nsBaseWidget debugging methods; r=karlt (36b2b66795)
- Bug 1250560 - Fix crash in HandleTouchEvent. r=roc (9586890edf)
- Bug 1121468 - Go to NoActionState after receiving release on LongTapState. r=roc (4e05f9ad70)
- Bug 1248847 - Assert AccessibleCaretEventHub mRefCnt > 1 in all its entry points. r=mats (89ced3c3e2)
- Bug 1251915 - Correct AccessibleCaretEventHub coding style by clang-format. r=roc (12d5b507d7)
- Bug 1259668 Rename WidgetTouchEvent::touches to WidgetTouchEvent::mTouches r=smaug (9c53824e17)
- Bug 1259657 Rename WidgetGUIEvent::widget to WidgetGUIEvent::mWidget r=smaug (8707f57a28)
- Bug 1246477 - Fix carets not updated by scroll events in LongTapState. r=roc (ba6f12001c)
- Bug 1259662 part.1 Rename WidgetDragEvent::dataTransfer to WidgetDragEvent::mDataTransfer r=smaug (79ffebe3ae)
- Bug 1259662 part.2 Rename WidgetDragEvent::userCancelled to WidgetDragEvent::mUserCancelled r=smaug (4b7ee565e7)
- Bug 1241008 - Add preference to show or hide selection bars. r=mtseng (aefd4c430d)
- Bug 1242349 - Provide unique AccessibleCaret pref for JS selection changes, r=TYLin (e964cb16cf)
- Bug 1240917 - Do not show caret in empty input on Fennec. r=roc (d73c6bd94d)
- Bug 1121468 - Show carets when long-pressing on selection highlight. r=roc (bf134067de)
- Bug 1246064 - Support long press to show AccessibleCaret on empty input for Fennec. r=roc (90791443cb)
- Bug 1246918 - Fix carets missing after scrolling down in selection mode on Fennec. r=roc (bc0915ad70)
- Bug 1246918 - Handle PresShell gone after FlushLayout(). r=roc (b2f18c9a03)
- Bug 1251915 - Ignore handling eTouchCancel events. r=roc (a04c3ad8eb)
- Bug 1121468 - Use auto* to explicit declare 'self' as a pointer. r=roc (d83a6020e3)
- Bug 1251346 - Fennec should not generate touch events from mouse events. r=kats (d8077748fc)
- Bug 1259656 part.1 Rename WidgetEvent::refPoint to WidgetEvent::mRefPoint r=smaug (fa66825fc9)
- Bug 1259656 part.2 Rename WidgetEvent::lastRefPoint to WidgetEvent::mLastRefPoint r=smaug (c964d62185)
- Bug 1259656 part.3 Rename WidgetEvent::userType to WidgetEvent::mSpecifiedEventType r=smaug (218ae50355)
- Bug 1259656 part.4 Rename WidgetEvent::typeString to WidgetEvent::mSpecifiedEventTypeString r=smaug (0192c890c9)
- Bug 1259656 part.5 Rename WidgetEvent::target to WidgetEvent::mTarget r=smaug (031356f40d)
- Bug 1259656 part.6 Rename WidgetEvent::currentTarget to WidgetEvent::mCurrentTarget r=smaug (451810f6d3)
- Bug 1259656 part.7 Rename WidgetEvent::originalTarget to WidgetEvent::mOriginalTarget r=smaug (643379c9cb)
- Bug 1259673 rename from InternalClipboardEvent.clipboardData to InternalClipboardEvent.mClipboardData. r=masayuki (5ad3c180fe)
- Bug 1259674 Part 1 rename InternalFocusEvent::fromRaise to InternalFocusEvent::mFrameRaise r=masayuki (400f1ba6e9)
- Bug 1259674 Part 2 rename InternalFocusEvent::isRefocus to InternalFocusEvent::mIsRefocus r=masayuki (93b5799c31)
- Bug 1259674 Part 3 rename InternalFocusEvent::relatedTarget to InternalFocusEvent::mRelatedTarget r=masayuki (2382b8de82)
- Bug 1256589 part.7 Add PropagationStopped() to WidgetEvent r=smaug (09325f188d)
- Bug 1259663 - Clean up WidgetMouseScrollEvent. r=masayuki (48e1389e22)
- Bug 1263782 - Kill off the deprecated nsINode::IsInDoc(). r=baku (ae80ec21f7)
- Bug 1223751 - Assume all frames are visible in subdocuments of a top level content document that's assuming all frames are visible. r=tn (3b4f99b2fc)
- Bug 1223747 - Don't assume all frames are visible in XUL documents. r=tn (7f26104ff8)
- Bug 1180267 - Switch Fennec over to using the MobileViewportManager for computing the CSS viewport. r=snorp (b85a3a5fb7)
- put back some SPS stuff (960414c383)
- Bug 1151152 - Change behavior when pointer is dragged out of the document. r=smaug (64779386f0)
- Bug 1263787 - Kill off the deprecated nsINode::GetCrossShadowCurrentDoc. r=baku (ed490173ff)
- Bug 1261933 - Continue unlocking pointer even if the widget has gone. r=smaug (93a781887a)
- Bug 1259296 - Do not scroll snap on the main thread for wheel events handled by APZ. r=kats (f72a7fef66)
- Bug 1208371 - Pass parent window to DOMMediaStream through constructor. r=roc (1c2cc7e7c7)
- Bug 1208371 - Make AudioCaptureStream startable. r=padenot (15849ae011)
- Bug 1208371 - Move OnTracksAvailableCallback out of DOMMediaStream. r=roc (a772c949e0)
- Bug 1208371 - Remove unused MediaManager::NotifyMediaStreamTrackEnded. r=jib (9157aa056e)
- Bug 1208371 - Introduce MediaStreamTrack logs. r=roc,jib (72ff4d4c59)
- Bug 1208371 - Track original track in MediaStreamTrack clones. r=jib (39e9ae1200)
- Bug 1208371 - Un-nest MediaEngineSource::PhotoCallback. r=roc (b1e0b48012)
- Bug 1253333: Don't cause a second MediaManager to be created if there's a race with NotifyFinished r=jib (d22d6d01e5)
- Bug 1251357 - fix regression where last MediaStreamTrack.stop did not turn off the camera light. r=jesup (11b4880c02)
- Bug 1208371 - Add a MediaStreamTrackSource interface. r=roc (bb1880524b)
- Bug 1208371 - Add MediaStreamTrackSourceGetter interface. r=roc (c57a1c6a74)
- Bug 1208371 - Let MediaStreamTracks know their TrackID at the source. r=roc (62739d72bf)
- Bug 1259236 - throw NotSupportedError on pc.addTrack of track in constructed stream. r=bwc (8b828e80e4)
- Bug 1208371 - Let FindOwnedDOMTrack operate on input stream. r=roc (26c24ad3c7)
- Bug 1208371 - Add some MediaStreamTrack helper methods. r=roc (1627cd36f8)
- Bug 1208371 - Count the users of a MediaStream to ease Destroy() resonsibility. r=roc (613d446b39)
- bug 1223670 assert that connected streams have the same graph r=padenot (17ea987392)
- Bug 1208371 - Add convenience method for checking if TrackID is explicit. r=roc (32c9d5fe45)
- Bug 1208371 - Allow MediaInputPorts mapped to a destination TrackID. r=roc (71d3c66c4d)
- Bug 1208371 - Remove obsolete SetTrackEnabled() from DOMMediaStream r=roc (cbcf54a342)
- Bug 1208371 - Add MediaStreamTrack::Graph(). r=jib (044b348267)
- Bug 1208371 - Add DOMMediaStream::GetTrackById/GetOwnedTrackById. r=jib (6f58360808)
- Bug 1208371 - Add a generic PrincipalChangeObserver interface. r=mt (79dfb91a89)
- Bug 1208371 - Turn DOMMediaStream::PrincipalChangeObserver into PrincipalChangeObserver<DOMMediaStream>. r=mt (41fdd835de)
- Bug 1208371 - Add principal APIs to MediaStreamTrack. r=mt (a8aab0e0d9)
- Bug 1208371 - Create MediaStreamTrackSource::Sink that forwards principal changes from the source. r=mt (d9fefd4e3c)
- Bug 1208371 - Let DOMMediaStream base its principal on the tracks it contains. r=mt (0c046c7c20)
- Bug 1208371 - Add an interface DecoderPrincipalChangeObserver to HTMLMediaElement. r=roc (ecde0ddae0)
- Bug 1208371 - Make HTMLMediaElement::CaptureStream pass its principal to MediaStreamTrack. r=mt (03ccd4ab12)
- Bug 1208371 - Make MediaManager pass its principal to MediaStreamTrack for gUM. r=mt (5a4b1eb0bc)
- Bug 1208371 - Make ImageCapture listen to principal changes of MediaStreamTrack instead. r=mt (d29fc5c36e)
- Bug 1208371 - Break PCImpl::SetRemoteDescription into smaller pieces. r=mt,bwc (e4337cc413)
- Bug 1208371 - Make PeerConnectionImpl pass its principal to MediaStreamTrack through a new RemoteTrackSource. r=mt (9a7c744a19)
- Bug 1208371 - Make remaining DOMMediaStream principal sources use MediaStreamTrack. r=mt (b30919c681)
- Bug 1208371 - Remove some no longer necessary principal methods on DOMMediaStream. r=mt (5279935d2b)
- Bug 1208371 - Add a MediaStreamTrackListener to MediaStreamGraph. r=roc (5d7048793e)
- Bug 1208371 - Move ImageCapture to a MediaStreamTrackListener. r=roc (98d081b034)
- Bug 1208371 - Make it possible to look up stream id by track in PeerConnectionImpl. r=jib (c65d07cb55)
- Bug 1208371 - Fix DOMMediaStream::OwnsTrack. r=roc (092dad3654)
- Bug 1208371 - Remove MediaStreamTrack::GetStream. r=jib (a78f873d89)
- Bug 1208371 - Route ApplyConstraints through MediaStreamTrackSource. r=jib (32dfd76245)
- Bug 1208371 - Kill nsDOMUserMediaStream with fire. r=jib (9550ad61be)
- Bug 1208371 - Make it possible to block tracks in a MediaInputPort initally. r=roc (39fdd2322f)
- Bug 1208371 - Implement MediaStreamTrack::Clone(). r=smaug,jib,roc (1995b87f10)
- Bug 1208371 - Implement DOMMediaStream::Clone() r=smaug,jib,roc (d445dffd30)
- Bug 1208371 - Various cleanups in DOMMediaStream/MediaStreamTrack. r=jib (a174781a1b)
- Bug 1208371 - Forward input stream and track id on regular track changes for union streams. r=roc (36ed98f3e4)
- Bug 1208371 - Move track.stop() helpers to MediaStreamPlayback. r=jib (123bcd8192)
- Bug 1240478 - Add test for video size on 'loadedmetadata'. r=jesup,jib Bug 1208371 - Test DOMMediaStream::Clone(). r=jib (5ff908fcad)
- Bug 1208371 - Test DOMMediaStream::Clone(). r=jib (445556e6b5)
- Bug 1208371 - Rename CreateOwnDOMTrack/CreateClonedDOMTrack to CreateDOMTrack/CloneDOMTrack. r=jib (41c71b073c)
- Bug 1208371 - Resolve ambiguous symbol MediaStreamTrack. r=bwc (f998354d96)
- Bug 1208371 - Test MediaStreamTrack::Clone(). r=jib (34865902b0)
- Bug 1208371 - Add CORSMode methods to MediaStreamTrack. r=mt (2244b06567)
- Bug 1208371 - Add convenience method for forwarding a track to an MSG-stream. r=roc (f21675220b)
- bug 1223670 throw not supported when creating a node from a stream with different channel r=baku (55e1d67356)
- Bug 1208371 - Lock MediaStreamAudioSourceNode onto the first AudioStreamTrack in mInputStream at time of construction. r=mt,padenot (77640fa752)
- Bug 1208371 - Move HTMLMediaElement::CaptureStream to forward CORSMode changes through MediaStreamTrackSource. r=mt (aa533e8945)
- Bug 1208371 - Remove CORSMode methods from DOMMediaStream. r=mt (41447ccea1)
- Bug 1208371 - Change HTMLMediaElement video sinks to check principal for video only tracks. r=mt (b8168de792)
- Bug 1208371 - Remove ref counting from DOMMediaStream::TrackListener. r=roc (fe275597ca)
- Bug 1208371 - Update tests to accomodate the fact that MediaStreamAudioSourceNodes lock onto the first audio track. r=padenot (ee97d9f274)
- bug 916387 remove workarounds in tests r=padenot (0285f2b98a)
- Bug 1208371 - Modify WebAudio source nodes tests to wait for tracks befoure measuring nr of samples. r=padenot (bb3afcdd12)
- Bug 1208371 - Make PeerIdentity RefCounted. r=mt (74320ca464)
- Bug 1208371 - Add GetPeerIdentity() to MediaStreamTrackSource. r=mt (77bffa988f)
- Bug 1208371 - Add PeerIdentity to LocalTrackSource for gUM tracks. r=mt (4b4163b66d)
- Bug 1208371 - Move PeerConnection to use PeerIdentity on MediaStreamTrack. r=mt (30b5ab4b5d)
- Bug 1208371 - Remove PeerIdentity from DOMMediaStream. r=mt (0d6b66614e)
- Bug 1208371 - Add convenience method for checking track forwarding to MediaStreamTrack. r=roc (d9eb5210e0)
- Bug 1208371 - Remove test_mediarecorder_record_nosrc.html. r=roc (5d7b83b51c)
- Bug 1208371 - Inline MediaRecorder::Session::SetupStreams. r=roc (1f8463266e)
- Bug 1153690 - Release the Session and MediaRecorder objects correctly if there is no ExtractRunnable running. r=roc (424117e697)
- Bug 1257318: Move MediaRecorder to use DirectListeners wherever possible. r=roc (1d6336641b)
- Bug 1208371 - Check principal per track instead of per stream in MediaRecorder. r=roc (946080d5e7)
- Bug 1219711 - Add mochitest for track disabling over a peer connection. r=jib (ad345e05e2)
- Bug 1166832 - Add test to verify audio (using AudioStreamAnalyser) after renegotiation. r=bwc (ad11535ee3)
- Bug 1250934: Make tests use the correct audio frequency when fake devices are used r=drno (1b8cb18b8f)
- Bug 1182426 - Test that we can record CanvasCaptureMediaStreams. r=roc (e65a5dce61)
- Bug 1219711 - Refactor captureStream_common.js to accept generic pixel testing method. r=jib (e55194c8f5)
- Bug 1223696 - Make canvas captureStream helper resilient to exceptions when there's no video. r=roc (215711b89d)
- Bug 1223696. Don't destroy VideoFrameContainer when we reach MetadataLoaded without a video track. r=jwwang (2c83a23b24)
- Bug 1166832 - Add test for canvas capture on multiple streams. r=bwc (592db27fc4)
- Bug 1224029: ensure video elements that may be disabled (black) are scaled r=mattwoodrow (bfef6af17d)
- Bug 1208371 - Simplify track disabling test code. r=jib (771d560f40)
- Bug 1208371 - Test disabling track across peerconnection not affecting clones. r=jib (31913dd9e6)
- Bug 1208371 - Add DirectTrackLister to MediaStreamGraph and MediaStreamTrack. r=roc,jesup (ae86375502)
- Bug 1208371 - Switch MediaPipeline to use direct listeners on tracks. r=jesup,bwc (aa32ce43e1)
- Bug 1208371 - Let PeerConnection consume principals from tracks instead of streams. r=mt (825d6775d0)
- Bug 1257318: Make recorder.pause()/resume() work with DirectListeners r=padenot (65ff6bff4e)
- Bug 1208371 - Move FindTrack from SourceMediaStream to MediaStream. r=roc (5725a863ae)
- Bug 1208371 - Switch MediaStreamTrack to enable/disable tracks on owned stream. r=jesup (ea7445369d)
- Bug 1208371 - Make GraphDriver callback log calls verbose. r=padenot (a502ceea55)
- Bug 1208371 - Do not require DOMLocalMediaStream for gUM (audioCapture). r=jib (c27ee1c308)
- Bug 1208371 - Add a track getter to gUM for fake tracks. r=jib (4958d2b392)
- Bug 1208371 - Remove unnecessary fakeTracks:true from test_streams_individual_pause.html. r=jib (2437b932b2)
- Bug 1208371 - Remove debug canvas from addTrackRemoveTrack test to help android perf. r=padenot (38b1ad91e8)
- Bug 1208371 - Remove debug canvas from peerConnection_trackDisabling test to help android perf. r=padenot (a8b5a62ad6)
- Bug 1208371 - Enable test_peerConnection_trackDisabling.html on android 4.3 debug. r=jib (19e14785f3)
- Bug 1208371 - Remove debug canvas from mediaStreamConstructors test to help android perf. r=padenot (b7e3280b68)
- Bug 1208371 - Add disconnect method to test helper AudioStreamAnalyser to improve performance on slow devices. r=padenot (2a18d693a7)
- Bug 1208371 - Guard LoadManagerSingleton with a WeakPtr. r=pkerr (0f6d425cf4)
- Bug 1208371 - Clear output canvas on each drawImage(). r=jib (45731c0c9a)
- Bug 1208371 - Wait for "loadedmetadata" before setting up nodes in test_mediaElementAudioSourceNodeCrossOrigin.html. r=padenot (8e9398fe88)
- Bug 1181051 - Remove BOM from dom/media/test/test*.html. r=kinetik (c98b2c9b96)
- Bug 1070110 - Ensure the testcase will receive at least 2 blob. r=jwwang (028cb09b08)
- Bug 1208371 - Improve reliability of test_mediarecorder_record_timeslice.html. r=jwwang (c89bd3fe0b)
- Bug 1251494 - Remove remaining references to MOZILLA_XPCOMRT_API from dom. r=jesup (5b8e7ef603)
- Bug 1234230: Don't pass null images for video encoding, and don't reencode the same image r=roc (eb09c07d8d)
- Bug 1258567 - per comment 3, ensure volume is only applied once to the AudioSegment. r=kinetik. (a7e184e483)
- Bug 1250934: Modify MediaEngine shutdown to allow neutering the AudioDataListener r=padenot (70f4831508)
- Bug 1208371 - Add PrincipalHandle to MediaChunks. r=mt,jesup (0662c26a97)
- Bug 1208371 - Add NotifyPrincipalHandleChanged to MediaStreamTrackListener. r=mt,jesup (54d896b1ff)
- Bug 1208371 - Add a PrincipalHandleListener to MediaStreamTrack. r=mt,jesup (9b4d2e0996)
- Bug 1256520 - use SyncRunnable to create DecodedStreamData synchronously to ensure the creation and destruction of DecodedStreamData happen in order. r=kikuo. (7d28eaebba)
- Bug 1237482 - Remove MediaDecoderStateMachine::mStreamSink. r=kikuo. (609efed70f)
- Bug 1208371 - Hook up DecodedStream with PrincipalHandle. r=mt,jwwang (9290efb216)
- Bug 1208371 - Hook up MediaPipeline with PrincipalHandle. r=mt,bwc (b00ed70ddc)
- Bug 1208371 - Ensure DOMMediaStream principals reflect what could reside in their playback streams. r=mt,jesup (bd3e32ef16)
- Bug 1208371 - Ensure a media element's ImageContainer is protected when playing a stream. r=mt,jesup (7914faa5dc)
- Bug 1208371 - Forward declare MediaStreamTrack in MediaPipeline.h. r=bwc (4c88b79137)
- Bug 1208371 - Clean up unnecessary virtuals in MediaPipeline. r=bwc (b7112f4b34)
- Bug 1208371 - Move MediaStreamTrack's label to MediaStreamTrackSource. r=jib (045bfcc738)
- Bug 1259590 - Remove B2G ACL code. r=khuey (e13223c0f6)
- Bug 1265452 followup - Make mGlyphExtentsArray an array of UniquePtr. r=jrmuizel (d12ce46244)
- Bug 1250540 - have media.navigator.permission.disabled no longer bypass media.getusermedia.screensharing.allowed_domains. r=jesup (e55aa02580)
- Bug 1247806 - Fix HSTS redirect check in WebSocketChannel, r=mcmanus (4e44becf9e)
- Bug 1251530: Use 'MakeUnique' instead of 'new' to populate UniquePtr variable in AddCSSValuePair. r=jwatt (286bf2289a)
- Bug 1264787: Make nsCSSValue's AdoptListValue & AdoptPairListValue methods take a UniquePtr. r=heycam (0f7dc7164f)
- Bug 1151243 part 3 - [css-grid] Add a generic nsHTMLReflowState::STATIC_POS_IS_CB_ORIGIN flag to place the static-position at the CB origin, and make nsAbsoluteContainingBlock use it in Grid containers where the placeholder is a child too. r=dholbert (7bde498cc4)
- Bug 1151243 part 4 - Some code cleanup in nsHTMLReflowState::CalculateHypotheticalPosition, and make a few methods 'const' (idempotent patch). r=dholbert (e430f9b99d)
- Bug 1250540 - fix string-parsing regression that made screen share whitelisting stop working. r=jesup (f8af7c3053)
- Bug 1265641: Move AEC tail length and delay-agnostic settings to getUserMedia r=padenot (3feaf716ee)
- Bug 950936 - Introduce ui.popup.disable_autohide pref to ease debugging popups. r=neil (bc28dcd531)
- bug 1211892 read -unico-border-gradient of early Unico versions for ThreeDHighlight and ThreeDShadow r=acomminos (39c83b1865)
- bug 1257695 disable GTK3 deprecation warnings in widget/gtk r=acomminos (1ad2ba0271)
- Bug 1258989 - Switch gtk3drawing to a C++ file, r=karlt (55b8ea3cdf)
- Bug 1259433 - remove gtk_widget_style_get() from gtk3drawing, r=karlt a=kwierso (a9fc049140)
- Bug 1266680 - Rename BlockTrackId to BlockSourceTrackId. r=jesup (5066bbf870)
- Bug 1262808: Refactor |PrincipalID| to |PrincipalHandle| in Gonk media code, r=rjesup (49ec99e852)
- Bug 1144096 part 1 - [css-grid] Refactor nsGridContainerFrame state and methods. r=dholbert (502fb7d424)
- Bug 1144096 part 2 - [css-grid] Make GridItemInfo::mFrame available also in non-DEBUG builds since we'll need it to support fragmentation. r=dholbert (fe0b396741)
- Bug 1144096 part 3 - [css-grid] Remove CellMap::ClearOccupied() since it's not needed anymore. r=dholbert (7aeacdccab)
- Bug 1144096 part 4 - [css-grid] Move more local nsGridContainerFrame classes into .cpp file. r=dholbert (896fc410ac)
- Bug 1144096 part 5 - [css-grid] Create a couple of Grid container frame bits. r=dholbert (abd007fd90)
- Bug 1144096 part 6 - [css-grid] Add support for creating Grid container continuations and deal with overflow containers. r=dholbert (3f02728f24)
- Bug 1144096 part 7 - [css-grid] Don't create PageBreakFrames inside a Grid container. The container will handle forced breaks on its items. r=dholbert (5a0c64369c)
- Bug 1144096 part 8 - [css-grid] Add a new state flag, eBreakBefore, to record where breaks occur between tracks. r=dholbert (5f5d8761c6)
- Bug 1144096 part 9 - [css-grid] Create a SharedGridData object owned by the first-in-flow Grid container to share state between its continuations. r=dholbert (7e510f0bf0)
- Bug 1144096 part 10 - [css-grid] Add a few helper methods to do a break before a row, and resize a row. r=dholbert (d3fec771a6)
- Bug 1144096 part 11 - [css-grid] Add a GetNearestFragmentainer() method that collects some data from the nearest enclosing fragmentainer needed for fragmentation. r=dholbert (20d4736a1c)
- Bug 1144096 part 12 - [css-grid] Collect and merge child frames we need for reflow. r=dholbert (3b5c619f34)
- Bug 1144096 part 13 - [css-grid] Refactor ReflowChildren() by separating out the code that reflows normal flow children (grid items and placeholders) into a new method ReflowInFlowChild(). r=dholbert (ba8a1edc7b)
- Bug 1144096 part 14 - [css-grid] Make ReflowInFlowChild() deal with a constrained available block-size. r=dholbert (292df4167a)
- Bug 1144096 part 15 - [css-grid] Compute our pre-reflow logical skip sides and cache the result of ComputedLogicalBorderPadding() with that applied. r=dholbert (0c7f59389e)
- Bug 1144096 part 16 - [css-grid] Implement fragmentation. r=dholbert (af8b8aac41)
- Bug 1144096 part 17 - [css-grid] Add helper methods that add a sorted list of child frames to the Overflow and ExcessOverflowContainers child lists. r=dholbert (a6c80c9e9c)
- Bug 1144096 part 18 - [css-grid] Fix a couple of bugs in how we handle child existing continuations when pushing/pulling children. r=dholbert (b8a62fab65)
- Bug 1144096 part 19 - [css-grid] Sanity check the initial child lists we get from the frame constructor (DEBUG only). r=dholbert (f56955c3ec)
- Bug 1144096 part 20 - [css-grid] Sanity check our child lists before starting a Reflow (DEBUG only). r=dholbert (d89c771238)
- Bug 1144096 part 21 - [css-grid] Deal with dynamically inserted/appended/removed child frames. r=dholbert (a07ecc06e2)
- Bug 1144096 part 22 - [css-grid] Check NS_INLINE_IS_BREAK_BEFORE before checking other completion status. r=dholbert (731dcd0ac5)
- Bug 1144096 part 23 - [css-grid] A grid container fragment that is an overflow container can't be INCOMPLETE, only OVERFLOW_INCOMPLETE and it should always have zero BSize. r=dholbert (afcd6c1741)
- Bug 1144096 part 24 - [css-grid] Move the child frame merging code at the start of ReflowOverflowContainerChildren into a new method: DrainExcessOverflowContainersList. Make both take a param so that we can override how the OC child lists are merged together (normally just an Append; MergeSortedFrameLists for Grid). r=dholbert (95323b0a56)
- Bug 1144096 part 25 - [css-grid] Enable fragmentation to occur by reporting our actual reflow status. r=dholbert (767c389238)
- Bug 1144096 part 26 - [css-grid] Fragmentation reftests. (07e62f8fd6)
- Bug 1244006 - Use const instead of MOZ_CONSTEXPR to avoid startup crash; r=dbaron (39b0bb32fb)
- Bug 1053986 - Fix comment referring to a GetBorder method that no longer exists. r=dholbert (2cde22a42c)
- Bug 1264784 - part 1 - call nsIFrame::{GetScreenRect,GetView} instead of their *External counterparts; r=dholbert (a2cd84b7a2)
- Bug 963238: Support isTypeSupported() in MediaRecorder, and throw on invalid mimetypes at construction r=cpearce,khuey (5a3709e45f)
- Bug 963238: Fix compilation errors. r=me (09b541337f)
- Bug 1157654 - 1. Do not call MediaRecorder.stop immediately after MediaRecorder.start, because we want to receive an onerror callback. 2. Make the NofityError async. r=roc (ad56918042)
- Bug 1128448 - 1. Close the pref media.encoder.omx.enabled for newer android version. 2. Modify testcase and MR to eusure no timing issue. r=roc (9dfff44a2c)
- Bug 1197669 - Part3 - Ensure the start event comes before any blobs. r=jwwang (d4e950fa49)
- Bug 1225327 - fix |mEncoder| null-dereference. r=jwwang (5ffce18e33)
- Bug 1260702: Don't crash on input sources from WebAudio in MediaRecorder r=padenot (28bcb80a03)
- Bug 1018299 - Throw security error if principal check fails in MediaRecorder::Start(). r=jib, r=mt (1130168c8d)
- Bug 1261007 - Part 1 - Force to send video sample into encoder if we got the same video sample more than 1 seconds. Enable testcases. r=jolin (5698b39b45)
- Bug 1182426 - Test that changing video resolution of a recorded stream throws an error. r=roc (edaf49f2cf)
- Bug 1261007 - Part 2 - fix test_mediarecorder_webm_support. r=rillian (16ef931949)
- Bug 1250054. Part 1 - implement MediaDecoderReaderWrapper. r=jya. (4b78b4335d)
- Bug 1242841 - Make MDSM::mDecodedAudioEndTime zero-based. r=kikuo. (c6c756d554)
- Bug 1242843 - Make MDSM::mDecodedVideoEndTime zero-based. r=kikuo. (c194178323)
- Bug 1242783. Part 1 - per comment 11, increase mAmpleAudioThresholdUsecs to 2s to avoid audio underrun when BT is connected. r=kinetik. (49567f587e)
- Bug 1242783. Part 2 - per comment 12, buffer only 1s when audio is captured. r=kinetik. (e0f0cd9826)
- Bug 1230641: P1. Use UYVY (YUV422) format in decoders. r=mattwoodrow (17d4de398c)
- Bug 1230641: P2. Increase the video queue size on mac. r=cpearce (e575c85f44)
- Bug 1230641 - Make our NSOpenGLContext opaque when in fullscreen mode. r=mstange (51da9e1e70)
- Bug 1257094 - Remove MediaDecoderStateMachine::DECODER_STATE_DECODING_NONE. r=cpearce. (f0993582c7)
- Bug 1252344. Part 1 - remove unnecessary checks from MediaDecoderStateMachine::NeedToDecodeVideo(). r=bechen. (1c9b7aadf4)
- Bug 1252344. Part 2 - remove unnecessary checks from MediaDecoderStateMachine::NeedToDecodeAudio(). r=bechen. (6896d7d1f6)
- Bug 1252360 - remove some check from NeedToDecodeAudio(). r=bechen. (1c064a9985)
- Bug 1252762 - Decode at most one audio/video sample before finishing seeking. r=cpearce. (73ec7691df)
- Bug 1253928 - adjust the time passed to RequestVideoData() by the start time to avoid incorrectly skipping key frames. r=jya. (1bc203d8e6)
- Bug 1252766 - Remove MediaDecoderStateMachine::mDecodeToSeekTarget which is never read. r=kaku. (aac1fe8018)
- Bug 1251460 - MDSM now waits on a promise to enqueue first frame loaded. r=jya (0e7e67e006)
- Bug 1257013 - Part 3: Stop checking for corrupt frames in MediaDecoderStateMachine since we no longer produce them. r=ajones (fbbbabafbb)
2024-04-24 23:53:16 +08:00

3505 lines
101 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Implementation of the DOM nsIDOMRange object.
*/
#include "nscore.h"
#include "nsRange.h"
#include "nsString.h"
#include "nsReadableUtils.h"
#include "nsIDOMNode.h"
#include "nsIDOMDocumentFragment.h"
#include "nsIContent.h"
#include "nsIDocument.h"
#include "nsIDOMText.h"
#include "nsError.h"
#include "nsIContentIterator.h"
#include "nsIDOMNodeList.h"
#include "nsGkAtoms.h"
#include "nsContentUtils.h"
#include "nsGenericDOMDataNode.h"
#include "nsTextFrame.h"
#include "nsFontFaceList.h"
#include "mozilla/dom/DocumentFragment.h"
#include "mozilla/dom/DocumentType.h"
#include "mozilla/dom/RangeBinding.h"
#include "mozilla/dom/DOMRect.h"
#include "mozilla/dom/ShadowRoot.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Likely.h"
#include "nsCSSFrameConstructor.h"
#include "nsStyleStruct.h"
#include "nsStyleStructInlines.h"
#include "nsComputedDOMStyle.h"
using namespace mozilla;
using namespace mozilla::dom;
JSObject*
nsRange::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
return RangeBinding::Wrap(aCx, this, aGivenProto);
}
/******************************************************
* stack based utilty class for managing monitor
******************************************************/
static void InvalidateAllFrames(nsINode* aNode)
{
NS_PRECONDITION(aNode, "bad arg");
nsIFrame* frame = nullptr;
switch (aNode->NodeType()) {
case nsIDOMNode::TEXT_NODE:
case nsIDOMNode::ELEMENT_NODE:
{
nsIContent* content = static_cast<nsIContent*>(aNode);
frame = content->GetPrimaryFrame();
break;
}
case nsIDOMNode::DOCUMENT_NODE:
{
nsIDocument* doc = static_cast<nsIDocument*>(aNode);
nsIPresShell* shell = doc ? doc->GetShell() : nullptr;
frame = shell ? shell->GetRootFrame() : nullptr;
break;
}
}
for (nsIFrame* f = frame; f; f = f->GetNextContinuation()) {
f->InvalidateFrameSubtree();
}
}
// Utility routine to detect if a content node is completely contained in a range
// If outNodeBefore is returned true, then the node starts before the range does.
// If outNodeAfter is returned true, then the node ends after the range does.
// Note that both of the above might be true.
// If neither are true, the node is contained inside of the range.
// XXX - callers responsibility to ensure node in same doc as range!
// static
nsresult
nsRange::CompareNodeToRange(nsINode* aNode, nsRange* aRange,
bool *outNodeBefore, bool *outNodeAfter)
{
NS_ENSURE_STATE(aNode);
// create a pair of dom points that expresses location of node:
// NODE(start), NODE(end)
// Let incoming range be:
// {RANGE(start), RANGE(end)}
// if (RANGE(start) <= NODE(start)) and (RANGE(end) => NODE(end))
// then the Node is contained (completely) by the Range.
if (!aRange || !aRange->IsPositioned())
return NS_ERROR_UNEXPECTED;
// gather up the dom point info
int32_t nodeStart, nodeEnd;
nsINode* parent = aNode->GetParentNode();
if (!parent) {
// can't make a parent/offset pair to represent start or
// end of the root node, because it has no parent.
// so instead represent it by (node,0) and (node,numChildren)
parent = aNode;
nodeStart = 0;
nodeEnd = aNode->GetChildCount();
}
else {
nodeStart = parent->IndexOf(aNode);
nodeEnd = nodeStart + 1;
}
nsINode* rangeStartParent = aRange->GetStartParent();
nsINode* rangeEndParent = aRange->GetEndParent();
int32_t rangeStartOffset = aRange->StartOffset();
int32_t rangeEndOffset = aRange->EndOffset();
// is RANGE(start) <= NODE(start) ?
bool disconnected = false;
*outNodeBefore = nsContentUtils::ComparePoints(rangeStartParent,
rangeStartOffset,
parent, nodeStart,
&disconnected) > 0;
NS_ENSURE_TRUE(!disconnected, NS_ERROR_DOM_WRONG_DOCUMENT_ERR);
// is RANGE(end) >= NODE(end) ?
*outNodeAfter = nsContentUtils::ComparePoints(rangeEndParent,
rangeEndOffset,
parent, nodeEnd,
&disconnected) < 0;
NS_ENSURE_TRUE(!disconnected, NS_ERROR_DOM_WRONG_DOCUMENT_ERR);
return NS_OK;
}
static nsINode*
GetNextRangeCommonAncestor(nsINode* aNode)
{
while (aNode && !aNode->IsCommonAncestorForRangeInSelection()) {
if (!aNode->IsDescendantOfCommonAncestorForRangeInSelection()) {
return nullptr;
}
aNode = aNode->GetParentNode();
}
return aNode;
}
/**
* A Comparator suitable for mozilla::BinarySearchIf for searching a collection
* of nsRange* for an overlap of (mNode, mStartOffset) .. (mNode, mEndOffset).
*/
struct IsItemInRangeComparator
{
nsINode* mNode;
uint32_t mStartOffset;
uint32_t mEndOffset;
int operator()(const nsRange* const aRange) const
{
int32_t cmp = nsContentUtils::ComparePoints(mNode, mEndOffset,
aRange->GetStartParent(),
aRange->StartOffset());
if (cmp == 1) {
cmp = nsContentUtils::ComparePoints(mNode, mStartOffset,
aRange->GetEndParent(),
aRange->EndOffset());
if (cmp == -1) {
return 0;
}
return 1;
}
return -1;
}
};
/* static */ bool
nsRange::IsNodeSelected(nsINode* aNode, uint32_t aStartOffset,
uint32_t aEndOffset)
{
NS_PRECONDITION(aNode, "bad arg");
nsINode* n = GetNextRangeCommonAncestor(aNode);
NS_ASSERTION(n || !aNode->IsSelectionDescendant(),
"orphan selection descendant");
// Collect the potential ranges and their selection objects.
RangeHashTable ancestorSelectionRanges;
nsTHashtable<nsPtrHashKey<Selection>> ancestorSelections;
uint32_t maxRangeCount = 0;
for (; n; n = GetNextRangeCommonAncestor(n->GetParentNode())) {
RangeHashTable* ranges =
static_cast<RangeHashTable*>(n->GetProperty(nsGkAtoms::range));
for (auto iter = ranges->ConstIter(); !iter.Done(); iter.Next()) {
nsRange* range = iter.Get()->GetKey();
if (range->IsInSelection() && !range->Collapsed()) {
ancestorSelectionRanges.PutEntry(range);
Selection* selection = range->mSelection;
ancestorSelections.PutEntry(selection);
maxRangeCount = std::max(maxRangeCount, selection->RangeCount());
}
}
}
if (!ancestorSelectionRanges.IsEmpty()) {
nsTArray<const nsRange*> sortedRanges(maxRangeCount);
for (auto iter = ancestorSelections.ConstIter(); !iter.Done(); iter.Next()) {
Selection* selection = iter.Get()->GetKey();
// Sort the found ranges for |selection| in document order
// (Selection::GetRangeAt returns its ranges ordered).
for (uint32_t i = 0, len = selection->RangeCount(); i < len; ++i) {
nsRange* range = selection->GetRangeAt(i);
if (ancestorSelectionRanges.Contains(range)) {
sortedRanges.AppendElement(range);
}
}
MOZ_ASSERT(!sortedRanges.IsEmpty());
// Binary search the now sorted ranges.
IsItemInRangeComparator comparator = { aNode, aStartOffset, aEndOffset };
size_t unused;
if (mozilla::BinarySearchIf(sortedRanges, 0, sortedRanges.Length(), comparator, &unused)) {
return true;
}
sortedRanges.ClearAndRetainStorage();
}
}
return false;
}
/******************************************************
* constructor/destructor
******************************************************/
nsRange::~nsRange()
{
NS_ASSERTION(!IsInSelection(), "deleting nsRange that is in use");
// Maybe we can remove Detach() -- bug 702948.
Telemetry::Accumulate(Telemetry::DOM_RANGE_DETACHED, mIsDetached);
// we want the side effects (releases and list removals)
DoSetRange(nullptr, 0, nullptr, 0, nullptr);
}
nsRange::nsRange(nsINode* aNode)
: mRoot(nullptr)
, mStartOffset(0)
, mEndOffset(0)
, mIsPositioned(false)
, mIsDetached(false)
, mMaySpanAnonymousSubtrees(false)
, mIsGenerated(false)
, mStartOffsetWasIncremented(false)
, mEndOffsetWasIncremented(false)
, mEnableGravitationOnElementRemoval(true)
#ifdef DEBUG
, mAssertNextInsertOrAppendIndex(-1)
, mAssertNextInsertOrAppendNode(nullptr)
#endif
{
MOZ_ASSERT(aNode, "range isn't in a document!");
mOwner = aNode->OwnerDoc();
}
/* static */
nsresult
nsRange::CreateRange(nsINode* aStartParent, int32_t aStartOffset,
nsINode* aEndParent, int32_t aEndOffset,
nsRange** aRange)
{
nsCOMPtr<nsIDOMNode> startDomNode = do_QueryInterface(aStartParent);
nsCOMPtr<nsIDOMNode> endDomNode = do_QueryInterface(aEndParent);
nsresult rv = CreateRange(startDomNode, aStartOffset, endDomNode, aEndOffset,
aRange);
return rv;
}
/* static */
nsresult
nsRange::CreateRange(nsIDOMNode* aStartParent, int32_t aStartOffset,
nsIDOMNode* aEndParent, int32_t aEndOffset,
nsRange** aRange)
{
MOZ_ASSERT(aRange);
*aRange = nullptr;
nsCOMPtr<nsINode> startParent = do_QueryInterface(aStartParent);
NS_ENSURE_ARG_POINTER(startParent);
RefPtr<nsRange> range = new nsRange(startParent);
nsresult rv = range->SetStart(startParent, aStartOffset);
NS_ENSURE_SUCCESS(rv, rv);
rv = range->SetEnd(aEndParent, aEndOffset);
NS_ENSURE_SUCCESS(rv, rv);
range.forget(aRange);
return NS_OK;
}
/* static */
nsresult
nsRange::CreateRange(nsIDOMNode* aStartParent, int32_t aStartOffset,
nsIDOMNode* aEndParent, int32_t aEndOffset,
nsIDOMRange** aRange)
{
RefPtr<nsRange> range;
nsresult rv = nsRange::CreateRange(aStartParent, aStartOffset, aEndParent,
aEndOffset, getter_AddRefs(range));
range.forget(aRange);
return rv;
}
/******************************************************
* nsISupports
******************************************************/
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsRange)
NS_IMPL_CYCLE_COLLECTING_RELEASE_WITH_LAST_RELEASE(nsRange,
DoSetRange(nullptr, 0, nullptr, 0, nullptr))
// QueryInterface implementation for nsRange
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsRange)
NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
NS_INTERFACE_MAP_ENTRY(nsIDOMRange)
NS_INTERFACE_MAP_ENTRY(nsIMutationObserver)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMRange)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION_CLASS(nsRange)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsRange)
NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_UNLINK(mOwner);
tmp->Reset();
// This needs to be unlinked after Reset() is called, as it controls
// the result of IsInSelection() which is used by tmp->Reset().
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelection);
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsRange)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOwner)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStartParent)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEndParent)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRoot)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelection)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsRange)
NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_TRACE_END
static void MarkDescendants(nsINode* aNode)
{
// Set NodeIsDescendantOfCommonAncestorForRangeInSelection on aNode's
// descendants unless aNode is already marked as a range common ancestor
// or a descendant of one, in which case all of our descendants have the
// bit set already.
if (!aNode->IsSelectionDescendant()) {
// don't set the Descendant bit on |aNode| itself
nsINode* node = aNode->GetNextNode(aNode);
while (node) {
node->SetDescendantOfCommonAncestorForRangeInSelection();
if (!node->IsCommonAncestorForRangeInSelection()) {
node = node->GetNextNode(aNode);
} else {
// optimize: skip this sub-tree since it's marked already.
node = node->GetNextNonChildNode(aNode);
}
}
}
}
static void UnmarkDescendants(nsINode* aNode)
{
// Unset NodeIsDescendantOfCommonAncestorForRangeInSelection on aNode's
// descendants unless aNode is a descendant of another range common ancestor.
// Also, exclude descendants of range common ancestors (but not the common
// ancestor itself).
if (!aNode->IsDescendantOfCommonAncestorForRangeInSelection()) {
// we know |aNode| doesn't have any bit set
nsINode* node = aNode->GetNextNode(aNode);
while (node) {
node->ClearDescendantOfCommonAncestorForRangeInSelection();
if (!node->IsCommonAncestorForRangeInSelection()) {
node = node->GetNextNode(aNode);
} else {
// We found an ancestor of an overlapping range, skip its descendants.
node = node->GetNextNonChildNode(aNode);
}
}
}
}
void
nsRange::RegisterCommonAncestor(nsINode* aNode)
{
NS_PRECONDITION(aNode, "bad arg");
NS_ASSERTION(IsInSelection(), "registering range not in selection");
MarkDescendants(aNode);
RangeHashTable* ranges =
static_cast<RangeHashTable*>(aNode->GetProperty(nsGkAtoms::range));
if (!ranges) {
ranges = new RangeHashTable;
aNode->SetProperty(nsGkAtoms::range, ranges,
nsINode::DeleteProperty<nsRange::RangeHashTable>, true);
}
ranges->PutEntry(this);
aNode->SetCommonAncestorForRangeInSelection();
}
void
nsRange::UnregisterCommonAncestor(nsINode* aNode)
{
NS_PRECONDITION(aNode, "bad arg");
NS_ASSERTION(aNode->IsCommonAncestorForRangeInSelection(), "wrong node");
RangeHashTable* ranges =
static_cast<RangeHashTable*>(aNode->GetProperty(nsGkAtoms::range));
NS_ASSERTION(ranges->GetEntry(this), "unknown range");
if (ranges->Count() == 1) {
aNode->ClearCommonAncestorForRangeInSelection();
aNode->DeleteProperty(nsGkAtoms::range);
UnmarkDescendants(aNode);
} else {
ranges->RemoveEntry(this);
}
}
/******************************************************
* nsIMutationObserver implementation
******************************************************/
void
nsRange::CharacterDataChanged(nsIDocument* aDocument,
nsIContent* aContent,
CharacterDataChangeInfo* aInfo)
{
MOZ_ASSERT(mAssertNextInsertOrAppendIndex == -1,
"splitText failed to notify insert/append?");
NS_ASSERTION(mIsPositioned, "shouldn't be notified if not positioned");
nsINode* newRoot = nullptr;
nsINode* newStartNode = nullptr;
nsINode* newEndNode = nullptr;
uint32_t newStartOffset = 0;
uint32_t newEndOffset = 0;
if (aInfo->mDetails &&
aInfo->mDetails->mType == CharacterDataChangeInfo::Details::eSplit) {
// If the splitted text node is immediately before a range boundary point
// that refers to a child index (i.e. its parent is the boundary container)
// then we need to increment the corresponding offset to account for the new
// text node that will be inserted. If so, we need to prevent the next
// ContentInserted or ContentAppended for this range from incrementing it
// again (when the new text node is notified).
nsINode* parentNode = aContent->GetParentNode();
int32_t index = -1;
if (parentNode == mEndParent && mEndOffset > 0 &&
(index = parentNode->IndexOf(aContent)) + 1 == mEndOffset) {
++mEndOffset;
mEndOffsetWasIncremented = true;
}
if (parentNode == mStartParent && mStartOffset > 0 &&
(index != -1 ? index : parentNode->IndexOf(aContent)) + 1 == mStartOffset) {
++mStartOffset;
mStartOffsetWasIncremented = true;
}
#ifdef DEBUG
if (mStartOffsetWasIncremented || mEndOffsetWasIncremented) {
mAssertNextInsertOrAppendIndex =
(mStartOffsetWasIncremented ? mStartOffset : mEndOffset) - 1;
mAssertNextInsertOrAppendNode = aInfo->mDetails->mNextSibling;
}
#endif
}
// If the changed node contains our start boundary and the change starts
// before the boundary we'll need to adjust the offset.
if (aContent == mStartParent &&
aInfo->mChangeStart < static_cast<uint32_t>(mStartOffset)) {
if (aInfo->mDetails) {
// splitText(), aInfo->mDetails->mNextSibling is the new text node
NS_ASSERTION(aInfo->mDetails->mType ==
CharacterDataChangeInfo::Details::eSplit,
"only a split can start before the end");
NS_ASSERTION(static_cast<uint32_t>(mStartOffset) <= aInfo->mChangeEnd + 1,
"mStartOffset is beyond the end of this node");
newStartOffset = static_cast<uint32_t>(mStartOffset) - aInfo->mChangeStart;
newStartNode = aInfo->mDetails->mNextSibling;
if (MOZ_UNLIKELY(aContent == mRoot)) {
newRoot = IsValidBoundary(newStartNode);
}
bool isCommonAncestor = IsInSelection() && mStartParent == mEndParent;
if (isCommonAncestor) {
UnregisterCommonAncestor(mStartParent);
RegisterCommonAncestor(newStartNode);
}
if (mStartParent->IsDescendantOfCommonAncestorForRangeInSelection()) {
newStartNode->SetDescendantOfCommonAncestorForRangeInSelection();
}
} else {
// If boundary is inside changed text, position it before change
// else adjust start offset for the change in length.
mStartOffset = static_cast<uint32_t>(mStartOffset) <= aInfo->mChangeEnd ?
aInfo->mChangeStart :
mStartOffset + aInfo->mChangeStart - aInfo->mChangeEnd +
aInfo->mReplaceLength;
}
}
// Do the same thing for the end boundary, except for splitText of a node
// with no parent then only switch to the new node if the start boundary
// did so too (otherwise the range would end up with disconnected nodes).
if (aContent == mEndParent &&
aInfo->mChangeStart < static_cast<uint32_t>(mEndOffset)) {
if (aInfo->mDetails && (aContent->GetParentNode() || newStartNode)) {
// splitText(), aInfo->mDetails->mNextSibling is the new text node
NS_ASSERTION(aInfo->mDetails->mType ==
CharacterDataChangeInfo::Details::eSplit,
"only a split can start before the end");
NS_ASSERTION(static_cast<uint32_t>(mEndOffset) <= aInfo->mChangeEnd + 1,
"mEndOffset is beyond the end of this node");
newEndOffset = static_cast<uint32_t>(mEndOffset) - aInfo->mChangeStart;
newEndNode = aInfo->mDetails->mNextSibling;
bool isCommonAncestor = IsInSelection() && mStartParent == mEndParent;
if (isCommonAncestor && !newStartNode) {
// The split occurs inside the range.
UnregisterCommonAncestor(mStartParent);
RegisterCommonAncestor(mStartParent->GetParentNode());
newEndNode->SetDescendantOfCommonAncestorForRangeInSelection();
} else if (mEndParent->IsDescendantOfCommonAncestorForRangeInSelection()) {
newEndNode->SetDescendantOfCommonAncestorForRangeInSelection();
}
} else {
mEndOffset = static_cast<uint32_t>(mEndOffset) <= aInfo->mChangeEnd ?
aInfo->mChangeStart :
mEndOffset + aInfo->mChangeStart - aInfo->mChangeEnd +
aInfo->mReplaceLength;
}
}
if (aInfo->mDetails &&
aInfo->mDetails->mType == CharacterDataChangeInfo::Details::eMerge) {
// normalize(), aInfo->mDetails->mNextSibling is the merged text node
// that will be removed
nsIContent* removed = aInfo->mDetails->mNextSibling;
if (removed == mStartParent) {
newStartOffset = static_cast<uint32_t>(mStartOffset) + aInfo->mChangeStart;
newStartNode = aContent;
if (MOZ_UNLIKELY(removed == mRoot)) {
newRoot = IsValidBoundary(newStartNode);
}
}
if (removed == mEndParent) {
newEndOffset = static_cast<uint32_t>(mEndOffset) + aInfo->mChangeStart;
newEndNode = aContent;
if (MOZ_UNLIKELY(removed == mRoot)) {
newRoot = IsValidBoundary(newEndNode);
}
}
// When the removed text node's parent is one of our boundary nodes we may
// need to adjust the offset to account for the removed node. However,
// there will also be a ContentRemoved notification later so the only cases
// we need to handle here is when the removed node is the text node after
// the boundary. (The m*Offset > 0 check is an optimization - a boundary
// point before the first child is never affected by normalize().)
nsINode* parentNode = aContent->GetParentNode();
if (parentNode == mStartParent && mStartOffset > 0 &&
uint32_t(mStartOffset) < parentNode->GetChildCount() &&
removed == parentNode->GetChildAt(mStartOffset)) {
newStartNode = aContent;
newStartOffset = aInfo->mChangeStart;
}
if (parentNode == mEndParent && mEndOffset > 0 &&
uint32_t(mEndOffset) < parentNode->GetChildCount() &&
removed == parentNode->GetChildAt(mEndOffset)) {
newEndNode = aContent;
newEndOffset = aInfo->mChangeEnd;
}
}
if (newStartNode || newEndNode) {
if (!newStartNode) {
newStartNode = mStartParent;
newStartOffset = mStartOffset;
}
if (!newEndNode) {
newEndNode = mEndParent;
newEndOffset = mEndOffset;
}
DoSetRange(newStartNode, newStartOffset, newEndNode, newEndOffset,
newRoot ? newRoot : mRoot.get(),
!newEndNode->GetParentNode() || !newStartNode->GetParentNode());
}
}
void
nsRange::ContentAppended(nsIDocument* aDocument,
nsIContent* aContainer,
nsIContent* aFirstNewContent,
int32_t aNewIndexInContainer)
{
NS_ASSERTION(mIsPositioned, "shouldn't be notified if not positioned");
nsINode* container = NODE_FROM(aContainer, aDocument);
if (container->IsSelectionDescendant() && IsInSelection()) {
nsINode* child = aFirstNewContent;
while (child) {
if (!child->IsDescendantOfCommonAncestorForRangeInSelection()) {
MarkDescendants(child);
child->SetDescendantOfCommonAncestorForRangeInSelection();
}
child = child->GetNextSibling();
}
}
if (mStartOffsetWasIncremented || mEndOffsetWasIncremented) {
MOZ_ASSERT(mAssertNextInsertOrAppendIndex == aNewIndexInContainer);
MOZ_ASSERT(mAssertNextInsertOrAppendNode == aFirstNewContent);
MOZ_ASSERT(aFirstNewContent->IsNodeOfType(nsINode::eDATA_NODE));
mStartOffsetWasIncremented = mEndOffsetWasIncremented = false;
#ifdef DEBUG
mAssertNextInsertOrAppendIndex = -1;
mAssertNextInsertOrAppendNode = nullptr;
#endif
}
}
void
nsRange::ContentInserted(nsIDocument* aDocument,
nsIContent* aContainer,
nsIContent* aChild,
int32_t aIndexInContainer)
{
NS_ASSERTION(mIsPositioned, "shouldn't be notified if not positioned");
nsINode* container = NODE_FROM(aContainer, aDocument);
// Adjust position if a sibling was inserted.
if (container == mStartParent && aIndexInContainer < mStartOffset &&
!mStartOffsetWasIncremented) {
++mStartOffset;
}
if (container == mEndParent && aIndexInContainer < mEndOffset &&
!mEndOffsetWasIncremented) {
++mEndOffset;
}
if (container->IsSelectionDescendant() &&
!aChild->IsDescendantOfCommonAncestorForRangeInSelection()) {
MarkDescendants(aChild);
aChild->SetDescendantOfCommonAncestorForRangeInSelection();
}
if (mStartOffsetWasIncremented || mEndOffsetWasIncremented) {
MOZ_ASSERT(mAssertNextInsertOrAppendIndex == aIndexInContainer);
MOZ_ASSERT(mAssertNextInsertOrAppendNode == aChild);
MOZ_ASSERT(aChild->IsNodeOfType(nsINode::eDATA_NODE));
mStartOffsetWasIncremented = mEndOffsetWasIncremented = false;
#ifdef DEBUG
mAssertNextInsertOrAppendIndex = -1;
mAssertNextInsertOrAppendNode = nullptr;
#endif
}
}
void
nsRange::ContentRemoved(nsIDocument* aDocument,
nsIContent* aContainer,
nsIContent* aChild,
int32_t aIndexInContainer,
nsIContent* aPreviousSibling)
{
NS_ASSERTION(mIsPositioned, "shouldn't be notified if not positioned");
MOZ_ASSERT(!mStartOffsetWasIncremented && !mEndOffsetWasIncremented &&
mAssertNextInsertOrAppendIndex == -1,
"splitText failed to notify insert/append?");
nsINode* container = NODE_FROM(aContainer, aDocument);
bool gravitateStart = false;
bool gravitateEnd = false;
bool didCheckStartParentDescendant = false;
// Adjust position if a sibling was removed...
if (container == mStartParent) {
if (aIndexInContainer < mStartOffset) {
--mStartOffset;
}
} else { // ...or gravitate if an ancestor was removed.
didCheckStartParentDescendant = true;
gravitateStart = nsContentUtils::ContentIsDescendantOf(mStartParent, aChild);
}
// Do same thing for end boundry.
if (container == mEndParent) {
if (aIndexInContainer < mEndOffset) {
--mEndOffset;
}
} else if (didCheckStartParentDescendant && mStartParent == mEndParent) {
gravitateEnd = gravitateStart;
} else {
gravitateEnd = nsContentUtils::ContentIsDescendantOf(mEndParent, aChild);
}
if (!mEnableGravitationOnElementRemoval) {
// Do not gravitate.
return;
}
if (gravitateStart || gravitateEnd) {
DoSetRange(gravitateStart ? container : mStartParent.get(),
gravitateStart ? aIndexInContainer : mStartOffset,
gravitateEnd ? container : mEndParent.get(),
gravitateEnd ? aIndexInContainer : mEndOffset,
mRoot);
}
if (container->IsSelectionDescendant() &&
aChild->IsDescendantOfCommonAncestorForRangeInSelection()) {
aChild->ClearDescendantOfCommonAncestorForRangeInSelection();
UnmarkDescendants(aChild);
}
}
void
nsRange::ParentChainChanged(nsIContent *aContent)
{
MOZ_ASSERT(!mStartOffsetWasIncremented && !mEndOffsetWasIncremented &&
mAssertNextInsertOrAppendIndex == -1,
"splitText failed to notify insert/append?");
NS_ASSERTION(mRoot == aContent, "Wrong ParentChainChanged notification?");
nsINode* newRoot = IsValidBoundary(mStartParent);
NS_ASSERTION(newRoot, "No valid boundary or root found!");
if (newRoot != IsValidBoundary(mEndParent)) {
// Sometimes ordering involved in cycle collection can lead to our
// start parent and/or end parent being disconnected from our root
// without our getting a ContentRemoved notification.
// See bug 846096 for more details.
NS_ASSERTION(mEndParent->IsInNativeAnonymousSubtree(),
"This special case should happen only with "
"native-anonymous content");
// When that happens, bail out and set pointers to null; since we're
// in cycle collection and unreachable it shouldn't matter.
Reset();
return;
}
// This is safe without holding a strong ref to self as long as the change
// of mRoot is the last thing in DoSetRange.
DoSetRange(mStartParent, mStartOffset, mEndParent, mEndOffset, newRoot);
}
/******************************************************
* Utilities for comparing points: API from nsIDOMRange
******************************************************/
NS_IMETHODIMP
nsRange::IsPointInRange(nsIDOMNode* aParent, int32_t aOffset, bool* aResult)
{
nsCOMPtr<nsINode> parent = do_QueryInterface(aParent);
if (!parent) {
return NS_ERROR_DOM_NOT_OBJECT_ERR;
}
ErrorResult rv;
*aResult = IsPointInRange(*parent, aOffset, rv);
return rv.StealNSResult();
}
bool
nsRange::IsPointInRange(nsINode& aParent, uint32_t aOffset, ErrorResult& aRv)
{
uint16_t compareResult = ComparePoint(aParent, aOffset, aRv);
// If the node isn't in the range's document, it clearly isn't in the range.
if (aRv.ErrorCodeIs(NS_ERROR_DOM_WRONG_DOCUMENT_ERR)) {
aRv.SuppressException();
return false;
}
return compareResult == 0;
}
// returns -1 if point is before range, 0 if point is in range,
// 1 if point is after range.
NS_IMETHODIMP
nsRange::ComparePoint(nsIDOMNode* aParent, int32_t aOffset, int16_t* aResult)
{
nsCOMPtr<nsINode> parent = do_QueryInterface(aParent);
NS_ENSURE_TRUE(parent, NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
ErrorResult rv;
*aResult = ComparePoint(*parent, aOffset, rv);
return rv.StealNSResult();
}
int16_t
nsRange::ComparePoint(nsINode& aParent, uint32_t aOffset, ErrorResult& aRv)
{
// our range is in a good state?
if (!mIsPositioned) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return 0;
}
if (!nsContentUtils::ContentIsDescendantOf(&aParent, mRoot)) {
aRv.Throw(NS_ERROR_DOM_WRONG_DOCUMENT_ERR);
return 0;
}
if (aParent.NodeType() == nsIDOMNode::DOCUMENT_TYPE_NODE) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return 0;
}
if (aOffset > aParent.Length()) {
aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
return 0;
}
int32_t cmp;
if ((cmp = nsContentUtils::ComparePoints(&aParent, aOffset,
mStartParent, mStartOffset)) <= 0) {
return cmp;
}
if (nsContentUtils::ComparePoints(mEndParent, mEndOffset,
&aParent, aOffset) == -1) {
return 1;
}
return 0;
}
NS_IMETHODIMP
nsRange::IntersectsNode(nsIDOMNode* aNode, bool* aResult)
{
*aResult = false;
nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
// TODO: This should throw a TypeError.
NS_ENSURE_ARG(node);
ErrorResult rv;
*aResult = IntersectsNode(*node, rv);
return rv.StealNSResult();
}
bool
nsRange::IntersectsNode(nsINode& aNode, ErrorResult& aRv)
{
if (!mIsPositioned) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return false;
}
// Step 3.
nsINode* parent = aNode.GetParentNode();
if (!parent) {
// Steps 2 and 4.
// |parent| is null, so |node|'s root is |node| itself.
return GetRoot() == &aNode;
}
// Step 5.
int32_t nodeIndex = parent->IndexOf(&aNode);
// Steps 6-7.
// Note: if disconnected is true, ComparePoints returns 1.
bool disconnected = false;
bool result = nsContentUtils::ComparePoints(mStartParent, mStartOffset,
parent, nodeIndex + 1,
&disconnected) < 0 &&
nsContentUtils::ComparePoints(parent, nodeIndex,
mEndParent, mEndOffset,
&disconnected) < 0;
// Step 2.
if (disconnected) {
result = false;
}
return result;
}
/******************************************************
* Private helper routines
******************************************************/
// It's important that all setting of the range start/end points
// go through this function, which will do all the right voodoo
// for content notification of range ownership.
// Calling DoSetRange with either parent argument null will collapse
// the range to have both endpoints point to the other node
void
nsRange::DoSetRange(nsINode* aStartN, int32_t aStartOffset,
nsINode* aEndN, int32_t aEndOffset,
nsINode* aRoot, bool aNotInsertedYet)
{
NS_PRECONDITION((aStartN && aEndN && aRoot) ||
(!aStartN && !aEndN && !aRoot),
"Set all or none");
NS_PRECONDITION(!aRoot || aNotInsertedYet ||
(nsContentUtils::ContentIsDescendantOf(aStartN, aRoot) &&
nsContentUtils::ContentIsDescendantOf(aEndN, aRoot) &&
aRoot == IsValidBoundary(aStartN) &&
aRoot == IsValidBoundary(aEndN)),
"Wrong root");
NS_PRECONDITION(!aRoot ||
(aStartN->IsNodeOfType(nsINode::eCONTENT) &&
aEndN->IsNodeOfType(nsINode::eCONTENT) &&
aRoot ==
static_cast<nsIContent*>(aStartN)->GetBindingParent() &&
aRoot ==
static_cast<nsIContent*>(aEndN)->GetBindingParent()) ||
(!aRoot->GetParentNode() &&
(aRoot->IsNodeOfType(nsINode::eDOCUMENT) ||
aRoot->IsNodeOfType(nsINode::eATTRIBUTE) ||
aRoot->IsNodeOfType(nsINode::eDOCUMENT_FRAGMENT) ||
/*For backward compatibility*/
aRoot->IsNodeOfType(nsINode::eCONTENT))),
"Bad root");
if (mRoot != aRoot) {
if (mRoot) {
mRoot->RemoveMutationObserver(this);
}
if (aRoot) {
aRoot->AddMutationObserver(this);
}
}
bool checkCommonAncestor = (mStartParent != aStartN || mEndParent != aEndN) &&
IsInSelection() && !aNotInsertedYet;
nsINode* oldCommonAncestor = checkCommonAncestor ? GetCommonAncestor() : nullptr;
mStartParent = aStartN;
mStartOffset = aStartOffset;
mEndParent = aEndN;
mEndOffset = aEndOffset;
mIsPositioned = !!mStartParent;
if (checkCommonAncestor) {
nsINode* newCommonAncestor = GetCommonAncestor();
if (newCommonAncestor != oldCommonAncestor) {
if (oldCommonAncestor) {
UnregisterCommonAncestor(oldCommonAncestor);
}
if (newCommonAncestor) {
RegisterCommonAncestor(newCommonAncestor);
} else {
NS_ASSERTION(!mIsPositioned, "unexpected disconnected nodes");
mSelection = nullptr;
}
}
}
// This needs to be the last thing this function does, other than notifying
// selection listeners. See comment in ParentChainChanged.
mRoot = aRoot;
// Notify any selection listeners. This has to occur last because otherwise the world
// could be observed by a selection listener while the range was in an invalid state.
if (mSelection) {
mSelection->NotifySelectionListeners();
}
}
static int32_t
IndexOf(nsINode* aChild)
{
nsINode* parent = aChild->GetParentNode();
return parent ? parent->IndexOf(aChild) : -1;
}
void
nsRange::SetSelection(mozilla::dom::Selection* aSelection)
{
if (mSelection == aSelection) {
return;
}
// At least one of aSelection and mSelection must be null
// aSelection will be null when we are removing from a selection
// and a range can't be in more than one selection at a time,
// thus mSelection must be null too.
MOZ_ASSERT(!aSelection || !mSelection);
mSelection = aSelection;
nsINode* commonAncestor = GetCommonAncestor();
NS_ASSERTION(commonAncestor, "unexpected disconnected nodes");
if (mSelection) {
RegisterCommonAncestor(commonAncestor);
} else {
UnregisterCommonAncestor(commonAncestor);
}
}
nsINode*
nsRange::GetCommonAncestor() const
{
return mIsPositioned ?
nsContentUtils::GetCommonAncestor(mStartParent, mEndParent) :
nullptr;
}
void
nsRange::Reset()
{
DoSetRange(nullptr, 0, nullptr, 0, nullptr);
}
/******************************************************
* public functionality
******************************************************/
NS_IMETHODIMP
nsRange::GetStartContainer(nsIDOMNode** aStartParent)
{
if (!mIsPositioned)
return NS_ERROR_NOT_INITIALIZED;
return CallQueryInterface(mStartParent, aStartParent);
}
nsINode*
nsRange::GetStartContainer(ErrorResult& aRv) const
{
if (!mIsPositioned) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return nullptr;
}
return mStartParent;
}
NS_IMETHODIMP
nsRange::GetStartOffset(int32_t* aStartOffset)
{
if (!mIsPositioned)
return NS_ERROR_NOT_INITIALIZED;
*aStartOffset = mStartOffset;
return NS_OK;
}
uint32_t
nsRange::GetStartOffset(ErrorResult& aRv) const
{
if (!mIsPositioned) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return 0;
}
return mStartOffset;
}
NS_IMETHODIMP
nsRange::GetEndContainer(nsIDOMNode** aEndParent)
{
if (!mIsPositioned)
return NS_ERROR_NOT_INITIALIZED;
return CallQueryInterface(mEndParent, aEndParent);
}
nsINode*
nsRange::GetEndContainer(ErrorResult& aRv) const
{
if (!mIsPositioned) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return nullptr;
}
return mEndParent;
}
NS_IMETHODIMP
nsRange::GetEndOffset(int32_t* aEndOffset)
{
if (!mIsPositioned)
return NS_ERROR_NOT_INITIALIZED;
*aEndOffset = mEndOffset;
return NS_OK;
}
uint32_t
nsRange::GetEndOffset(ErrorResult& aRv) const
{
if (!mIsPositioned) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return 0;
}
return mEndOffset;
}
NS_IMETHODIMP
nsRange::GetCollapsed(bool* aIsCollapsed)
{
if (!mIsPositioned)
return NS_ERROR_NOT_INITIALIZED;
*aIsCollapsed = Collapsed();
return NS_OK;
}
nsINode*
nsRange::GetCommonAncestorContainer(ErrorResult& aRv) const
{
if (!mIsPositioned) {
aRv.Throw(NS_ERROR_NOT_INITIALIZED);
return nullptr;
}
return nsContentUtils::GetCommonAncestor(mStartParent, mEndParent);
}
NS_IMETHODIMP
nsRange::GetCommonAncestorContainer(nsIDOMNode** aCommonParent)
{
ErrorResult rv;
nsINode* commonAncestor = GetCommonAncestorContainer(rv);
if (commonAncestor) {
NS_ADDREF(*aCommonParent = commonAncestor->AsDOMNode());
} else {
*aCommonParent = nullptr;
}
return rv.StealNSResult();
}
nsINode*
nsRange::IsValidBoundary(nsINode* aNode)
{
if (!aNode) {
return nullptr;
}
if (aNode->IsNodeOfType(nsINode::eCONTENT)) {
if (aNode->NodeInfo()->NameAtom() == nsGkAtoms::documentTypeNodeName) {
return nullptr;
}
nsIContent* content = static_cast<nsIContent*>(aNode);
if (!mMaySpanAnonymousSubtrees) {
// If the node is in a shadow tree then the ShadowRoot is the root.
ShadowRoot* containingShadow = content->GetContainingShadow();
if (containingShadow) {
return containingShadow;
}
// If the node has a binding parent, that should be the root.
// XXXbz maybe only for native anonymous content?
nsINode* root = content->GetBindingParent();
if (root) {
return root;
}
}
}
// Elements etc. must be in document or in document fragment,
// text nodes in document, in document fragment or in attribute.
nsINode* root = aNode->GetUncomposedDoc();
if (root) {
return root;
}
root = aNode->SubtreeRoot();
NS_ASSERTION(!root->IsNodeOfType(nsINode::eDOCUMENT),
"GetUncomposedDoc should have returned a doc");
// We allow this because of backward compatibility.
return root;
}
void
nsRange::SetStart(nsINode& aNode, uint32_t aOffset, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
aRv = SetStart(&aNode, aOffset);
}
NS_IMETHODIMP
nsRange::SetStart(nsIDOMNode* aParent, int32_t aOffset)
{
nsCOMPtr<nsINode> parent = do_QueryInterface(aParent);
if (!parent) {
return NS_ERROR_DOM_NOT_OBJECT_ERR;
}
ErrorResult rv;
SetStart(*parent, aOffset, rv);
return rv.StealNSResult();
}
/* virtual */ nsresult
nsRange::SetStart(nsINode* aParent, int32_t aOffset)
{
nsINode* newRoot = IsValidBoundary(aParent);
NS_ENSURE_TRUE(newRoot, NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
if (aOffset < 0 || uint32_t(aOffset) > aParent->Length()) {
return NS_ERROR_DOM_INDEX_SIZE_ERR;
}
// Collapse if not positioned yet, if positioned in another doc or
// if the new start is after end.
if (!mIsPositioned || newRoot != mRoot ||
nsContentUtils::ComparePoints(aParent, aOffset,
mEndParent, mEndOffset) == 1) {
DoSetRange(aParent, aOffset, aParent, aOffset, newRoot);
return NS_OK;
}
DoSetRange(aParent, aOffset, mEndParent, mEndOffset, mRoot);
return NS_OK;
}
void
nsRange::SetStartBefore(nsINode& aNode, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
aRv = SetStart(aNode.GetParentNode(), IndexOf(&aNode));
}
NS_IMETHODIMP
nsRange::SetStartBefore(nsIDOMNode* aSibling)
{
nsCOMPtr<nsINode> sibling = do_QueryInterface(aSibling);
if (!sibling) {
return NS_ERROR_DOM_NOT_OBJECT_ERR;
}
ErrorResult rv;
SetStartBefore(*sibling, rv);
return rv.StealNSResult();
}
void
nsRange::SetStartAfter(nsINode& aNode, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
aRv = SetStart(aNode.GetParentNode(), IndexOf(&aNode) + 1);
}
NS_IMETHODIMP
nsRange::SetStartAfter(nsIDOMNode* aSibling)
{
nsCOMPtr<nsINode> sibling = do_QueryInterface(aSibling);
if (!sibling) {
return NS_ERROR_DOM_NOT_OBJECT_ERR;
}
ErrorResult rv;
SetStartAfter(*sibling, rv);
return rv.StealNSResult();
}
void
nsRange::SetEnd(nsINode& aNode, uint32_t aOffset, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
aRv = SetEnd(&aNode, aOffset);
}
NS_IMETHODIMP
nsRange::SetEnd(nsIDOMNode* aParent, int32_t aOffset)
{
nsCOMPtr<nsINode> parent = do_QueryInterface(aParent);
if (!parent) {
return NS_ERROR_DOM_NOT_OBJECT_ERR;
}
ErrorResult rv;
SetEnd(*parent, aOffset, rv);
return rv.StealNSResult();
}
/* virtual */ nsresult
nsRange::SetEnd(nsINode* aParent, int32_t aOffset)
{
nsINode* newRoot = IsValidBoundary(aParent);
NS_ENSURE_TRUE(newRoot, NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
if (aOffset < 0 || uint32_t(aOffset) > aParent->Length()) {
return NS_ERROR_DOM_INDEX_SIZE_ERR;
}
// Collapse if not positioned yet, if positioned in another doc or
// if the new end is before start.
if (!mIsPositioned || newRoot != mRoot ||
nsContentUtils::ComparePoints(mStartParent, mStartOffset,
aParent, aOffset) == 1) {
DoSetRange(aParent, aOffset, aParent, aOffset, newRoot);
return NS_OK;
}
DoSetRange(mStartParent, mStartOffset, aParent, aOffset, mRoot);
return NS_OK;
}
void
nsRange::SetEndBefore(nsINode& aNode, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
aRv = SetEnd(aNode.GetParentNode(), IndexOf(&aNode));
}
NS_IMETHODIMP
nsRange::SetEndBefore(nsIDOMNode* aSibling)
{
nsCOMPtr<nsINode> sibling = do_QueryInterface(aSibling);
if (!sibling) {
return NS_ERROR_DOM_NOT_OBJECT_ERR;
}
ErrorResult rv;
SetEndBefore(*sibling, rv);
return rv.StealNSResult();
}
void
nsRange::SetEndAfter(nsINode& aNode, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
aRv = SetEnd(aNode.GetParentNode(), IndexOf(&aNode) + 1);
}
NS_IMETHODIMP
nsRange::SetEndAfter(nsIDOMNode* aSibling)
{
nsCOMPtr<nsINode> sibling = do_QueryInterface(aSibling);
if (!sibling) {
return NS_ERROR_DOM_NOT_OBJECT_ERR;
}
ErrorResult rv;
SetEndAfter(*sibling, rv);
return rv.StealNSResult();
}
NS_IMETHODIMP
nsRange::Collapse(bool aToStart)
{
if (!mIsPositioned)
return NS_ERROR_NOT_INITIALIZED;
AutoInvalidateSelection atEndOfBlock(this);
if (aToStart)
DoSetRange(mStartParent, mStartOffset, mStartParent, mStartOffset, mRoot);
else
DoSetRange(mEndParent, mEndOffset, mEndParent, mEndOffset, mRoot);
return NS_OK;
}
NS_IMETHODIMP
nsRange::SelectNode(nsIDOMNode* aN)
{
nsCOMPtr<nsINode> node = do_QueryInterface(aN);
NS_ENSURE_TRUE(node, NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
ErrorResult rv;
SelectNode(*node, rv);
return rv.StealNSResult();
}
void
nsRange::SelectNode(nsINode& aNode, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
nsINode* parent = aNode.GetParentNode();
nsINode* newRoot = IsValidBoundary(parent);
if (!newRoot) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
int32_t index = parent->IndexOf(&aNode);
if (index < 0) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
DoSetRange(parent, index, parent, index + 1, newRoot);
}
NS_IMETHODIMP
nsRange::SelectNodeContents(nsIDOMNode* aN)
{
nsCOMPtr<nsINode> node = do_QueryInterface(aN);
NS_ENSURE_TRUE(node, NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
ErrorResult rv;
SelectNodeContents(*node, rv);
return rv.StealNSResult();
}
void
nsRange::SelectNodeContents(nsINode& aNode, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
nsINode* newRoot = IsValidBoundary(&aNode);
if (!newRoot) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
AutoInvalidateSelection atEndOfBlock(this);
DoSetRange(&aNode, 0, &aNode, aNode.Length(), newRoot);
}
// The Subtree Content Iterator only returns subtrees that are
// completely within a given range. It doesn't return a CharacterData
// node that contains either the start or end point of the range.,
// nor does it return element nodes when nothing in the element is selected.
// We need an iterator that will also include these start/end points
// so that our methods/algorithms aren't cluttered with special
// case code that tries to include these points while iterating.
//
// The RangeSubtreeIterator class mimics the nsIContentIterator
// methods we need, so should the Content Iterator support the
// start/end points in the future, we can switchover relatively
// easy.
class MOZ_STACK_CLASS RangeSubtreeIterator
{
private:
enum RangeSubtreeIterState { eDone=0,
eUseStart,
eUseIterator,
eUseEnd };
nsCOMPtr<nsIContentIterator> mIter;
RangeSubtreeIterState mIterState;
nsCOMPtr<nsINode> mStart;
nsCOMPtr<nsINode> mEnd;
public:
RangeSubtreeIterator()
: mIterState(eDone)
{
}
~RangeSubtreeIterator()
{
}
nsresult Init(nsRange *aRange);
already_AddRefed<nsINode> GetCurrentNode();
void First();
void Last();
void Next();
void Prev();
bool IsDone()
{
return mIterState == eDone;
}
};
nsresult
RangeSubtreeIterator::Init(nsRange *aRange)
{
mIterState = eDone;
if (aRange->Collapsed()) {
return NS_OK;
}
// Grab the start point of the range and QI it to
// a CharacterData pointer. If it is CharacterData store
// a pointer to the node.
ErrorResult rv;
nsCOMPtr<nsINode> node = aRange->GetStartContainer(rv);
if (!node) return NS_ERROR_FAILURE;
nsCOMPtr<nsIDOMCharacterData> startData = do_QueryInterface(node);
if (startData || (node->IsElement() &&
node->AsElement()->GetChildCount() == aRange->GetStartOffset(rv))) {
mStart = node;
}
// Grab the end point of the range and QI it to
// a CharacterData pointer. If it is CharacterData store
// a pointer to the node.
node = aRange->GetEndContainer(rv);
if (!node) return NS_ERROR_FAILURE;
nsCOMPtr<nsIDOMCharacterData> endData = do_QueryInterface(node);
if (endData || (node->IsElement() && aRange->GetEndOffset(rv) == 0)) {
mEnd = node;
}
if (mStart && mStart == mEnd)
{
// The range starts and stops in the same CharacterData
// node. Null out the end pointer so we only visit the
// node once!
mEnd = nullptr;
}
else
{
// Now create a Content Subtree Iterator to be used
// for the subtrees between the end points!
mIter = NS_NewContentSubtreeIterator();
nsresult res = mIter->Init(aRange);
if (NS_FAILED(res)) return res;
if (mIter->IsDone())
{
// The subtree iterator thinks there's nothing
// to iterate over, so just free it up so we
// don't accidentally call into it.
mIter = nullptr;
}
}
// Initialize the iterator by calling First().
// Note that we are ignoring the return value on purpose!
First();
return NS_OK;
}
already_AddRefed<nsINode>
RangeSubtreeIterator::GetCurrentNode()
{
nsCOMPtr<nsINode> node;
if (mIterState == eUseStart && mStart) {
node = mStart;
} else if (mIterState == eUseEnd && mEnd) {
node = mEnd;
} else if (mIterState == eUseIterator && mIter) {
node = mIter->GetCurrentNode();
}
return node.forget();
}
void
RangeSubtreeIterator::First()
{
if (mStart)
mIterState = eUseStart;
else if (mIter)
{
mIter->First();
mIterState = eUseIterator;
}
else if (mEnd)
mIterState = eUseEnd;
else
mIterState = eDone;
}
void
RangeSubtreeIterator::Last()
{
if (mEnd)
mIterState = eUseEnd;
else if (mIter)
{
mIter->Last();
mIterState = eUseIterator;
}
else if (mStart)
mIterState = eUseStart;
else
mIterState = eDone;
}
void
RangeSubtreeIterator::Next()
{
if (mIterState == eUseStart)
{
if (mIter)
{
mIter->First();
mIterState = eUseIterator;
}
else if (mEnd)
mIterState = eUseEnd;
else
mIterState = eDone;
}
else if (mIterState == eUseIterator)
{
mIter->Next();
if (mIter->IsDone())
{
if (mEnd)
mIterState = eUseEnd;
else
mIterState = eDone;
}
}
else
mIterState = eDone;
}
void
RangeSubtreeIterator::Prev()
{
if (mIterState == eUseEnd)
{
if (mIter)
{
mIter->Last();
mIterState = eUseIterator;
}
else if (mStart)
mIterState = eUseStart;
else
mIterState = eDone;
}
else if (mIterState == eUseIterator)
{
mIter->Prev();
if (mIter->IsDone())
{
if (mStart)
mIterState = eUseStart;
else
mIterState = eDone;
}
}
else
mIterState = eDone;
}
// CollapseRangeAfterDelete() is a utility method that is used by
// DeleteContents() and ExtractContents() to collapse the range
// in the correct place, under the range's root container (the
// range end points common container) as outlined by the Range spec:
//
// http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113/ranges.html
// The assumption made by this method is that the delete or extract
// has been done already, and left the range in a state where there is
// no content between the 2 end points.
static nsresult
CollapseRangeAfterDelete(nsRange* aRange)
{
NS_ENSURE_ARG_POINTER(aRange);
// Check if range gravity took care of collapsing the range for us!
if (aRange->Collapsed())
{
// aRange is collapsed so there's nothing for us to do.
//
// There are 2 possible scenarios here:
//
// 1. aRange could've been collapsed prior to the delete/extract,
// which would've resulted in nothing being removed, so aRange
// is already where it should be.
//
// 2. Prior to the delete/extract, aRange's start and end were in
// the same container which would mean everything between them
// was removed, causing range gravity to collapse the range.
return NS_OK;
}
// aRange isn't collapsed so figure out the appropriate place to collapse!
// First get both end points and their common ancestor.
ErrorResult rv;
nsCOMPtr<nsINode> commonAncestor = aRange->GetCommonAncestorContainer(rv);
if (rv.Failed()) return rv.StealNSResult();
nsCOMPtr<nsINode> startContainer = aRange->GetStartContainer(rv);
if (rv.Failed()) return rv.StealNSResult();
nsCOMPtr<nsINode> endContainer = aRange->GetEndContainer(rv);
if (rv.Failed()) return rv.StealNSResult();
// Collapse to one of the end points if they are already in the
// commonAncestor. This should work ok since this method is called
// immediately after a delete or extract that leaves no content
// between the 2 end points!
if (startContainer == commonAncestor)
return aRange->Collapse(true);
if (endContainer == commonAncestor)
return aRange->Collapse(false);
// End points are at differing levels. We want to collapse to the
// point that is between the 2 subtrees that contain each point,
// under the common ancestor.
nsCOMPtr<nsINode> nodeToSelect(startContainer);
while (nodeToSelect)
{
nsCOMPtr<nsINode> parent = nodeToSelect->GetParentNode();
if (parent == commonAncestor)
break; // We found the nodeToSelect!
nodeToSelect = parent;
}
if (!nodeToSelect)
return NS_ERROR_FAILURE; // This should never happen!
aRange->SelectNode(*nodeToSelect, rv);
if (rv.Failed()) return rv.StealNSResult();
return aRange->Collapse(false);
}
/**
* Split a data node into two parts.
*
* @param aStartNode The original node we are trying to split.
* @param aStartIndex The index at which to split.
* @param aEndNode The second node.
* @param aCloneAfterOriginal Set false if the original node should be the
* latter one after split.
*/
static nsresult SplitDataNode(nsIDOMCharacterData* aStartNode,
uint32_t aStartIndex,
nsIDOMCharacterData** aEndNode,
bool aCloneAfterOriginal = true)
{
nsresult rv;
nsCOMPtr<nsINode> node = do_QueryInterface(aStartNode);
NS_ENSURE_STATE(node && node->IsNodeOfType(nsINode::eDATA_NODE));
nsGenericDOMDataNode* dataNode = static_cast<nsGenericDOMDataNode*>(node.get());
nsCOMPtr<nsIContent> newData;
rv = dataNode->SplitData(aStartIndex, getter_AddRefs(newData),
aCloneAfterOriginal);
NS_ENSURE_SUCCESS(rv, rv);
return CallQueryInterface(newData, aEndNode);
}
NS_IMETHODIMP
PrependChild(nsINode* aParent, nsINode* aChild)
{
nsCOMPtr<nsINode> first = aParent->GetFirstChild();
ErrorResult rv;
aParent->InsertBefore(*aChild, first, rv);
return rv.StealNSResult();
}
// Helper function for CutContents, making sure that the current node wasn't
// removed by mutation events (bug 766426)
static bool
ValidateCurrentNode(nsRange* aRange, RangeSubtreeIterator& aIter)
{
bool before, after;
nsCOMPtr<nsINode> node = aIter.GetCurrentNode();
if (!node) {
// We don't have to worry that the node was removed if it doesn't exist,
// e.g., the iterator is done.
return true;
}
nsresult res = nsRange::CompareNodeToRange(node, aRange, &before, &after);
return NS_SUCCEEDED(res) && !before && !after;
}
nsresult
nsRange::CutContents(DocumentFragment** aFragment)
{
if (aFragment) {
*aFragment = nullptr;
}
nsCOMPtr<nsIDocument> doc = mStartParent->OwnerDoc();
ErrorResult res;
nsCOMPtr<nsINode> commonAncestor = GetCommonAncestorContainer(res);
NS_ENSURE_TRUE(!res.Failed(), res.StealNSResult());
// If aFragment isn't null, create a temporary fragment to hold our return.
RefPtr<DocumentFragment> retval;
if (aFragment) {
retval = new DocumentFragment(doc->NodeInfoManager());
}
nsCOMPtr<nsINode> commonCloneAncestor = retval.get();
// Batch possible DOMSubtreeModified events.
mozAutoSubtreeModified subtree(mRoot ? mRoot->OwnerDoc(): nullptr, nullptr);
// Save the range end points locally to avoid interference
// of Range gravity during our edits!
nsCOMPtr<nsINode> startContainer = mStartParent;
int32_t startOffset = mStartOffset;
nsCOMPtr<nsINode> endContainer = mEndParent;
int32_t endOffset = mEndOffset;
if (retval) {
// For extractContents(), abort early if there's a doctype (bug 719533).
// This can happen only if the common ancestor is a document, in which case
// we just need to find its doctype child and check if that's in the range.
nsCOMPtr<nsIDocument> commonAncestorDocument = do_QueryInterface(commonAncestor);
if (commonAncestorDocument) {
RefPtr<DocumentType> doctype = commonAncestorDocument->GetDoctype();
if (doctype &&
nsContentUtils::ComparePoints(startContainer, startOffset,
doctype, 0) < 0 &&
nsContentUtils::ComparePoints(doctype, 0,
endContainer, endOffset) < 0) {
return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
}
}
}
// Create and initialize a subtree iterator that will give
// us all the subtrees within the range.
RangeSubtreeIterator iter;
nsresult rv = iter.Init(this);
if (NS_FAILED(rv)) return rv;
if (iter.IsDone())
{
// There's nothing for us to delete.
rv = CollapseRangeAfterDelete(this);
if (NS_SUCCEEDED(rv) && aFragment) {
retval.forget(aFragment);
}
return rv;
}
// We delete backwards to avoid iterator problems!
iter.Last();
bool handled = false;
// With the exception of text nodes that contain one of the range
// end points, the subtree iterator should only give us back subtrees
// that are completely contained between the range's end points.
while (!iter.IsDone())
{
nsCOMPtr<nsINode> nodeToResult;
nsCOMPtr<nsINode> node = iter.GetCurrentNode();
// Before we delete anything, advance the iterator to the
// next subtree.
iter.Prev();
handled = false;
// If it's CharacterData, make sure we might need to delete
// part of the data, instead of removing the whole node.
//
// XXX_kin: We need to also handle ProcessingInstruction
// XXX_kin: according to the spec.
nsCOMPtr<nsIDOMCharacterData> charData(do_QueryInterface(node));
if (charData)
{
uint32_t dataLength = 0;
if (node == startContainer)
{
if (node == endContainer)
{
// This range is completely contained within a single text node.
// Delete or extract the data between startOffset and endOffset.
if (endOffset > startOffset)
{
if (retval) {
nsAutoString cutValue;
rv = charData->SubstringData(startOffset, endOffset - startOffset,
cutValue);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIDOMNode> clone;
rv = charData->CloneNode(false, 1, getter_AddRefs(clone));
NS_ENSURE_SUCCESS(rv, rv);
clone->SetNodeValue(cutValue);
nodeToResult = do_QueryInterface(clone);
}
nsMutationGuard guard;
rv = charData->DeleteData(startOffset, endOffset - startOffset);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_STATE(!guard.Mutated(0) ||
ValidateCurrentNode(this, iter));
}
handled = true;
}
else
{
// Delete or extract everything after startOffset.
rv = charData->GetLength(&dataLength);
NS_ENSURE_SUCCESS(rv, rv);
if (dataLength >= (uint32_t)startOffset)
{
nsMutationGuard guard;
nsCOMPtr<nsIDOMCharacterData> cutNode;
rv = SplitDataNode(charData, startOffset, getter_AddRefs(cutNode));
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_STATE(!guard.Mutated(1) ||
ValidateCurrentNode(this, iter));
nodeToResult = do_QueryInterface(cutNode);
}
handled = true;
}
}
else if (node == endContainer)
{
// Delete or extract everything before endOffset.
if (endOffset >= 0)
{
nsMutationGuard guard;
nsCOMPtr<nsIDOMCharacterData> cutNode;
/* The Range spec clearly states clones get cut and original nodes
remain behind, so use false as the last parameter.
*/
rv = SplitDataNode(charData, endOffset, getter_AddRefs(cutNode),
false);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_STATE(!guard.Mutated(1) ||
ValidateCurrentNode(this, iter));
nodeToResult = do_QueryInterface(cutNode);
}
handled = true;
}
}
if (!handled && (node == endContainer || node == startContainer))
{
if (node && node->IsElement() &&
((node == endContainer && endOffset == 0) ||
(node == startContainer &&
int32_t(node->AsElement()->GetChildCount()) == startOffset)))
{
if (retval) {
ErrorResult rv;
nodeToResult = node->CloneNode(false, rv);
NS_ENSURE_TRUE(!rv.Failed(), rv.StealNSResult());
}
handled = true;
}
}
if (!handled)
{
// node was not handled above, so it must be completely contained
// within the range. Just remove it from the tree!
nodeToResult = node;
}
uint32_t parentCount = 0;
// Set the result to document fragment if we have 'retval'.
if (retval) {
nsCOMPtr<nsINode> oldCommonAncestor = commonAncestor;
if (!iter.IsDone()) {
// Setup the parameters for the next iteration of the loop.
nsCOMPtr<nsINode> prevNode = iter.GetCurrentNode();
NS_ENSURE_STATE(prevNode);
// Get node's and prevNode's common parent. Do this before moving
// nodes from original DOM to result fragment.
commonAncestor = nsContentUtils::GetCommonAncestor(node, prevNode);
NS_ENSURE_STATE(commonAncestor);
nsCOMPtr<nsINode> parentCounterNode = node;
while (parentCounterNode && parentCounterNode != commonAncestor)
{
++parentCount;
parentCounterNode = parentCounterNode->GetParentNode();
NS_ENSURE_STATE(parentCounterNode);
}
}
// Clone the parent hierarchy between commonAncestor and node.
nsCOMPtr<nsINode> closestAncestor, farthestAncestor;
rv = CloneParentsBetween(oldCommonAncestor, node,
getter_AddRefs(closestAncestor),
getter_AddRefs(farthestAncestor));
NS_ENSURE_SUCCESS(rv, rv);
if (farthestAncestor)
{
nsCOMPtr<nsINode> n = do_QueryInterface(commonCloneAncestor);
rv = PrependChild(n, farthestAncestor);
NS_ENSURE_SUCCESS(rv, rv);
}
nsMutationGuard guard;
nsCOMPtr<nsINode> parent = nodeToResult->GetParentNode();
rv = closestAncestor ? PrependChild(closestAncestor, nodeToResult)
: PrependChild(commonCloneAncestor, nodeToResult);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_STATE(!guard.Mutated(parent ? 2 : 1) ||
ValidateCurrentNode(this, iter));
} else if (nodeToResult) {
nsMutationGuard guard;
nsCOMPtr<nsINode> node = nodeToResult;
nsCOMPtr<nsINode> parent = node->GetParentNode();
if (parent) {
mozilla::ErrorResult error;
parent->RemoveChild(*node, error);
NS_ENSURE_FALSE(error.Failed(), error.StealNSResult());
}
NS_ENSURE_STATE(!guard.Mutated(1) ||
ValidateCurrentNode(this, iter));
}
if (!iter.IsDone() && retval) {
// Find the equivalent of commonAncestor in the cloned tree.
nsCOMPtr<nsINode> newCloneAncestor = nodeToResult;
for (uint32_t i = parentCount; i; --i)
{
newCloneAncestor = newCloneAncestor->GetParentNode();
NS_ENSURE_STATE(newCloneAncestor);
}
commonCloneAncestor = newCloneAncestor;
}
}
rv = CollapseRangeAfterDelete(this);
if (NS_SUCCEEDED(rv) && aFragment) {
retval.forget(aFragment);
}
return rv;
}
NS_IMETHODIMP
nsRange::DeleteContents()
{
return CutContents(nullptr);
}
void
nsRange::DeleteContents(ErrorResult& aRv)
{
aRv = CutContents(nullptr);
}
NS_IMETHODIMP
nsRange::ExtractContents(nsIDOMDocumentFragment** aReturn)
{
NS_ENSURE_ARG_POINTER(aReturn);
RefPtr<DocumentFragment> fragment;
nsresult rv = CutContents(getter_AddRefs(fragment));
fragment.forget(aReturn);
return rv;
}
already_AddRefed<DocumentFragment>
nsRange::ExtractContents(ErrorResult& rv)
{
RefPtr<DocumentFragment> fragment;
rv = CutContents(getter_AddRefs(fragment));
return fragment.forget();
}
NS_IMETHODIMP
nsRange::CompareBoundaryPoints(uint16_t aHow, nsIDOMRange* aOtherRange,
int16_t* aCmpRet)
{
nsRange* otherRange = static_cast<nsRange*>(aOtherRange);
NS_ENSURE_TRUE(otherRange, NS_ERROR_NULL_POINTER);
ErrorResult rv;
*aCmpRet = CompareBoundaryPoints(aHow, *otherRange, rv);
return rv.StealNSResult();
}
int16_t
nsRange::CompareBoundaryPoints(uint16_t aHow, nsRange& aOtherRange,
ErrorResult& rv)
{
if (!mIsPositioned || !aOtherRange.IsPositioned()) {
rv.Throw(NS_ERROR_NOT_INITIALIZED);
return 0;
}
nsINode *ourNode, *otherNode;
int32_t ourOffset, otherOffset;
switch (aHow) {
case nsIDOMRange::START_TO_START:
ourNode = mStartParent;
ourOffset = mStartOffset;
otherNode = aOtherRange.GetStartParent();
otherOffset = aOtherRange.StartOffset();
break;
case nsIDOMRange::START_TO_END:
ourNode = mEndParent;
ourOffset = mEndOffset;
otherNode = aOtherRange.GetStartParent();
otherOffset = aOtherRange.StartOffset();
break;
case nsIDOMRange::END_TO_START:
ourNode = mStartParent;
ourOffset = mStartOffset;
otherNode = aOtherRange.GetEndParent();
otherOffset = aOtherRange.EndOffset();
break;
case nsIDOMRange::END_TO_END:
ourNode = mEndParent;
ourOffset = mEndOffset;
otherNode = aOtherRange.GetEndParent();
otherOffset = aOtherRange.EndOffset();
break;
default:
// We were passed an illegal value
rv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return 0;
}
if (mRoot != aOtherRange.GetRoot()) {
rv.Throw(NS_ERROR_DOM_WRONG_DOCUMENT_ERR);
return 0;
}
return nsContentUtils::ComparePoints(ourNode, ourOffset,
otherNode, otherOffset);
}
/* static */ nsresult
nsRange::CloneParentsBetween(nsINode *aAncestor,
nsINode *aNode,
nsINode **aClosestAncestor,
nsINode **aFarthestAncestor)
{
NS_ENSURE_ARG_POINTER((aAncestor && aNode && aClosestAncestor && aFarthestAncestor));
*aClosestAncestor = nullptr;
*aFarthestAncestor = nullptr;
if (aAncestor == aNode)
return NS_OK;
nsCOMPtr<nsINode> firstParent, lastParent;
nsCOMPtr<nsINode> parent = aNode->GetParentNode();
while(parent && parent != aAncestor)
{
ErrorResult rv;
nsCOMPtr<nsINode> clone = parent->CloneNode(false, rv);
if (rv.Failed()) {
return rv.StealNSResult();
}
if (!clone) {
return NS_ERROR_FAILURE;
}
if (! firstParent) {
firstParent = lastParent = clone;
} else {
clone->AppendChild(*lastParent, rv);
if (rv.Failed()) return rv.StealNSResult();
lastParent = clone;
}
parent = parent->GetParentNode();
}
*aClosestAncestor = firstParent;
NS_IF_ADDREF(*aClosestAncestor);
*aFarthestAncestor = lastParent;
NS_IF_ADDREF(*aFarthestAncestor);
return NS_OK;
}
NS_IMETHODIMP
nsRange::CloneContents(nsIDOMDocumentFragment** aReturn)
{
ErrorResult rv;
*aReturn = CloneContents(rv).take();
return rv.StealNSResult();
}
already_AddRefed<DocumentFragment>
nsRange::CloneContents(ErrorResult& aRv)
{
nsCOMPtr<nsINode> commonAncestor = GetCommonAncestorContainer(aRv);
MOZ_ASSERT(!aRv.Failed(), "GetCommonAncestorContainer() shouldn't fail!");
nsCOMPtr<nsIDocument> doc = mStartParent->OwnerDoc();
NS_ASSERTION(doc, "CloneContents needs a document to continue.");
if (!doc) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
// Create a new document fragment in the context of this document,
// which might be null
RefPtr<DocumentFragment> clonedFrag =
new DocumentFragment(doc->NodeInfoManager());
nsCOMPtr<nsINode> commonCloneAncestor = clonedFrag.get();
// Create and initialize a subtree iterator that will give
// us all the subtrees within the range.
RangeSubtreeIterator iter;
aRv = iter.Init(this);
if (aRv.Failed()) {
return nullptr;
}
if (iter.IsDone())
{
// There's nothing to add to the doc frag, we must be done!
return clonedFrag.forget();
}
iter.First();
// With the exception of text nodes that contain one of the range
// end points and elements which don't have any content selected the subtree
// iterator should only give us back subtrees that are completely contained
// between the range's end points.
//
// Unfortunately these subtrees don't contain the parent hierarchy/context
// that the Range spec requires us to return. This loop clones the
// parent hierarchy, adds a cloned version of the subtree, to it, then
// correctly places this new subtree into the doc fragment.
while (!iter.IsDone())
{
nsCOMPtr<nsINode> node = iter.GetCurrentNode();
bool deepClone = !node->IsElement() ||
(!(node == mEndParent && mEndOffset == 0) &&
!(node == mStartParent &&
mStartOffset ==
int32_t(node->AsElement()->GetChildCount())));
// Clone the current subtree!
nsCOMPtr<nsINode> clone = node->CloneNode(deepClone, aRv);
if (aRv.Failed()) {
return nullptr;
}
// If it's CharacterData, make sure we only clone what
// is in the range.
//
// XXX_kin: We need to also handle ProcessingInstruction
// XXX_kin: according to the spec.
nsCOMPtr<nsIDOMCharacterData> charData(do_QueryInterface(clone));
if (charData)
{
if (node == mEndParent)
{
// We only need the data before mEndOffset, so get rid of any
// data after it.
uint32_t dataLength = 0;
aRv = charData->GetLength(&dataLength);
if (aRv.Failed()) {
return nullptr;
}
if (dataLength > (uint32_t)mEndOffset)
{
aRv = charData->DeleteData(mEndOffset, dataLength - mEndOffset);
if (aRv.Failed()) {
return nullptr;
}
}
}
if (node == mStartParent)
{
// We don't need any data before mStartOffset, so just
// delete it!
if (mStartOffset > 0)
{
aRv = charData->DeleteData(0, mStartOffset);
if (aRv.Failed()) {
return nullptr;
}
}
}
}
// Clone the parent hierarchy between commonAncestor and node.
nsCOMPtr<nsINode> closestAncestor, farthestAncestor;
aRv = CloneParentsBetween(commonAncestor, node,
getter_AddRefs(closestAncestor),
getter_AddRefs(farthestAncestor));
if (aRv.Failed()) {
return nullptr;
}
// Hook the parent hierarchy/context of the subtree into the clone tree.
if (farthestAncestor)
{
commonCloneAncestor->AppendChild(*farthestAncestor, aRv);
if (aRv.Failed()) {
return nullptr;
}
}
// Place the cloned subtree into the cloned doc frag tree!
nsCOMPtr<nsINode> cloneNode = do_QueryInterface(clone);
if (closestAncestor)
{
// Append the subtree under closestAncestor since it is the
// immediate parent of the subtree.
closestAncestor->AppendChild(*cloneNode, aRv);
}
else
{
// If we get here, there is no missing parent hierarchy between
// commonAncestor and node, so just append clone to commonCloneAncestor.
commonCloneAncestor->AppendChild(*cloneNode, aRv);
}
if (aRv.Failed()) {
return nullptr;
}
// Get the next subtree to be processed. The idea here is to setup
// the parameters for the next iteration of the loop.
iter.Next();
if (iter.IsDone())
break; // We must be done!
nsCOMPtr<nsINode> nextNode = iter.GetCurrentNode();
if (!nextNode) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
// Get node and nextNode's common parent.
commonAncestor = nsContentUtils::GetCommonAncestor(node, nextNode);
if (!commonAncestor) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
// Find the equivalent of commonAncestor in the cloned tree!
while (node && node != commonAncestor)
{
node = node->GetParentNode();
if (aRv.Failed()) {
return nullptr;
}
if (!node) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
cloneNode = cloneNode->GetParentNode();
if (!cloneNode) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
}
commonCloneAncestor = cloneNode;
}
return clonedFrag.forget();
}
already_AddRefed<nsRange>
nsRange::CloneRange() const
{
RefPtr<nsRange> range = new nsRange(mOwner);
range->SetMaySpanAnonymousSubtrees(mMaySpanAnonymousSubtrees);
range->DoSetRange(mStartParent, mStartOffset, mEndParent, mEndOffset, mRoot);
return range.forget();
}
NS_IMETHODIMP
nsRange::CloneRange(nsIDOMRange** aReturn)
{
*aReturn = CloneRange().take();
return NS_OK;
}
NS_IMETHODIMP
nsRange::InsertNode(nsIDOMNode* aNode)
{
nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
if (!node) {
return NS_ERROR_DOM_NOT_OBJECT_ERR;
}
ErrorResult rv;
InsertNode(*node, rv);
return rv.StealNSResult();
}
void
nsRange::InsertNode(nsINode& aNode, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNode)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
int32_t tStartOffset = StartOffset();
nsCOMPtr<nsINode> tStartContainer = GetStartContainer(aRv);
if (aRv.Failed()) {
return;
}
// This is the node we'll be inserting before, and its parent
nsCOMPtr<nsINode> referenceNode;
nsCOMPtr<nsINode> referenceParentNode = tStartContainer;
nsCOMPtr<nsIDOMText> startTextNode(do_QueryInterface(tStartContainer));
nsCOMPtr<nsIDOMNodeList> tChildList;
if (startTextNode) {
referenceParentNode = tStartContainer->GetParentNode();
if (!referenceParentNode) {
aRv.Throw(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR);
return;
}
nsCOMPtr<nsIDOMText> secondPart;
aRv = startTextNode->SplitText(tStartOffset, getter_AddRefs(secondPart));
if (aRv.Failed()) {
return;
}
referenceNode = do_QueryInterface(secondPart);
} else {
aRv = tStartContainer->AsDOMNode()->GetChildNodes(getter_AddRefs(tChildList));
if (aRv.Failed()) {
return;
}
// find the insertion point in the DOM and insert the Node
nsCOMPtr<nsIDOMNode> q;
aRv = tChildList->Item(tStartOffset, getter_AddRefs(q));
referenceNode = do_QueryInterface(q);
if (aRv.Failed()) {
return;
}
}
// We might need to update the end to include the new node (bug 433662).
// Ideally we'd only do this if needed, but it's tricky to know when it's
// needed in advance (bug 765799).
int32_t newOffset;
if (referenceNode) {
newOffset = IndexOf(referenceNode);
} else {
uint32_t length;
aRv = tChildList->GetLength(&length);
if (aRv.Failed()) {
return;
}
newOffset = length;
}
if (aNode.NodeType() == nsIDOMNode::DOCUMENT_FRAGMENT_NODE) {
newOffset += aNode.GetChildCount();
} else {
newOffset++;
}
// Now actually insert the node
nsCOMPtr<nsINode> tResultNode;
tResultNode = referenceParentNode->InsertBefore(aNode, referenceNode, aRv);
if (aRv.Failed()) {
return;
}
if (Collapsed()) {
aRv = SetEnd(referenceParentNode, newOffset);
}
}
NS_IMETHODIMP
nsRange::SurroundContents(nsIDOMNode* aNewParent)
{
nsCOMPtr<nsINode> node = do_QueryInterface(aNewParent);
if (!node) {
return NS_ERROR_DOM_NOT_OBJECT_ERR;
}
ErrorResult rv;
SurroundContents(*node, rv);
return rv.StealNSResult();
}
void
nsRange::SurroundContents(nsINode& aNewParent, ErrorResult& aRv)
{
if (!nsContentUtils::LegacyIsCallerNativeCode() &&
!nsContentUtils::CanCallerAccess(&aNewParent)) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
if (!mRoot) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
// INVALID_STATE_ERROR: Raised if the Range partially selects a non-text
// node.
if (mStartParent != mEndParent) {
bool startIsText = mStartParent->IsNodeOfType(nsINode::eTEXT);
bool endIsText = mEndParent->IsNodeOfType(nsINode::eTEXT);
nsINode* startGrandParent = mStartParent->GetParentNode();
nsINode* endGrandParent = mEndParent->GetParentNode();
if (!((startIsText && endIsText &&
startGrandParent &&
startGrandParent == endGrandParent) ||
(startIsText &&
startGrandParent &&
startGrandParent == mEndParent) ||
(endIsText &&
endGrandParent &&
endGrandParent == mStartParent))) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
}
// INVALID_NODE_TYPE_ERROR if aNewParent is something that can't be inserted
// (Document, DocumentType, DocumentFragment)
uint16_t nodeType = aNewParent.NodeType();
if (nodeType == nsIDOMNode::DOCUMENT_NODE ||
nodeType == nsIDOMNode::DOCUMENT_TYPE_NODE ||
nodeType == nsIDOMNode::DOCUMENT_FRAGMENT_NODE) {
aRv.Throw(NS_ERROR_DOM_INVALID_NODE_TYPE_ERR);
return;
}
// Extract the contents within the range.
RefPtr<DocumentFragment> docFrag = ExtractContents(aRv);
if (aRv.Failed()) {
return;
}
if (!docFrag) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
// Spec says we need to remove all of aNewParent's
// children prior to insertion.
nsCOMPtr<nsINodeList> children = aNewParent.ChildNodes();
if (!children) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
uint32_t numChildren = children->Length();
while (numChildren)
{
nsCOMPtr<nsINode> child = children->Item(--numChildren);
if (!child) {
aRv.Throw(NS_ERROR_FAILURE);
return;
}
aNewParent.RemoveChild(*child, aRv);
if (aRv.Failed()) {
return;
}
}
// Insert aNewParent at the range's start point.
InsertNode(aNewParent, aRv);
if (aRv.Failed()) {
return;
}
// Append the content we extracted under aNewParent.
aNewParent.AppendChild(*docFrag, aRv);
if (aRv.Failed()) {
return;
}
// Select aNewParent, and its contents.
SelectNode(aNewParent, aRv);
}
NS_IMETHODIMP
nsRange::ToString(nsAString& aReturn)
{
// clear the string
aReturn.Truncate();
// If we're unpositioned, return the empty string
if (!mIsPositioned) {
return NS_OK;
}
#ifdef DEBUG_range
printf("Range dump: -----------------------\n");
#endif /* DEBUG */
// effeciency hack for simple case
if (mStartParent == mEndParent)
{
nsCOMPtr<nsIDOMText> textNode( do_QueryInterface(mStartParent) );
if (textNode)
{
#ifdef DEBUG_range
// If debug, dump it:
nsCOMPtr<nsIContent> cN (do_QueryInterface(mStartParent));
if (cN) cN->List(stdout);
printf("End Range dump: -----------------------\n");
#endif /* DEBUG */
// grab the text
if (NS_FAILED(textNode->SubstringData(mStartOffset,mEndOffset-mStartOffset,aReturn)))
return NS_ERROR_UNEXPECTED;
return NS_OK;
}
}
/* complex case: mStartParent != mEndParent, or mStartParent not a text node
revisit - there are potential optimizations here and also tradeoffs.
*/
nsCOMPtr<nsIContentIterator> iter = NS_NewContentIterator();
nsresult rv = iter->Init(this);
NS_ENSURE_SUCCESS(rv, rv);
nsString tempString;
// loop through the content iterator, which returns nodes in the range in
// close tag order, and grab the text from any text node
while (!iter->IsDone())
{
nsINode *n = iter->GetCurrentNode();
#ifdef DEBUG_range
// If debug, dump it:
n->List(stdout);
#endif /* DEBUG */
nsCOMPtr<nsIDOMText> textNode(do_QueryInterface(n));
if (textNode) // if it's a text node, get the text
{
if (n == mStartParent) // only include text past start offset
{
uint32_t strLength;
textNode->GetLength(&strLength);
textNode->SubstringData(mStartOffset,strLength-mStartOffset,tempString);
aReturn += tempString;
}
else if (n == mEndParent) // only include text before end offset
{
textNode->SubstringData(0,mEndOffset,tempString);
aReturn += tempString;
}
else // grab the whole kit-n-kaboodle
{
textNode->GetData(tempString);
aReturn += tempString;
}
}
iter->Next();
}
#ifdef DEBUG_range
printf("End Range dump: -----------------------\n");
#endif /* DEBUG */
return NS_OK;
}
NS_IMETHODIMP
nsRange::Detach()
{
// No-op, but still set mIsDetached for telemetry (bug 702948)
mIsDetached = true;
return NS_OK;
}
NS_IMETHODIMP
nsRange::CreateContextualFragment(const nsAString& aFragment,
nsIDOMDocumentFragment** aReturn)
{
if (mIsPositioned) {
return nsContentUtils::CreateContextualFragment(mStartParent, aFragment,
false, aReturn);
}
return NS_ERROR_FAILURE;
}
already_AddRefed<DocumentFragment>
nsRange::CreateContextualFragment(const nsAString& aFragment, ErrorResult& aRv)
{
if (!mIsPositioned) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
return nsContentUtils::CreateContextualFragment(mStartParent, aFragment,
false, aRv);
}
static void ExtractRectFromOffset(nsIFrame* aFrame,
const int32_t aOffset, nsRect* aR, bool aKeepLeft,
bool aClampToEdge)
{
nsPoint point;
aFrame->GetPointFromOffset(aOffset, &point);
if (!aClampToEdge && !aR->Contains(point)) {
aR->width = 0;
aR->x = point.x;
return;
}
if (aClampToEdge) {
point = aR->ClampPoint(point);
}
if (aKeepLeft) {
aR->width = point.x - aR->x;
} else {
aR->width = aR->XMost() - point.x;
aR->x = point.x;
}
}
static nsTextFrame*
GetTextFrameForContent(nsIContent* aContent, bool aFlushLayout)
{
nsIPresShell* presShell = aContent->OwnerDoc()->GetShell();
if (presShell) {
presShell->FrameConstructor()->EnsureFrameForTextNode(
static_cast<nsGenericDOMDataNode*>(aContent));
if (aFlushLayout) {
aContent->OwnerDoc()->FlushPendingNotifications(Flush_Layout);
}
nsIFrame* frame = aContent->GetPrimaryFrame();
if (frame && frame->GetType() == nsGkAtoms::textFrame) {
return static_cast<nsTextFrame*>(frame);
}
}
return nullptr;
}
static nsresult GetPartialTextRect(nsLayoutUtils::RectCallback* aCallback,
nsIContent* aContent, int32_t aStartOffset,
int32_t aEndOffset, bool aClampToEdge,
bool aFlushLayout)
{
nsTextFrame* textFrame = GetTextFrameForContent(aContent, aFlushLayout);
if (textFrame) {
nsIFrame* relativeTo = nsLayoutUtils::GetContainingBlockForClientRect(textFrame);
for (nsTextFrame* f = textFrame; f; f = static_cast<nsTextFrame*>(f->GetNextContinuation())) {
int32_t fstart = f->GetContentOffset(), fend = f->GetContentEnd();
if (fend <= aStartOffset || fstart >= aEndOffset)
continue;
// overlapping with the offset we want
f->EnsureTextRun(nsTextFrame::eInflated);
NS_ENSURE_TRUE(f->GetTextRun(nsTextFrame::eInflated), NS_ERROR_OUT_OF_MEMORY);
bool rtl = f->GetTextRun(nsTextFrame::eInflated)->IsRightToLeft();
nsRect r = f->GetRectRelativeToSelf();
if (fstart < aStartOffset) {
// aStartOffset is within this frame
ExtractRectFromOffset(f, aStartOffset, &r, rtl, aClampToEdge);
}
if (fend > aEndOffset) {
// aEndOffset is in the middle of this frame
ExtractRectFromOffset(f, aEndOffset, &r, !rtl, aClampToEdge);
}
r = nsLayoutUtils::TransformFrameRectToAncestor(f, r, relativeTo);
aCallback->AddRect(r);
}
}
return NS_OK;
}
/* static */ void
nsRange::CollectClientRects(nsLayoutUtils::RectCallback* aCollector,
nsRange* aRange,
nsINode* aStartParent, int32_t aStartOffset,
nsINode* aEndParent, int32_t aEndOffset,
bool aClampToEdge, bool aFlushLayout)
{
// Hold strong pointers across the flush
nsCOMPtr<nsINode> startContainer = aStartParent;
nsCOMPtr<nsINode> endContainer = aEndParent;
// Flush out layout so our frames are up to date.
if (!aStartParent->IsInUncomposedDoc()) {
return;
}
if (aFlushLayout) {
aStartParent->OwnerDoc()->FlushPendingNotifications(Flush_Layout);
// Recheck whether we're still in the document
if (!aStartParent->IsInUncomposedDoc()) {
return;
}
}
RangeSubtreeIterator iter;
nsresult rv = iter.Init(aRange);
if (NS_FAILED(rv)) return;
if (iter.IsDone()) {
// the range is collapsed, only continue if the cursor is in a text node
nsCOMPtr<nsIContent> content = do_QueryInterface(aStartParent);
if (content && content->IsNodeOfType(nsINode::eTEXT)) {
nsTextFrame* textFrame = GetTextFrameForContent(content, aFlushLayout);
if (textFrame) {
int32_t outOffset;
nsIFrame* outFrame;
textFrame->GetChildFrameContainingOffset(aStartOffset, false,
&outOffset, &outFrame);
if (outFrame) {
nsIFrame* relativeTo =
nsLayoutUtils::GetContainingBlockForClientRect(outFrame);
nsRect r = outFrame->GetRectRelativeToSelf();
ExtractRectFromOffset(outFrame, aStartOffset, &r, false, aClampToEdge);
r.width = 0;
r = nsLayoutUtils::TransformFrameRectToAncestor(outFrame, r, relativeTo);
aCollector->AddRect(r);
}
}
}
return;
}
do {
nsCOMPtr<nsINode> node = iter.GetCurrentNode();
iter.Next();
nsCOMPtr<nsIContent> content = do_QueryInterface(node);
if (!content)
continue;
if (content->IsNodeOfType(nsINode::eTEXT)) {
if (node == startContainer) {
int32_t offset = startContainer == endContainer ?
aEndOffset : content->GetText()->GetLength();
GetPartialTextRect(aCollector, content, aStartOffset, offset,
aClampToEdge, aFlushLayout);
continue;
} else if (node == endContainer) {
GetPartialTextRect(aCollector, content, 0, aEndOffset,
aClampToEdge, aFlushLayout);
continue;
}
}
nsIFrame* frame = content->GetPrimaryFrame();
if (frame) {
nsLayoutUtils::GetAllInFlowRects(frame,
nsLayoutUtils::GetContainingBlockForClientRect(frame), aCollector,
nsLayoutUtils::RECTS_ACCOUNT_FOR_TRANSFORMS);
}
} while (!iter.IsDone());
}
NS_IMETHODIMP
nsRange::GetBoundingClientRect(nsIDOMClientRect** aResult)
{
*aResult = GetBoundingClientRect(true).take();
return NS_OK;
}
already_AddRefed<DOMRect>
nsRange::GetBoundingClientRect(bool aClampToEdge, bool aFlushLayout)
{
RefPtr<DOMRect> rect = new DOMRect(ToSupports(this));
if (!mStartParent) {
return rect.forget();
}
nsLayoutUtils::RectAccumulator accumulator;
CollectClientRects(&accumulator, this, mStartParent, mStartOffset,
mEndParent, mEndOffset, aClampToEdge, aFlushLayout);
nsRect r = accumulator.mResultRect.IsEmpty() ? accumulator.mFirstRect :
accumulator.mResultRect;
rect->SetLayoutRect(r);
return rect.forget();
}
NS_IMETHODIMP
nsRange::GetClientRects(nsIDOMClientRectList** aResult)
{
*aResult = GetClientRects(true).take();
return NS_OK;
}
already_AddRefed<DOMRectList>
nsRange::GetClientRects(bool aClampToEdge, bool aFlushLayout)
{
if (!mStartParent) {
return nullptr;
}
RefPtr<DOMRectList> rectList =
new DOMRectList(static_cast<nsIDOMRange*>(this));
nsLayoutUtils::RectListBuilder builder(rectList);
CollectClientRects(&builder, this, mStartParent, mStartOffset,
mEndParent, mEndOffset, aClampToEdge, aFlushLayout);
return rectList.forget();
}
NS_IMETHODIMP
nsRange::GetUsedFontFaces(nsIDOMFontFaceList** aResult)
{
*aResult = nullptr;
NS_ENSURE_TRUE(mStartParent, NS_ERROR_UNEXPECTED);
nsCOMPtr<nsINode> startContainer = do_QueryInterface(mStartParent);
nsCOMPtr<nsINode> endContainer = do_QueryInterface(mEndParent);
// Flush out layout so our frames are up to date.
nsIDocument* doc = mStartParent->OwnerDoc();
NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED);
doc->FlushPendingNotifications(Flush_Frames);
// Recheck whether we're still in the document
NS_ENSURE_TRUE(mStartParent->IsInUncomposedDoc(), NS_ERROR_UNEXPECTED);
RefPtr<nsFontFaceList> fontFaceList = new nsFontFaceList();
RangeSubtreeIterator iter;
nsresult rv = iter.Init(this);
NS_ENSURE_SUCCESS(rv, rv);
while (!iter.IsDone()) {
// only collect anything if the range is not collapsed
nsCOMPtr<nsINode> node = iter.GetCurrentNode();
iter.Next();
nsCOMPtr<nsIContent> content = do_QueryInterface(node);
if (!content) {
continue;
}
nsIFrame* frame = content->GetPrimaryFrame();
if (!frame) {
continue;
}
if (content->IsNodeOfType(nsINode::eTEXT)) {
if (node == startContainer) {
int32_t offset = startContainer == endContainer ?
mEndOffset : content->GetText()->GetLength();
nsLayoutUtils::GetFontFacesForText(frame, mStartOffset, offset,
true, fontFaceList);
continue;
}
if (node == endContainer) {
nsLayoutUtils::GetFontFacesForText(frame, 0, mEndOffset,
true, fontFaceList);
continue;
}
}
nsLayoutUtils::GetFontFacesForFrames(frame, fontFaceList);
}
fontFaceList.forget(aResult);
return NS_OK;
}
nsINode*
nsRange::GetRegisteredCommonAncestor()
{
NS_ASSERTION(IsInSelection(),
"GetRegisteredCommonAncestor only valid for range in selection");
nsINode* ancestor = GetNextRangeCommonAncestor(mStartParent);
while (ancestor) {
RangeHashTable* ranges =
static_cast<RangeHashTable*>(ancestor->GetProperty(nsGkAtoms::range));
if (ranges->GetEntry(this)) {
break;
}
ancestor = GetNextRangeCommonAncestor(ancestor->GetParentNode());
}
NS_ASSERTION(ancestor, "can't find common ancestor for selected range");
return ancestor;
}
/* static */ bool nsRange::AutoInvalidateSelection::mIsNested;
nsRange::AutoInvalidateSelection::~AutoInvalidateSelection()
{
NS_ASSERTION(mWasInSelection == mRange->IsInSelection(),
"Range got unselected in AutoInvalidateSelection block");
if (!mCommonAncestor) {
return;
}
mIsNested = false;
::InvalidateAllFrames(mCommonAncestor);
nsINode* commonAncestor = mRange->GetRegisteredCommonAncestor();
if (commonAncestor && commonAncestor != mCommonAncestor) {
::InvalidateAllFrames(commonAncestor);
}
}
/* static */ already_AddRefed<nsRange>
nsRange::Constructor(const GlobalObject& aGlobal,
ErrorResult& aRv)
{
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aGlobal.GetAsSupports());
if (!window || !window->GetDoc()) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
return window->GetDoc()->CreateRange(aRv);
}
static bool ExcludeIfNextToNonSelectable(nsIContent* aContent)
{
return aContent->IsNodeOfType(nsINode::eTEXT) &&
aContent->HasFlag(NS_CREATE_FRAME_IF_NON_WHITESPACE);
}
void
nsRange::ExcludeNonSelectableNodes(nsTArray<RefPtr<nsRange>>* aOutRanges)
{
MOZ_ASSERT(mIsPositioned);
MOZ_ASSERT(mEndParent);
MOZ_ASSERT(mStartParent);
nsRange* range = this;
RefPtr<nsRange> newRange;
while (range) {
nsCOMPtr<nsIContentIterator> iter = NS_NewPreContentIterator();
nsresult rv = iter->Init(range);
if (NS_FAILED(rv)) {
return;
}
bool added = false;
bool seenSelectable = false;
// |firstNonSelectableContent| is the first node in a consecutive sequence
// of non-IsSelectable nodes. When we find a selectable node after such
// a sequence we'll end the last nsRange, create a new one and restart
// the outer loop.
nsIContent* firstNonSelectableContent = nullptr;
while (true) {
ErrorResult err;
nsINode* node = iter->GetCurrentNode();
iter->Next();
bool selectable = true;
nsIContent* content =
node && node->IsContent() ? node->AsContent() : nullptr;
if (content) {
if (firstNonSelectableContent && ExcludeIfNextToNonSelectable(content)) {
// Ignorable whitespace next to a sequence of non-selectable nodes
// counts as non-selectable (bug 1216001).
selectable = false;
}
if (selectable) {
nsIFrame* frame = content->GetPrimaryFrame();
for (nsIContent* p = content; !frame && (p = p->GetParent()); ) {
frame = p->GetPrimaryFrame();
}
if (frame) {
frame->IsSelectable(&selectable, nullptr);
}
}
}
if (!selectable) {
if (!firstNonSelectableContent) {
firstNonSelectableContent = content;
}
if (iter->IsDone() && seenSelectable) {
// The tail end of the initial range is non-selectable - truncate the
// current range before the first non-selectable node.
range->SetEndBefore(*firstNonSelectableContent, err);
}
} else if (firstNonSelectableContent) {
if (range == this && !seenSelectable) {
// This is the initial range and all its nodes until now are
// non-selectable so just trim them from the start.
range->SetStartBefore(*node, err);
if (err.Failed()) {
return;
}
break; // restart the same range with a new iterator
} else {
// Save the end point before truncating the range.
nsINode* endParent = range->mEndParent;
int32_t endOffset = range->mEndOffset;
// Truncate the current range before the first non-selectable node.
range->SetEndBefore(*firstNonSelectableContent, err);
// Store it in the result (strong ref) - do this before creating
// a new range in |newRange| below so we don't drop the last ref
// to the range created in the previous iteration.
if (!added && !err.Failed()) {
aOutRanges->AppendElement(range);
}
// Create a new range for the remainder.
nsINode* startParent = node;
int32_t startOffset = 0;
// Don't start *inside* a node with independent selection though
// (e.g. <input>).
if (content && content->HasIndependentSelection()) {
nsINode* parent = startParent->GetParent();
if (parent) {
startOffset = parent->IndexOf(startParent);
startParent = parent;
}
}
rv = CreateRange(startParent, startOffset, endParent, endOffset,
getter_AddRefs(newRange));
if (NS_FAILED(rv) || newRange->Collapsed()) {
newRange = nullptr;
}
range = newRange;
break; // create a new iterator for the new range, if any
}
} else {
seenSelectable = true;
if (!added) {
added = true;
aOutRanges->AppendElement(range);
}
}
if (iter->IsDone()) {
return;
}
}
}
}
struct InnerTextAccumulator
{
explicit InnerTextAccumulator(mozilla::dom::DOMString& aValue)
: mString(aValue.AsAString()), mRequiredLineBreakCount(0) {}
void FlushLineBreaks()
{
while (mRequiredLineBreakCount > 0) {
// Required line breaks at the start of the text are suppressed.
if (!mString.IsEmpty()) {
mString.Append('\n');
}
--mRequiredLineBreakCount;
}
}
void Append(char aCh)
{
Append(nsAutoString(aCh));
}
void Append(const nsAString& aString)
{
if (aString.IsEmpty()) {
return;
}
FlushLineBreaks();
mString.Append(aString);
}
void AddRequiredLineBreakCount(int8_t aCount)
{
mRequiredLineBreakCount = std::max(mRequiredLineBreakCount, aCount);
}
nsAString& mString;
int8_t mRequiredLineBreakCount;
};
static bool
IsVisibleAndNotInReplacedElement(nsIFrame* aFrame)
{
if (!aFrame || !aFrame->StyleVisibility()->IsVisible()) {
return false;
}
for (nsIFrame* f = aFrame->GetParent(); f; f = f->GetParent()) {
if (f->IsFrameOfType(nsIFrame::eReplaced) &&
!f->GetContent()->IsHTMLElement(nsGkAtoms::button)) {
return false;
}
}
return true;
}
static bool
ElementIsVisibleNoFlush(Element* aElement)
{
if (!aElement) {
return false;
}
RefPtr<nsStyleContext> sc =
nsComputedDOMStyle::GetStyleContextForElementNoFlush(aElement, nullptr,
nullptr);
return sc && sc->StyleVisibility()->IsVisible();
}
static void
AppendTransformedText(InnerTextAccumulator& aResult,
nsGenericDOMDataNode* aTextNode,
int32_t aStart, int32_t aEnd)
{
nsIFrame* frame = aTextNode->GetPrimaryFrame();
if (!IsVisibleAndNotInReplacedElement(frame)) {
return;
}
nsIFrame::RenderedText text = frame->GetRenderedText(aStart, aEnd);
aResult.Append(text.mString);
}
/**
* States for tree traversal. AT_NODE means that we are about to enter
* the current DOM node. AFTER_NODE means that we have just finished traversing
* the children of the current DOM node and are about to apply any
* "after processing the node's children" steps before we finish visiting
* the node.
*/
enum TreeTraversalState {
AT_NODE,
AFTER_NODE
};
static int8_t
GetRequiredInnerTextLineBreakCount(nsIFrame* aFrame)
{
if (aFrame->GetContent()->IsHTMLElement(nsGkAtoms::p)) {
return 2;
}
const nsStyleDisplay* styleDisplay = aFrame->StyleDisplay();
if (styleDisplay->IsBlockOutside(aFrame) ||
styleDisplay->mDisplay == NS_STYLE_DISPLAY_TABLE_CAPTION) {
return 1;
}
return 0;
}
static bool
IsLastCellOfRow(nsIFrame* aFrame)
{
nsIAtom* type = aFrame->GetType();
if (type != nsGkAtoms::tableCellFrame &&
type != nsGkAtoms::bcTableCellFrame) {
return true;
}
for (nsIFrame* c = aFrame; c; c = c->GetNextContinuation()) {
if (c->GetNextSibling()) {
return false;
}
}
return true;
}
static bool
IsLastRowOfRowGroup(nsIFrame* aFrame)
{
if (aFrame->GetType() != nsGkAtoms::tableRowFrame) {
return true;
}
for (nsIFrame* c = aFrame; c; c = c->GetNextContinuation()) {
if (c->GetNextSibling()) {
return false;
}
}
return true;
}
static bool
IsLastNonemptyRowGroupOfTable(nsIFrame* aFrame)
{
if (aFrame->GetType() != nsGkAtoms::tableRowGroupFrame) {
return true;
}
for (nsIFrame* c = aFrame; c; c = c->GetNextContinuation()) {
for (nsIFrame* next = c->GetNextSibling(); next; next = next->GetNextSibling()) {
if (next->PrincipalChildList().FirstChild()) {
return false;
}
}
}
return true;
}
void
nsRange::GetInnerTextNoFlush(DOMString& aValue, ErrorResult& aError,
nsIContent* aStartParent, uint32_t aStartOffset,
nsIContent* aEndParent, uint32_t aEndOffset)
{
InnerTextAccumulator result(aValue);
nsIContent* currentNode = aStartParent;
TreeTraversalState currentState = AFTER_NODE;
if (aStartParent->IsNodeOfType(nsINode::eTEXT)) {
auto t = static_cast<nsGenericDOMDataNode*>(aStartParent);
if (aStartParent == aEndParent) {
AppendTransformedText(result, t, aStartOffset, aEndOffset);
return;
}
AppendTransformedText(result, t, aStartOffset, t->TextLength());
} else {
if (uint32_t(aStartOffset) < aStartParent->GetChildCount()) {
currentNode = aStartParent->GetChildAt(aStartOffset);
currentState = AT_NODE;
}
}
nsIContent* endNode = aEndParent;
TreeTraversalState endState = AFTER_NODE;
if (aEndParent->IsNodeOfType(nsINode::eTEXT)) {
endState = AT_NODE;
} else {
if (uint32_t(aEndOffset) < aEndParent->GetChildCount()) {
endNode = aEndParent->GetChildAt(aEndOffset);
endState = AT_NODE;
}
}
while (currentNode != endNode || currentState != endState) {
nsIFrame* f = currentNode->GetPrimaryFrame();
bool isVisibleAndNotReplaced = IsVisibleAndNotInReplacedElement(f);
if (currentState == AT_NODE) {
bool isText = currentNode->IsNodeOfType(nsINode::eTEXT);
if (isText && currentNode->GetParent()->IsHTMLElement(nsGkAtoms::rp) &&
ElementIsVisibleNoFlush(currentNode->GetParent()->AsElement())) {
nsAutoString str;
currentNode->GetTextContent(str, aError);
result.Append(str);
} else if (isVisibleAndNotReplaced) {
result.AddRequiredLineBreakCount(GetRequiredInnerTextLineBreakCount(f));
if (isText) {
nsIFrame::RenderedText text = f->GetRenderedText();
result.Append(text.mString);
}
}
nsIContent* child = currentNode->GetFirstChild();
if (child) {
currentNode = child;
continue;
}
currentState = AFTER_NODE;
}
if (currentNode == endNode && currentState == endState) {
break;
}
if (isVisibleAndNotReplaced) {
if (currentNode->IsHTMLElement(nsGkAtoms::br)) {
result.Append('\n');
}
switch (f->StyleDisplay()->mDisplay) {
case NS_STYLE_DISPLAY_TABLE_CELL:
if (!IsLastCellOfRow(f)) {
result.Append('\t');
}
break;
case NS_STYLE_DISPLAY_TABLE_ROW:
if (!IsLastRowOfRowGroup(f) ||
!IsLastNonemptyRowGroupOfTable(f->GetParent())) {
result.Append('\n');
}
break;
}
result.AddRequiredLineBreakCount(GetRequiredInnerTextLineBreakCount(f));
}
nsIContent* next = currentNode->GetNextSibling();
if (next) {
currentNode = next;
currentState = AT_NODE;
} else {
currentNode = currentNode->GetParent();
}
}
if (aEndParent->IsNodeOfType(nsINode::eTEXT)) {
nsGenericDOMDataNode* t = static_cast<nsGenericDOMDataNode*>(aEndParent);
AppendTransformedText(result, t, 0, aEndOffset);
}
// Do not flush trailing line breaks! Required breaks at the end of the text
// are suppressed.
}