Bug 1247796. Use keyboardFocusIndicatorColor for ActiveBorder system color keyword...
[gecko.git] / editor / libeditor / nsHTMLAnonymousUtils.cpp
blob798146acc4c8494ab490de589959c1849c7c5058
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #include "mozilla/Attributes.h"
6 #include "mozilla/dom/Element.h"
7 #include "mozilla/mozalloc.h"
8 #include "nsAString.h"
9 #include "nsAutoPtr.h"
10 #include "nsCOMPtr.h"
11 #include "nsComputedDOMStyle.h"
12 #include "nsDebug.h"
13 #include "nsError.h"
14 #include "nsGkAtoms.h"
15 #include "nsHTMLCSSUtils.h"
16 #include "nsHTMLEditor.h"
17 #include "nsIAtom.h"
18 #include "nsIContent.h"
19 #include "nsID.h"
20 #include "nsIDOMCSSPrimitiveValue.h"
21 #include "nsIDOMCSSStyleDeclaration.h"
22 #include "nsIDOMCSSValue.h"
23 #include "nsIDOMElement.h"
24 #include "nsIDOMEventTarget.h"
25 #include "nsIDOMHTMLElement.h"
26 #include "nsIDOMNode.h"
27 #include "nsIDOMWindow.h"
28 #include "nsIDocument.h"
29 #include "nsIDocumentObserver.h"
30 #include "nsIHTMLAbsPosEditor.h"
31 #include "nsIHTMLEditor.h"
32 #include "nsIHTMLInlineTableEditor.h"
33 #include "nsIHTMLObjectResizer.h"
34 #include "nsIMutationObserver.h"
35 #include "nsINode.h"
36 #include "nsIPresShell.h"
37 #include "nsISupportsImpl.h"
38 #include "nsISupportsUtils.h"
39 #include "nsLiteralString.h"
40 #include "nsPresContext.h"
41 #include "nsReadableUtils.h"
42 #include "nsString.h"
43 #include "nsStringFwd.h"
44 #include "nsUnicharUtils.h"
45 #include "nscore.h"
46 #include "nsContentUtils.h" // for nsAutoScriptBlocker
48 class nsIDOMEventListener;
49 class nsISelection;
51 using namespace mozilla;
52 using namespace mozilla::dom;
54 // retrieve an integer stored into a CSS computed float value
55 static int32_t GetCSSFloatValue(nsIDOMCSSStyleDeclaration * aDecl,
56 const nsAString & aProperty)
58 MOZ_ASSERT(aDecl);
60 nsCOMPtr<nsIDOMCSSValue> value;
61 // get the computed CSSValue of the property
62 nsresult res = aDecl->GetPropertyCSSValue(aProperty, getter_AddRefs(value));
63 if (NS_FAILED(res) || !value) return 0;
65 // check the type of the returned CSSValue; we handle here only
66 // pixel and enum types
67 nsCOMPtr<nsIDOMCSSPrimitiveValue> val = do_QueryInterface(value);
68 uint16_t type;
69 val->GetPrimitiveType(&type);
71 float f = 0;
72 switch (type) {
73 case nsIDOMCSSPrimitiveValue::CSS_PX:
74 // the value is in pixels, just get it
75 res = val->GetFloatValue(nsIDOMCSSPrimitiveValue::CSS_PX, &f);
76 NS_ENSURE_SUCCESS(res, 0);
77 break;
78 case nsIDOMCSSPrimitiveValue::CSS_IDENT: {
79 // the value is keyword, we have to map these keywords into
80 // numeric values
81 nsAutoString str;
82 res = val->GetStringValue(str);
83 if (str.EqualsLiteral("thin"))
84 f = 1;
85 else if (str.EqualsLiteral("medium"))
86 f = 3;
87 else if (str.EqualsLiteral("thick"))
88 f = 5;
89 break;
93 return (int32_t) f;
96 class nsElementDeletionObserver final : public nsIMutationObserver
98 public:
99 nsElementDeletionObserver(nsINode* aNativeAnonNode, nsINode* aObservedNode)
100 : mNativeAnonNode(aNativeAnonNode), mObservedNode(aObservedNode) {}
101 NS_DECL_ISUPPORTS
102 NS_DECL_NSIMUTATIONOBSERVER
103 protected:
104 ~nsElementDeletionObserver() {}
105 nsINode* mNativeAnonNode;
106 nsINode* mObservedNode;
109 NS_IMPL_ISUPPORTS(nsElementDeletionObserver, nsIMutationObserver)
110 NS_IMPL_NSIMUTATIONOBSERVER_CONTENT(nsElementDeletionObserver)
112 void
113 nsElementDeletionObserver::NodeWillBeDestroyed(const nsINode* aNode)
115 NS_ASSERTION(aNode == mNativeAnonNode || aNode == mObservedNode,
116 "Wrong aNode!");
117 if (aNode == mNativeAnonNode) {
118 mObservedNode->RemoveMutationObserver(this);
119 } else {
120 mNativeAnonNode->RemoveMutationObserver(this);
121 static_cast<nsIContent*>(mNativeAnonNode)->UnbindFromTree();
124 NS_RELEASE_THIS();
127 // Returns in *aReturn an anonymous nsDOMElement of type aTag,
128 // child of aParentNode. If aIsCreatedHidden is true, the class
129 // "hidden" is added to the created element. If aAnonClass is not
130 // the empty string, it becomes the value of the attribute "_moz_anonclass"
131 nsresult
132 nsHTMLEditor::CreateAnonymousElement(const nsAString & aTag, nsIDOMNode * aParentNode,
133 const nsAString & aAnonClass, bool aIsCreatedHidden,
134 nsIDOMElement ** aReturn)
136 NS_ENSURE_ARG_POINTER(aParentNode);
137 NS_ENSURE_ARG_POINTER(aReturn);
138 *aReturn = nullptr;
140 nsCOMPtr<nsIContent> parentContent( do_QueryInterface(aParentNode) );
141 NS_ENSURE_TRUE(parentContent, NS_OK);
143 nsCOMPtr<nsIDocument> doc = GetDocument();
144 NS_ENSURE_TRUE(doc, NS_ERROR_NULL_POINTER);
146 // Get the pres shell
147 nsCOMPtr<nsIPresShell> ps = GetPresShell();
148 NS_ENSURE_TRUE(ps, NS_ERROR_NOT_INITIALIZED);
150 // Create a new node through the element factory
151 nsCOMPtr<Element> newContent =
152 CreateHTMLContent(nsCOMPtr<nsIAtom>(do_GetAtom(aTag)));
153 NS_ENSURE_STATE(newContent);
155 nsCOMPtr<nsIDOMElement> newElement = do_QueryInterface(newContent);
156 NS_ENSURE_TRUE(newElement, NS_ERROR_FAILURE);
158 // add the "hidden" class if needed
159 nsresult res;
160 if (aIsCreatedHidden) {
161 res = newElement->SetAttribute(NS_LITERAL_STRING("class"),
162 NS_LITERAL_STRING("hidden"));
163 NS_ENSURE_SUCCESS(res, res);
166 // add an _moz_anonclass attribute if needed
167 if (!aAnonClass.IsEmpty()) {
168 res = newElement->SetAttribute(NS_LITERAL_STRING("_moz_anonclass"),
169 aAnonClass);
170 NS_ENSURE_SUCCESS(res, res);
174 nsAutoScriptBlocker scriptBlocker;
176 // establish parenthood of the element
177 newContent->SetIsNativeAnonymousRoot();
178 res = newContent->BindToTree(doc, parentContent, parentContent, true);
179 if (NS_FAILED(res)) {
180 newContent->UnbindFromTree();
181 return res;
185 nsElementDeletionObserver* observer =
186 new nsElementDeletionObserver(newContent, parentContent);
187 NS_ADDREF(observer); // NodeWillBeDestroyed releases.
188 parentContent->AddMutationObserver(observer);
189 newContent->AddMutationObserver(observer);
191 #ifdef DEBUG
192 // Editor anonymous content gets passed to RecreateFramesFor... which can't
193 // _really_ deal with anonymous content (because it can't get the frame tree
194 // ordering right). But for us the ordering doesn't matter so this is sort of
195 // ok.
196 newContent->SetProperty(nsGkAtoms::restylableAnonymousNode,
197 reinterpret_cast<void*>(true));
198 #endif // DEBUG
200 // display the element
201 ps->RecreateFramesFor(newContent);
203 newElement.forget(aReturn);
204 return NS_OK;
207 // Removes event listener and calls DeleteRefToAnonymousNode.
208 void
209 nsHTMLEditor::RemoveListenerAndDeleteRef(const nsAString& aEvent,
210 nsIDOMEventListener* aListener,
211 bool aUseCapture,
212 Element* aElement,
213 nsIContent * aParentContent,
214 nsIPresShell* aShell)
216 nsCOMPtr<nsIDOMEventTarget> evtTarget(do_QueryInterface(aElement));
217 if (evtTarget) {
218 evtTarget->RemoveEventListener(aEvent, aListener, aUseCapture);
220 DeleteRefToAnonymousNode(static_cast<nsIDOMElement*>(GetAsDOMNode(aElement)), aParentContent, aShell);
223 // Deletes all references to an anonymous element
224 void
225 nsHTMLEditor::DeleteRefToAnonymousNode(nsIDOMElement* aElement,
226 nsIContent* aParentContent,
227 nsIPresShell* aShell)
229 // call ContentRemoved() for the anonymous content
230 // node so its references get removed from the frame manager's
231 // undisplay map, and its layout frames get destroyed!
233 if (aElement) {
234 nsCOMPtr<nsIContent> content = do_QueryInterface(aElement);
235 if (content) {
236 nsAutoScriptBlocker scriptBlocker;
237 // Need to check whether aShell has been destroyed (but not yet deleted).
238 // In that case presContext->GetPresShell() returns nullptr.
239 // See bug 338129.
240 if (aShell && aShell->GetPresContext() &&
241 aShell->GetPresContext()->GetPresShell() == aShell) {
242 nsCOMPtr<nsIDocumentObserver> docObserver = do_QueryInterface(aShell);
243 if (docObserver) {
244 // Call BeginUpdate() so that the nsCSSFrameConstructor/PresShell
245 // knows we're messing with the frame tree.
246 nsCOMPtr<nsIDocument> document = GetDocument();
247 if (document)
248 docObserver->BeginUpdate(document, UPDATE_CONTENT_MODEL);
250 // XXX This is wrong (bug 439258). Once it's fixed, the NS_WARNING
251 // in RestyleManager::RestyleForRemove should be changed back
252 // to an assertion.
253 docObserver->ContentRemoved(content->GetCurrentDoc(),
254 aParentContent, content, -1,
255 content->GetPreviousSibling());
256 if (document)
257 docObserver->EndUpdate(document, UPDATE_CONTENT_MODEL);
260 content->UnbindFromTree();
265 // The following method is mostly called by a selection listener. When a
266 // selection change is notified, the method is called to check if resizing
267 // handles, a grabber and/or inline table editing UI need to be displayed
268 // or refreshed
269 NS_IMETHODIMP
270 nsHTMLEditor::CheckSelectionStateForAnonymousButtons(nsISelection * aSelection)
272 NS_ENSURE_ARG_POINTER(aSelection);
274 // early way out if all contextual UI extensions are disabled
275 NS_ENSURE_TRUE(mIsObjectResizingEnabled ||
276 mIsAbsolutelyPositioningEnabled ||
277 mIsInlineTableEditingEnabled, NS_OK);
279 // Don't change selection state if we're moving.
280 if (mIsMoving) {
281 return NS_OK;
284 nsCOMPtr<nsIDOMElement> focusElement;
285 // let's get the containing element of the selection
286 nsresult res = GetSelectionContainer(getter_AddRefs(focusElement));
287 NS_ENSURE_TRUE(focusElement, NS_OK);
288 NS_ENSURE_SUCCESS(res, res);
290 // If we're not in a document, don't try to add resizers
291 nsCOMPtr<dom::Element> focusElementNode = do_QueryInterface(focusElement);
292 NS_ENSURE_STATE(focusElementNode);
293 if (!focusElementNode->IsInDoc()) {
294 return NS_OK;
297 // what's its tag?
298 nsAutoString focusTagName;
299 res = focusElement->GetTagName(focusTagName);
300 NS_ENSURE_SUCCESS(res, res);
301 ToLowerCase(focusTagName);
302 nsCOMPtr<nsIAtom> focusTagAtom = do_GetAtom(focusTagName);
304 nsCOMPtr<nsIDOMElement> absPosElement;
305 if (mIsAbsolutelyPositioningEnabled) {
306 // Absolute Positioning support is enabled, is the selection contained
307 // in an absolutely positioned element ?
308 res = GetAbsolutelyPositionedSelectionContainer(getter_AddRefs(absPosElement));
309 NS_ENSURE_SUCCESS(res, res);
312 nsCOMPtr<nsIDOMElement> cellElement;
313 if (mIsObjectResizingEnabled || mIsInlineTableEditingEnabled) {
314 // Resizing or Inline Table Editing is enabled, we need to check if the
315 // selection is contained in a table cell
316 res = GetElementOrParentByTagName(NS_LITERAL_STRING("td"),
317 nullptr,
318 getter_AddRefs(cellElement));
319 NS_ENSURE_SUCCESS(res, res);
322 if (mIsObjectResizingEnabled && cellElement) {
323 // we are here because Resizing is enabled AND selection is contained in
324 // a cell
326 // get the enclosing table
327 if (nsGkAtoms::img != focusTagAtom) {
328 // the element container of the selection is not an image, so we'll show
329 // the resizers around the table
330 nsCOMPtr<nsIDOMNode> tableNode = GetEnclosingTable(cellElement);
331 focusElement = do_QueryInterface(tableNode);
332 focusTagAtom = nsGkAtoms::table;
336 // we allow resizers only around images, tables, and absolutely positioned
337 // elements. If we don't have image/table, let's look at the latter case.
338 if (nsGkAtoms::img != focusTagAtom && nsGkAtoms::table != focusTagAtom) {
339 focusElement = absPosElement;
342 // at this point, focusElement contains the element for Resizing,
343 // cellElement contains the element for InlineTableEditing
344 // absPosElement contains the element for Positioning
346 // Note: All the Hide/Show methods below may change attributes on real
347 // content which means a DOMAttrModified handler may cause arbitrary
348 // side effects while this code runs (bug 420439).
350 if (mIsAbsolutelyPositioningEnabled && mAbsolutelyPositionedObject &&
351 absPosElement != GetAsDOMNode(mAbsolutelyPositionedObject)) {
352 res = HideGrabber();
353 NS_ENSURE_SUCCESS(res, res);
354 NS_ASSERTION(!mAbsolutelyPositionedObject, "HideGrabber failed");
357 if (mIsObjectResizingEnabled && mResizedObject &&
358 GetAsDOMNode(mResizedObject) != focusElement) {
359 res = HideResizers();
360 NS_ENSURE_SUCCESS(res, res);
361 NS_ASSERTION(!mResizedObject, "HideResizers failed");
364 if (mIsInlineTableEditingEnabled && mInlineEditedCell &&
365 mInlineEditedCell != cellElement) {
366 res = HideInlineTableEditingUI();
367 NS_ENSURE_SUCCESS(res, res);
368 NS_ASSERTION(!mInlineEditedCell, "HideInlineTableEditingUI failed");
371 // now, let's display all contextual UI for good
372 nsIContent* hostContent = GetActiveEditingHost();
373 nsCOMPtr<nsIDOMNode> hostNode = do_QueryInterface(hostContent);
375 if (mIsObjectResizingEnabled && focusElement &&
376 IsModifiableNode(focusElement) && focusElement != hostNode) {
377 if (nsGkAtoms::img == focusTagAtom) {
378 mResizedObjectIsAnImage = true;
380 if (mResizedObject)
381 res = RefreshResizers();
382 else
383 res = ShowResizers(focusElement);
384 NS_ENSURE_SUCCESS(res, res);
387 if (mIsAbsolutelyPositioningEnabled && absPosElement &&
388 IsModifiableNode(absPosElement) && absPosElement != hostNode) {
389 if (mAbsolutelyPositionedObject)
390 res = RefreshGrabber();
391 else
392 res = ShowGrabberOnElement(absPosElement);
393 NS_ENSURE_SUCCESS(res, res);
396 if (mIsInlineTableEditingEnabled && cellElement &&
397 IsModifiableNode(cellElement) && cellElement != hostNode) {
398 if (mInlineEditedCell)
399 res = RefreshInlineTableEditingUI();
400 else
401 res = ShowInlineTableEditingUI(cellElement);
404 return res;
407 // Resizing and Absolute Positioning need to know everything about the
408 // containing box of the element: position, size, margins, borders
409 nsresult
410 nsHTMLEditor::GetPositionAndDimensions(nsIDOMElement * aElement,
411 int32_t & aX, int32_t & aY,
412 int32_t & aW, int32_t & aH,
413 int32_t & aBorderLeft,
414 int32_t & aBorderTop,
415 int32_t & aMarginLeft,
416 int32_t & aMarginTop)
418 nsCOMPtr<Element> element = do_QueryInterface(aElement);
419 NS_ENSURE_ARG_POINTER(element);
421 // Is the element positioned ? let's check the cheap way first...
422 bool isPositioned = false;
423 nsresult res = aElement->HasAttribute(NS_LITERAL_STRING("_moz_abspos"), &isPositioned);
424 NS_ENSURE_SUCCESS(res, res);
425 if (!isPositioned) {
426 // hmmm... the expensive way now...
427 nsAutoString positionStr;
428 mHTMLCSSUtils->GetComputedProperty(*element, *nsGkAtoms::position,
429 positionStr);
430 isPositioned = positionStr.EqualsLiteral("absolute");
433 if (isPositioned) {
434 // Yes, it is absolutely positioned
435 mResizedObjectIsAbsolutelyPositioned = true;
437 // Get the all the computed css styles attached to the element node
438 RefPtr<nsComputedDOMStyle> cssDecl =
439 mHTMLCSSUtils->GetComputedStyle(element);
440 NS_ENSURE_STATE(cssDecl);
442 aBorderLeft = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("border-left-width"));
443 aBorderTop = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("border-top-width"));
444 aMarginLeft = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("margin-left"));
445 aMarginTop = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("margin-top"));
447 aX = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("left")) +
448 aMarginLeft + aBorderLeft;
449 aY = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("top")) +
450 aMarginTop + aBorderTop;
451 aW = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("width"));
452 aH = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("height"));
454 else {
455 mResizedObjectIsAbsolutelyPositioned = false;
456 nsCOMPtr<nsIDOMHTMLElement> htmlElement = do_QueryInterface(aElement);
457 if (!htmlElement) {
458 return NS_ERROR_NULL_POINTER;
460 GetElementOrigin(aElement, aX, aY);
462 res = htmlElement->GetOffsetWidth(&aW);
463 NS_ENSURE_SUCCESS(res, res);
464 res = htmlElement->GetOffsetHeight(&aH);
466 aBorderLeft = 0;
467 aBorderTop = 0;
468 aMarginLeft = 0;
469 aMarginTop = 0;
471 return res;
474 // self-explanatory
475 void
476 nsHTMLEditor::SetAnonymousElementPosition(int32_t aX, int32_t aY, nsIDOMElement *aElement)
478 mHTMLCSSUtils->SetCSSPropertyPixels(aElement, NS_LITERAL_STRING("left"), aX);
479 mHTMLCSSUtils->SetCSSPropertyPixels(aElement, NS_LITERAL_STRING("top"), aY);