Make castv2 performance test work.
[chromium-blink-merge.git] / ui / views / widget / desktop_aura / desktop_window_tree_host_x11.cc
blob1316b8b2d0eb80567429451e029ab661e111ce14
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/desktop_window_tree_host_x11.h"
7 #include <X11/extensions/shape.h>
8 #include <X11/extensions/XInput2.h>
9 #include <X11/Xatom.h>
10 #include <X11/Xregion.h>
11 #include <X11/Xutil.h>
13 #include "base/basictypes.h"
14 #include "base/command_line.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/trace_event/trace_event.h"
18 #include "third_party/skia/include/core/SkPath.h"
19 #include "ui/aura/client/cursor_client.h"
20 #include "ui/aura/client/focus_client.h"
21 #include "ui/aura/window.h"
22 #include "ui/aura/window_event_dispatcher.h"
23 #include "ui/aura/window_property.h"
24 #include "ui/base/dragdrop/os_exchange_data_provider_aurax11.h"
25 #include "ui/base/hit_test.h"
26 #include "ui/base/x/x11_util.h"
27 #include "ui/events/devices/x11/device_data_manager_x11.h"
28 #include "ui/events/devices/x11/device_list_cache_x11.h"
29 #include "ui/events/devices/x11/touch_factory_x11.h"
30 #include "ui/events/event_utils.h"
31 #include "ui/events/platform/platform_event_source.h"
32 #include "ui/events/platform/x11/x11_event_source.h"
33 #include "ui/gfx/display.h"
34 #include "ui/gfx/geometry/insets.h"
35 #include "ui/gfx/geometry/size_conversions.h"
36 #include "ui/gfx/image/image_skia.h"
37 #include "ui/gfx/image/image_skia_rep.h"
38 #include "ui/gfx/path.h"
39 #include "ui/gfx/path_x11.h"
40 #include "ui/gfx/screen.h"
41 #include "ui/native_theme/native_theme.h"
42 #include "ui/views/corewm/tooltip_aura.h"
43 #include "ui/views/ime/input_method.h"
44 #include "ui/views/linux_ui/linux_ui.h"
45 #include "ui/views/views_delegate.h"
46 #include "ui/views/views_switches.h"
47 #include "ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.h"
48 #include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h"
49 #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
50 #include "ui/views/widget/desktop_aura/desktop_window_tree_host_observer_x11.h"
51 #include "ui/views/widget/desktop_aura/x11_desktop_handler.h"
52 #include "ui/views/widget/desktop_aura/x11_desktop_window_move_client.h"
53 #include "ui/views/widget/desktop_aura/x11_pointer_grab.h"
54 #include "ui/views/widget/desktop_aura/x11_window_event_filter.h"
55 #include "ui/wm/core/compound_event_filter.h"
56 #include "ui/wm/core/window_util.h"
58 DECLARE_WINDOW_PROPERTY_TYPE(views::DesktopWindowTreeHostX11*);
60 namespace views {
62 DesktopWindowTreeHostX11* DesktopWindowTreeHostX11::g_current_capture =
63 NULL;
64 std::list<XID>* DesktopWindowTreeHostX11::open_windows_ = NULL;
66 DEFINE_WINDOW_PROPERTY_KEY(
67 aura::Window*, kViewsWindowForRootWindow, NULL);
69 DEFINE_WINDOW_PROPERTY_KEY(
70 DesktopWindowTreeHostX11*, kHostForRootWindow, NULL);
72 namespace {
74 // Constants that are part of EWMH.
75 const int k_NET_WM_STATE_ADD = 1;
76 const int k_NET_WM_STATE_REMOVE = 0;
78 // Special value of the _NET_WM_DESKTOP property which indicates that the window
79 // should appear on all desktops.
80 const int kAllDesktops = 0xFFFFFFFF;
82 const char* kAtomsToCache[] = {
83 "UTF8_STRING",
84 "WM_DELETE_WINDOW",
85 "WM_PROTOCOLS",
86 "_NET_FRAME_EXTENTS",
87 "_NET_WM_CM_S0",
88 "_NET_WM_DESKTOP",
89 "_NET_WM_ICON",
90 "_NET_WM_NAME",
91 "_NET_WM_PID",
92 "_NET_WM_PING",
93 "_NET_WM_STATE",
94 "_NET_WM_STATE_ABOVE",
95 "_NET_WM_STATE_FULLSCREEN",
96 "_NET_WM_STATE_HIDDEN",
97 "_NET_WM_STATE_MAXIMIZED_HORZ",
98 "_NET_WM_STATE_MAXIMIZED_VERT",
99 "_NET_WM_STATE_SKIP_TASKBAR",
100 "_NET_WM_STATE_STICKY",
101 "_NET_WM_USER_TIME",
102 "_NET_WM_WINDOW_OPACITY",
103 "_NET_WM_WINDOW_TYPE",
104 "_NET_WM_WINDOW_TYPE_DND",
105 "_NET_WM_WINDOW_TYPE_MENU",
106 "_NET_WM_WINDOW_TYPE_NORMAL",
107 "_NET_WM_WINDOW_TYPE_NOTIFICATION",
108 "_NET_WM_WINDOW_TYPE_TOOLTIP",
109 "XdndActionAsk",
110 "XdndActionCopy"
111 "XdndActionLink",
112 "XdndActionList",
113 "XdndActionMove",
114 "XdndActionPrivate",
115 "XdndAware",
116 "XdndDrop",
117 "XdndEnter",
118 "XdndFinished",
119 "XdndLeave",
120 "XdndPosition",
121 "XdndProxy", // Proxy windows?
122 "XdndSelection",
123 "XdndStatus",
124 "XdndTypeList",
125 NULL
128 const char kX11WindowRolePopup[] = "popup";
129 const char kX11WindowRoleBubble[] = "bubble";
131 } // namespace
133 ////////////////////////////////////////////////////////////////////////////////
134 // DesktopWindowTreeHostX11, public:
136 DesktopWindowTreeHostX11::DesktopWindowTreeHostX11(
137 internal::NativeWidgetDelegate* native_widget_delegate,
138 DesktopNativeWidgetAura* desktop_native_widget_aura)
139 : xdisplay_(gfx::GetXDisplay()),
140 xwindow_(0),
141 x_root_window_(DefaultRootWindow(xdisplay_)),
142 atom_cache_(xdisplay_, kAtomsToCache),
143 window_mapped_(false),
144 is_fullscreen_(false),
145 is_always_on_top_(false),
146 use_native_frame_(false),
147 should_maximize_after_map_(false),
148 use_argb_visual_(false),
149 drag_drop_client_(NULL),
150 native_widget_delegate_(native_widget_delegate),
151 desktop_native_widget_aura_(desktop_native_widget_aura),
152 content_window_(NULL),
153 window_parent_(NULL),
154 custom_window_shape_(false),
155 urgency_hint_set_(false),
156 close_widget_factory_(this) {
159 DesktopWindowTreeHostX11::~DesktopWindowTreeHostX11() {
160 window()->ClearProperty(kHostForRootWindow);
161 aura::client::SetWindowMoveClient(window(), NULL);
162 desktop_native_widget_aura_->OnDesktopWindowTreeHostDestroyed(this);
163 DestroyDispatcher();
166 // static
167 aura::Window* DesktopWindowTreeHostX11::GetContentWindowForXID(XID xid) {
168 aura::WindowTreeHost* host =
169 aura::WindowTreeHost::GetForAcceleratedWidget(xid);
170 return host ? host->window()->GetProperty(kViewsWindowForRootWindow) : NULL;
173 // static
174 DesktopWindowTreeHostX11* DesktopWindowTreeHostX11::GetHostForXID(XID xid) {
175 aura::WindowTreeHost* host =
176 aura::WindowTreeHost::GetForAcceleratedWidget(xid);
177 return host ? host->window()->GetProperty(kHostForRootWindow) : NULL;
180 // static
181 std::vector<aura::Window*> DesktopWindowTreeHostX11::GetAllOpenWindows() {
182 std::vector<aura::Window*> windows(open_windows().size());
183 std::transform(open_windows().begin(),
184 open_windows().end(),
185 windows.begin(),
186 GetContentWindowForXID);
187 return windows;
190 gfx::Rect DesktopWindowTreeHostX11::GetX11RootWindowBounds() const {
191 return bounds_in_pixels_;
194 gfx::Rect DesktopWindowTreeHostX11::GetX11RootWindowOuterBounds() const {
195 gfx::Rect outer_bounds(bounds_in_pixels_);
196 outer_bounds.Inset(-native_window_frame_borders_in_pixels_);
197 return outer_bounds;
200 ::Region DesktopWindowTreeHostX11::GetWindowShape() const {
201 return window_shape_.get();
204 void DesktopWindowTreeHostX11::HandleNativeWidgetActivationChanged(
205 bool active) {
206 if (active) {
207 FlashFrame(false);
208 OnHostActivated();
209 open_windows().remove(xwindow_);
210 open_windows().insert(open_windows().begin(), xwindow_);
211 } else {
212 ReleaseCapture();
215 desktop_native_widget_aura_->HandleActivationChanged(active);
217 native_widget_delegate_->AsWidget()->GetRootView()->SchedulePaint();
220 void DesktopWindowTreeHostX11::AddObserver(
221 views::DesktopWindowTreeHostObserverX11* observer) {
222 observer_list_.AddObserver(observer);
225 void DesktopWindowTreeHostX11::RemoveObserver(
226 views::DesktopWindowTreeHostObserverX11* observer) {
227 observer_list_.RemoveObserver(observer);
230 void DesktopWindowTreeHostX11::SwapNonClientEventHandler(
231 scoped_ptr<ui::EventHandler> handler) {
232 wm::CompoundEventFilter* compound_event_filter =
233 desktop_native_widget_aura_->root_window_event_filter();
234 if (x11_non_client_event_filter_)
235 compound_event_filter->RemoveHandler(x11_non_client_event_filter_.get());
236 compound_event_filter->AddHandler(handler.get());
237 x11_non_client_event_filter_ = handler.Pass();
240 void DesktopWindowTreeHostX11::CleanUpWindowList() {
241 delete open_windows_;
242 open_windows_ = NULL;
245 ////////////////////////////////////////////////////////////////////////////////
246 // DesktopWindowTreeHostX11, DesktopWindowTreeHost implementation:
248 void DesktopWindowTreeHostX11::Init(aura::Window* content_window,
249 const Widget::InitParams& params) {
250 content_window_ = content_window;
252 // TODO(erg): Check whether we *should* be building a WindowTreeHost here, or
253 // whether we should be proxying requests to another DRWHL.
255 // In some situations, views tries to make a zero sized window, and that
256 // makes us crash. Make sure we have valid sizes.
257 Widget::InitParams sanitized_params = params;
258 if (sanitized_params.bounds.width() == 0)
259 sanitized_params.bounds.set_width(100);
260 if (sanitized_params.bounds.height() == 0)
261 sanitized_params.bounds.set_height(100);
263 InitX11Window(sanitized_params);
266 void DesktopWindowTreeHostX11::OnNativeWidgetCreated(
267 const Widget::InitParams& params) {
268 window()->SetProperty(kViewsWindowForRootWindow, content_window_);
269 window()->SetProperty(kHostForRootWindow, this);
271 // Ensure that the X11DesktopHandler exists so that it dispatches activation
272 // messages to us.
273 X11DesktopHandler::get();
275 // TODO(erg): Unify this code once the other consumer goes away.
276 SwapNonClientEventHandler(
277 scoped_ptr<ui::EventHandler>(new X11WindowEventFilter(this)).Pass());
278 SetUseNativeFrame(params.type == Widget::InitParams::TYPE_WINDOW &&
279 !params.remove_standard_frame);
281 x11_window_move_client_.reset(new X11DesktopWindowMoveClient);
282 aura::client::SetWindowMoveClient(window(), x11_window_move_client_.get());
284 SetWindowTransparency();
286 native_widget_delegate_->OnNativeWidgetCreated(true);
289 scoped_ptr<corewm::Tooltip> DesktopWindowTreeHostX11::CreateTooltip() {
290 return make_scoped_ptr(new corewm::TooltipAura);
293 scoped_ptr<aura::client::DragDropClient>
294 DesktopWindowTreeHostX11::CreateDragDropClient(
295 DesktopNativeCursorManager* cursor_manager) {
296 drag_drop_client_ = new DesktopDragDropClientAuraX11(
297 window(), cursor_manager, xdisplay_, xwindow_);
298 drag_drop_client_->Init();
299 return make_scoped_ptr(drag_drop_client_);
302 void DesktopWindowTreeHostX11::Close() {
303 // TODO(erg): Might need to do additional hiding tasks here.
304 delayed_resize_task_.Cancel();
306 if (!close_widget_factory_.HasWeakPtrs()) {
307 // And we delay the close so that if we are called from an ATL callback,
308 // we don't destroy the window before the callback returned (as the caller
309 // may delete ourselves on destroy and the ATL callback would still
310 // dereference us when the callback returns).
311 base::MessageLoop::current()->PostTask(
312 FROM_HERE,
313 base::Bind(&DesktopWindowTreeHostX11::CloseNow,
314 close_widget_factory_.GetWeakPtr()));
318 void DesktopWindowTreeHostX11::CloseNow() {
319 if (xwindow_ == None)
320 return;
322 ReleaseCapture();
323 native_widget_delegate_->OnNativeWidgetDestroying();
325 // If we have children, close them. Use a copy for iteration because they'll
326 // remove themselves.
327 std::set<DesktopWindowTreeHostX11*> window_children_copy = window_children_;
328 for (std::set<DesktopWindowTreeHostX11*>::iterator it =
329 window_children_copy.begin(); it != window_children_copy.end();
330 ++it) {
331 (*it)->CloseNow();
333 DCHECK(window_children_.empty());
335 // If we have a parent, remove ourselves from its children list.
336 if (window_parent_) {
337 window_parent_->window_children_.erase(this);
338 window_parent_ = NULL;
341 // Remove the event listeners we've installed. We need to remove these
342 // because otherwise we get assert during ~WindowEventDispatcher().
343 desktop_native_widget_aura_->root_window_event_filter()->RemoveHandler(
344 x11_non_client_event_filter_.get());
345 x11_non_client_event_filter_.reset();
347 // Destroy the compositor before destroying the |xwindow_| since shutdown
348 // may try to swap, and the swap without a window causes an X error, which
349 // causes a crash with in-process renderer.
350 DestroyCompositor();
352 open_windows().remove(xwindow_);
353 // Actually free our native resources.
354 if (ui::PlatformEventSource::GetInstance())
355 ui::PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this);
356 XDestroyWindow(xdisplay_, xwindow_);
357 xwindow_ = None;
359 desktop_native_widget_aura_->OnHostClosed();
362 aura::WindowTreeHost* DesktopWindowTreeHostX11::AsWindowTreeHost() {
363 return this;
366 void DesktopWindowTreeHostX11::ShowWindowWithState(
367 ui::WindowShowState show_state) {
368 if (!window_mapped_)
369 MapWindow(show_state);
371 if (show_state == ui::SHOW_STATE_NORMAL ||
372 show_state == ui::SHOW_STATE_MAXIMIZED) {
373 Activate();
376 native_widget_delegate_->AsWidget()->SetInitialFocus(show_state);
379 void DesktopWindowTreeHostX11::ShowMaximizedWithBounds(
380 const gfx::Rect& restored_bounds) {
381 ShowWindowWithState(ui::SHOW_STATE_MAXIMIZED);
382 // Enforce |restored_bounds_in_pixels_| since calling Maximize() could have
383 // reset it.
384 restored_bounds_in_pixels_ = ToPixelRect(restored_bounds);
387 bool DesktopWindowTreeHostX11::IsVisible() const {
388 return window_mapped_;
391 void DesktopWindowTreeHostX11::SetSize(const gfx::Size& requested_size) {
392 gfx::Size size_in_pixels = ToPixelRect(gfx::Rect(requested_size)).size();
393 size_in_pixels = AdjustSize(size_in_pixels);
394 bool size_changed = bounds_in_pixels_.size() != size_in_pixels;
395 XResizeWindow(xdisplay_, xwindow_, size_in_pixels.width(),
396 size_in_pixels.height());
397 bounds_in_pixels_.set_size(size_in_pixels);
398 if (size_changed) {
399 OnHostResized(size_in_pixels);
400 ResetWindowRegion();
404 void DesktopWindowTreeHostX11::StackAtTop() {
405 XRaiseWindow(xdisplay_, xwindow_);
408 void DesktopWindowTreeHostX11::CenterWindow(const gfx::Size& size) {
409 gfx::Size size_in_pixels = ToPixelRect(gfx::Rect(size)).size();
410 gfx::Rect parent_bounds_in_pixels = GetWorkAreaBoundsInPixels();
412 // If |window_|'s transient parent bounds are big enough to contain |size|,
413 // use them instead.
414 if (wm::GetTransientParent(content_window_)) {
415 gfx::Rect transient_parent_rect =
416 wm::GetTransientParent(content_window_)->GetBoundsInScreen();
417 if (transient_parent_rect.height() >= size.height() &&
418 transient_parent_rect.width() >= size.width()) {
419 parent_bounds_in_pixels = ToPixelRect(transient_parent_rect);
423 gfx::Rect window_bounds_in_pixels(
424 parent_bounds_in_pixels.x() +
425 (parent_bounds_in_pixels.width() - size_in_pixels.width()) / 2,
426 parent_bounds_in_pixels.y() +
427 (parent_bounds_in_pixels.height() - size_in_pixels.height()) / 2,
428 size_in_pixels.width(), size_in_pixels.height());
429 // Don't size the window bigger than the parent, otherwise the user may not be
430 // able to close or move it.
431 window_bounds_in_pixels.AdjustToFit(parent_bounds_in_pixels);
433 SetBounds(window_bounds_in_pixels);
436 void DesktopWindowTreeHostX11::GetWindowPlacement(
437 gfx::Rect* bounds,
438 ui::WindowShowState* show_state) const {
439 *bounds = GetRestoredBounds();
441 if (IsFullscreen()) {
442 *show_state = ui::SHOW_STATE_FULLSCREEN;
443 } else if (IsMinimized()) {
444 *show_state = ui::SHOW_STATE_MINIMIZED;
445 } else if (IsMaximized()) {
446 *show_state = ui::SHOW_STATE_MAXIMIZED;
447 } else if (!IsActive()) {
448 *show_state = ui::SHOW_STATE_INACTIVE;
449 } else {
450 *show_state = ui::SHOW_STATE_NORMAL;
454 gfx::Rect DesktopWindowTreeHostX11::GetWindowBoundsInScreen() const {
455 return ToDIPRect(bounds_in_pixels_);
458 gfx::Rect DesktopWindowTreeHostX11::GetClientAreaBoundsInScreen() const {
459 // TODO(erg): The NativeWidgetAura version returns |bounds_in_pixels_|,
460 // claiming it's needed for View::ConvertPointToScreen() to work correctly.
461 // DesktopWindowTreeHostWin::GetClientAreaBoundsInScreen() just asks windows
462 // what it thinks the client rect is.
464 // Attempts to calculate the rect by asking the NonClientFrameView what it
465 // thought its GetBoundsForClientView() were broke combobox drop down
466 // placement.
467 return GetWindowBoundsInScreen();
470 gfx::Rect DesktopWindowTreeHostX11::GetRestoredBounds() const {
471 // We can't reliably track the restored bounds of a window, but we can get
472 // the 90% case down. When *chrome* is the process that requests maximizing
473 // or restoring bounds, we can record the current bounds before we request
474 // maximization, and clear it when we detect a state change.
475 if (!restored_bounds_in_pixels_.IsEmpty())
476 return ToDIPRect(restored_bounds_in_pixels_);
478 return GetWindowBoundsInScreen();
481 gfx::Rect DesktopWindowTreeHostX11::GetWorkAreaBoundsInScreen() const {
482 return ToDIPRect(GetWorkAreaBoundsInPixels());
485 void DesktopWindowTreeHostX11::SetShape(gfx::NativeRegion native_region) {
486 custom_window_shape_ = false;
487 window_shape_.reset();
489 if (native_region) {
490 gfx::Transform transform = GetRootTransform();
491 if (!transform.IsIdentity() && !native_region->isEmpty()) {
492 SkPath path_in_dip;
493 if (native_region->getBoundaryPath(&path_in_dip)) {
494 SkPath path_in_pixels;
495 path_in_dip.transform(transform.matrix(), &path_in_pixels);
496 window_shape_.reset(gfx::CreateRegionFromSkPath(path_in_pixels));
497 } else {
498 window_shape_.reset(XCreateRegion());
500 } else {
501 window_shape_.reset(gfx::CreateRegionFromSkRegion(*native_region));
504 custom_window_shape_ = true;
505 delete native_region;
507 ResetWindowRegion();
510 void DesktopWindowTreeHostX11::Activate() {
511 if (!window_mapped_)
512 return;
514 X11DesktopHandler::get()->ActivateWindow(xwindow_);
517 void DesktopWindowTreeHostX11::Deactivate() {
518 if (!IsActive())
519 return;
521 ReleaseCapture();
522 X11DesktopHandler::get()->DeactivateWindow(xwindow_);
525 bool DesktopWindowTreeHostX11::IsActive() const {
526 return X11DesktopHandler::get()->IsActiveWindow(xwindow_);
529 void DesktopWindowTreeHostX11::Maximize() {
530 if (HasWMSpecProperty("_NET_WM_STATE_FULLSCREEN")) {
531 // Unfullscreen the window if it is fullscreen.
532 SetWMSpecState(false,
533 atom_cache_.GetAtom("_NET_WM_STATE_FULLSCREEN"),
534 None);
536 // Resize the window so that it does not have the same size as a monitor.
537 // (Otherwise, some window managers immediately put the window back in
538 // fullscreen mode).
539 gfx::Rect adjusted_bounds_in_pixels(bounds_in_pixels_.origin(),
540 AdjustSize(bounds_in_pixels_.size()));
541 if (adjusted_bounds_in_pixels != bounds_in_pixels_)
542 SetBounds(adjusted_bounds_in_pixels);
545 // Some WMs do not respect maximization hints on unmapped windows, so we
546 // save this one for later too.
547 should_maximize_after_map_ = !window_mapped_;
549 // When we are in the process of requesting to maximize a window, we can
550 // accurately keep track of our restored bounds instead of relying on the
551 // heuristics that are in the PropertyNotify and ConfigureNotify handlers.
552 restored_bounds_in_pixels_ = bounds_in_pixels_;
554 SetWMSpecState(true,
555 atom_cache_.GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"),
556 atom_cache_.GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ"));
557 if (IsMinimized())
558 ShowWindowWithState(ui::SHOW_STATE_NORMAL);
561 void DesktopWindowTreeHostX11::Minimize() {
562 ReleaseCapture();
563 XIconifyWindow(xdisplay_, xwindow_, 0);
566 void DesktopWindowTreeHostX11::Restore() {
567 should_maximize_after_map_ = false;
568 SetWMSpecState(false,
569 atom_cache_.GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"),
570 atom_cache_.GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ"));
571 if (IsMinimized())
572 ShowWindowWithState(ui::SHOW_STATE_NORMAL);
575 bool DesktopWindowTreeHostX11::IsMaximized() const {
576 return (HasWMSpecProperty("_NET_WM_STATE_MAXIMIZED_VERT") &&
577 HasWMSpecProperty("_NET_WM_STATE_MAXIMIZED_HORZ"));
580 bool DesktopWindowTreeHostX11::IsMinimized() const {
581 return HasWMSpecProperty("_NET_WM_STATE_HIDDEN");
584 bool DesktopWindowTreeHostX11::HasCapture() const {
585 return g_current_capture == this;
588 void DesktopWindowTreeHostX11::SetAlwaysOnTop(bool always_on_top) {
589 is_always_on_top_ = always_on_top;
590 SetWMSpecState(always_on_top,
591 atom_cache_.GetAtom("_NET_WM_STATE_ABOVE"),
592 None);
595 bool DesktopWindowTreeHostX11::IsAlwaysOnTop() const {
596 return is_always_on_top_;
599 void DesktopWindowTreeHostX11::SetVisibleOnAllWorkspaces(bool always_visible) {
600 SetWMSpecState(always_visible,
601 atom_cache_.GetAtom("_NET_WM_STATE_STICKY"),
602 None);
604 int new_desktop = 0;
605 if (always_visible) {
606 new_desktop = kAllDesktops;
607 } else {
608 if (!ui::GetCurrentDesktop(&new_desktop))
609 return;
612 XEvent xevent;
613 memset (&xevent, 0, sizeof (xevent));
614 xevent.type = ClientMessage;
615 xevent.xclient.window = xwindow_;
616 xevent.xclient.message_type = atom_cache_.GetAtom("_NET_WM_DESKTOP");
617 xevent.xclient.format = 32;
618 xevent.xclient.data.l[0] = new_desktop;
619 xevent.xclient.data.l[1] = 0;
620 xevent.xclient.data.l[2] = 0;
621 xevent.xclient.data.l[3] = 0;
622 xevent.xclient.data.l[4] = 0;
623 XSendEvent(xdisplay_, x_root_window_, False,
624 SubstructureRedirectMask | SubstructureNotifyMask,
625 &xevent);
628 bool DesktopWindowTreeHostX11::SetWindowTitle(const base::string16& title) {
629 if (window_title_ == title)
630 return false;
631 window_title_ = title;
632 std::string utf8str = base::UTF16ToUTF8(title);
633 XChangeProperty(xdisplay_,
634 xwindow_,
635 atom_cache_.GetAtom("_NET_WM_NAME"),
636 atom_cache_.GetAtom("UTF8_STRING"),
638 PropModeReplace,
639 reinterpret_cast<const unsigned char*>(utf8str.c_str()),
640 utf8str.size());
641 XTextProperty xtp;
642 char *c_utf8_str = const_cast<char *>(utf8str.c_str());
643 if (Xutf8TextListToTextProperty(xdisplay_, &c_utf8_str, 1,
644 XUTF8StringStyle, &xtp) == Success) {
645 XSetWMName(xdisplay_, xwindow_, &xtp);
646 XFree(xtp.value);
648 return true;
651 void DesktopWindowTreeHostX11::ClearNativeFocus() {
652 // This method is weird and misnamed. Instead of clearing the native focus,
653 // it sets the focus to our |content_window_|, which will trigger a cascade
654 // of focus changes into views.
655 if (content_window_ && aura::client::GetFocusClient(content_window_) &&
656 content_window_->Contains(
657 aura::client::GetFocusClient(content_window_)->GetFocusedWindow())) {
658 aura::client::GetFocusClient(content_window_)->FocusWindow(content_window_);
662 Widget::MoveLoopResult DesktopWindowTreeHostX11::RunMoveLoop(
663 const gfx::Vector2d& drag_offset,
664 Widget::MoveLoopSource source,
665 Widget::MoveLoopEscapeBehavior escape_behavior) {
666 aura::client::WindowMoveSource window_move_source =
667 source == Widget::MOVE_LOOP_SOURCE_MOUSE ?
668 aura::client::WINDOW_MOVE_SOURCE_MOUSE :
669 aura::client::WINDOW_MOVE_SOURCE_TOUCH;
670 if (x11_window_move_client_->RunMoveLoop(content_window_, drag_offset,
671 window_move_source) == aura::client::MOVE_SUCCESSFUL)
672 return Widget::MOVE_LOOP_SUCCESSFUL;
674 return Widget::MOVE_LOOP_CANCELED;
677 void DesktopWindowTreeHostX11::EndMoveLoop() {
678 x11_window_move_client_->EndMoveLoop();
681 void DesktopWindowTreeHostX11::SetVisibilityChangedAnimationsEnabled(
682 bool value) {
683 // Much like the previous NativeWidgetGtk, we don't have anything to do here.
686 bool DesktopWindowTreeHostX11::ShouldUseNativeFrame() const {
687 return use_native_frame_;
690 bool DesktopWindowTreeHostX11::ShouldWindowContentsBeTransparent() const {
691 return false;
694 void DesktopWindowTreeHostX11::FrameTypeChanged() {
695 Widget::FrameType new_type =
696 native_widget_delegate_->AsWidget()->frame_type();
697 if (new_type == Widget::FRAME_TYPE_DEFAULT) {
698 // The default is determined by Widget::InitParams::remove_standard_frame
699 // and does not change.
700 return;
703 SetUseNativeFrame(new_type == Widget::FRAME_TYPE_FORCE_NATIVE);
704 // Replace the frame and layout the contents. Even though we don't have a
705 // swapable glass frame like on Windows, we still replace the frame because
706 // the button assets don't update otherwise.
707 native_widget_delegate_->AsWidget()->non_client_view()->UpdateFrame();
710 void DesktopWindowTreeHostX11::SetFullscreen(bool fullscreen) {
711 if (is_fullscreen_ == fullscreen)
712 return;
713 is_fullscreen_ = fullscreen;
714 if (is_fullscreen_)
715 delayed_resize_task_.Cancel();
717 // Work around a bug where if we try to unfullscreen, metacity immediately
718 // fullscreens us again. This is a little flickery and not necessary if
719 // there's a gnome-panel, but it's not easy to detect whether there's a
720 // panel or not.
721 bool unmaximize_and_remaximize = !fullscreen && IsMaximized() &&
722 ui::GuessWindowManager() == ui::WM_METACITY;
724 if (unmaximize_and_remaximize)
725 Restore();
726 SetWMSpecState(fullscreen,
727 atom_cache_.GetAtom("_NET_WM_STATE_FULLSCREEN"),
728 None);
729 if (unmaximize_and_remaximize)
730 Maximize();
732 // Try to guess the size we will have after the switch to/from fullscreen:
733 // - (may) avoid transient states
734 // - works around Flash content which expects to have the size updated
735 // synchronously.
736 // See https://crbug.com/361408
737 if (fullscreen) {
738 restored_bounds_in_pixels_ = bounds_in_pixels_;
739 const gfx::Display display =
740 gfx::Screen::GetScreenFor(NULL)->GetDisplayNearestWindow(window());
741 bounds_in_pixels_ = ToPixelRect(display.bounds());
742 } else {
743 bounds_in_pixels_ = restored_bounds_in_pixels_;
745 OnHostMoved(bounds_in_pixels_.origin());
746 OnHostResized(bounds_in_pixels_.size());
748 if (HasWMSpecProperty("_NET_WM_STATE_FULLSCREEN") == fullscreen) {
749 Relayout();
750 ResetWindowRegion();
752 // Else: the widget will be relaid out either when the window bounds change or
753 // when |xwindow_|'s fullscreen state changes.
756 bool DesktopWindowTreeHostX11::IsFullscreen() const {
757 return is_fullscreen_;
760 void DesktopWindowTreeHostX11::SetOpacity(unsigned char opacity) {
761 // X server opacity is in terms of 32 bit unsigned int space, and counts from
762 // the opposite direction.
763 // XChangeProperty() expects "cardinality" to be long.
764 unsigned long cardinality = opacity * 0x1010101;
766 if (cardinality == 0xffffffff) {
767 XDeleteProperty(xdisplay_, xwindow_,
768 atom_cache_.GetAtom("_NET_WM_WINDOW_OPACITY"));
769 } else {
770 XChangeProperty(xdisplay_, xwindow_,
771 atom_cache_.GetAtom("_NET_WM_WINDOW_OPACITY"),
772 XA_CARDINAL, 32,
773 PropModeReplace,
774 reinterpret_cast<unsigned char*>(&cardinality), 1);
778 void DesktopWindowTreeHostX11::SetWindowIcons(
779 const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) {
780 // TODO(erg): The way we handle icons across different versions of chrome
781 // could be substantially improved. The Windows version does its own thing
782 // and only sometimes comes down this code path. The icon stuff in
783 // ChromeViewsDelegate is hard coded to use HICONs. Likewise, we're hard
784 // coded to be given two images instead of an arbitrary collection of images
785 // so that we can pass to the WM.
787 // All of this could be made much, much better.
788 std::vector<unsigned long> data;
790 if (window_icon.HasRepresentation(1.0f))
791 SerializeImageRepresentation(window_icon.GetRepresentation(1.0f), &data);
793 if (app_icon.HasRepresentation(1.0f))
794 SerializeImageRepresentation(app_icon.GetRepresentation(1.0f), &data);
796 if (data.empty())
797 XDeleteProperty(xdisplay_, xwindow_, atom_cache_.GetAtom("_NET_WM_ICON"));
798 else
799 ui::SetAtomArrayProperty(xwindow_, "_NET_WM_ICON", "CARDINAL", data);
802 void DesktopWindowTreeHostX11::InitModalType(ui::ModalType modal_type) {
803 switch (modal_type) {
804 case ui::MODAL_TYPE_NONE:
805 break;
806 default:
807 // TODO(erg): Figure out under what situations |modal_type| isn't
808 // none. The comment in desktop_native_widget_aura.cc suggests that this
809 // is rare.
810 NOTIMPLEMENTED();
814 void DesktopWindowTreeHostX11::FlashFrame(bool flash_frame) {
815 if (urgency_hint_set_ == flash_frame)
816 return;
818 gfx::XScopedPtr<XWMHints> hints(XGetWMHints(xdisplay_, xwindow_));
819 if (!hints) {
820 // The window hasn't had its hints set yet.
821 hints.reset(XAllocWMHints());
824 if (flash_frame)
825 hints->flags |= XUrgencyHint;
826 else
827 hints->flags &= ~XUrgencyHint;
829 XSetWMHints(xdisplay_, xwindow_, hints.get());
831 urgency_hint_set_ = flash_frame;
834 void DesktopWindowTreeHostX11::OnRootViewLayout() {
835 UpdateMinAndMaxSize();
838 void DesktopWindowTreeHostX11::OnNativeWidgetFocus() {
839 native_widget_delegate_->AsWidget()->GetInputMethod()->OnFocus();
842 void DesktopWindowTreeHostX11::OnNativeWidgetBlur() {
843 if (xwindow_)
844 native_widget_delegate_->AsWidget()->GetInputMethod()->OnBlur();
847 bool DesktopWindowTreeHostX11::IsAnimatingClosed() const {
848 return false;
851 bool DesktopWindowTreeHostX11::IsTranslucentWindowOpacitySupported() const {
852 return false;
855 void DesktopWindowTreeHostX11::SizeConstraintsChanged() {
856 UpdateMinAndMaxSize();
859 ////////////////////////////////////////////////////////////////////////////////
860 // DesktopWindowTreeHostX11, aura::WindowTreeHost implementation:
862 gfx::Transform DesktopWindowTreeHostX11::GetRootTransform() const {
863 gfx::Display display = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();
864 if (window_mapped_) {
865 aura::Window* win = const_cast<aura::Window*>(window());
866 display = gfx::Screen::GetNativeScreen()->GetDisplayNearestWindow(win);
869 float scale = display.device_scale_factor();
870 gfx::Transform transform;
871 transform.Scale(scale, scale);
872 return transform;
875 ui::EventSource* DesktopWindowTreeHostX11::GetEventSource() {
876 return this;
879 gfx::AcceleratedWidget DesktopWindowTreeHostX11::GetAcceleratedWidget() {
880 return xwindow_;
883 void DesktopWindowTreeHostX11::Show() {
884 ShowWindowWithState(ui::SHOW_STATE_NORMAL);
885 native_widget_delegate_->OnNativeWidgetVisibilityChanged(true);
888 void DesktopWindowTreeHostX11::Hide() {
889 if (window_mapped_) {
890 XWithdrawWindow(xdisplay_, xwindow_, 0);
891 window_mapped_ = false;
893 native_widget_delegate_->OnNativeWidgetVisibilityChanged(false);
896 gfx::Rect DesktopWindowTreeHostX11::GetBounds() const {
897 return bounds_in_pixels_;
900 void DesktopWindowTreeHostX11::SetBounds(
901 const gfx::Rect& requested_bounds_in_pixel) {
902 gfx::Rect bounds_in_pixels(requested_bounds_in_pixel.origin(),
903 AdjustSize(requested_bounds_in_pixel.size()));
904 bool origin_changed = bounds_in_pixels_.origin() != bounds_in_pixels.origin();
905 bool size_changed = bounds_in_pixels_.size() != bounds_in_pixels.size();
906 XWindowChanges changes = {0};
907 unsigned value_mask = 0;
909 if (size_changed) {
910 if (bounds_in_pixels.width() < min_size_in_pixels_.width() ||
911 bounds_in_pixels.height() < min_size_in_pixels_.height() ||
912 (!max_size_in_pixels_.IsEmpty() &&
913 (bounds_in_pixels.width() > max_size_in_pixels_.width() ||
914 bounds_in_pixels.height() > max_size_in_pixels_.height()))) {
915 // Update the minimum and maximum sizes in case they have changed.
916 UpdateMinAndMaxSize();
918 gfx::Size size_in_pixels = bounds_in_pixels.size();
919 size_in_pixels.SetToMin(max_size_in_pixels_);
920 size_in_pixels.SetToMax(min_size_in_pixels_);
921 bounds_in_pixels.set_size(size_in_pixels);
924 changes.width = bounds_in_pixels.width();
925 changes.height = bounds_in_pixels.height();
926 value_mask |= CWHeight | CWWidth;
929 if (origin_changed) {
930 changes.x = bounds_in_pixels.x();
931 changes.y = bounds_in_pixels.y();
932 value_mask |= CWX | CWY;
934 if (value_mask)
935 XConfigureWindow(xdisplay_, xwindow_, value_mask, &changes);
937 // Assume that the resize will go through as requested, which should be the
938 // case if we're running without a window manager. If there's a window
939 // manager, it can modify or ignore the request, but (per ICCCM) we'll get a
940 // (possibly synthetic) ConfigureNotify about the actual size and correct
941 // |bounds_in_pixels_| later.
942 bounds_in_pixels_ = bounds_in_pixels;
944 if (origin_changed)
945 native_widget_delegate_->AsWidget()->OnNativeWidgetMove();
946 if (size_changed) {
947 OnHostResized(bounds_in_pixels.size());
948 ResetWindowRegion();
952 gfx::Point DesktopWindowTreeHostX11::GetLocationOnNativeScreen() const {
953 return bounds_in_pixels_.origin();
956 void DesktopWindowTreeHostX11::SetCapture() {
957 if (HasCapture())
958 return;
960 // Grabbing the mouse is asynchronous. However, we synchronously start
961 // forwarding all mouse events received by Chrome to the
962 // aura::WindowEventDispatcher which has capture. This makes capture
963 // synchronous for all intents and purposes if either:
964 // - |g_current_capture|'s X window has capture.
965 // OR
966 // - The topmost window underneath the mouse is managed by Chrome.
967 DesktopWindowTreeHostX11* old_capturer = g_current_capture;
969 // Update |g_current_capture| prior to calling OnHostLostWindowCapture() to
970 // avoid releasing pointer grab.
971 g_current_capture = this;
972 if (old_capturer)
973 old_capturer->OnHostLostWindowCapture();
975 GrabPointer(xwindow_, true, None);
978 void DesktopWindowTreeHostX11::ReleaseCapture() {
979 if (g_current_capture == this) {
980 // Release mouse grab asynchronously. A window managed by Chrome is likely
981 // the topmost window underneath the mouse so the capture release being
982 // asynchronous is likely inconsequential.
983 g_current_capture = NULL;
984 UngrabPointer();
986 OnHostLostWindowCapture();
990 void DesktopWindowTreeHostX11::SetCursorNative(gfx::NativeCursor cursor) {
991 XDefineCursor(xdisplay_, xwindow_, cursor.platform());
994 void DesktopWindowTreeHostX11::MoveCursorToNative(const gfx::Point& location) {
995 XWarpPointer(xdisplay_, None, x_root_window_, 0, 0, 0, 0,
996 bounds_in_pixels_.x() + location.x(),
997 bounds_in_pixels_.y() + location.y());
1000 void DesktopWindowTreeHostX11::OnCursorVisibilityChangedNative(bool show) {
1001 // TODO(erg): Conditional on us enabling touch on desktop linux builds, do
1002 // the same tap-to-click disabling here that chromeos does.
1005 ////////////////////////////////////////////////////////////////////////////////
1006 // DesktopWindowTreeHostX11, ui::EventSource implementation:
1008 ui::EventProcessor* DesktopWindowTreeHostX11::GetEventProcessor() {
1009 return dispatcher();
1012 ////////////////////////////////////////////////////////////////////////////////
1013 // DesktopWindowTreeHostX11, private:
1015 void DesktopWindowTreeHostX11::InitX11Window(
1016 const Widget::InitParams& params) {
1017 unsigned long attribute_mask = CWBackPixmap;
1018 XSetWindowAttributes swa;
1019 memset(&swa, 0, sizeof(swa));
1020 swa.background_pixmap = None;
1022 ::Atom window_type;
1023 switch (params.type) {
1024 case Widget::InitParams::TYPE_MENU:
1025 swa.override_redirect = True;
1026 window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_MENU");
1027 break;
1028 case Widget::InitParams::TYPE_TOOLTIP:
1029 swa.override_redirect = True;
1030 window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_TOOLTIP");
1031 break;
1032 case Widget::InitParams::TYPE_POPUP:
1033 swa.override_redirect = True;
1034 window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_NOTIFICATION");
1035 break;
1036 case Widget::InitParams::TYPE_DRAG:
1037 swa.override_redirect = True;
1038 window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_DND");
1039 break;
1040 default:
1041 window_type = atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE_NORMAL");
1042 break;
1044 if (swa.override_redirect)
1045 attribute_mask |= CWOverrideRedirect;
1047 // Detect whether we're running inside a compositing manager. If so, try to
1048 // use the ARGB visual. Otherwise, just use our parent's visual.
1049 Visual* visual = CopyFromParent;
1050 int depth = CopyFromParent;
1051 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1052 switches::kEnableTransparentVisuals) &&
1053 XGetSelectionOwner(xdisplay_, atom_cache_.GetAtom("_NET_WM_CM_S0")) !=
1054 None) {
1055 Visual* rgba_visual = GetARGBVisual();
1056 if (rgba_visual) {
1057 visual = rgba_visual;
1058 depth = 32;
1060 attribute_mask |= CWColormap;
1061 swa.colormap = XCreateColormap(xdisplay_, x_root_window_, visual,
1062 AllocNone);
1064 // x.org will BadMatch if we don't set a border when the depth isn't the
1065 // same as the parent depth.
1066 attribute_mask |= CWBorderPixel;
1067 swa.border_pixel = 0;
1069 use_argb_visual_ = true;
1073 bounds_in_pixels_ = ToPixelRect(params.bounds);
1074 bounds_in_pixels_.set_size(AdjustSize(bounds_in_pixels_.size()));
1075 xwindow_ = XCreateWindow(xdisplay_, x_root_window_, bounds_in_pixels_.x(),
1076 bounds_in_pixels_.y(), bounds_in_pixels_.width(),
1077 bounds_in_pixels_.height(),
1078 0, // border width
1079 depth, InputOutput, visual, attribute_mask, &swa);
1080 if (ui::PlatformEventSource::GetInstance())
1081 ui::PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this);
1082 open_windows().push_back(xwindow_);
1084 // TODO(erg): Maybe need to set a ViewProp here like in RWHL::RWHL().
1086 long event_mask = ButtonPressMask | ButtonReleaseMask | FocusChangeMask |
1087 KeyPressMask | KeyReleaseMask |
1088 EnterWindowMask | LeaveWindowMask |
1089 ExposureMask | VisibilityChangeMask |
1090 StructureNotifyMask | PropertyChangeMask |
1091 PointerMotionMask;
1092 XSelectInput(xdisplay_, xwindow_, event_mask);
1093 XFlush(xdisplay_);
1095 if (ui::IsXInput2Available())
1096 ui::TouchFactory::GetInstance()->SetupXI2ForXWindow(xwindow_);
1098 // TODO(erg): We currently only request window deletion events. We also
1099 // should listen for activation events and anything else that GTK+ listens
1100 // for, and do something useful.
1101 ::Atom protocols[2];
1102 protocols[0] = atom_cache_.GetAtom("WM_DELETE_WINDOW");
1103 protocols[1] = atom_cache_.GetAtom("_NET_WM_PING");
1104 XSetWMProtocols(xdisplay_, xwindow_, protocols, 2);
1106 // We need a WM_CLIENT_MACHINE and WM_LOCALE_NAME value so we integrate with
1107 // the desktop environment.
1108 XSetWMProperties(xdisplay_, xwindow_, NULL, NULL, NULL, 0, NULL, NULL, NULL);
1110 // Likewise, the X server needs to know this window's pid so it knows which
1111 // program to kill if the window hangs.
1112 // XChangeProperty() expects "pid" to be long.
1113 static_assert(sizeof(long) >= sizeof(pid_t),
1114 "pid_t should not be larger than long");
1115 long pid = getpid();
1116 XChangeProperty(xdisplay_,
1117 xwindow_,
1118 atom_cache_.GetAtom("_NET_WM_PID"),
1119 XA_CARDINAL,
1121 PropModeReplace,
1122 reinterpret_cast<unsigned char*>(&pid), 1);
1124 XChangeProperty(xdisplay_,
1125 xwindow_,
1126 atom_cache_.GetAtom("_NET_WM_WINDOW_TYPE"),
1127 XA_ATOM,
1129 PropModeReplace,
1130 reinterpret_cast<unsigned char*>(&window_type), 1);
1132 // List of window state properties (_NET_WM_STATE) to set, if any.
1133 std::vector< ::Atom> state_atom_list;
1135 // Remove popup windows from taskbar unless overridden.
1136 if ((params.type == Widget::InitParams::TYPE_POPUP ||
1137 params.type == Widget::InitParams::TYPE_BUBBLE) &&
1138 !params.force_show_in_taskbar) {
1139 state_atom_list.push_back(
1140 atom_cache_.GetAtom("_NET_WM_STATE_SKIP_TASKBAR"));
1143 // If the window should stay on top of other windows, add the
1144 // _NET_WM_STATE_ABOVE property.
1145 is_always_on_top_ = params.keep_on_top;
1146 if (is_always_on_top_)
1147 state_atom_list.push_back(atom_cache_.GetAtom("_NET_WM_STATE_ABOVE"));
1149 if (params.visible_on_all_workspaces) {
1150 state_atom_list.push_back(atom_cache_.GetAtom("_NET_WM_STATE_STICKY"));
1151 ui::SetIntProperty(xwindow_, "_NET_WM_DESKTOP", "CARDINAL", kAllDesktops);
1154 // Setting _NET_WM_STATE by sending a message to the root_window (with
1155 // SetWMSpecState) has no effect here since the window has not yet been
1156 // mapped. So we manually change the state.
1157 if (!state_atom_list.empty()) {
1158 ui::SetAtomArrayProperty(xwindow_,
1159 "_NET_WM_STATE",
1160 "ATOM",
1161 state_atom_list);
1164 if (!params.wm_class_name.empty() || !params.wm_class_class.empty()) {
1165 ui::SetWindowClassHint(
1166 xdisplay_, xwindow_, params.wm_class_name, params.wm_class_class);
1169 const char* wm_role_name = NULL;
1170 // If the widget isn't overriding the role, provide a default value for popup
1171 // and bubble types.
1172 if (!params.wm_role_name.empty()) {
1173 wm_role_name = params.wm_role_name.c_str();
1174 } else {
1175 switch (params.type) {
1176 case Widget::InitParams::TYPE_POPUP:
1177 wm_role_name = kX11WindowRolePopup;
1178 break;
1179 case Widget::InitParams::TYPE_BUBBLE:
1180 wm_role_name = kX11WindowRoleBubble;
1181 break;
1182 default:
1183 break;
1186 if (wm_role_name)
1187 ui::SetWindowRole(xdisplay_, xwindow_, std::string(wm_role_name));
1189 if (params.remove_standard_frame) {
1190 // Setting _GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED tells gnome-shell to not force
1191 // fullscreen on the window when it matches the desktop size.
1192 ui::SetHideTitlebarWhenMaximizedProperty(xwindow_,
1193 ui::HIDE_TITLEBAR_WHEN_MAXIMIZED);
1196 // If we have a parent, record the parent/child relationship. We use this
1197 // data during destruction to make sure that when we try to close a parent
1198 // window, we also destroy all child windows.
1199 if (params.parent && params.parent->GetHost()) {
1200 XID parent_xid =
1201 params.parent->GetHost()->GetAcceleratedWidget();
1202 window_parent_ = GetHostForXID(parent_xid);
1203 DCHECK(window_parent_);
1204 window_parent_->window_children_.insert(this);
1207 // If we have a delegate which is providing a default window icon, use that
1208 // icon.
1209 gfx::ImageSkia* window_icon = ViewsDelegate::views_delegate ?
1210 ViewsDelegate::views_delegate->GetDefaultWindowIcon() : NULL;
1211 if (window_icon) {
1212 SetWindowIcons(gfx::ImageSkia(), *window_icon);
1214 CreateCompositor(GetAcceleratedWidget());
1217 gfx::Size DesktopWindowTreeHostX11::AdjustSize(
1218 const gfx::Size& requested_size_in_pixels) {
1219 std::vector<gfx::Display> displays =
1220 gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE)->GetAllDisplays();
1221 // Compare against all monitor sizes. The window manager can move the window
1222 // to whichever monitor it wants.
1223 for (size_t i = 0; i < displays.size(); ++i) {
1224 if (requested_size_in_pixels == displays[i].GetSizeInPixel()) {
1225 return gfx::Size(requested_size_in_pixels.width() - 1,
1226 requested_size_in_pixels.height() - 1);
1230 // Do not request a 0x0 window size. It causes an XError.
1231 gfx::Size size_in_pixels = requested_size_in_pixels;
1232 size_in_pixels.SetToMax(gfx::Size(1, 1));
1233 return size_in_pixels;
1236 void DesktopWindowTreeHostX11::OnWMStateUpdated() {
1237 std::vector< ::Atom> atom_list;
1238 // Ignore the return value of ui::GetAtomArrayProperty(). Fluxbox removes the
1239 // _NET_WM_STATE property when no _NET_WM_STATE atoms are set.
1240 ui::GetAtomArrayProperty(xwindow_, "_NET_WM_STATE", &atom_list);
1242 bool was_minimized = IsMinimized();
1244 window_properties_.clear();
1245 std::copy(atom_list.begin(), atom_list.end(),
1246 inserter(window_properties_, window_properties_.begin()));
1248 // Propagate the window minimization information to the content window, so
1249 // the render side can update its visibility properly. OnWMStateUpdated() is
1250 // called by PropertyNofify event from DispatchEvent() when the browser is
1251 // minimized or shown from minimized state. On Windows, this is realized by
1252 // calling OnHostResized() with an empty size. In particular,
1253 // HWNDMessageHandler::GetClientAreaBounds() returns an empty size when the
1254 // window is minimized. On Linux, returning empty size in GetBounds() or
1255 // SetBounds() does not work.
1256 // We also propagate the minimization to the compositor, to makes sure that we
1257 // don't draw any 'blank' frames that could be noticed in applications such as
1258 // window manager previews, which show content even when a window is
1259 // minimized.
1260 bool is_minimized = IsMinimized();
1261 if (is_minimized != was_minimized) {
1262 if (is_minimized) {
1263 compositor()->SetVisible(false);
1264 content_window_->Hide();
1265 } else {
1266 content_window_->Show();
1267 compositor()->SetVisible(true);
1271 if (restored_bounds_in_pixels_.IsEmpty()) {
1272 DCHECK(!IsFullscreen());
1273 if (IsMaximized()) {
1274 // The request that we become maximized originated from a different
1275 // process. |bounds_in_pixels_| already contains our maximized bounds. Do
1276 // a best effort attempt to get restored bounds by setting it to our
1277 // previously set bounds (and if we get this wrong, we aren't any worse
1278 // off since we'd otherwise be returning our maximized bounds).
1279 restored_bounds_in_pixels_ = previous_bounds_in_pixels_;
1281 } else if (!IsMaximized() && !IsFullscreen()) {
1282 // If we have restored bounds, but WM_STATE no longer claims to be
1283 // maximized or fullscreen, we should clear our restored bounds.
1284 restored_bounds_in_pixels_ = gfx::Rect();
1287 // Ignore requests by the window manager to enter or exit fullscreen (e.g. as
1288 // a result of pressing a window manager accelerator key). Chrome does not
1289 // handle window manager initiated fullscreen. In particular, Chrome needs to
1290 // do preprocessing before the x window's fullscreen state is toggled.
1292 is_always_on_top_ = HasWMSpecProperty("_NET_WM_STATE_ABOVE");
1294 // Now that we have different window properties, we may need to relayout the
1295 // window. (The windows code doesn't need this because their window change is
1296 // synchronous.)
1297 Relayout();
1298 ResetWindowRegion();
1301 void DesktopWindowTreeHostX11::OnFrameExtentsUpdated() {
1302 std::vector<int> insets;
1303 if (ui::GetIntArrayProperty(xwindow_, "_NET_FRAME_EXTENTS", &insets) &&
1304 insets.size() == 4) {
1305 // |insets| are returned in the order: [left, right, top, bottom].
1306 native_window_frame_borders_in_pixels_ =
1307 gfx::Insets(insets[2], insets[0], insets[3], insets[1]);
1308 } else {
1309 native_window_frame_borders_in_pixels_ = gfx::Insets();
1313 void DesktopWindowTreeHostX11::UpdateMinAndMaxSize() {
1314 if (!window_mapped_)
1315 return;
1317 gfx::Size minimum_in_pixels =
1318 ToPixelRect(gfx::Rect(native_widget_delegate_->GetMinimumSize())).size();
1319 gfx::Size maximum_in_pixels =
1320 ToPixelRect(gfx::Rect(native_widget_delegate_->GetMaximumSize())).size();
1321 if (min_size_in_pixels_ == minimum_in_pixels &&
1322 max_size_in_pixels_ == maximum_in_pixels)
1323 return;
1325 min_size_in_pixels_ = minimum_in_pixels;
1326 max_size_in_pixels_ = maximum_in_pixels;
1328 XSizeHints hints;
1329 long supplied_return;
1330 XGetWMNormalHints(xdisplay_, xwindow_, &hints, &supplied_return);
1332 if (minimum_in_pixels.IsEmpty()) {
1333 hints.flags &= ~PMinSize;
1334 } else {
1335 hints.flags |= PMinSize;
1336 hints.min_width = min_size_in_pixels_.width();
1337 hints.min_height = min_size_in_pixels_.height();
1340 if (maximum_in_pixels.IsEmpty()) {
1341 hints.flags &= ~PMaxSize;
1342 } else {
1343 hints.flags |= PMaxSize;
1344 hints.max_width = max_size_in_pixels_.width();
1345 hints.max_height = max_size_in_pixels_.height();
1348 XSetWMNormalHints(xdisplay_, xwindow_, &hints);
1351 void DesktopWindowTreeHostX11::UpdateWMUserTime(
1352 const ui::PlatformEvent& event) {
1353 if (!IsActive())
1354 return;
1356 ui::EventType type = ui::EventTypeFromNative(event);
1357 if (type == ui::ET_MOUSE_PRESSED ||
1358 type == ui::ET_KEY_PRESSED ||
1359 type == ui::ET_TOUCH_PRESSED) {
1360 unsigned long wm_user_time_ms = static_cast<unsigned long>(
1361 ui::EventTimeFromNative(event).InMilliseconds());
1362 XChangeProperty(xdisplay_,
1363 xwindow_,
1364 atom_cache_.GetAtom("_NET_WM_USER_TIME"),
1365 XA_CARDINAL,
1367 PropModeReplace,
1368 reinterpret_cast<const unsigned char *>(&wm_user_time_ms),
1370 X11DesktopHandler::get()->set_wm_user_time_ms(wm_user_time_ms);
1374 void DesktopWindowTreeHostX11::SetWMSpecState(bool enabled,
1375 ::Atom state1,
1376 ::Atom state2) {
1377 XEvent xclient;
1378 memset(&xclient, 0, sizeof(xclient));
1379 xclient.type = ClientMessage;
1380 xclient.xclient.window = xwindow_;
1381 xclient.xclient.message_type = atom_cache_.GetAtom("_NET_WM_STATE");
1382 xclient.xclient.format = 32;
1383 xclient.xclient.data.l[0] =
1384 enabled ? k_NET_WM_STATE_ADD : k_NET_WM_STATE_REMOVE;
1385 xclient.xclient.data.l[1] = state1;
1386 xclient.xclient.data.l[2] = state2;
1387 xclient.xclient.data.l[3] = 1;
1388 xclient.xclient.data.l[4] = 0;
1390 XSendEvent(xdisplay_, x_root_window_, False,
1391 SubstructureRedirectMask | SubstructureNotifyMask,
1392 &xclient);
1395 bool DesktopWindowTreeHostX11::HasWMSpecProperty(const char* property) const {
1396 return window_properties_.find(atom_cache_.GetAtom(property)) !=
1397 window_properties_.end();
1400 void DesktopWindowTreeHostX11::SetUseNativeFrame(bool use_native_frame) {
1401 use_native_frame_ = use_native_frame;
1402 ui::SetUseOSWindowFrame(xwindow_, use_native_frame);
1403 ResetWindowRegion();
1406 void DesktopWindowTreeHostX11::DispatchMouseEvent(ui::MouseEvent* event) {
1407 // In Windows, the native events sent to chrome are separated into client
1408 // and non-client versions of events, which we record on our LocatedEvent
1409 // structures. On X11, we emulate the concept of non-client. Before we pass
1410 // this event to the cross platform event handling framework, we need to
1411 // make sure it is appropriately marked as non-client if it's in the non
1412 // client area, or otherwise, we can get into a state where the a window is
1413 // set as the |mouse_pressed_handler_| in window_event_dispatcher.cc
1414 // despite the mouse button being released.
1416 // We can't do this later in the dispatch process because we share that
1417 // with ash, and ash gets confused about event IS_NON_CLIENT-ness on
1418 // events, since ash doesn't expect this bit to be set, because it's never
1419 // been set before. (This works on ash on Windows because none of the mouse
1420 // events on the ash desktop are clicking in what Windows considers to be a
1421 // non client area.) Likewise, we won't want to do the following in any
1422 // WindowTreeHost that hosts ash.
1423 if (content_window_ && content_window_->delegate()) {
1424 int flags = event->flags();
1425 int hit_test_code =
1426 content_window_->delegate()->GetNonClientComponent(event->location());
1427 if (hit_test_code != HTCLIENT && hit_test_code != HTNOWHERE)
1428 flags |= ui::EF_IS_NON_CLIENT;
1429 event->set_flags(flags);
1432 // While we unset the urgency hint when we gain focus, we also must remove it
1433 // on mouse clicks because we can call FlashFrame() on an active window.
1434 if (event->IsAnyButton() || event->IsMouseWheelEvent())
1435 FlashFrame(false);
1437 if (!g_current_capture || g_current_capture == this) {
1438 SendEventToProcessor(event);
1439 } else {
1440 // Another DesktopWindowTreeHostX11 has installed itself as
1441 // capture. Translate the event's location and dispatch to the other.
1442 ConvertEventToDifferentHost(event, g_current_capture);
1443 g_current_capture->SendEventToProcessor(event);
1447 void DesktopWindowTreeHostX11::DispatchTouchEvent(ui::TouchEvent* event) {
1448 if (g_current_capture && g_current_capture != this &&
1449 event->type() == ui::ET_TOUCH_PRESSED) {
1450 ConvertEventToDifferentHost(event, g_current_capture);
1451 g_current_capture->SendEventToProcessor(event);
1452 } else {
1453 SendEventToProcessor(event);
1457 void DesktopWindowTreeHostX11::ConvertEventToDifferentHost(
1458 ui::LocatedEvent* located_event,
1459 DesktopWindowTreeHostX11* host) {
1460 DCHECK_NE(this, host);
1461 const gfx::Display display_src =
1462 gfx::Screen::GetNativeScreen()->GetDisplayNearestWindow(window());
1463 const gfx::Display display_dest =
1464 gfx::Screen::GetNativeScreen()->GetDisplayNearestWindow(host->window());
1465 DCHECK_EQ(display_src.device_scale_factor(),
1466 display_dest.device_scale_factor());
1467 gfx::Vector2d offset = GetLocationOnNativeScreen() -
1468 host->GetLocationOnNativeScreen();
1469 gfx::Point location_in_pixel_in_host = located_event->location() + offset;
1470 located_event->set_location(location_in_pixel_in_host);
1473 void DesktopWindowTreeHostX11::ResetWindowRegion() {
1474 // If a custom window shape was supplied then apply it.
1475 if (custom_window_shape_) {
1476 XShapeCombineRegion(xdisplay_, xwindow_, ShapeBounding, 0, 0,
1477 window_shape_.get(), false);
1478 return;
1481 window_shape_.reset();
1483 if (!IsMaximized() && !IsFullscreen()) {
1484 gfx::Path window_mask;
1485 views::Widget* widget = native_widget_delegate_->AsWidget();
1486 if (widget->non_client_view()) {
1487 // Some frame views define a custom (non-rectangular) window mask. If
1488 // so, use it to define the window shape. If not, fall through.
1489 widget->non_client_view()->GetWindowMask(bounds_in_pixels_.size(),
1490 &window_mask);
1491 if (window_mask.countPoints() > 0) {
1492 window_shape_.reset(gfx::CreateRegionFromSkPath(window_mask));
1493 XShapeCombineRegion(xdisplay_, xwindow_, ShapeBounding, 0, 0,
1494 window_shape_.get(), false);
1495 return;
1500 // If we didn't set the shape for any reason, reset the shaping information.
1501 // How this is done depends on the border style, due to quirks and bugs in
1502 // various window managers.
1503 if (ShouldUseNativeFrame()) {
1504 // If the window has system borders, the mask must be set to null (not a
1505 // rectangle), because several window managers (eg, KDE, XFCE, XMonad) will
1506 // not put borders on a window with a custom shape.
1507 XShapeCombineMask(xdisplay_, xwindow_, ShapeBounding, 0, 0, None, ShapeSet);
1508 } else {
1509 // Conversely, if the window does not have system borders, the mask must be
1510 // manually set to a rectangle that covers the whole window (not null). This
1511 // is due to a bug in KWin <= 4.11.5 (KDE bug #330573) where setting a null
1512 // shape causes the hint to disable system borders to be ignored (resulting
1513 // in a double border).
1514 XRectangle r = {0,
1516 static_cast<unsigned short>(bounds_in_pixels_.width()),
1517 static_cast<unsigned short>(bounds_in_pixels_.height())};
1518 XShapeCombineRectangles(
1519 xdisplay_, xwindow_, ShapeBounding, 0, 0, &r, 1, ShapeSet, YXBanded);
1523 void DesktopWindowTreeHostX11::SerializeImageRepresentation(
1524 const gfx::ImageSkiaRep& rep,
1525 std::vector<unsigned long>* data) {
1526 int width = rep.GetWidth();
1527 data->push_back(width);
1529 int height = rep.GetHeight();
1530 data->push_back(height);
1532 const SkBitmap& bitmap = rep.sk_bitmap();
1533 SkAutoLockPixels locker(bitmap);
1535 for (int y = 0; y < height; ++y)
1536 for (int x = 0; x < width; ++x)
1537 data->push_back(bitmap.getColor(x, y));
1540 Visual* DesktopWindowTreeHostX11::GetARGBVisual() {
1541 XVisualInfo visual_template;
1542 visual_template.screen = 0;
1544 int visuals_len;
1545 gfx::XScopedPtr<XVisualInfo[]> visual_list(XGetVisualInfo(
1546 xdisplay_, VisualScreenMask, &visual_template, &visuals_len));
1547 for (int i = 0; i < visuals_len; ++i) {
1548 // Why support only 8888 ARGB? Because it's all that GTK+ supports. In
1549 // gdkvisual-x11.cc, they look for this specific visual and use it for all
1550 // their alpha channel using needs.
1552 // TODO(erg): While the following does find a valid visual, some GL drivers
1553 // don't believe that this has an alpha channel. According to marcheu@,
1554 // this should work on open source driver though. (It doesn't work with
1555 // NVidia's binaries currently.) http://crbug.com/369209
1556 const XVisualInfo& info = visual_list[i];
1557 if (info.depth == 32 && info.visual->red_mask == 0xff0000 &&
1558 info.visual->green_mask == 0x00ff00 &&
1559 info.visual->blue_mask == 0x0000ff) {
1560 return info.visual;
1564 return nullptr;
1567 std::list<XID>& DesktopWindowTreeHostX11::open_windows() {
1568 if (!open_windows_)
1569 open_windows_ = new std::list<XID>();
1570 return *open_windows_;
1573 void DesktopWindowTreeHostX11::MapWindow(ui::WindowShowState show_state) {
1574 if (show_state != ui::SHOW_STATE_DEFAULT &&
1575 show_state != ui::SHOW_STATE_NORMAL &&
1576 show_state != ui::SHOW_STATE_INACTIVE &&
1577 show_state != ui::SHOW_STATE_MAXIMIZED) {
1578 // It will behave like SHOW_STATE_NORMAL.
1579 NOTIMPLEMENTED();
1582 // Before we map the window, set size hints. Otherwise, some window managers
1583 // will ignore toplevel XMoveWindow commands.
1584 XSizeHints size_hints;
1585 size_hints.flags = PPosition;
1586 size_hints.x = bounds_in_pixels_.x();
1587 size_hints.y = bounds_in_pixels_.y();
1588 XSetWMNormalHints(xdisplay_, xwindow_, &size_hints);
1590 // If SHOW_STATE_INACTIVE, tell the window manager not to focus the window
1591 // when mapping. This is done by setting the _NET_WM_USER_TIME to 0. See e.g.
1592 // http://standards.freedesktop.org/wm-spec/latest/ar01s05.html
1593 unsigned long wm_user_time_ms = (show_state == ui::SHOW_STATE_INACTIVE) ?
1594 0 : X11DesktopHandler::get()->wm_user_time_ms();
1595 if (show_state == ui::SHOW_STATE_INACTIVE || wm_user_time_ms != 0) {
1596 XChangeProperty(xdisplay_,
1597 xwindow_,
1598 atom_cache_.GetAtom("_NET_WM_USER_TIME"),
1599 XA_CARDINAL,
1601 PropModeReplace,
1602 reinterpret_cast<const unsigned char *>(&wm_user_time_ms),
1606 XMapWindow(xdisplay_, xwindow_);
1608 // We now block until our window is mapped. Some X11 APIs will crash and
1609 // burn if passed |xwindow_| before the window is mapped, and XMapWindow is
1610 // asynchronous.
1611 if (ui::X11EventSource::GetInstance())
1612 ui::X11EventSource::GetInstance()->BlockUntilWindowMapped(xwindow_);
1613 window_mapped_ = true;
1615 // Some WMs only respect maximize hints after the window has been mapped.
1616 // Check whether we need to re-do a maximization.
1617 if (should_maximize_after_map_) {
1618 Maximize();
1619 should_maximize_after_map_ = false;
1623 void DesktopWindowTreeHostX11::SetWindowTransparency() {
1624 compositor()->SetHostHasTransparentBackground(use_argb_visual_);
1625 window()->SetTransparent(use_argb_visual_);
1626 content_window_->SetTransparent(use_argb_visual_);
1629 void DesktopWindowTreeHostX11::Relayout() {
1630 Widget* widget = native_widget_delegate_->AsWidget();
1631 NonClientView* non_client_view = widget->non_client_view();
1632 // non_client_view may be NULL, especially during creation.
1633 if (non_client_view) {
1634 non_client_view->client_view()->InvalidateLayout();
1635 non_client_view->InvalidateLayout();
1637 widget->GetRootView()->Layout();
1640 ////////////////////////////////////////////////////////////////////////////////
1641 // DesktopWindowTreeHostX11, ui::PlatformEventDispatcher implementation:
1643 bool DesktopWindowTreeHostX11::CanDispatchEvent(
1644 const ui::PlatformEvent& event) {
1645 return event->xany.window == xwindow_ ||
1646 (event->type == GenericEvent &&
1647 static_cast<XIDeviceEvent*>(event->xcookie.data)->event == xwindow_);
1650 uint32_t DesktopWindowTreeHostX11::DispatchEvent(
1651 const ui::PlatformEvent& event) {
1652 XEvent* xev = event;
1654 TRACE_EVENT1("views", "DesktopWindowTreeHostX11::Dispatch",
1655 "event->type", event->type);
1657 UpdateWMUserTime(event);
1659 // May want to factor CheckXEventForConsistency(xev); into a common location
1660 // since it is called here.
1661 switch (xev->type) {
1662 case EnterNotify:
1663 case LeaveNotify: {
1664 // Ignore EventNotify and LeaveNotify events from children of |xwindow_|.
1665 // NativeViewGLSurfaceGLX adds a child to |xwindow_|.
1666 // TODO(pkotwicz|tdanderson): Figure out whether the suppression is
1667 // necessary. crbug.com/385716
1668 if (xev->xcrossing.detail == NotifyInferior)
1669 break;
1671 ui::MouseEvent mouse_event(xev);
1672 DispatchMouseEvent(&mouse_event);
1673 break;
1675 case Expose: {
1676 gfx::Rect damage_rect_in_pixels(xev->xexpose.x, xev->xexpose.y,
1677 xev->xexpose.width, xev->xexpose.height);
1678 compositor()->ScheduleRedrawRect(damage_rect_in_pixels);
1679 break;
1681 case KeyPress: {
1682 ui::KeyEvent keydown_event(xev);
1683 SendEventToProcessor(&keydown_event);
1684 break;
1686 case KeyRelease: {
1687 // There is no way to deactivate a window in X11 so ignore input if
1688 // window is supposed to be 'inactive'. See comments in
1689 // X11DesktopHandler::DeactivateWindow() for more details.
1690 if (!IsActive() && !HasCapture())
1691 break;
1693 ui::KeyEvent key_event(xev);
1694 SendEventToProcessor(&key_event);
1695 break;
1697 case ButtonPress:
1698 case ButtonRelease: {
1699 ui::EventType event_type = ui::EventTypeFromNative(xev);
1700 switch (event_type) {
1701 case ui::ET_MOUSEWHEEL: {
1702 ui::MouseWheelEvent mouseev(xev);
1703 DispatchMouseEvent(&mouseev);
1704 break;
1706 case ui::ET_MOUSE_PRESSED:
1707 case ui::ET_MOUSE_RELEASED: {
1708 ui::MouseEvent mouseev(xev);
1709 DispatchMouseEvent(&mouseev);
1710 break;
1712 case ui::ET_UNKNOWN:
1713 // No event is created for X11-release events for mouse-wheel buttons.
1714 break;
1715 default:
1716 NOTREACHED() << event_type;
1718 break;
1720 case FocusOut:
1721 if (xev->xfocus.mode != NotifyGrab) {
1722 ReleaseCapture();
1723 OnHostLostWindowCapture();
1724 X11DesktopHandler::get()->ProcessXEvent(xev);
1725 } else {
1726 dispatcher()->OnHostLostMouseGrab();
1728 break;
1729 case FocusIn:
1730 X11DesktopHandler::get()->ProcessXEvent(xev);
1731 break;
1732 case ConfigureNotify: {
1733 DCHECK_EQ(xwindow_, xev->xconfigure.window);
1734 DCHECK_EQ(xwindow_, xev->xconfigure.event);
1735 // It's possible that the X window may be resized by some other means than
1736 // from within aura (e.g. the X window manager can change the size). Make
1737 // sure the root window size is maintained properly.
1738 int translated_x_in_pixels = xev->xconfigure.x;
1739 int translated_y_in_pixels = xev->xconfigure.y;
1740 if (!xev->xconfigure.send_event && !xev->xconfigure.override_redirect) {
1741 Window unused;
1742 XTranslateCoordinates(xdisplay_, xwindow_, x_root_window_, 0, 0,
1743 &translated_x_in_pixels, &translated_y_in_pixels,
1744 &unused);
1746 gfx::Rect bounds_in_pixels(translated_x_in_pixels, translated_y_in_pixels,
1747 xev->xconfigure.width, xev->xconfigure.height);
1748 bool size_changed = bounds_in_pixels_.size() != bounds_in_pixels.size();
1749 bool origin_changed =
1750 bounds_in_pixels_.origin() != bounds_in_pixels.origin();
1751 previous_bounds_in_pixels_ = bounds_in_pixels_;
1752 bounds_in_pixels_ = bounds_in_pixels;
1754 if (origin_changed)
1755 OnHostMoved(bounds_in_pixels_.origin());
1757 if (size_changed) {
1758 delayed_resize_task_.Reset(base::Bind(
1759 &DesktopWindowTreeHostX11::DelayedResize,
1760 close_widget_factory_.GetWeakPtr(), bounds_in_pixels.size()));
1761 base::MessageLoop::current()->PostTask(
1762 FROM_HERE, delayed_resize_task_.callback());
1764 break;
1766 case GenericEvent: {
1767 ui::TouchFactory* factory = ui::TouchFactory::GetInstance();
1768 if (!factory->ShouldProcessXI2Event(xev))
1769 break;
1771 ui::EventType type = ui::EventTypeFromNative(xev);
1772 XEvent last_event;
1773 int num_coalesced = 0;
1775 switch (type) {
1776 case ui::ET_TOUCH_MOVED:
1777 num_coalesced = ui::CoalescePendingMotionEvents(xev, &last_event);
1778 if (num_coalesced > 0)
1779 xev = &last_event;
1780 // fallthrough
1781 case ui::ET_TOUCH_PRESSED:
1782 case ui::ET_TOUCH_RELEASED: {
1783 ui::TouchEvent touchev(xev);
1784 DispatchTouchEvent(&touchev);
1785 break;
1787 case ui::ET_MOUSE_MOVED:
1788 case ui::ET_MOUSE_DRAGGED:
1789 case ui::ET_MOUSE_PRESSED:
1790 case ui::ET_MOUSE_RELEASED:
1791 case ui::ET_MOUSE_ENTERED:
1792 case ui::ET_MOUSE_EXITED: {
1793 if (type == ui::ET_MOUSE_MOVED || type == ui::ET_MOUSE_DRAGGED) {
1794 // If this is a motion event, we want to coalesce all pending motion
1795 // events that are at the top of the queue.
1796 num_coalesced = ui::CoalescePendingMotionEvents(xev, &last_event);
1797 if (num_coalesced > 0)
1798 xev = &last_event;
1800 ui::MouseEvent mouseev(xev);
1801 DispatchMouseEvent(&mouseev);
1802 break;
1804 case ui::ET_MOUSEWHEEL: {
1805 ui::MouseWheelEvent mouseev(xev);
1806 DispatchMouseEvent(&mouseev);
1807 break;
1809 case ui::ET_SCROLL_FLING_START:
1810 case ui::ET_SCROLL_FLING_CANCEL:
1811 case ui::ET_SCROLL: {
1812 ui::ScrollEvent scrollev(xev);
1813 SendEventToProcessor(&scrollev);
1814 break;
1816 case ui::ET_KEY_PRESSED:
1817 case ui::ET_KEY_RELEASED: {
1818 ui::KeyEvent key_event(xev);
1819 SendEventToProcessor(&key_event);
1820 break;
1822 case ui::ET_UNKNOWN:
1823 break;
1824 default:
1825 NOTREACHED();
1828 // If we coalesced an event we need to free its cookie.
1829 if (num_coalesced > 0)
1830 XFreeEventData(xev->xgeneric.display, &last_event.xcookie);
1831 break;
1833 case MapNotify: {
1834 FOR_EACH_OBSERVER(DesktopWindowTreeHostObserverX11,
1835 observer_list_,
1836 OnWindowMapped(xwindow_));
1837 break;
1839 case UnmapNotify: {
1840 FOR_EACH_OBSERVER(DesktopWindowTreeHostObserverX11,
1841 observer_list_,
1842 OnWindowUnmapped(xwindow_));
1843 break;
1845 case ClientMessage: {
1846 Atom message_type = xev->xclient.message_type;
1847 if (message_type == atom_cache_.GetAtom("WM_PROTOCOLS")) {
1848 Atom protocol = static_cast<Atom>(xev->xclient.data.l[0]);
1849 if (protocol == atom_cache_.GetAtom("WM_DELETE_WINDOW")) {
1850 // We have received a close message from the window manager.
1851 OnHostCloseRequested();
1852 } else if (protocol == atom_cache_.GetAtom("_NET_WM_PING")) {
1853 XEvent reply_event = *xev;
1854 reply_event.xclient.window = x_root_window_;
1856 XSendEvent(xdisplay_,
1857 reply_event.xclient.window,
1858 False,
1859 SubstructureRedirectMask | SubstructureNotifyMask,
1860 &reply_event);
1862 } else if (message_type == atom_cache_.GetAtom("XdndEnter")) {
1863 drag_drop_client_->OnXdndEnter(xev->xclient);
1864 } else if (message_type == atom_cache_.GetAtom("XdndLeave")) {
1865 drag_drop_client_->OnXdndLeave(xev->xclient);
1866 } else if (message_type == atom_cache_.GetAtom("XdndPosition")) {
1867 drag_drop_client_->OnXdndPosition(xev->xclient);
1868 } else if (message_type == atom_cache_.GetAtom("XdndStatus")) {
1869 drag_drop_client_->OnXdndStatus(xev->xclient);
1870 } else if (message_type == atom_cache_.GetAtom("XdndFinished")) {
1871 drag_drop_client_->OnXdndFinished(xev->xclient);
1872 } else if (message_type == atom_cache_.GetAtom("XdndDrop")) {
1873 drag_drop_client_->OnXdndDrop(xev->xclient);
1875 break;
1877 case MappingNotify: {
1878 switch (xev->xmapping.request) {
1879 case MappingModifier:
1880 case MappingKeyboard:
1881 XRefreshKeyboardMapping(&xev->xmapping);
1882 break;
1883 case MappingPointer:
1884 ui::DeviceDataManagerX11::GetInstance()->UpdateButtonMap();
1885 break;
1886 default:
1887 NOTIMPLEMENTED() << " Unknown request: " << xev->xmapping.request;
1888 break;
1890 break;
1892 case MotionNotify: {
1893 // Discard all but the most recent motion event that targets the same
1894 // window with unchanged state.
1895 XEvent last_event;
1896 while (XPending(xev->xany.display)) {
1897 XEvent next_event;
1898 XPeekEvent(xev->xany.display, &next_event);
1899 if (next_event.type == MotionNotify &&
1900 next_event.xmotion.window == xev->xmotion.window &&
1901 next_event.xmotion.subwindow == xev->xmotion.subwindow &&
1902 next_event.xmotion.state == xev->xmotion.state) {
1903 XNextEvent(xev->xany.display, &last_event);
1904 xev = &last_event;
1905 } else {
1906 break;
1910 ui::MouseEvent mouseev(xev);
1911 DispatchMouseEvent(&mouseev);
1912 break;
1914 case PropertyNotify: {
1915 ::Atom changed_atom = xev->xproperty.atom;
1916 if (changed_atom == atom_cache_.GetAtom("_NET_WM_STATE"))
1917 OnWMStateUpdated();
1918 else if (changed_atom == atom_cache_.GetAtom("_NET_FRAME_EXTENTS"))
1919 OnFrameExtentsUpdated();
1920 break;
1922 case SelectionNotify: {
1923 drag_drop_client_->OnSelectionNotify(xev->xselection);
1924 break;
1927 return ui::POST_DISPATCH_STOP_PROPAGATION;
1930 void DesktopWindowTreeHostX11::DelayedResize(const gfx::Size& size_in_pixels) {
1931 OnHostResized(size_in_pixels);
1932 ResetWindowRegion();
1933 delayed_resize_task_.Cancel();
1936 gfx::Rect DesktopWindowTreeHostX11::GetWorkAreaBoundsInPixels() const {
1937 std::vector<int> value;
1938 if (ui::GetIntArrayProperty(x_root_window_, "_NET_WORKAREA", &value) &&
1939 value.size() >= 4) {
1940 return gfx::Rect(value[0], value[1], value[2], value[3]);
1943 // Fetch the geometry of the root window.
1944 Window root;
1945 int x, y;
1946 unsigned int width, height;
1947 unsigned int border_width, depth;
1948 if (!XGetGeometry(xdisplay_, x_root_window_, &root, &x, &y, &width, &height,
1949 &border_width, &depth)) {
1950 NOTIMPLEMENTED();
1951 return gfx::Rect(0, 0, 10, 10);
1954 return gfx::Rect(x, y, width, height);
1957 gfx::Rect DesktopWindowTreeHostX11::ToDIPRect(
1958 const gfx::Rect& rect_in_pixels) const {
1959 gfx::RectF rect_in_dip = rect_in_pixels;
1960 GetRootTransform().TransformRectReverse(&rect_in_dip);
1961 return gfx::ToEnclosingRect(rect_in_dip);
1964 gfx::Rect DesktopWindowTreeHostX11::ToPixelRect(
1965 const gfx::Rect& rect_in_dip) const {
1966 gfx::RectF rect_in_pixels = rect_in_dip;
1967 GetRootTransform().TransformRect(&rect_in_pixels);
1968 return gfx::ToEnclosingRect(rect_in_pixels);
1971 ////////////////////////////////////////////////////////////////////////////////
1972 // DesktopWindowTreeHost, public:
1974 // static
1975 DesktopWindowTreeHost* DesktopWindowTreeHost::Create(
1976 internal::NativeWidgetDelegate* native_widget_delegate,
1977 DesktopNativeWidgetAura* desktop_native_widget_aura) {
1978 return new DesktopWindowTreeHostX11(native_widget_delegate,
1979 desktop_native_widget_aura);
1982 // static
1983 ui::NativeTheme* DesktopWindowTreeHost::GetNativeTheme(aura::Window* window) {
1984 const views::LinuxUI* linux_ui = views::LinuxUI::instance();
1985 if (linux_ui) {
1986 ui::NativeTheme* native_theme = linux_ui->GetNativeTheme(window);
1987 if (native_theme)
1988 return native_theme;
1991 return ui::NativeTheme::instance();
1994 } // namespace views