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.
5 #include "ui/views/widget/desktop_aura/x11_whole_screen_move_loop.h"
8 // Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class.
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"
32 // The minimum alpha before we declare a pixel transparent when searching in
34 const uint32 kMinAlpha = 32;
35 const unsigned char kDragWidgetOpacity = 0xc0;
37 class ScopedCapturer {
39 explicit ScopedCapturer(aura::WindowTreeHost* host)
45 host_->ReleaseCapture();
49 aura::WindowTreeHost* host_;
51 DISALLOW_COPY_AND_ASSIGN(ScopedCapturer);
56 X11WholeScreenMoveLoop::X11WholeScreenMoveLoop(
57 X11WholeScreenMoveLoopDelegate* delegate)
58 : delegate_(delegate),
60 should_reset_mouse_flags_(false),
61 grab_input_window_(None),
63 last_xmotion_.type = LASTEvent;
66 X11WholeScreenMoveLoop::~X11WholeScreenMoveLoop() {}
68 ////////////////////////////////////////////////////////////////////////////////
69 // DesktopWindowTreeHostLinux, MessagePumpDispatcher implementation:
71 void X11WholeScreenMoveLoop::DispatchMouseMovement() {
72 if (!weak_factory_.HasWeakPtrs())
74 weak_factory_.InvalidateWeakPtrs();
75 DCHECK_EQ(MotionNotify, last_xmotion_.type);
76 delegate_->OnMouseMovement(&last_xmotion_);
77 last_xmotion_.type = LASTEvent;
80 uint32_t X11WholeScreenMoveLoop::Dispatch(const base::NativeEvent& event) {
83 // Note: the escape key is handled in the tab drag controller, which has
84 // keyboard focus even though we took pointer grab.
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();
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(
101 base::Bind(&X11WholeScreenMoveLoop::DispatchMouseMovement,
102 weak_factory_.GetWeakPtr()));
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();
116 if (ui::KeyboardCodeFromXKeyEvent(xev) == ui::VKEY_ESCAPE)
122 return POST_DISPATCH_NONE;
125 ////////////////////////////////////////////////////////////////////////////////
126 // DesktopWindowTreeHostLinux, aura::client::WindowMoveClient implementation:
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
137 ScopedCapturer capturer(source->GetHost());
139 DCHECK(!in_move_loop_); // Can only handle one nested loop at a time.
140 in_move_loop_ = true;
142 XDisplay* display = gfx::GetXDisplay();
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
153 // TODO(varkha): Consider integrating GrabPointerAndKeyboard with
154 // ScopedCapturer to avoid possibility of logically keeping multiple grabs.
155 if (!GrabPointerAndKeyboard(cursor))
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;
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();
175 void X11WholeScreenMoveLoop::UpdateCursor(gfx::NativeCursor cursor) {
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);
184 void X11WholeScreenMoveLoop::EndMoveLoop() {
188 // Prevent DispatchMouseMovement from dispatching any posted motion event.
189 weak_factory_.InvalidateWeakPtrs();
190 last_xmotion_.type = LASTEvent;
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;
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.
202 // Ungrab before we let go of the window.
203 XDisplay* display = gfx::GetXDisplay();
204 XUngrabPointer(display, CurrentTime);
205 XUngrabKeyboard(display, CurrentTime);
207 base::MessagePumpX11::Current()->RemoveDispatcherForWindow(
209 drag_widget_.reset();
210 delegate_->OnMoveLoopEnded();
211 XDestroyWindow(display, grab_input_window_);
213 in_move_loop_ = false;
217 void X11WholeScreenMoveLoop::SetDragImage(const gfx::ImageSkia& image,
218 gfx::Vector2dF offset) {
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);
226 bool X11WholeScreenMoveLoop::GrabPointerAndKeyboard(gfx::NativeCursor cursor) {
227 XDisplay* display = gfx::GetXDisplay();
228 XGrabServer(display);
230 XUngrabPointer(display, CurrentTime);
231 int ret = XGrabPointer(
235 ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
241 if (ret != GrabSuccess) {
242 DLOG(ERROR) << "Grabbing pointer for dragging failed: "
243 << ui::GetX11ErrorString(display, ret);
245 XUngrabKeyboard(display, CurrentTime);
253 if (ret != GrabSuccess) {
254 DLOG(ERROR) << "Grabbing keyboard for dragging failed: "
255 << ui::GetX11ErrorString(display, ret);
259 XUngrabServer(display);
260 return ret == GrabSuccess;
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),
278 0, CopyFromParent, InputOnly, CopyFromParent,
279 attribute_mask, &swa);
280 XMapRaised(display, window);
281 base::MessagePumpX11::Current()->BlockUntilWindowMapped(window);
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;
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");
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);
306 widget->GetNativeWindow()->layer()->SetFillsBoundsOpaquely(false);
308 drag_widget_.reset(widget);
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
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.
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);
328 for (int x = 0; x < in_bitmap->width(); ++x) {
329 if (SkColorGetA(in_row[x]) > kMinAlpha)