3
* Copyright 2010 Google Inc.
5
* Redistribution and use in source and binary forms, with or without
6
* modification, are permitted provided that the following conditions are met:
8
* 1. Redistributions of source code must retain the above copyright notice,
9
* this list of conditions and the following disclaimer.
10
* 2. Redistributions in binary form must reproduce the above copyright notice,
11
* this list of conditions and the following disclaimer in the documentation
12
* and/or other materials provided with the distribution.
13
* 3. The name of the author may not be used to endorse or promote products
14
* derived from this software without specific prior written permission.
16
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
#include "talk/base/linuxwindowpicker.h"
35
#include <X11/Xatom.h>
36
#include <X11/extensions/Xcomposite.h>
37
#include <X11/extensions/Xrender.h>
38
#include <X11/Xutil.h>
40
#include "talk/base/logging.h"
44
// Stupid X11. It seems none of the synchronous returns codes from X11 calls
45
// are meaningful unless an asynchronous error handler is configured. This
46
// RAII class registers and unregisters an X11 error handler.
47
class XErrorSuppressor {
49
explicit XErrorSuppressor(Display* display)
50
: display_(display), original_error_handler_(NULL) {
54
UnsuppressX11Errors();
58
static int ErrorHandler(Display* display, XErrorEvent* e) {
60
XGetErrorText(display, e->error_code, buf, sizeof buf);
61
LOG(LS_WARNING) << "Received X11 error \"" << buf << "\" for request code "
62
<< static_cast<unsigned int>(e->request_code);
66
void SuppressX11Errors() {
68
XSync(display_, False);
69
original_error_handler_ = XSetErrorHandler(&ErrorHandler);
72
void UnsuppressX11Errors() {
74
XSync(display_, False);
75
XErrorHandler handler = XSetErrorHandler(original_error_handler_);
76
if (handler != &ErrorHandler) {
77
LOG(LS_WARNING) << "Unbalanced XSetErrorHandler() calls detected. "
78
<< "Final error handler may not be what you expect!";
80
original_error_handler_ = NULL;
84
XErrorHandler original_error_handler_;
86
DISALLOW_COPY_AND_ASSIGN(XErrorSuppressor);
89
// Hiding all X11 specifics inside its own class. This to avoid
90
// conflicts between talk and X11 header declarations.
91
class XWindowEnumerator {
95
has_composite_extension_(false),
96
has_render_extension_(false) {
99
~XWindowEnumerator() {
100
if (display_ != NULL) {
101
XCloseDisplay(display_);
106
if (display_ != NULL) {
107
// Already initialized.
110
display_ = XOpenDisplay(NULL);
111
if (display_ == NULL) {
112
LOG(LS_ERROR) << "Failed to open display.";
116
XErrorSuppressor error_suppressor(display_);
118
wm_state_ = XInternAtom(display_, "WM_STATE", True);
119
net_wm_icon_ = XInternAtom(display_, "_NET_WM_ICON", False);
121
int event_base, error_base, major_version, minor_version;
122
if (XCompositeQueryExtension(display_, &event_base, &error_base) &&
123
XCompositeQueryVersion(display_, &major_version, &minor_version) &&
124
// XCompositeNameWindowPixmap() requires version 0.2
125
(major_version > 0 || minor_version >= 2)) {
126
has_composite_extension_ = true;
128
LOG(LS_INFO) << "Xcomposite extension not available or too old.";
131
if (XRenderQueryExtension(display_, &event_base, &error_base) &&
132
XRenderQueryVersion(display_, &major_version, &minor_version) &&
133
// XRenderSetPictureTransform() requires version 0.6
134
(major_version > 0 || minor_version >= 6)) {
135
has_render_extension_ = true;
137
LOG(LS_INFO) << "Xrender extension not available or too old.";
142
bool EnumerateWindows(WindowDescriptionList* descriptions) {
146
XErrorSuppressor error_suppressor(display_);
147
int num_screens = XScreenCount(display_);
149
for (int i = 0; i < num_screens; ++i) {
150
if (EnumerateScreenWindows(descriptions, i)) {
151
// We know we succeded on at least one screen.
158
bool EnumerateDesktops(DesktopDescriptionList* descriptions) {
162
XErrorSuppressor error_suppressor(display_);
163
int num_screens = XScreenCount(display_);
164
for (int i = 0; i < num_screens; ++i) {
165
Window root_window = XRootWindow(display_, i);
166
DesktopId id(DesktopId(root_window, i));
167
// TODO: Figure out an appropriate desktop title.
168
DesktopDescription desc(id, "");
169
descriptions->push_back(desc);
171
return num_screens > 0;
174
bool IsVisible(const WindowId& id) {
178
XErrorSuppressor error_suppressor(display_);
179
XWindowAttributes attr;
180
if (!XGetWindowAttributes(display_, id.id(), &attr)) {
181
LOG(LS_ERROR) << "XGetWindowAttributes() failed";
184
return attr.map_state == IsViewable;
187
bool MoveToFront(const WindowId& id) {
191
XErrorSuppressor error_suppressor(display_);
192
unsigned int num_children;
197
// Find root window to pass event to.
198
int status = XQueryTree(display_, id.id(), &root, &parent, &children,
201
LOG(LS_WARNING) << "Failed to query for child windows.";
204
if (children != NULL) {
208
// Move the window to front.
209
XRaiseWindow(display_, id.id());
211
// Some window managers (e.g., metacity in GNOME) consider it illegal to
212
// raise a window without also giving it input focus with
213
// _NET_ACTIVE_WINDOW, so XRaiseWindow() on its own isn't enough.
214
Atom atom = XInternAtom(display_, "_NET_ACTIVE_WINDOW", True);
219
xev.xclient.type = ClientMessage;
220
xev.xclient.serial = 0;
221
xev.xclient.send_event = True;
222
xev.xclient.window = id.id();
223
xev.xclient.message_type = atom;
225
// The format member is set to 8, 16, or 32 and specifies whether the
226
// data should be viewed as a list of bytes, shorts, or longs.
227
xev.xclient.format = 32;
229
xev.xclient.data.l[0] = 0;
230
xev.xclient.data.l[1] = 0;
231
xev.xclient.data.l[2] = 0;
232
xev.xclient.data.l[3] = 0;
233
xev.xclient.data.l[4] = 0;
235
event_mask = SubstructureRedirectMask | SubstructureNotifyMask;
237
XSendEvent(display_, root, False, event_mask, &xev);
243
uint8* GetWindowIcon(const WindowId& id, int* width, int* height) {
247
XErrorSuppressor error_suppressor(display_);
250
unsigned long length, bytes_after, size;
251
unsigned char* data = NULL;
253
// Find out the size of the icon data.
254
if (XGetWindowProperty(
255
display_, id.id(), net_wm_icon_, 0, 0, False, XA_CARDINAL,
256
&ret_type, &format, &length, &size, &data) == Success &&
260
LOG(LS_ERROR) << "Failed to get size of the icon.";
263
// Get the icon data, the format is one uint32 each for width and height,
264
// followed by the actual pixel data.
267
display_, id.id(), net_wm_icon_, 0, size, False, XA_CARDINAL,
268
&ret_type, &format, &length, &bytes_after, &data) == Success &&
270
uint32* data_ptr = reinterpret_cast<uint32*>(data);
274
if (size < static_cast<unsigned long>(w * h + 2)) {
276
LOG(LS_ERROR) << "Not a vaild icon.";
280
ArgbToRgba(&data_ptr[2], 0, 0, w, h, w, h, true);
286
LOG(LS_ERROR) << "Failed to get window icon data.";
291
uint8* GetWindowThumbnail(const WindowId& id, int width, int height) {
296
if (!has_composite_extension_) {
297
// Without the Xcomposite extension we would only get a good thumbnail if
298
// the whole window is visible on screen and not covered by any
299
// other window. This is not something we want so instead, just
301
LOG(LS_INFO) << "No Xcomposite extension detected.";
304
XErrorSuppressor error_suppressor(display_);
309
unsigned int src_width;
310
unsigned int src_height;
311
unsigned int border_width;
314
// In addition to needing X11 server-side support for Xcomposite, it
315
// actually needs to be turned on for this window in order to get a good
316
// thumbnail. If the user has modern hardware/drivers but isn't using a
317
// compositing window manager, that won't be the case. We could
318
// automatically turn it on for all windows here so that we can get
319
// thumbnails, but the transition is visually ugly, so instead we just want
320
// to detect this case and bail out. To do so, we attempt to retrieve the
321
// backing pixmap for the window, which will only exist if the window has
322
// been redirected to offscreen drawing by a compositing window manager. If
323
// it doesn't exist, the calls will raise errors, so we must suppress errors
324
// to prevent libX11 from aborting the program.
325
Pixmap src_pixmap = XCompositeNameWindowPixmap(display_, id.id());
327
// Even if the backing pixmap doesn't exist, this still should have
328
// succeeded and returned a valid handle (it just wouldn't be a handle to
329
// anything). So this is a real error path.
330
LOG(LS_ERROR) << "XCompositeNameWindowPixmap() failed";
333
if (!XGetGeometry(display_, src_pixmap, &root, &x, &y,
334
&src_width, &src_height, &border_width,
336
// If the window does not actually have a backing pixmap, this is the path
337
// that will "fail", so it's a warning rather than an error.
338
LOG(LS_WARNING) << "XGetGeometry() failed (probably composite is not in "
340
XFreePixmap(display_, src_pixmap);
344
// If we get to here, then composite is in use for this window and it has a
345
// valid backing pixmap.
347
XWindowAttributes attr;
348
if (!XGetWindowAttributes(display_, id.id(), &attr)) {
349
LOG(LS_ERROR) << "XGetWindowAttributes() failed";
350
XFreePixmap(display_, src_pixmap);
354
uint8* data = GetDrawableThumbnail(src_pixmap,
360
XFreePixmap(display_, src_pixmap);
364
int GetNumDesktops() {
369
return XScreenCount(display_);
372
uint8* GetDesktopThumbnail(const DesktopId& id, int width, int height) {
376
XErrorSuppressor error_suppressor(display_);
378
Window root_window = id.id();
379
XWindowAttributes attr;
380
if (!XGetWindowAttributes(display_, root_window, &attr)) {
381
LOG(LS_ERROR) << "XGetWindowAttributes() failed";
385
return GetDrawableThumbnail(root_window,
394
uint8* GetDrawableThumbnail(Drawable src_drawable,
400
if (!has_render_extension_) {
401
// Without the Xrender extension we would have to read the full window and
402
// scale it down in our process. Xrender is over a decade old so we aren't
403
// going to expend effort to support that situation. We still need to
404
// check though because probably some virtual VNC displays are in this
406
LOG(LS_INFO) << "No Xrender extension detected.";
410
XRenderPictFormat* format = XRenderFindVisualFormat(display_,
413
LOG(LS_ERROR) << "XRenderFindVisualFormat() failed";
417
// Create a picture to reference the window pixmap.
418
XRenderPictureAttributes pa;
419
pa.subwindow_mode = IncludeInferiors; // Don't clip child widgets
420
Picture src = XRenderCreatePicture(display_,
426
LOG(LS_ERROR) << "XRenderCreatePicture() failed";
430
// Create a picture to reference the destination pixmap.
431
Pixmap dst_pixmap = XCreatePixmap(display_,
437
LOG(LS_ERROR) << "XCreatePixmap() failed";
438
XRenderFreePicture(display_, src);
442
Picture dst = XRenderCreatePicture(display_, dst_pixmap, format, 0, NULL);
444
LOG(LS_ERROR) << "XRenderCreatePicture() failed";
445
XFreePixmap(display_, dst_pixmap);
446
XRenderFreePicture(display_, src);
450
// Clear the background.
451
XRenderColor transparent = {0};
452
XRenderFillRectangle(display_,
461
// Calculate how much we need to scale the image.
462
double scale_x = static_cast<double>(dst_width) /
463
static_cast<double>(src_width);
464
double scale_y = static_cast<double>(dst_height) /
465
static_cast<double>(src_height);
466
double scale = talk_base::_min(scale_y, scale_x);
468
int scaled_width = round(src_width * scale);
469
int scaled_height = round(src_height * scale);
471
// Render the thumbnail centered on both axis.
472
int centered_x = (dst_width - scaled_width) / 2;
473
int centered_y = (dst_height - scaled_height) / 2;
476
XTransform xform = { {
477
{ XDoubleToFixed(1), XDoubleToFixed(0), XDoubleToFixed(0) },
478
{ XDoubleToFixed(0), XDoubleToFixed(1), XDoubleToFixed(0) },
479
{ XDoubleToFixed(0), XDoubleToFixed(0), XDoubleToFixed(scale) }
481
XRenderSetPictureTransform(display_, src, &xform);
483
// Apply filter to smooth out the image.
484
XRenderSetPictureFilter(display_, src, FilterBest, NULL, 0);
486
// Render the image to the destination picture.
487
XRenderComposite(display_,
501
// Get the pixel data from the X server. TODO: XGetImage
502
// might be slow here, compare with ShmGetImage.
503
XImage* image = XGetImage(display_,
510
uint8* data = ArgbToRgba(reinterpret_cast<uint32*>(image->data),
518
XDestroyImage(image);
519
XRenderFreePicture(display_, dst);
520
XFreePixmap(display_, dst_pixmap);
521
XRenderFreePicture(display_, src);
525
uint8* ArgbToRgba(uint32* argb_data, int x, int y, int w, int h,
526
int stride_x, int stride_y, bool has_alpha) {
528
int len = stride_x * stride_y * 4;
529
uint8* data = new uint8[len];
530
memset(data, 0, len);
531
p = data + 4 * (y * stride_x + x);
532
for (int i = 0; i < h; ++i) {
533
for (int j = 0; j < w; ++j) {
536
argb = argb_data[stride_x * (y + i) + x + j];
537
rgba = (argb << 8) | (argb >> 24);
540
*p = (rgba >> 16) & 0xff;
542
*p = (rgba >> 8) & 0xff;
544
*p = has_alpha ? rgba & 0xFF : 0xFF;
547
p += (stride_x - w) * 4;
552
bool EnumerateScreenWindows(WindowDescriptionList* descriptions, int screen) {
556
unsigned int num_children;
557
Window root_window = XRootWindow(display_, screen);
558
status = XQueryTree(display_, root_window, &root_window, &parent, &children,
561
LOG(LS_ERROR) << "Failed to query for child windows.";
564
for (unsigned int i = 0; i < num_children; ++i) {
565
// Iterate in reverse order to display windows from front to back.
566
Window app_window = GetApplicationWindow(children[num_children - 1 - i]);
568
!LinuxWindowPicker::IsDesktopElement(display_, app_window)) {
570
if (GetWindowTitle(app_window, &title)) {
571
WindowId id(app_window);
572
WindowDescription desc(id, title);
573
descriptions->push_back(desc);
577
if (children != NULL) {
583
bool GetWindowTitle(Window window, std::string* title) {
586
XTextProperty window_name;
587
window_name.value = NULL;
589
status = XGetWMName(display_, window, &window_name);
590
if (status && window_name.value && window_name.nitems) {
593
status = Xutf8TextPropertyToTextList(display_, &window_name, &list,
595
if (status >= Success && cnt && *list) {
597
LOG(LS_INFO) << "Window has " << cnt
598
<< " text properties, only using the first one.";
604
XFreeStringList(list);
607
if (window_name.value != NULL) {
608
XFree(window_name.value);
614
Window GetApplicationWindow(Window window) {
616
Window app_window = 0;
618
unsigned int num_children;
621
unsigned long nitems, after;
624
int ret = XGetWindowProperty(display_, window,
626
False, wm_state_, &type, &format,
627
&nitems, &after, &data);
628
if (ret != Success) {
629
LOG(LS_ERROR) << "XGetWindowProperty failed with return code " << ret
630
<< " for window " << window << ".";
634
int64 state = static_cast<int64>(*data);
636
return state == NormalState ? window : 0;
639
if (!XQueryTree(display_, window, &root, &parent, &children,
641
LOG(LS_ERROR) << "Failed to query for child windows although window"
642
<< "does not have a valid WM_STATE.";
645
for (unsigned int i = 0; i < num_children; ++i) {
646
app_window = GetApplicationWindow(children[i]);
651
if (children != NULL) {
660
bool has_composite_extension_;
661
bool has_render_extension_;
664
LinuxWindowPicker::LinuxWindowPicker() : enumerator_(new XWindowEnumerator()) {
667
LinuxWindowPicker::~LinuxWindowPicker() {
670
bool LinuxWindowPicker::IsDesktopElement(_XDisplay* display, Window window) {
672
LOG(LS_WARNING) << "Zero is never a valid window.";
675
XClassHint class_hint;
676
Status s = XGetClassHint(display, window, &class_hint);
679
// No hints, assume this is a normal application window.
682
static const std::string gnome_panel("gnome-panel");
683
static const std::string desktop_window("desktop_window");
685
if (gnome_panel.compare(class_hint.res_name) == 0 ||
686
desktop_window.compare(class_hint.res_name) == 0) {
689
XFree(class_hint.res_name);
690
XFree(class_hint.res_class);
694
bool LinuxWindowPicker::Init() {
695
return enumerator_->Init();
698
bool LinuxWindowPicker::GetWindowList(WindowDescriptionList* descriptions) {
699
return enumerator_->EnumerateWindows(descriptions);
702
bool LinuxWindowPicker::GetDesktopList(DesktopDescriptionList* descriptions) {
703
return enumerator_->EnumerateDesktops(descriptions);
706
bool LinuxWindowPicker::IsVisible(const WindowId& id) {
707
return enumerator_->IsVisible(id);
710
bool LinuxWindowPicker::MoveToFront(const WindowId& id) {
711
return enumerator_->MoveToFront(id);
715
uint8* LinuxWindowPicker::GetWindowIcon(const WindowId& id, int* width,
717
return enumerator_->GetWindowIcon(id, width, height);
720
uint8* LinuxWindowPicker::GetWindowThumbnail(const WindowId& id, int width,
722
return enumerator_->GetWindowThumbnail(id, width, height);
725
int LinuxWindowPicker::GetNumDesktops() {
726
return enumerator_->GetNumDesktops();
729
uint8* LinuxWindowPicker::GetDesktopThumbnail(const DesktopId& id,
732
return enumerator_->GetDesktopThumbnail(id, width, height);
735
} // namespace talk_base