09e36dcae7586f279c222530862e7412a1968138
[platform/framework/web/crosswalk.git] / src / ui / views / widget / desktop_aura / x11_whole_screen_move_loop.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ui/views/widget/desktop_aura/x11_whole_screen_move_loop.h"
6
7 #include <X11/Xlib.h>
8 // Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class.
9 #undef RootWindow
10
11 #include "base/bind.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/message_loop/message_pump_x11.h"
14 #include "base/run_loop.h"
15 #include "third_party/skia/include/core/SkBitmap.h"
16 #include "ui/aura/env.h"
17 #include "ui/aura/window.h"
18 #include "ui/aura/window_event_dispatcher.h"
19 #include "ui/aura/window_tree_host.h"
20 #include "ui/base/x/x11_util.h"
21 #include "ui/events/event.h"
22 #include "ui/events/keycodes/keyboard_code_conversion_x.h"
23 #include "ui/gfx/point_conversions.h"
24 #include "ui/gfx/screen.h"
25 #include "ui/views/controls/image_view.h"
26 #include "ui/views/widget/widget.h"
27
28 namespace views {
29
30 namespace {
31
32 // The minimum alpha before we declare a pixel transparent when searching in
33 // our source image.
34 const uint32 kMinAlpha = 32;
35 const unsigned char kDragWidgetOpacity = 0xc0;
36
37 class ScopedCapturer {
38  public:
39   explicit ScopedCapturer(aura::WindowTreeHost* host)
40       : host_(host) {
41     host_->SetCapture();
42   }
43
44   ~ScopedCapturer() {
45     host_->ReleaseCapture();
46   }
47
48  private:
49   aura::WindowTreeHost* host_;
50
51   DISALLOW_COPY_AND_ASSIGN(ScopedCapturer);
52 };
53
54 }  // namespace
55
56 X11WholeScreenMoveLoop::X11WholeScreenMoveLoop(
57     X11WholeScreenMoveLoopDelegate* delegate)
58     : delegate_(delegate),
59       in_move_loop_(false),
60       should_reset_mouse_flags_(false),
61       grab_input_window_(None),
62       weak_factory_(this) {
63   last_xmotion_.type = LASTEvent;
64 }
65
66 X11WholeScreenMoveLoop::~X11WholeScreenMoveLoop() {}
67
68 ////////////////////////////////////////////////////////////////////////////////
69 // DesktopWindowTreeHostLinux, MessagePumpDispatcher implementation:
70
71 void X11WholeScreenMoveLoop::DispatchMouseMovement() {
72   if (!weak_factory_.HasWeakPtrs())
73     return;
74   weak_factory_.InvalidateWeakPtrs();
75   DCHECK_EQ(MotionNotify, last_xmotion_.type);
76   delegate_->OnMouseMovement(&last_xmotion_);
77   last_xmotion_.type = LASTEvent;
78 }
79
80 uint32_t X11WholeScreenMoveLoop::Dispatch(const base::NativeEvent& event) {
81   XEvent* xev = event;
82
83   // Note: the escape key is handled in the tab drag controller, which has
84   // keyboard focus even though we took pointer grab.
85   switch (xev->type) {
86     case MotionNotify: {
87       if (drag_widget_.get()) {
88         gfx::Screen* screen = gfx::Screen::GetNativeScreen();
89         gfx::Point location = gfx::ToFlooredPoint(
90             screen->GetCursorScreenPoint() - drag_offset_);
91         drag_widget_->SetBounds(gfx::Rect(location, drag_image_.size()));
92         drag_widget_->StackAtTop();
93       }
94       last_xmotion_ = xev->xmotion;
95       if (!weak_factory_.HasWeakPtrs()) {
96         // Post a task to dispatch mouse movement event when control returns to
97         // the message loop. This allows smoother dragging since the events are
98         // dispatched without waiting for the drag widget updates.
99         base::MessageLoopForUI::current()->PostTask(
100             FROM_HERE,
101             base::Bind(&X11WholeScreenMoveLoop::DispatchMouseMovement,
102                        weak_factory_.GetWeakPtr()));
103       }
104       break;
105     }
106     case ButtonRelease: {
107       if (xev->xbutton.button == Button1) {
108         // Assume that drags are being done with the left mouse button. Only
109         // break the drag if the left mouse button was released.
110         DispatchMouseMovement();
111         delegate_->OnMouseReleased();
112       }
113       break;
114     }
115     case KeyPress: {
116       if (ui::KeyboardCodeFromXKeyEvent(xev) == ui::VKEY_ESCAPE)
117         EndMoveLoop();
118       break;
119     }
120   }
121
122   return POST_DISPATCH_NONE;
123 }
124
125 ////////////////////////////////////////////////////////////////////////////////
126 // DesktopWindowTreeHostLinux, aura::client::WindowMoveClient implementation:
127
128 bool X11WholeScreenMoveLoop::RunMoveLoop(aura::Window* source,
129                                          gfx::NativeCursor cursor) {
130   // Start a capture on the host, so that it continues to receive events during
131   // the drag. This may be second time we are capturing the mouse events - the
132   // first being when a mouse is first pressed. That first capture needs to be
133   // released before the call to GrabPointerAndKeyboard below, otherwise it may
134   // get released while we still need the pointer grab, which is why we restrict
135   // the scope here.
136   {
137     ScopedCapturer capturer(source->GetHost());
138
139     DCHECK(!in_move_loop_);  // Can only handle one nested loop at a time.
140     in_move_loop_ = true;
141
142     XDisplay* display = gfx::GetXDisplay();
143
144     grab_input_window_ = CreateDragInputWindow(display);
145     if (!drag_image_.isNull() && CheckIfIconValid())
146       CreateDragImageWindow();
147     base::MessagePumpX11::Current()->AddDispatcherForWindow(
148         this, grab_input_window_);
149     // Releasing ScopedCapturer ensures that any other instance of
150     // X11ScopedCapture will not prematurely release grab that will be acquired
151     // below.
152   }
153   // TODO(varkha): Consider integrating GrabPointerAndKeyboard with
154   // ScopedCapturer to avoid possibility of logically keeping multiple grabs.
155   if (!GrabPointerAndKeyboard(cursor))
156     return false;
157
158   // We are handling a mouse drag outside of the aura::RootWindow system. We
159   // must manually make aura think that the mouse button is pressed so that we
160   // don't draw extraneous tooltips.
161   aura::Env* env = aura::Env::GetInstance();
162   if (!env->IsMouseButtonDown()) {
163     env->set_mouse_button_flags(ui::EF_LEFT_MOUSE_BUTTON);
164     should_reset_mouse_flags_ = true;
165   }
166
167   base::MessageLoopForUI* loop = base::MessageLoopForUI::current();
168   base::MessageLoop::ScopedNestableTaskAllower allow_nested(loop);
169   base::RunLoop run_loop;
170   quit_closure_ = run_loop.QuitClosure();
171   run_loop.Run();
172   return true;
173 }
174
175 void X11WholeScreenMoveLoop::UpdateCursor(gfx::NativeCursor cursor) {
176   if (in_move_loop_) {
177     // If we're still in the move loop, regrab the pointer with the updated
178     // cursor. Note: we can be called from handling an XdndStatus message after
179     // EndMoveLoop() was called, but before we return from the nested RunLoop.
180     GrabPointerAndKeyboard(cursor);
181   }
182 }
183
184 void X11WholeScreenMoveLoop::EndMoveLoop() {
185   if (!in_move_loop_)
186     return;
187
188   // Prevent DispatchMouseMovement from dispatching any posted motion event.
189   weak_factory_.InvalidateWeakPtrs();
190   last_xmotion_.type = LASTEvent;
191
192   // We undo our emulated mouse click from RunMoveLoop();
193   if (should_reset_mouse_flags_) {
194     aura::Env::GetInstance()->set_mouse_button_flags(0);
195     should_reset_mouse_flags_ = false;
196   }
197
198   // TODO(erg): Is this ungrab the cause of having to click to give input focus
199   // on drawn out windows? Not ungrabbing here screws the X server until I kill
200   // the chrome process.
201
202   // Ungrab before we let go of the window.
203   XDisplay* display = gfx::GetXDisplay();
204   XUngrabPointer(display, CurrentTime);
205   XUngrabKeyboard(display, CurrentTime);
206
207   base::MessagePumpX11::Current()->RemoveDispatcherForWindow(
208       grab_input_window_);
209   drag_widget_.reset();
210   delegate_->OnMoveLoopEnded();
211   XDestroyWindow(display, grab_input_window_);
212
213   in_move_loop_ = false;
214   quit_closure_.Run();
215 }
216
217 void X11WholeScreenMoveLoop::SetDragImage(const gfx::ImageSkia& image,
218                                           gfx::Vector2dF offset) {
219   drag_image_ = image;
220   drag_offset_ = offset;
221   // Reset the Y offset, so that the drag-image is always just below the cursor,
222   // so that it is possible to see where the cursor is going.
223   drag_offset_.set_y(0.f);
224 }
225
226 bool X11WholeScreenMoveLoop::GrabPointerAndKeyboard(gfx::NativeCursor cursor) {
227   XDisplay* display = gfx::GetXDisplay();
228   XGrabServer(display);
229
230   XUngrabPointer(display, CurrentTime);
231   int ret = XGrabPointer(
232       display,
233       grab_input_window_,
234       False,
235       ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
236       GrabModeAsync,
237       GrabModeAsync,
238       None,
239       cursor.platform(),
240       CurrentTime);
241   if (ret != GrabSuccess) {
242     DLOG(ERROR) << "Grabbing pointer for dragging failed: "
243                 << ui::GetX11ErrorString(display, ret);
244   } else {
245     XUngrabKeyboard(display, CurrentTime);
246     ret = XGrabKeyboard(
247         display,
248         grab_input_window_,
249         False,
250         GrabModeAsync,
251         GrabModeAsync,
252         CurrentTime);
253     if (ret != GrabSuccess) {
254       DLOG(ERROR) << "Grabbing keyboard for dragging failed: "
255                   << ui::GetX11ErrorString(display, ret);
256     }
257   }
258
259   XUngrabServer(display);
260   return ret == GrabSuccess;
261 }
262
263 Window X11WholeScreenMoveLoop::CreateDragInputWindow(XDisplay* display) {
264   // Creates an invisible, InputOnly toplevel window. This window will receive
265   // all mouse movement for drags. It turns out that normal windows doing a
266   // grab doesn't redirect pointer motion events if the pointer isn't over the
267   // grabbing window. But InputOnly windows are able to grab everything. This
268   // is what GTK+ does, and I found a patch to KDE that did something similar.
269   unsigned long attribute_mask = CWEventMask | CWOverrideRedirect;
270   XSetWindowAttributes swa;
271   memset(&swa, 0, sizeof(swa));
272   swa.event_mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
273                    KeyPressMask | KeyReleaseMask | StructureNotifyMask;
274   swa.override_redirect = True;
275   Window window = XCreateWindow(display,
276                                 DefaultRootWindow(display),
277                                 -100, -100, 10, 10,
278                                 0, CopyFromParent, InputOnly, CopyFromParent,
279                                 attribute_mask, &swa);
280   XMapRaised(display, window);
281   base::MessagePumpX11::Current()->BlockUntilWindowMapped(window);
282   return window;
283 }
284
285 void X11WholeScreenMoveLoop::CreateDragImageWindow() {
286   Widget* widget = new Widget;
287   Widget::InitParams params(Widget::InitParams::TYPE_DRAG);
288   params.opacity = Widget::InitParams::OPAQUE_WINDOW;
289   params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
290   params.accept_events = false;
291
292   gfx::Point location = gfx::ToFlooredPoint(
293       gfx::Screen::GetNativeScreen()->GetCursorScreenPoint() - drag_offset_);
294   params.bounds = gfx::Rect(location, drag_image_.size());
295   widget->set_focus_on_creation(false);
296   widget->set_frame_type(Widget::FRAME_TYPE_FORCE_NATIVE);
297   widget->Init(params);
298   widget->SetOpacity(kDragWidgetOpacity);
299   widget->GetNativeWindow()->SetName("DragWindow");
300
301   ImageView* image = new ImageView();
302   image->SetImage(drag_image_);
303   image->SetBounds(0, 0, drag_image_.width(), drag_image_.height());
304   widget->SetContentsView(image);
305   widget->Show();
306   widget->GetNativeWindow()->layer()->SetFillsBoundsOpaquely(false);
307
308   drag_widget_.reset(widget);
309 }
310
311 bool X11WholeScreenMoveLoop::CheckIfIconValid() {
312   // TODO(erg): I've tried at least five different strategies for trying to
313   // build a mask based off the alpha channel. While all of them have worked,
314   // none of them have been performant and introduced multiple second
315   // delays. (I spent a day getting a rectangle segmentation algorithm polished
316   // here...and then found that even through I had the rectangle extraction
317   // down to mere milliseconds, SkRegion still fell over on the number of
318   // rectangles.)
319   //
320   // Creating a mask here near instantaneously should be possible, as GTK does
321   // it, but I've blown days on this and I'm punting now.
322
323   const SkBitmap* in_bitmap = drag_image_.bitmap();
324   SkAutoLockPixels in_lock(*in_bitmap);
325   for (int y = 0; y < in_bitmap->height(); ++y) {
326     uint32* in_row = in_bitmap->getAddr32(0, y);
327
328     for (int x = 0; x < in_bitmap->width(); ++x) {
329       if (SkColorGetA(in_row[x]) > kMinAlpha)
330         return true;
331     }
332   }
333
334   return false;
335 }
336
337 }  // namespace views