1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 
6 #include "nsAutoPtr.h"
7 #include "nsCOMPtr.h"
8 #include "nsIServiceManager.h"
9 #include "nsResizerFrame.h"
10 #include "nsIContent.h"
11 #include "nsIDocument.h"
12 #include "nsIDOMNodeList.h"
13 #include "nsGkAtoms.h"
14 #include "nsNameSpaceManager.h"
15 #include "nsIDOMCSSStyleDeclaration.h"
16 
17 #include "nsPresContext.h"
18 #include "nsFrameManager.h"
19 #include "nsIDocShell.h"
20 #include "nsIDocShellTreeOwner.h"
21 #include "nsIBaseWindow.h"
22 #include "nsPIDOMWindow.h"
23 #include "mozilla/MouseEvents.h"
24 #include "nsContentUtils.h"
25 #include "nsMenuPopupFrame.h"
26 #include "nsIScreenManager.h"
27 #include "mozilla/dom/Element.h"
28 #include "nsError.h"
29 #include "nsICSSDeclaration.h"
30 #include "nsStyledElement.h"
31 #include <algorithm>
32 
33 using namespace mozilla;
34 
35 //
36 // NS_NewResizerFrame
37 //
38 // Creates a new Resizer frame and returns it
39 //
40 nsIFrame*
NS_NewResizerFrame(nsIPresShell * aPresShell,nsStyleContext * aContext)41 NS_NewResizerFrame(nsIPresShell* aPresShell, nsStyleContext* aContext)
42 {
43   return new (aPresShell) nsResizerFrame(aContext);
44 }
45 
NS_IMPL_FRAMEARENA_HELPERS(nsResizerFrame)46 NS_IMPL_FRAMEARENA_HELPERS(nsResizerFrame)
47 
48 nsResizerFrame::nsResizerFrame(nsStyleContext* aContext)
49 :nsTitleBarFrame(aContext)
50 {
51 }
52 
53 nsresult
HandleEvent(nsPresContext * aPresContext,WidgetGUIEvent * aEvent,nsEventStatus * aEventStatus)54 nsResizerFrame::HandleEvent(nsPresContext* aPresContext,
55                             WidgetGUIEvent* aEvent,
56                             nsEventStatus* aEventStatus)
57 {
58   NS_ENSURE_ARG_POINTER(aEventStatus);
59   if (nsEventStatus_eConsumeNoDefault == *aEventStatus) {
60     return NS_OK;
61   }
62 
63   nsWeakFrame weakFrame(this);
64   bool doDefault = true;
65 
66   switch (aEvent->mMessage) {
67     case eTouchStart:
68     case eMouseDown: {
69       if (aEvent->mClass == eTouchEventClass ||
70           (aEvent->mClass == eMouseEventClass &&
71            aEvent->AsMouseEvent()->button == WidgetMouseEvent::eLeftButton)) {
72         nsCOMPtr<nsIBaseWindow> window;
73         nsIPresShell* presShell = aPresContext->GetPresShell();
74         nsIContent* contentToResize =
75           GetContentToResize(presShell, getter_AddRefs(window));
76         if (contentToResize) {
77           nsIFrame* frameToResize = contentToResize->GetPrimaryFrame();
78           if (!frameToResize)
79             break;
80 
81           // cache the content rectangle for the frame to resize
82           // GetScreenRectInAppUnits returns the border box rectangle, so
83           // adjust to get the desired content rectangle.
84           nsRect rect = frameToResize->GetScreenRectInAppUnits();
85           if (frameToResize->StylePosition()->mBoxSizing == StyleBoxSizing::Content) {
86             rect.Deflate(frameToResize->GetUsedBorderAndPadding());
87           }
88 
89           mMouseDownRect =
90             LayoutDeviceIntRect::FromAppUnitsToNearest(rect, aPresContext->AppUnitsPerDevPixel());
91           doDefault = false;
92         }
93         else {
94           // If there is no window, then resizing isn't allowed.
95           if (!window)
96             break;
97 
98           doDefault = false;
99 
100           // ask the widget implementation to begin a resize drag if it can
101           Direction direction = GetDirection();
102           nsresult rv = aEvent->mWidget->BeginResizeDrag(aEvent,
103                         direction.mHorizontal, direction.mVertical);
104           // for native drags, don't set the fields below
105           if (rv != NS_ERROR_NOT_IMPLEMENTED)
106              break;
107 
108           // if there's no native resize support, we need to do window
109           // resizing ourselves
110           window->GetPositionAndSize(&mMouseDownRect.x, &mMouseDownRect.y,
111                                      &mMouseDownRect.width, &mMouseDownRect.height);
112         }
113 
114         // remember current mouse coordinates
115         LayoutDeviceIntPoint refPoint;
116         if (!GetEventPoint(aEvent, refPoint))
117           return NS_OK;
118         mMouseDownPoint = refPoint + aEvent->mWidget->WidgetToScreenOffset();
119 
120         // we're tracking
121         mTrackingMouseMove = true;
122 
123         nsIPresShell::SetCapturingContent(GetContent(), CAPTURE_IGNOREALLOWED);
124       }
125     }
126     break;
127 
128   case eTouchEnd:
129   case eMouseUp: {
130     if (aEvent->mClass == eTouchEventClass ||
131         (aEvent->mClass == eMouseEventClass &&
132          aEvent->AsMouseEvent()->button == WidgetMouseEvent::eLeftButton)) {
133       // we're done tracking.
134       mTrackingMouseMove = false;
135 
136       nsIPresShell::SetCapturingContent(nullptr, 0);
137 
138       doDefault = false;
139     }
140   }
141   break;
142 
143   case eTouchMove:
144   case eMouseMove: {
145     if (mTrackingMouseMove)
146     {
147       nsCOMPtr<nsIBaseWindow> window;
148       nsIPresShell* presShell = aPresContext->GetPresShell();
149       nsCOMPtr<nsIContent> contentToResize =
150         GetContentToResize(presShell, getter_AddRefs(window));
151 
152       // check if the returned content really is a menupopup
153       nsMenuPopupFrame* menuPopupFrame = nullptr;
154       if (contentToResize) {
155         menuPopupFrame = do_QueryFrame(contentToResize->GetPrimaryFrame());
156       }
157 
158       // both MouseMove and direction are negative when pointing to the
159       // top and left, and positive when pointing to the bottom and right
160 
161       // retrieve the offset of the mousemove event relative to the mousedown.
162       // The difference is how much the resize needs to be
163       LayoutDeviceIntPoint refPoint;
164       if (!GetEventPoint(aEvent, refPoint))
165         return NS_OK;
166       LayoutDeviceIntPoint screenPoint =
167         refPoint + aEvent->mWidget->WidgetToScreenOffset();
168       LayoutDeviceIntPoint mouseMove(screenPoint - mMouseDownPoint);
169 
170       // Determine which direction to resize by checking the dir attribute.
171       // For windows and menus, ensure that it can be resized in that direction.
172       Direction direction = GetDirection();
173       if (window || menuPopupFrame) {
174         if (menuPopupFrame) {
175           menuPopupFrame->CanAdjustEdges(
176             (direction.mHorizontal == -1) ? NS_SIDE_LEFT : NS_SIDE_RIGHT,
177             (direction.mVertical == -1) ? NS_SIDE_TOP : NS_SIDE_BOTTOM, mouseMove);
178         }
179       }
180       else if (!contentToResize) {
181         break; // don't do anything if there's nothing to resize
182       }
183 
184       LayoutDeviceIntRect rect = mMouseDownRect;
185 
186       // Check if there are any size constraints on this window.
187       widget::SizeConstraints sizeConstraints;
188       if (window) {
189         nsCOMPtr<nsIWidget> widget;
190         window->GetMainWidget(getter_AddRefs(widget));
191         sizeConstraints = widget->GetSizeConstraints();
192       }
193 
194       AdjustDimensions(&rect.x, &rect.width, sizeConstraints.mMinSize.width,
195                        sizeConstraints.mMaxSize.width, mouseMove.x, direction.mHorizontal);
196       AdjustDimensions(&rect.y, &rect.height, sizeConstraints.mMinSize.height,
197                        sizeConstraints.mMaxSize.height, mouseMove.y, direction.mVertical);
198 
199       // Don't allow resizing a window or a popup past the edge of the screen,
200       // so adjust the rectangle to fit within the available screen area.
201       if (window) {
202         nsCOMPtr<nsIScreen> screen;
203         nsCOMPtr<nsIScreenManager> sm(do_GetService("@mozilla.org/gfx/screenmanager;1"));
204         if (sm) {
205           nsIntRect frameRect = GetScreenRect();
206           // ScreenForRect requires display pixels, so scale from device pix
207           double scale;
208           window->GetUnscaledDevicePixelsPerCSSPixel(&scale);
209           sm->ScreenForRect(NSToIntRound(frameRect.x / scale),
210                             NSToIntRound(frameRect.y / scale), 1, 1,
211                             getter_AddRefs(screen));
212           if (screen) {
213             LayoutDeviceIntRect screenRect;
214             screen->GetRect(&screenRect.x, &screenRect.y,
215                             &screenRect.width, &screenRect.height);
216             rect.IntersectRect(rect, screenRect);
217           }
218         }
219       }
220       else if (menuPopupFrame) {
221         nsRect frameRect = menuPopupFrame->GetScreenRectInAppUnits();
222         nsIFrame* rootFrame = aPresContext->PresShell()->FrameManager()->GetRootFrame();
223         nsRect rootScreenRect = rootFrame->GetScreenRectInAppUnits();
224 
225         nsPopupLevel popupLevel = menuPopupFrame->PopupLevel();
226         int32_t appPerDev = aPresContext->AppUnitsPerDevPixel();
227         LayoutDeviceIntRect screenRect = menuPopupFrame->GetConstraintRect
228           (LayoutDeviceIntRect::FromAppUnitsToNearest(frameRect, appPerDev),
229            // round using ...ToInside as it's better to be a pixel too small
230            // than be too large. If the popup is too large it could get flipped
231            // to the opposite side of the anchor point while resizing.
232            LayoutDeviceIntRect::FromAppUnitsToInside(rootScreenRect, appPerDev),
233            popupLevel);
234         rect.IntersectRect(rect, screenRect);
235       }
236 
237       if (contentToResize) {
238         // convert the rectangle into css pixels. When changing the size in a
239         // direction, don't allow the new size to be less that the resizer's
240         // size. This ensures that content isn't resized too small as to make
241         // the resizer invisible.
242         nsRect appUnitsRect = ToAppUnits(rect.ToUnknownRect(), aPresContext->AppUnitsPerDevPixel());
243         if (appUnitsRect.width < mRect.width && mouseMove.x)
244           appUnitsRect.width = mRect.width;
245         if (appUnitsRect.height < mRect.height && mouseMove.y)
246           appUnitsRect.height = mRect.height;
247         nsIntRect cssRect = appUnitsRect.ToInsidePixels(nsPresContext::AppUnitsPerCSSPixel());
248 
249         LayoutDeviceIntRect oldRect;
250         nsWeakFrame weakFrame(menuPopupFrame);
251         if (menuPopupFrame) {
252           nsCOMPtr<nsIWidget> widget = menuPopupFrame->GetWidget();
253           if (widget)
254             oldRect = widget->GetScreenBounds();
255 
256           // convert the new rectangle into outer window coordinates
257           LayoutDeviceIntPoint clientOffset = widget->GetClientOffset();
258           rect.x -= clientOffset.x;
259           rect.y -= clientOffset.y;
260         }
261 
262         SizeInfo sizeInfo, originalSizeInfo;
263         sizeInfo.width.AppendInt(cssRect.width);
264         sizeInfo.height.AppendInt(cssRect.height);
265         ResizeContent(contentToResize, direction, sizeInfo, &originalSizeInfo);
266         MaybePersistOriginalSize(contentToResize, originalSizeInfo);
267 
268         // Move the popup to the new location unless it is anchored, since
269         // the position shouldn't change. nsMenuPopupFrame::SetPopupPosition
270         // will instead ensure that the popup's position is anchored at the
271         // right place.
272         if (weakFrame.IsAlive() &&
273             (oldRect.x != rect.x || oldRect.y != rect.y) &&
274             (!menuPopupFrame->IsAnchored() ||
275              menuPopupFrame->PopupLevel() != ePopupLevelParent)) {
276 
277           CSSPoint cssPos = rect.TopLeft() / aPresContext->CSSToDevPixelScale();
278           menuPopupFrame->MoveTo(RoundedToInt(cssPos), true);
279         }
280       }
281       else {
282         window->SetPositionAndSize(rect.x, rect.y, rect.width, rect.height,
283                                    nsIBaseWindow::eRepaint); // do the repaint.
284       }
285 
286       doDefault = false;
287     }
288   }
289   break;
290 
291   case eMouseClick: {
292     WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
293     if (mouseEvent->IsLeftClickEvent()) {
294       MouseClicked(mouseEvent);
295     }
296     break;
297   }
298   case eMouseDoubleClick:
299     if (aEvent->AsMouseEvent()->button == WidgetMouseEvent::eLeftButton) {
300       nsCOMPtr<nsIBaseWindow> window;
301       nsIPresShell* presShell = aPresContext->GetPresShell();
302       nsIContent* contentToResize =
303         GetContentToResize(presShell, getter_AddRefs(window));
304       if (contentToResize) {
305         nsMenuPopupFrame* menuPopupFrame = do_QueryFrame(contentToResize->GetPrimaryFrame());
306         if (menuPopupFrame)
307           break; // Don't restore original sizing for menupopup frames until
308                  // we handle screen constraints here. (Bug 357725)
309 
310         RestoreOriginalSize(contentToResize);
311       }
312     }
313     break;
314 
315   default:
316     break;
317   }
318 
319   if (!doDefault)
320     *aEventStatus = nsEventStatus_eConsumeNoDefault;
321 
322   if (doDefault && weakFrame.IsAlive())
323     return nsTitleBarFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
324 
325   return NS_OK;
326 }
327 
328 nsIContent*
GetContentToResize(nsIPresShell * aPresShell,nsIBaseWindow ** aWindow)329 nsResizerFrame::GetContentToResize(nsIPresShell* aPresShell, nsIBaseWindow** aWindow)
330 {
331   *aWindow = nullptr;
332 
333   nsAutoString elementid;
334   mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::element, elementid);
335   if (elementid.IsEmpty()) {
336     // If the resizer is in a popup, resize the popup's widget, otherwise
337     // resize the widget associated with the window.
338     nsIFrame* popup = GetParent();
339     while (popup) {
340       nsMenuPopupFrame* popupFrame = do_QueryFrame(popup);
341       if (popupFrame) {
342         return popupFrame->GetContent();
343       }
344       popup = popup->GetParent();
345     }
346 
347     // don't allow resizing windows in content shells
348     nsCOMPtr<nsIDocShellTreeItem> dsti = aPresShell->GetPresContext()->GetDocShell();
349     if (!dsti || dsti->ItemType() != nsIDocShellTreeItem::typeChrome) {
350       // don't allow resizers in content shells, except for the viewport
351       // scrollbar which doesn't have a parent
352       nsIContent* nonNativeAnon = mContent->FindFirstNonChromeOnlyAccessContent();
353       if (!nonNativeAnon || nonNativeAnon->GetParent()) {
354         return nullptr;
355       }
356     }
357 
358     // get the document and the window - should this be cached?
359     if (nsPIDOMWindowOuter* domWindow = aPresShell->GetDocument()->GetWindow()) {
360       nsCOMPtr<nsIDocShell> docShell = domWindow->GetDocShell();
361       if (docShell) {
362         nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
363         docShell->GetTreeOwner(getter_AddRefs(treeOwner));
364         if (treeOwner) {
365           CallQueryInterface(treeOwner, aWindow);
366         }
367       }
368     }
369 
370     return nullptr;
371   }
372 
373   if (elementid.EqualsLiteral("_parent")) {
374     // return the parent, but skip over native anonymous content
375     nsIContent* parent = mContent->GetParent();
376     return parent ? parent->FindFirstNonChromeOnlyAccessContent() : nullptr;
377   }
378 
379   return aPresShell->GetDocument()->GetElementById(elementid);
380 }
381 
382 void
AdjustDimensions(int32_t * aPos,int32_t * aSize,int32_t aMinSize,int32_t aMaxSize,int32_t aMovement,int8_t aResizerDirection)383 nsResizerFrame::AdjustDimensions(int32_t* aPos, int32_t* aSize,
384                                  int32_t aMinSize, int32_t aMaxSize,
385                                  int32_t aMovement, int8_t aResizerDirection)
386 {
387   int32_t oldSize = *aSize;
388 
389   *aSize += aResizerDirection * aMovement;
390   // use one as a minimum size or the element could disappear
391   if (*aSize < 1)
392     *aSize = 1;
393 
394   // Constrain the size within the minimum and maximum size.
395   *aSize = std::max(aMinSize, std::min(aMaxSize, *aSize));
396 
397   // For left and top resizers, the window must be moved left by the same
398   // amount that the window was resized.
399   if (aResizerDirection == -1)
400     *aPos += oldSize - *aSize;
401 }
402 
403 /* static */ void
ResizeContent(nsIContent * aContent,const Direction & aDirection,const SizeInfo & aSizeInfo,SizeInfo * aOriginalSizeInfo)404 nsResizerFrame::ResizeContent(nsIContent* aContent, const Direction& aDirection,
405                               const SizeInfo& aSizeInfo, SizeInfo* aOriginalSizeInfo)
406 {
407   // for XUL elements, just set the width and height attributes. For
408   // other elements, set style.width and style.height
409   if (aContent->IsXULElement()) {
410     if (aOriginalSizeInfo) {
411       aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::width,
412                         aOriginalSizeInfo->width);
413       aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::height,
414                         aOriginalSizeInfo->height);
415     }
416     // only set the property if the element could have changed in that direction
417     if (aDirection.mHorizontal) {
418       aContent->SetAttr(kNameSpaceID_None, nsGkAtoms::width, aSizeInfo.width, true);
419     }
420     if (aDirection.mVertical) {
421       aContent->SetAttr(kNameSpaceID_None, nsGkAtoms::height, aSizeInfo.height, true);
422     }
423   }
424   else {
425     nsCOMPtr<nsStyledElement> inlineStyleContent =
426       do_QueryInterface(aContent);
427     if (inlineStyleContent) {
428       nsICSSDeclaration* decl = inlineStyleContent->Style();
429 
430       if (aOriginalSizeInfo) {
431         decl->GetPropertyValue(NS_LITERAL_STRING("width"),
432                                aOriginalSizeInfo->width);
433         decl->GetPropertyValue(NS_LITERAL_STRING("height"),
434                                aOriginalSizeInfo->height);
435       }
436 
437       // only set the property if the element could have changed in that direction
438       if (aDirection.mHorizontal) {
439         nsAutoString widthstr(aSizeInfo.width);
440         if (!widthstr.IsEmpty() &&
441             !Substring(widthstr, widthstr.Length() - 2, 2).EqualsLiteral("px"))
442           widthstr.AppendLiteral("px");
443         decl->SetProperty(NS_LITERAL_STRING("width"), widthstr, EmptyString());
444       }
445       if (aDirection.mVertical) {
446         nsAutoString heightstr(aSizeInfo.height);
447         if (!heightstr.IsEmpty() &&
448             !Substring(heightstr, heightstr.Length() - 2, 2).EqualsLiteral("px"))
449           heightstr.AppendLiteral("px");
450         decl->SetProperty(NS_LITERAL_STRING("height"), heightstr, EmptyString());
451       }
452     }
453   }
454 }
455 
456 /* static */ void
MaybePersistOriginalSize(nsIContent * aContent,const SizeInfo & aSizeInfo)457 nsResizerFrame::MaybePersistOriginalSize(nsIContent* aContent,
458                                          const SizeInfo& aSizeInfo)
459 {
460   nsresult rv;
461 
462   aContent->GetProperty(nsGkAtoms::_moz_original_size, &rv);
463   if (rv != NS_PROPTABLE_PROP_NOT_THERE)
464     return;
465 
466   nsAutoPtr<SizeInfo> sizeInfo(new SizeInfo(aSizeInfo));
467   rv = aContent->SetProperty(nsGkAtoms::_moz_original_size, sizeInfo.get(),
468                              nsINode::DeleteProperty<nsResizerFrame::SizeInfo>);
469   if (NS_SUCCEEDED(rv))
470     sizeInfo.forget();
471 }
472 
473 /* static */ void
RestoreOriginalSize(nsIContent * aContent)474 nsResizerFrame::RestoreOriginalSize(nsIContent* aContent)
475 {
476   nsresult rv;
477   SizeInfo* sizeInfo =
478     static_cast<SizeInfo*>(aContent->GetProperty(nsGkAtoms::_moz_original_size,
479                            &rv));
480   if (NS_FAILED(rv))
481     return;
482 
483   NS_ASSERTION(sizeInfo, "We set a null sizeInfo!?");
484   Direction direction = {1, 1};
485   ResizeContent(aContent, direction, *sizeInfo, nullptr);
486   aContent->DeleteProperty(nsGkAtoms::_moz_original_size);
487 }
488 
489 /* returns a Direction struct containing the horizontal and vertical direction
490  */
491 nsResizerFrame::Direction
GetDirection()492 nsResizerFrame::GetDirection()
493 {
494   static const nsIContent::AttrValuesArray strings[] =
495     {&nsGkAtoms::topleft,    &nsGkAtoms::top,    &nsGkAtoms::topright,
496      &nsGkAtoms::left,                           &nsGkAtoms::right,
497      &nsGkAtoms::bottomleft, &nsGkAtoms::bottom, &nsGkAtoms::bottomright,
498      &nsGkAtoms::bottomstart,                    &nsGkAtoms::bottomend,
499      nullptr};
500 
501   static const Direction directions[] =
502     {{-1, -1}, {0, -1}, {1, -1},
503      {-1,  0},          {1,  0},
504      {-1,  1}, {0,  1}, {1,  1},
505      {-1,  1},          {1,  1}
506     };
507 
508   if (!GetContent()) {
509     return directions[0]; // default: topleft
510   }
511 
512   int32_t index = GetContent()->FindAttrValueIn(kNameSpaceID_None,
513                                                 nsGkAtoms::dir,
514                                                 strings, eCaseMatters);
515   if (index < 0) {
516     return directions[0]; // default: topleft
517   }
518 
519   if (index >= 8) {
520     // Directions 8 and higher are RTL-aware directions and should reverse the
521     // horizontal component if RTL.
522     WritingMode wm = GetWritingMode();
523     if (!(wm.IsVertical() ? wm.IsVerticalLR() : wm.IsBidiLTR())) {
524       Direction direction = directions[index];
525       direction.mHorizontal *= -1;
526       return direction;
527     }
528   }
529 
530   return directions[index];
531 }
532 
533 void
MouseClicked(WidgetMouseEvent * aEvent)534 nsResizerFrame::MouseClicked(WidgetMouseEvent* aEvent)
535 {
536   // Execute the oncommand event handler.
537   nsContentUtils::DispatchXULCommand(mContent, aEvent && aEvent->IsTrusted());
538 }
539