1 /*
2 * This file is part of mpv.
3 *
4 * mpv is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * mpv is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with mpv. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <math.h>
21 #include <inttypes.h>
22 #include <limits.h>
23 #include <unistd.h>
24 #include <poll.h>
25 #include <string.h>
26 #include <assert.h>
27
28 #include <X11/Xmd.h>
29 #include <X11/Xlib.h>
30 #include <X11/Xutil.h>
31 #include <X11/Xatom.h>
32 #include <X11/keysym.h>
33 #include <X11/XKBlib.h>
34 #include <X11/XF86keysym.h>
35
36 #include <X11/extensions/scrnsaver.h>
37 #include <X11/extensions/dpms.h>
38 #include <X11/extensions/Xinerama.h>
39 #include <X11/extensions/Xrandr.h>
40
41 #include "config.h"
42 #include "misc/bstr.h"
43 #include "options/options.h"
44 #include "options/m_config.h"
45 #include "common/common.h"
46 #include "common/msg.h"
47 #include "input/input.h"
48 #include "input/event.h"
49 #include "video/image_loader.h"
50 #include "video/mp_image.h"
51 #include "x11_common.h"
52 #include "mpv_talloc.h"
53
54 #include "vo.h"
55 #include "win_state.h"
56 #include "osdep/io.h"
57 #include "osdep/timer.h"
58 #include "osdep/subprocess.h"
59
60 #include "input/input.h"
61 #include "input/keycodes.h"
62
63 #define vo_wm_LAYER 1
64 #define vo_wm_FULLSCREEN 2
65 #define vo_wm_STAYS_ON_TOP 4
66 #define vo_wm_ABOVE 8
67 #define vo_wm_BELOW 16
68
69 /* EWMH state actions, see
70 http://freedesktop.org/Standards/wm-spec/index.html#id2768769 */
71 #define NET_WM_STATE_REMOVE 0 /* remove/unset property */
72 #define NET_WM_STATE_ADD 1 /* add/set property */
73 #define NET_WM_STATE_TOGGLE 2 /* toggle property */
74
75 #define WIN_LAYER_ONBOTTOM 2
76 #define WIN_LAYER_NORMAL 4
77 #define WIN_LAYER_ONTOP 6
78 #define WIN_LAYER_ABOVE_DOCK 10
79
80 #define DND_VERSION 5
81
82 #define XEMBED_VERSION 0
83 #define XEMBED_MAPPED (1 << 0)
84 #define XEMBED_EMBEDDED_NOTIFY 0
85 #define XEMBED_REQUEST_FOCUS 3
86
87 // ----- Motif header: -------
88
89 #define MWM_HINTS_FUNCTIONS (1L << 0)
90 #define MWM_HINTS_DECORATIONS (1L << 1)
91
92 #define MWM_FUNC_RESIZE (1L << 1)
93 #define MWM_FUNC_MOVE (1L << 2)
94 #define MWM_FUNC_MINIMIZE (1L << 3)
95 #define MWM_FUNC_MAXIMIZE (1L << 4)
96 #define MWM_FUNC_CLOSE (1L << 5)
97
98 #define MWM_DECOR_ALL (1L << 0)
99
100 typedef struct
101 {
102 long flags;
103 long functions;
104 long decorations;
105 long input_mode;
106 long state;
107 } MotifWmHints;
108
109 static const char x11_icon_16[] =
110 #include "generated/etc/mpv-icon-8bit-16x16.png.inc"
111 ;
112
113 static const char x11_icon_32[] =
114 #include "generated/etc/mpv-icon-8bit-32x32.png.inc"
115 ;
116
117 static const char x11_icon_64[] =
118 #include "generated/etc/mpv-icon-8bit-64x64.png.inc"
119 ;
120
121 static const char x11_icon_128[] =
122 #include "generated/etc/mpv-icon-8bit-128x128.png.inc"
123 ;
124
125 #define ICON_ENTRY(var) { (char *)var, sizeof(var) }
126 static const struct bstr x11_icons[] = {
127 ICON_ENTRY(x11_icon_16),
128 ICON_ENTRY(x11_icon_32),
129 ICON_ENTRY(x11_icon_64),
130 ICON_ENTRY(x11_icon_128),
131 {0}
132 };
133
134 static struct mp_log *x11_error_output;
135 static atomic_int x11_error_silence;
136
137 static void vo_x11_update_geometry(struct vo *vo);
138 static void vo_x11_fullscreen(struct vo *vo);
139 static void xscreensaver_heartbeat(struct vo_x11_state *x11);
140 static void set_screensaver(struct vo_x11_state *x11, bool enabled);
141 static void vo_x11_selectinput_witherr(struct vo *vo, Display *display,
142 Window w, long event_mask);
143 static void vo_x11_setlayer(struct vo *vo, bool ontop);
144 static void vo_x11_xembed_handle_message(struct vo *vo, XClientMessageEvent *ce);
145 static void vo_x11_xembed_send_message(struct vo_x11_state *x11, long m[4]);
146 static void vo_x11_move_resize(struct vo *vo, bool move, bool resize,
147 struct mp_rect rc);
148 static void vo_x11_maximize(struct vo *vo);
149 static void vo_x11_minimize(struct vo *vo);
150
151 #define XA(x11, s) (XInternAtom((x11)->display, # s, False))
152 #define XAs(x11, s) XInternAtom((x11)->display, s, False)
153
154 #define RC_W(rc) ((rc).x1 - (rc).x0)
155 #define RC_H(rc) ((rc).y1 - (rc).y0)
156
x11_atom_name_buf(struct vo_x11_state * x11,Atom atom,char * buf,size_t buf_size)157 static char *x11_atom_name_buf(struct vo_x11_state *x11, Atom atom,
158 char *buf, size_t buf_size)
159 {
160 buf[0] = '\0';
161
162 char *new_name = XGetAtomName(x11->display, atom);
163 if (new_name) {
164 snprintf(buf, buf_size, "%s", new_name);
165 XFree(new_name);
166 }
167
168 return buf;
169 }
170
171 #define x11_atom_name(x11, atom) x11_atom_name_buf(x11, atom, (char[80]){0}, 80)
172
173 // format = 8 (unsigned char), 16 (short), 32 (long, even on LP64 systems)
174 // *out_nitems = returned number of items of requested format
x11_get_property(struct vo_x11_state * x11,Window w,Atom property,Atom type,int format,int * out_nitems)175 static void *x11_get_property(struct vo_x11_state *x11, Window w, Atom property,
176 Atom type, int format, int *out_nitems)
177 {
178 assert(format == 8 || format == 16 || format == 32);
179 *out_nitems = 0;
180 if (!w)
181 return NULL;
182 long max_len = 128 * 1024 * 1024; // static maximum limit
183 Atom ret_type = 0;
184 int ret_format = 0;
185 unsigned long ret_nitems = 0;
186 unsigned long ret_bytesleft = 0;
187 unsigned char *ret_prop = NULL;
188 if (XGetWindowProperty(x11->display, w, property, 0, max_len, False, type,
189 &ret_type, &ret_format, &ret_nitems, &ret_bytesleft,
190 &ret_prop) != Success)
191 return NULL;
192 if (ret_format != format || ret_nitems < 1 || ret_bytesleft) {
193 XFree(ret_prop);
194 ret_prop = NULL;
195 ret_nitems = 0;
196 }
197 *out_nitems = ret_nitems;
198 return ret_prop;
199 }
200
x11_get_property_copy(struct vo_x11_state * x11,Window w,Atom property,Atom type,int format,void * dst,size_t dst_size)201 static bool x11_get_property_copy(struct vo_x11_state *x11, Window w,
202 Atom property, Atom type, int format,
203 void *dst, size_t dst_size)
204 {
205 bool ret = false;
206 int len;
207 void *ptr = x11_get_property(x11, w, property, type, format, &len);
208 if (ptr) {
209 size_t ib = format == 32 ? sizeof(long) : format / 8;
210 if (dst_size <= len * ib) {
211 memcpy(dst, ptr, dst_size);
212 ret = true;
213 }
214 XFree(ptr);
215 }
216 return ret;
217 }
218
x11_send_ewmh_msg(struct vo_x11_state * x11,char * message_type,long params[5])219 static void x11_send_ewmh_msg(struct vo_x11_state *x11, char *message_type,
220 long params[5])
221 {
222 if (!x11->window)
223 return;
224
225 XEvent xev = {
226 .xclient = {
227 .type = ClientMessage,
228 .send_event = True,
229 .message_type = XInternAtom(x11->display, message_type, False),
230 .window = x11->window,
231 .format = 32,
232 },
233 };
234 for (int n = 0; n < 5; n++)
235 xev.xclient.data.l[n] = params[n];
236
237 if (!XSendEvent(x11->display, x11->rootwin, False,
238 SubstructureRedirectMask | SubstructureNotifyMask,
239 &xev))
240 MP_ERR(x11, "Couldn't send EWMH %s message!\n", message_type);
241 }
242
243 // change the _NET_WM_STATE hint. Remove or add the state according to "set".
x11_set_ewmh_state(struct vo_x11_state * x11,char * state,bool set)244 static void x11_set_ewmh_state(struct vo_x11_state *x11, char *state, bool set)
245 {
246 long params[5] = {
247 set ? NET_WM_STATE_ADD : NET_WM_STATE_REMOVE,
248 XInternAtom(x11->display, state, False),
249 0, // No second state
250 1, // source indication: normal
251 };
252 x11_send_ewmh_msg(x11, "_NET_WM_STATE", params);
253 }
254
vo_update_cursor(struct vo * vo)255 static void vo_update_cursor(struct vo *vo)
256 {
257 Cursor no_ptr;
258 Pixmap bm_no;
259 XColor black, dummy;
260 Colormap colormap;
261 const char bm_no_data[] = {0, 0, 0, 0, 0, 0, 0, 0};
262 struct vo_x11_state *x11 = vo->x11;
263 Display *disp = x11->display;
264 Window win = x11->window;
265 bool should_hide = x11->has_focus && !x11->mouse_cursor_visible;
266
267 if (should_hide == x11->mouse_cursor_set)
268 return;
269
270 x11->mouse_cursor_set = should_hide;
271
272 if (x11->parent == x11->rootwin || !win)
273 return; // do not hide if playing on the root window
274
275 if (x11->mouse_cursor_set) {
276 colormap = DefaultColormap(disp, DefaultScreen(disp));
277 if (!XAllocNamedColor(disp, colormap, "black", &black, &dummy))
278 return; // color alloc failed, give up
279 bm_no = XCreateBitmapFromData(disp, win, bm_no_data, 8, 8);
280 no_ptr = XCreatePixmapCursor(disp, bm_no, bm_no, &black, &black, 0, 0);
281 XDefineCursor(disp, win, no_ptr);
282 XFreeCursor(disp, no_ptr);
283 if (bm_no != None)
284 XFreePixmap(disp, bm_no);
285 XFreeColors(disp, colormap, &black.pixel, 1, 0);
286 } else {
287 XDefineCursor(x11->display, x11->window, 0);
288 }
289 }
290
x11_errorhandler(Display * display,XErrorEvent * event)291 static int x11_errorhandler(Display *display, XErrorEvent *event)
292 {
293 struct mp_log *log = x11_error_output;
294 if (!log)
295 return 0;
296
297 char msg[60];
298 XGetErrorText(display, event->error_code, (char *) &msg, sizeof(msg));
299
300 int lev = atomic_load(&x11_error_silence) ? MSGL_V : MSGL_ERR;
301 mp_msg(log, lev, "X11 error: %s\n", msg);
302 mp_msg(log, lev, "Type: %x, display: %p, resourceid: %lx, serial: %lx\n",
303 event->type, event->display, event->resourceid, event->serial);
304 mp_msg(log, lev, "Error code: %x, request code: %x, minor code: %x\n",
305 event->error_code, event->request_code, event->minor_code);
306
307 return 0;
308 }
309
vo_x11_silence_xlib(int dir)310 void vo_x11_silence_xlib(int dir)
311 {
312 atomic_fetch_add(&x11_error_silence, dir);
313 }
314
net_wm_support_state_test(struct vo_x11_state * x11,Atom atom)315 static int net_wm_support_state_test(struct vo_x11_state *x11, Atom atom)
316 {
317 #define NET_WM_STATE_TEST(x) { \
318 if (atom == XA(x11, _NET_WM_STATE_##x)) { \
319 MP_DBG(x11, "Detected wm supports " #x " state.\n" ); \
320 return vo_wm_##x; \
321 } \
322 }
323
324 NET_WM_STATE_TEST(FULLSCREEN);
325 NET_WM_STATE_TEST(ABOVE);
326 NET_WM_STATE_TEST(STAYS_ON_TOP);
327 NET_WM_STATE_TEST(BELOW);
328 return 0;
329 }
330
vo_wm_detect(struct vo * vo)331 static int vo_wm_detect(struct vo *vo)
332 {
333 struct vo_x11_state *x11 = vo->x11;
334 int i;
335 int wm = 0;
336 int nitems;
337 Atom *args = NULL;
338 Window win = x11->rootwin;
339
340 if (x11->parent)
341 return 0;
342
343 // -- supports layers
344 args = x11_get_property(x11, win, XA(x11, _WIN_PROTOCOLS), XA_ATOM, 32,
345 &nitems);
346 if (args) {
347 for (i = 0; i < nitems; i++) {
348 if (args[i] == XA(x11, _WIN_LAYER)) {
349 MP_DBG(x11, "Detected wm supports layers.\n");
350 wm |= vo_wm_LAYER;
351 }
352 }
353 XFree(args);
354 }
355 // --- netwm
356 args = x11_get_property(x11, win, XA(x11, _NET_SUPPORTED), XA_ATOM, 32,
357 &nitems);
358 if (args) {
359 MP_DBG(x11, "Detected wm supports NetWM.\n");
360 if (x11->opts->x11_netwm >= 0) {
361 for (i = 0; i < nitems; i++)
362 wm |= net_wm_support_state_test(vo->x11, args[i]);
363 } else {
364 MP_DBG(x11, "NetWM usage disabled by user.\n");
365 }
366 XFree(args);
367 }
368
369 if (wm == 0)
370 MP_DBG(x11, "Unknown wm type...\n");
371 if (x11->opts->x11_netwm > 0 && !(wm & vo_wm_FULLSCREEN)) {
372 MP_WARN(x11, "Forcing NetWM FULLSCREEN support.\n");
373 wm |= vo_wm_FULLSCREEN;
374 }
375 return wm;
376 }
377
xrandr_read(struct vo_x11_state * x11)378 static void xrandr_read(struct vo_x11_state *x11)
379 {
380 for(int i = 0; i < x11->num_displays; i++)
381 talloc_free(x11->displays[i].name);
382
383 x11->num_displays = 0;
384
385 if (x11->xrandr_event < 0) {
386 int event_base, error_base;
387 if (!XRRQueryExtension(x11->display, &event_base, &error_base)) {
388 MP_VERBOSE(x11, "Couldn't init Xrandr.\n");
389 return;
390 }
391 x11->xrandr_event = event_base + RRNotify;
392 XRRSelectInput(x11->display, x11->rootwin, RRScreenChangeNotifyMask |
393 RRCrtcChangeNotifyMask | RROutputChangeNotifyMask);
394 }
395
396 XRRScreenResources *r = XRRGetScreenResourcesCurrent(x11->display, x11->rootwin);
397 if (!r) {
398 MP_VERBOSE(x11, "Xrandr doesn't work.\n");
399 return;
400 }
401
402 int primary_id = -1;
403 RROutput primary = XRRGetOutputPrimary(x11->display, x11->rootwin);
404 for (int o = 0; o < r->noutput; o++) {
405 RROutput output = r->outputs[o];
406 XRRCrtcInfo *crtc = NULL;
407 XRROutputInfo *out = XRRGetOutputInfo(x11->display, r, output);
408 if (!out || !out->crtc)
409 goto next;
410 crtc = XRRGetCrtcInfo(x11->display, r, out->crtc);
411 if (!crtc)
412 goto next;
413 for (int om = 0; om < out->nmode; om++) {
414 RRMode xm = out->modes[om];
415 for (int n = 0; n < r->nmode; n++) {
416 XRRModeInfo m = r->modes[n];
417 if (m.id != xm || crtc->mode != xm)
418 continue;
419 if (x11->num_displays >= MAX_DISPLAYS)
420 continue;
421 double vTotal = m.vTotal;
422 if (m.modeFlags & RR_DoubleScan)
423 vTotal *= 2;
424 if (m.modeFlags & RR_Interlace)
425 vTotal /= 2;
426 struct xrandr_display d = {
427 .rc = { crtc->x, crtc->y,
428 crtc->x + crtc->width, crtc->y + crtc->height },
429 .fps = m.dotClock / (m.hTotal * vTotal),
430 .name = talloc_strdup(x11, out->name),
431 };
432 int num = x11->num_displays++;
433 MP_VERBOSE(x11, "Display %d (%s): [%d, %d, %d, %d] @ %f FPS\n",
434 num, d.name, d.rc.x0, d.rc.y0, d.rc.x1, d.rc.y1, d.fps);
435 x11->displays[num] = d;
436 if (output == primary)
437 primary_id = num;
438 }
439 }
440 next:
441 if (crtc)
442 XRRFreeCrtcInfo(crtc);
443 if (out)
444 XRRFreeOutputInfo(out);
445 }
446
447 for (int i = 0; i < x11->num_displays; i++) {
448 struct xrandr_display *d = &(x11->displays[i]);
449
450 if (i == primary_id) {
451 d->atom_id = 0;
452 continue;
453 }
454 if (primary_id > 0 && i < primary_id) {
455 d->atom_id = i+1;
456 continue;
457 }
458 d->atom_id = i;
459 }
460
461 XRRFreeScreenResources(r);
462 }
463
vo_x11_update_screeninfo(struct vo * vo)464 static void vo_x11_update_screeninfo(struct vo *vo)
465 {
466 struct vo_x11_state *x11 = vo->x11;
467 struct mp_vo_opts *opts = x11->opts;
468 bool all_screens = opts->fullscreen && opts->fsscreen_id == -2;
469 x11->screenrc = (struct mp_rect){.x1 = x11->ws_width, .y1 = x11->ws_height};
470 if ((opts->screen_id >= -1 || opts->screen_name) && XineramaIsActive(x11->display) &&
471 !all_screens)
472 {
473 int screen = opts->fullscreen ? opts->fsscreen_id : opts->screen_id;
474 XineramaScreenInfo *screens;
475 int num_screens;
476
477 if (opts->fullscreen && opts->fsscreen_id == -1)
478 screen = opts->screen_id;
479
480 if (screen == -1 && (opts->fsscreen_name || opts->screen_name)) {
481 char *screen_name = opts->fullscreen ? opts->fsscreen_name : opts->screen_name;
482 if (screen_name) {
483 bool screen_found = false;
484 for (int n = 0; n < x11->num_displays; n++) {
485 char *display_name = x11->displays[n].name;
486 if (!strcmp(display_name, screen_name)) {
487 screen = n;
488 screen_found = true;
489 break;
490 }
491 }
492 if (!screen_found)
493 MP_WARN(x11, "Screen name %s not found!\n", screen_name);
494 }
495 }
496
497 screens = XineramaQueryScreens(x11->display, &num_screens);
498 if (screen >= num_screens)
499 screen = num_screens - 1;
500 if (screen == -1) {
501 int x = x11->winrc.x0 + RC_W(x11->winrc) / 2;
502 int y = x11->winrc.y0 + RC_H(x11->winrc) / 2;
503 for (screen = num_screens - 1; screen > 0; screen--) {
504 int left = screens[screen].x_org;
505 int right = left + screens[screen].width;
506 int top = screens[screen].y_org;
507 int bottom = top + screens[screen].height;
508 if (left <= x && x <= right && top <= y && y <= bottom)
509 break;
510 }
511 }
512 if (screen < 0)
513 screen = 0;
514 x11->screenrc = (struct mp_rect){
515 .x0 = screens[screen].x_org,
516 .y0 = screens[screen].y_org,
517 .x1 = screens[screen].x_org + screens[screen].width,
518 .y1 = screens[screen].y_org + screens[screen].height,
519 };
520
521 XFree(screens);
522 }
523 }
524
525 // Get the monitors for the 4 edges of the rectangle spanning all screens.
vo_x11_get_bounding_monitors(struct vo_x11_state * x11,long b[4])526 static void vo_x11_get_bounding_monitors(struct vo_x11_state *x11, long b[4])
527 {
528 //top bottom left right
529 b[0] = b[1] = b[2] = b[3] = 0;
530 int num_screens = 0;
531 XineramaScreenInfo *screens = XineramaQueryScreens(x11->display, &num_screens);
532 if (!screens)
533 return;
534 for (int n = 0; n < num_screens; n++) {
535 XineramaScreenInfo *s = &screens[n];
536 if (s->y_org < screens[b[0]].y_org)
537 b[0] = n;
538 if (s->y_org + s->height > screens[b[1]].y_org + screens[b[1]].height)
539 b[1] = n;
540 if (s->x_org < screens[b[2]].x_org)
541 b[2] = n;
542 if (s->x_org + s->width > screens[b[3]].x_org + screens[b[3]].width)
543 b[3] = n;
544 }
545 XFree(screens);
546 }
547
vo_x11_init(struct vo * vo)548 int vo_x11_init(struct vo *vo)
549 {
550 char *dispName;
551
552 assert(!vo->x11);
553
554 XInitThreads();
555
556 struct vo_x11_state *x11 = talloc_ptrtype(NULL, x11);
557 *x11 = (struct vo_x11_state){
558 .log = mp_log_new(x11, vo->log, "x11"),
559 .input_ctx = vo->input_ctx,
560 .screensaver_enabled = true,
561 .xrandr_event = -1,
562 .wakeup_pipe = {-1, -1},
563 .dpi_scale = 1,
564 .opts_cache = m_config_cache_alloc(x11, vo->global, &vo_sub_opts),
565 };
566 x11->opts = x11->opts_cache->opts;
567 vo->x11 = x11;
568
569 x11_error_output = x11->log;
570 XSetErrorHandler(x11_errorhandler);
571
572 dispName = XDisplayName(NULL);
573
574 MP_VERBOSE(x11, "X11 opening display: %s\n", dispName);
575
576 x11->display = XOpenDisplay(dispName);
577 if (!x11->display) {
578 MP_MSG(x11, vo->probing ? MSGL_V : MSGL_ERR,
579 "couldn't open the X11 display (%s)!\n", dispName);
580 goto error;
581 }
582 x11->screen = DefaultScreen(x11->display); // screen ID
583 x11->rootwin = RootWindow(x11->display, x11->screen); // root window ID
584
585 if (x11->opts->WinID >= 0)
586 x11->parent = x11->opts->WinID ? x11->opts->WinID : x11->rootwin;
587
588 if (!x11->opts->native_keyrepeat) {
589 Bool ok = False;
590 XkbSetDetectableAutoRepeat(x11->display, True, &ok);
591 x11->no_autorepeat = ok;
592 }
593
594 x11->xim = XOpenIM(x11->display, NULL, NULL, NULL);
595 if (!x11->xim)
596 MP_WARN(x11, "XOpenIM() failed. Unicode input will not work.\n");
597
598 x11->ws_width = DisplayWidth(x11->display, x11->screen);
599 x11->ws_height = DisplayHeight(x11->display, x11->screen);
600
601 if (strncmp(dispName, "unix:", 5) == 0)
602 dispName += 4;
603 else if (strncmp(dispName, "localhost:", 10) == 0)
604 dispName += 9;
605 x11->display_is_local = dispName[0] == ':' &&
606 strtoul(dispName + 1, NULL, 10) < 10;
607 MP_DBG(x11, "X11 running at %dx%d (\"%s\" => %s display)\n",
608 x11->ws_width, x11->ws_height, dispName,
609 x11->display_is_local ? "local" : "remote");
610
611 int w_mm = DisplayWidthMM(x11->display, x11->screen);
612 int h_mm = DisplayHeightMM(x11->display, x11->screen);
613 double dpi_x = x11->ws_width * 25.4 / w_mm;
614 double dpi_y = x11->ws_height * 25.4 / h_mm;
615 double base_dpi = 96;
616 if (isfinite(dpi_x) && isfinite(dpi_y) && x11->opts->hidpi_window_scale) {
617 int s_x = lrint(MPCLAMP(dpi_x / base_dpi, 0, 10));
618 int s_y = lrint(MPCLAMP(dpi_y / base_dpi, 0, 10));
619 if (s_x == s_y && s_x > 1 && s_x < 10) {
620 x11->dpi_scale = s_x;
621 MP_VERBOSE(x11, "Assuming DPI scale %d for prescaling. This can "
622 "be disabled with --hidpi-window-scale=no.\n",
623 x11->dpi_scale);
624 }
625 }
626
627 x11->wm_type = vo_wm_detect(vo);
628
629 x11->event_fd = ConnectionNumber(x11->display);
630 mp_make_wakeup_pipe(x11->wakeup_pipe);
631
632 xrandr_read(x11);
633
634 vo_x11_update_geometry(vo);
635
636 return 1;
637
638 error:
639 vo_x11_uninit(vo);
640 return 0;
641 }
642
643 static const struct mp_keymap keymap[] = {
644 // special keys
645 {XK_Pause, MP_KEY_PAUSE}, {XK_Escape, MP_KEY_ESC},
646 {XK_BackSpace, MP_KEY_BS}, {XK_Tab, MP_KEY_TAB}, {XK_Return, MP_KEY_ENTER},
647 {XK_Menu, MP_KEY_MENU}, {XK_Print, MP_KEY_PRINT},
648 {XK_Cancel, MP_KEY_CANCEL}, {XK_ISO_Left_Tab, MP_KEY_TAB},
649
650 // cursor keys
651 {XK_Left, MP_KEY_LEFT}, {XK_Right, MP_KEY_RIGHT}, {XK_Up, MP_KEY_UP},
652 {XK_Down, MP_KEY_DOWN},
653
654 // navigation block
655 {XK_Insert, MP_KEY_INSERT}, {XK_Delete, MP_KEY_DELETE},
656 {XK_Home, MP_KEY_HOME}, {XK_End, MP_KEY_END}, {XK_Page_Up, MP_KEY_PAGE_UP},
657 {XK_Page_Down, MP_KEY_PAGE_DOWN},
658
659 // F-keys
660 {XK_F1, MP_KEY_F+1}, {XK_F2, MP_KEY_F+2}, {XK_F3, MP_KEY_F+3},
661 {XK_F4, MP_KEY_F+4}, {XK_F5, MP_KEY_F+5}, {XK_F6, MP_KEY_F+6},
662 {XK_F7, MP_KEY_F+7}, {XK_F8, MP_KEY_F+8}, {XK_F9, MP_KEY_F+9},
663 {XK_F10, MP_KEY_F+10}, {XK_F11, MP_KEY_F+11}, {XK_F12, MP_KEY_F+12},
664
665 // numpad independent of numlock
666 {XK_KP_Subtract, '-'}, {XK_KP_Add, '+'}, {XK_KP_Multiply, '*'},
667 {XK_KP_Divide, '/'}, {XK_KP_Enter, MP_KEY_KPENTER},
668
669 // numpad with numlock
670 {XK_KP_0, MP_KEY_KP0}, {XK_KP_1, MP_KEY_KP1}, {XK_KP_2, MP_KEY_KP2},
671 {XK_KP_3, MP_KEY_KP3}, {XK_KP_4, MP_KEY_KP4}, {XK_KP_5, MP_KEY_KP5},
672 {XK_KP_6, MP_KEY_KP6}, {XK_KP_7, MP_KEY_KP7}, {XK_KP_8, MP_KEY_KP8},
673 {XK_KP_9, MP_KEY_KP9}, {XK_KP_Decimal, MP_KEY_KPDEC},
674 {XK_KP_Separator, MP_KEY_KPDEC},
675
676 // numpad without numlock
677 {XK_KP_Insert, MP_KEY_KPINS}, {XK_KP_End, MP_KEY_KP1},
678 {XK_KP_Down, MP_KEY_KP2}, {XK_KP_Page_Down, MP_KEY_KP3},
679 {XK_KP_Left, MP_KEY_KP4}, {XK_KP_Begin, MP_KEY_KP5},
680 {XK_KP_Right, MP_KEY_KP6}, {XK_KP_Home, MP_KEY_KP7}, {XK_KP_Up, MP_KEY_KP8},
681 {XK_KP_Page_Up, MP_KEY_KP9}, {XK_KP_Delete, MP_KEY_KPDEL},
682
683 {XF86XK_MenuKB, MP_KEY_MENU},
684 {XF86XK_AudioPlay, MP_KEY_PLAY}, {XF86XK_AudioPause, MP_KEY_PAUSE},
685 {XF86XK_AudioStop, MP_KEY_STOP},
686 {XF86XK_AudioPrev, MP_KEY_PREV}, {XF86XK_AudioNext, MP_KEY_NEXT},
687 {XF86XK_AudioRewind, MP_KEY_REWIND}, {XF86XK_AudioForward, MP_KEY_FORWARD},
688 {XF86XK_AudioMute, MP_KEY_MUTE},
689 {XF86XK_AudioLowerVolume, MP_KEY_VOLUME_DOWN},
690 {XF86XK_AudioRaiseVolume, MP_KEY_VOLUME_UP},
691 {XF86XK_HomePage, MP_KEY_HOMEPAGE}, {XF86XK_WWW, MP_KEY_WWW},
692 {XF86XK_Mail, MP_KEY_MAIL}, {XF86XK_Favorites, MP_KEY_FAVORITES},
693 {XF86XK_Search, MP_KEY_SEARCH}, {XF86XK_Sleep, MP_KEY_SLEEP},
694
695 {0, 0}
696 };
697
vo_x11_lookupkey(int key)698 static int vo_x11_lookupkey(int key)
699 {
700 const char *passthrough_keys = " -+*/<>`~!@#$%^&()_{}:;\"\',.?\\|=[]";
701 int mpkey = 0;
702 if ((key >= 'a' && key <= 'z') ||
703 (key >= 'A' && key <= 'Z') ||
704 (key >= '0' && key <= '9') ||
705 (key > 0 && key < 256 && strchr(passthrough_keys, key)))
706 mpkey = key;
707
708 if (!mpkey)
709 mpkey = lookup_keymap_table(keymap, key);
710
711 // XFree86 keysym range; typically contains obscure "extra" keys
712 if (!mpkey && key >= 0x10080001 && key <= 0x1008FFFF) {
713 mpkey = MP_KEY_UNKNOWN_RESERVED_START + (key - 0x10080000);
714 if (mpkey > MP_KEY_UNKNOWN_RESERVED_LAST)
715 mpkey = 0;
716 }
717
718 return mpkey;
719 }
720
vo_x11_decoration(struct vo * vo,bool d)721 static void vo_x11_decoration(struct vo *vo, bool d)
722 {
723 struct vo_x11_state *x11 = vo->x11;
724
725 if (x11->parent || !x11->window)
726 return;
727
728 Atom motif_hints = XA(x11, _MOTIF_WM_HINTS);
729 MotifWmHints mhints = {0};
730 bool got = x11_get_property_copy(x11, x11->window, motif_hints,
731 motif_hints, 32, &mhints, sizeof(mhints));
732 // hints weren't set, and decorations requested -> assume WM displays them
733 if (!got && d)
734 return;
735 if (!got) {
736 mhints.flags = MWM_HINTS_FUNCTIONS;
737 mhints.functions = MWM_FUNC_MOVE | MWM_FUNC_CLOSE | MWM_FUNC_MINIMIZE |
738 MWM_FUNC_MAXIMIZE | MWM_FUNC_RESIZE;
739 }
740 mhints.flags |= MWM_HINTS_DECORATIONS;
741 mhints.decorations = d ? MWM_DECOR_ALL : 0;
742 XChangeProperty(x11->display, x11->window, motif_hints, motif_hints, 32,
743 PropModeReplace, (unsigned char *) &mhints, 5);
744 }
745
vo_x11_wm_hints(struct vo * vo,Window window)746 static void vo_x11_wm_hints(struct vo *vo, Window window)
747 {
748 struct vo_x11_state *x11 = vo->x11;
749 XWMHints hints = {0};
750 hints.flags = InputHint | StateHint;
751 hints.input = 1;
752 hints.initial_state = NormalState;
753 XSetWMHints(x11->display, window, &hints);
754 }
755
vo_x11_classhint(struct vo * vo,Window window,const char * name)756 static void vo_x11_classhint(struct vo *vo, Window window, const char *name)
757 {
758 struct vo_x11_state *x11 = vo->x11;
759 struct mp_vo_opts *opts = x11->opts;
760 XClassHint wmClass;
761 long pid = getpid();
762
763 wmClass.res_name = opts->winname ? opts->winname : (char *)name;
764 wmClass.res_class = "mpv";
765 XSetClassHint(x11->display, window, &wmClass);
766 XChangeProperty(x11->display, window, XA(x11, _NET_WM_PID), XA_CARDINAL,
767 32, PropModeReplace, (unsigned char *) &pid, 1);
768 }
769
vo_x11_uninit(struct vo * vo)770 void vo_x11_uninit(struct vo *vo)
771 {
772 struct vo_x11_state *x11 = vo->x11;
773 if (!x11)
774 return;
775
776 mp_input_put_key(x11->input_ctx, MP_INPUT_RELEASE_ALL);
777
778 set_screensaver(x11, true);
779
780 if (x11->window != None && x11->window != x11->rootwin) {
781 XUnmapWindow(x11->display, x11->window);
782 XDestroyWindow(x11->display, x11->window);
783 }
784 if (x11->xic)
785 XDestroyIC(x11->xic);
786 if (x11->colormap != None)
787 XFreeColormap(vo->x11->display, x11->colormap);
788
789 MP_DBG(x11, "uninit ...\n");
790 if (x11->xim)
791 XCloseIM(x11->xim);
792 if (x11->display) {
793 XSetErrorHandler(NULL);
794 x11_error_output = NULL;
795 XCloseDisplay(x11->display);
796 }
797
798 if (x11->wakeup_pipe[0] >= 0) {
799 close(x11->wakeup_pipe[0]);
800 close(x11->wakeup_pipe[1]);
801 }
802
803 talloc_free(x11);
804 vo->x11 = NULL;
805 }
806
807 #define DND_PROPERTY "mpv_dnd_selection"
808
vo_x11_dnd_init_window(struct vo * vo)809 static void vo_x11_dnd_init_window(struct vo *vo)
810 {
811 struct vo_x11_state *x11 = vo->x11;
812
813 Atom version = DND_VERSION;
814 XChangeProperty(x11->display, x11->window, XA(x11, XdndAware), XA_ATOM,
815 32, PropModeReplace, (unsigned char *)&version, 1);
816 }
817
818 // The Atom does not always map to a mime type, but often.
x11_dnd_mime_type_buf(struct vo_x11_state * x11,Atom atom,char * buf,size_t buf_size)819 static char *x11_dnd_mime_type_buf(struct vo_x11_state *x11, Atom atom,
820 char *buf, size_t buf_size)
821 {
822 if (atom == XInternAtom(x11->display, "UTF8_STRING", False))
823 return "text";
824 return x11_atom_name_buf(x11, atom, buf, buf_size);
825 }
826
827 #define x11_dnd_mime_type(x11, atom) \
828 x11_dnd_mime_type_buf(x11, atom, (char[80]){0}, 80)
829
dnd_format_is_better(struct vo_x11_state * x11,Atom cur,Atom new)830 static bool dnd_format_is_better(struct vo_x11_state *x11, Atom cur, Atom new)
831 {
832 int new_score = mp_event_get_mime_type_score(x11->input_ctx,
833 x11_dnd_mime_type(x11, new));
834 int cur_score = -1;
835 if (cur) {
836 cur_score = mp_event_get_mime_type_score(x11->input_ctx,
837 x11_dnd_mime_type(x11, cur));
838 }
839 return new_score >= 0 && new_score > cur_score;
840 }
841
dnd_select_format(struct vo_x11_state * x11,Atom * args,int items)842 static void dnd_select_format(struct vo_x11_state *x11, Atom *args, int items)
843 {
844 x11->dnd_requested_format = 0;
845
846 for (int n = 0; n < items; n++) {
847 MP_VERBOSE(x11, "DnD type: '%s'\n", x11_atom_name(x11, args[n]));
848 // There are other types; possibly not worth supporting.
849 if (dnd_format_is_better(x11, x11->dnd_requested_format, args[n]))
850 x11->dnd_requested_format = args[n];
851 }
852
853 MP_VERBOSE(x11, "Selected DnD type: %s\n", x11->dnd_requested_format ?
854 x11_atom_name(x11, x11->dnd_requested_format) : "(none)");
855 }
856
dnd_reset(struct vo * vo)857 static void dnd_reset(struct vo *vo)
858 {
859 struct vo_x11_state *x11 = vo->x11;
860
861 x11->dnd_src_window = 0;
862 x11->dnd_requested_format = 0;
863 }
864
vo_x11_dnd_handle_message(struct vo * vo,XClientMessageEvent * ce)865 static void vo_x11_dnd_handle_message(struct vo *vo, XClientMessageEvent *ce)
866 {
867 struct vo_x11_state *x11 = vo->x11;
868
869 if (!x11->window)
870 return;
871
872 if (ce->message_type == XA(x11, XdndEnter)) {
873 x11->dnd_requested_format = 0;
874
875 Window src = ce->data.l[0];
876 if (ce->data.l[1] & 1) {
877 int nitems;
878 Atom *args = x11_get_property(x11, src, XA(x11, XdndTypeList),
879 XA_ATOM, 32, &nitems);
880 if (args) {
881 dnd_select_format(x11, args, nitems);
882 XFree(args);
883 }
884 } else {
885 Atom args[3];
886 for (int n = 2; n <= 4; n++)
887 args[n - 2] = ce->data.l[n];
888 dnd_select_format(x11, args, 3);
889 }
890 } else if (ce->message_type == XA(x11, XdndPosition)) {
891 x11->dnd_requested_action = ce->data.l[4];
892
893 Window src = ce->data.l[0];
894 XEvent xev;
895
896 xev.xclient.type = ClientMessage;
897 xev.xclient.serial = 0;
898 xev.xclient.send_event = True;
899 xev.xclient.message_type = XA(x11, XdndStatus);
900 xev.xclient.window = src;
901 xev.xclient.format = 32;
902 xev.xclient.data.l[0] = x11->window;
903 xev.xclient.data.l[1] = x11->dnd_requested_format ? 1 : 0;
904 xev.xclient.data.l[2] = 0;
905 xev.xclient.data.l[3] = 0;
906 xev.xclient.data.l[4] = XA(x11, XdndActionCopy);
907
908 XSendEvent(x11->display, src, False, 0, &xev);
909 } else if (ce->message_type == XA(x11, XdndDrop)) {
910 x11->dnd_src_window = ce->data.l[0];
911 XConvertSelection(x11->display, XA(x11, XdndSelection),
912 x11->dnd_requested_format, XAs(x11, DND_PROPERTY),
913 x11->window, ce->data.l[2]);
914 } else if (ce->message_type == XA(x11, XdndLeave)) {
915 dnd_reset(vo);
916 }
917 }
918
vo_x11_dnd_handle_selection(struct vo * vo,XSelectionEvent * se)919 static void vo_x11_dnd_handle_selection(struct vo *vo, XSelectionEvent *se)
920 {
921 struct vo_x11_state *x11 = vo->x11;
922
923 if (!x11->window || !x11->dnd_src_window)
924 return;
925
926 bool success = false;
927
928 if (se->selection == XA(x11, XdndSelection) &&
929 se->property == XAs(x11, DND_PROPERTY) &&
930 se->target == x11->dnd_requested_format)
931 {
932 int nitems;
933 void *prop = x11_get_property(x11, x11->window, XAs(x11, DND_PROPERTY),
934 x11->dnd_requested_format, 8, &nitems);
935 if (prop) {
936 enum mp_dnd_action action =
937 x11->dnd_requested_action == XA(x11, XdndActionCopy) ?
938 DND_REPLACE : DND_APPEND;
939
940 char *mime_type = x11_dnd_mime_type(x11, x11->dnd_requested_format);
941 MP_VERBOSE(x11, "Dropping type: %s (%s)\n",
942 x11_atom_name(x11, x11->dnd_requested_format), mime_type);
943
944 // No idea if this is guaranteed to be \0-padded, so use bstr.
945 success = mp_event_drop_mime_data(x11->input_ctx, mime_type,
946 (bstr){prop, nitems}, action) > 0;
947 XFree(prop);
948 }
949 }
950
951 XEvent xev;
952
953 xev.xclient.type = ClientMessage;
954 xev.xclient.serial = 0;
955 xev.xclient.send_event = True;
956 xev.xclient.message_type = XA(x11, XdndFinished);
957 xev.xclient.window = x11->dnd_src_window;
958 xev.xclient.format = 32;
959 xev.xclient.data.l[0] = x11->window;
960 xev.xclient.data.l[1] = success ? 1 : 0;
961 xev.xclient.data.l[2] = success ? XA(x11, XdndActionCopy) : 0;
962 xev.xclient.data.l[3] = 0;
963 xev.xclient.data.l[4] = 0;
964
965 XSendEvent(x11->display, x11->dnd_src_window, False, 0, &xev);
966
967 dnd_reset(vo);
968 }
969
update_vo_size(struct vo * vo)970 static void update_vo_size(struct vo *vo)
971 {
972 struct vo_x11_state *x11 = vo->x11;
973
974 if (RC_W(x11->winrc) != vo->dwidth || RC_H(x11->winrc) != vo->dheight) {
975 vo->dwidth = RC_W(x11->winrc);
976 vo->dheight = RC_H(x11->winrc);
977 x11->pending_vo_events |= VO_EVENT_RESIZE;
978 }
979 }
980
get_mods(unsigned int state)981 static int get_mods(unsigned int state)
982 {
983 int modifiers = 0;
984 if (state & ShiftMask)
985 modifiers |= MP_KEY_MODIFIER_SHIFT;
986 if (state & ControlMask)
987 modifiers |= MP_KEY_MODIFIER_CTRL;
988 if (state & Mod1Mask)
989 modifiers |= MP_KEY_MODIFIER_ALT;
990 if (state & Mod4Mask)
991 modifiers |= MP_KEY_MODIFIER_META;
992 return modifiers;
993 }
994
vo_x11_update_composition_hint(struct vo * vo)995 static void vo_x11_update_composition_hint(struct vo *vo)
996 {
997 struct vo_x11_state *x11 = vo->x11;
998
999 long hint = 0;
1000 switch (x11->opts->x11_bypass_compositor) {
1001 case 0: hint = 0; break; // leave default
1002 case 1: hint = 1; break; // always bypass
1003 case 2: hint = x11->fs ? 1 : 0; break; // bypass in FS
1004 case 3: hint = 2; break; // always enable
1005 }
1006
1007 XChangeProperty(x11->display, x11->window, XA(x11,_NET_WM_BYPASS_COMPOSITOR),
1008 XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&hint, 1);
1009 }
1010
vo_x11_check_net_wm_state_change(struct vo * vo)1011 static void vo_x11_check_net_wm_state_change(struct vo *vo)
1012 {
1013 struct vo_x11_state *x11 = vo->x11;
1014 struct mp_vo_opts *opts = x11->opts;
1015
1016 if (x11->parent)
1017 return;
1018
1019 if (x11->wm_type & vo_wm_FULLSCREEN) {
1020 int num_elems;
1021 long *elems = x11_get_property(x11, x11->window, XA(x11, _NET_WM_STATE),
1022 XA_ATOM, 32, &num_elems);
1023 int is_fullscreen = 0, is_minimized = 0, is_maximized = 0;
1024 if (elems) {
1025 Atom fullscreen_prop = XA(x11, _NET_WM_STATE_FULLSCREEN);
1026 Atom hidden = XA(x11, _NET_WM_STATE_HIDDEN);
1027 Atom max_vert = XA(x11, _NET_WM_STATE_MAXIMIZED_VERT);
1028 Atom max_horiz = XA(x11, _NET_WM_STATE_MAXIMIZED_HORZ);
1029 for (int n = 0; n < num_elems; n++) {
1030 if (elems[n] == fullscreen_prop)
1031 is_fullscreen = 1;
1032 if (elems[n] == hidden)
1033 is_minimized = 1;
1034 if (elems[n] == max_vert || elems[n] == max_horiz)
1035 is_maximized = 1;
1036 }
1037 XFree(elems);
1038 }
1039
1040 if (opts->window_maximized && !is_maximized && x11->pending_geometry_change) {
1041 vo_x11_config_vo_window(vo);
1042 x11->pending_geometry_change = false;
1043 }
1044
1045 opts->window_minimized = is_minimized;
1046 m_config_cache_write_opt(x11->opts_cache, &opts->window_minimized);
1047 opts->window_maximized = is_maximized;
1048 m_config_cache_write_opt(x11->opts_cache, &opts->window_maximized);
1049
1050 if ((x11->opts->fullscreen && !is_fullscreen) ||
1051 (!x11->opts->fullscreen && is_fullscreen))
1052 {
1053 x11->opts->fullscreen = is_fullscreen;
1054 x11->fs = is_fullscreen;
1055 m_config_cache_write_opt(x11->opts_cache, &x11->opts->fullscreen);
1056
1057 if (!is_fullscreen && (x11->pos_changed_during_fs ||
1058 x11->size_changed_during_fs))
1059 {
1060 vo_x11_move_resize(vo, x11->pos_changed_during_fs,
1061 x11->size_changed_during_fs,
1062 x11->nofsrc);
1063 }
1064
1065 x11->size_changed_during_fs = false;
1066 x11->pos_changed_during_fs = false;
1067
1068 vo_x11_update_composition_hint(vo);
1069 }
1070 }
1071 }
1072
vo_x11_check_net_wm_desktop_change(struct vo * vo)1073 static void vo_x11_check_net_wm_desktop_change(struct vo *vo)
1074 {
1075 struct vo_x11_state *x11 = vo->x11;
1076
1077 if (x11->parent)
1078 return;
1079
1080 long params[1] = {0};
1081 if (x11_get_property_copy(x11, x11->window, XA(x11, _NET_WM_DESKTOP),
1082 XA_CARDINAL, 32, params, sizeof(params)))
1083 {
1084 x11->opts->all_workspaces = params[0] == -1; // (gets sign-extended?)
1085 m_config_cache_write_opt(x11->opts_cache, &x11->opts->all_workspaces);
1086 }
1087 }
1088
1089 // Releasing all keys on key-up or defocus is simpler and ensures no keys can
1090 // get "stuck".
release_all_keys(struct vo * vo)1091 static void release_all_keys(struct vo *vo)
1092 {
1093 struct vo_x11_state *x11 = vo->x11;
1094
1095 if (x11->no_autorepeat)
1096 mp_input_put_key(x11->input_ctx, MP_INPUT_RELEASE_ALL);
1097 x11->win_drag_button1_down = false;
1098 }
1099
vo_x11_check_events(struct vo * vo)1100 void vo_x11_check_events(struct vo *vo)
1101 {
1102 struct vo_x11_state *x11 = vo->x11;
1103 Display *display = vo->x11->display;
1104 XEvent Event;
1105
1106 xscreensaver_heartbeat(vo->x11);
1107
1108 while (XPending(display)) {
1109 XNextEvent(display, &Event);
1110 MP_TRACE(x11, "XEvent: %d\n", Event.type);
1111 switch (Event.type) {
1112 case Expose:
1113 x11->pending_vo_events |= VO_EVENT_EXPOSE;
1114 break;
1115 case ConfigureNotify:
1116 if (x11->window == None)
1117 break;
1118 vo_x11_update_geometry(vo);
1119 if (x11->parent && Event.xconfigure.window == x11->parent) {
1120 MP_TRACE(x11, "adjusting embedded window position\n");
1121 XMoveResizeWindow(x11->display, x11->window,
1122 0, 0, RC_W(x11->winrc), RC_H(x11->winrc));
1123 }
1124 break;
1125 case KeyPress: {
1126 char buf[100];
1127 KeySym keySym = 0;
1128 int modifiers = get_mods(Event.xkey.state);
1129 if (x11->no_autorepeat)
1130 modifiers |= MP_KEY_STATE_DOWN;
1131 if (x11->xic) {
1132 Status status;
1133 int len = Xutf8LookupString(x11->xic, &Event.xkey, buf,
1134 sizeof(buf), &keySym, &status);
1135 int mpkey = vo_x11_lookupkey(keySym);
1136 if (mpkey) {
1137 mp_input_put_key(x11->input_ctx, mpkey | modifiers);
1138 } else if (status == XLookupChars || status == XLookupBoth) {
1139 struct bstr t = { buf, len };
1140 mp_input_put_key_utf8(x11->input_ctx, modifiers, t);
1141 }
1142 } else {
1143 XLookupString(&Event.xkey, buf, sizeof(buf), &keySym,
1144 &x11->compose_status);
1145 int mpkey = vo_x11_lookupkey(keySym);
1146 if (mpkey)
1147 mp_input_put_key(x11->input_ctx, mpkey | modifiers);
1148 }
1149 break;
1150 }
1151 case FocusIn:
1152 x11->has_focus = true;
1153 vo_update_cursor(vo);
1154 x11->pending_vo_events |= VO_EVENT_FOCUS;
1155 break;
1156 case FocusOut:
1157 release_all_keys(vo);
1158 x11->has_focus = false;
1159 vo_update_cursor(vo);
1160 x11->pending_vo_events |= VO_EVENT_FOCUS;
1161 break;
1162 case KeyRelease:
1163 release_all_keys(vo);
1164 break;
1165 case MotionNotify:
1166 if (x11->win_drag_button1_down && !x11->fs &&
1167 !mp_input_test_dragging(x11->input_ctx, Event.xmotion.x,
1168 Event.xmotion.y))
1169 {
1170 mp_input_put_key(x11->input_ctx, MP_INPUT_RELEASE_ALL);
1171 XUngrabPointer(x11->display, CurrentTime);
1172
1173 long params[5] = {
1174 Event.xmotion.x_root, Event.xmotion.y_root,
1175 8, // _NET_WM_MOVERESIZE_MOVE
1176 1, // button 1
1177 1, // source indication: normal
1178 };
1179 x11_send_ewmh_msg(x11, "_NET_WM_MOVERESIZE", params);
1180 } else {
1181 mp_input_set_mouse_pos(x11->input_ctx, Event.xmotion.x,
1182 Event.xmotion.y);
1183 }
1184 x11->win_drag_button1_down = false;
1185 break;
1186 case LeaveNotify:
1187 if (Event.xcrossing.mode != NotifyNormal)
1188 break;
1189 x11->win_drag_button1_down = false;
1190 mp_input_put_key(x11->input_ctx, MP_KEY_MOUSE_LEAVE);
1191 break;
1192 case EnterNotify:
1193 if (Event.xcrossing.mode != NotifyNormal)
1194 break;
1195 mp_input_put_key(x11->input_ctx, MP_KEY_MOUSE_ENTER);
1196 break;
1197 case ButtonPress:
1198 if (Event.xbutton.button - 1 >= MP_KEY_MOUSE_BTN_COUNT)
1199 break;
1200 if (Event.xbutton.button == 1)
1201 x11->win_drag_button1_down = true;
1202 mp_input_put_key(x11->input_ctx,
1203 (MP_MBTN_BASE + Event.xbutton.button - 1) |
1204 get_mods(Event.xbutton.state) | MP_KEY_STATE_DOWN);
1205 long msg[4] = {XEMBED_REQUEST_FOCUS};
1206 vo_x11_xembed_send_message(x11, msg);
1207 break;
1208 case ButtonRelease:
1209 if (Event.xbutton.button - 1 >= MP_KEY_MOUSE_BTN_COUNT)
1210 break;
1211 if (Event.xbutton.button == 1)
1212 x11->win_drag_button1_down = false;
1213 mp_input_put_key(x11->input_ctx,
1214 (MP_MBTN_BASE + Event.xbutton.button - 1) |
1215 get_mods(Event.xbutton.state) | MP_KEY_STATE_UP);
1216 break;
1217 case MapNotify:
1218 x11->window_hidden = false;
1219 x11->pseudo_mapped = true;
1220 x11->current_icc_screen = -1;
1221 vo_x11_update_geometry(vo);
1222 break;
1223 case DestroyNotify:
1224 MP_WARN(x11, "Our window was destroyed, exiting\n");
1225 mp_input_put_key(x11->input_ctx, MP_KEY_CLOSE_WIN);
1226 x11->window = 0;
1227 break;
1228 case ClientMessage:
1229 if (Event.xclient.message_type == XA(x11, WM_PROTOCOLS) &&
1230 Event.xclient.data.l[0] == XA(x11, WM_DELETE_WINDOW))
1231 mp_input_put_key(x11->input_ctx, MP_KEY_CLOSE_WIN);
1232 vo_x11_dnd_handle_message(vo, &Event.xclient);
1233 vo_x11_xembed_handle_message(vo, &Event.xclient);
1234 break;
1235 case SelectionNotify:
1236 vo_x11_dnd_handle_selection(vo, &Event.xselection);
1237 break;
1238 case PropertyNotify:
1239 if (Event.xproperty.atom == XA(x11, _NET_FRAME_EXTENTS) ||
1240 Event.xproperty.atom == XA(x11, WM_STATE))
1241 {
1242 if (!x11->pseudo_mapped && !x11->parent) {
1243 MP_VERBOSE(x11, "not waiting for MapNotify\n");
1244 x11->pseudo_mapped = true;
1245 }
1246 } else if (Event.xproperty.atom == XA(x11, _NET_WM_STATE)) {
1247 vo_x11_check_net_wm_state_change(vo);
1248 } else if (Event.xproperty.atom == XA(x11, _NET_WM_DESKTOP)) {
1249 vo_x11_check_net_wm_desktop_change(vo);
1250 } else if (Event.xproperty.atom == x11->icc_profile_property) {
1251 x11->pending_vo_events |= VO_EVENT_ICC_PROFILE_CHANGED;
1252 }
1253 break;
1254 default:
1255 if (Event.type == x11->ShmCompletionEvent) {
1256 if (x11->ShmCompletionWaitCount > 0)
1257 x11->ShmCompletionWaitCount--;
1258 }
1259 if (Event.type == x11->xrandr_event) {
1260 xrandr_read(x11);
1261 vo_x11_update_geometry(vo);
1262 }
1263 break;
1264 }
1265 }
1266
1267 update_vo_size(vo);
1268 }
1269
vo_x11_sizehint(struct vo * vo,struct mp_rect rc,bool override_pos)1270 static void vo_x11_sizehint(struct vo *vo, struct mp_rect rc, bool override_pos)
1271 {
1272 struct vo_x11_state *x11 = vo->x11;
1273 struct mp_vo_opts *opts = x11->opts;
1274
1275 if (!x11->window || x11->parent)
1276 return;
1277
1278 bool force_pos = opts->geometry.xy_valid || // explicitly forced by user
1279 opts->force_window_position || // resize -> reset position
1280 opts->screen_id >= 0 || // force onto screen area
1281 x11->parent || // force to fill parent
1282 override_pos; // for fullscreen and such
1283
1284 XSizeHints *hint = XAllocSizeHints();
1285 if (!hint)
1286 return; // OOM
1287
1288 hint->flags |= PSize | (force_pos ? PPosition : 0);
1289 hint->x = rc.x0;
1290 hint->y = rc.y0;
1291 hint->width = RC_W(rc);
1292 hint->height = RC_H(rc);
1293 hint->max_width = 0;
1294 hint->max_height = 0;
1295
1296 if (opts->keepaspect && opts->keepaspect_window) {
1297 hint->flags |= PAspect;
1298 hint->min_aspect.x = hint->width;
1299 hint->min_aspect.y = hint->height;
1300 hint->max_aspect.x = hint->width;
1301 hint->max_aspect.y = hint->height;
1302 }
1303
1304 // Set minimum height/width to 4 to avoid off-by-one errors.
1305 hint->flags |= PMinSize;
1306 hint->min_width = hint->min_height = 4;
1307
1308 hint->flags |= PWinGravity;
1309 hint->win_gravity = StaticGravity;
1310
1311 XSetWMNormalHints(x11->display, x11->window, hint);
1312 XFree(hint);
1313 }
1314
vo_x11_move_resize(struct vo * vo,bool move,bool resize,struct mp_rect rc)1315 static void vo_x11_move_resize(struct vo *vo, bool move, bool resize,
1316 struct mp_rect rc)
1317 {
1318 if (!vo->x11->window)
1319 return;
1320 int w = RC_W(rc), h = RC_H(rc);
1321 XWindowChanges req = {.x = rc.x0, .y = rc.y0, .width = w, .height = h};
1322 unsigned mask = (move ? CWX | CWY : 0) | (resize ? CWWidth | CWHeight : 0);
1323 if (mask)
1324 XConfigureWindow(vo->x11->display, vo->x11->window, mask, &req);
1325 vo_x11_sizehint(vo, rc, false);
1326 }
1327
1328 // set a X text property that expects a UTF8_STRING type
vo_x11_set_property_utf8(struct vo * vo,Atom name,const char * t)1329 static void vo_x11_set_property_utf8(struct vo *vo, Atom name, const char *t)
1330 {
1331 struct vo_x11_state *x11 = vo->x11;
1332
1333 XChangeProperty(x11->display, x11->window, name, XA(x11, UTF8_STRING), 8,
1334 PropModeReplace, t, strlen(t));
1335 }
1336
1337 // set a X text property that expects a STRING or COMPOUND_TEXT type
vo_x11_set_property_string(struct vo * vo,Atom name,const char * t)1338 static void vo_x11_set_property_string(struct vo *vo, Atom name, const char *t)
1339 {
1340 struct vo_x11_state *x11 = vo->x11;
1341 XTextProperty prop = {0};
1342
1343 if (Xutf8TextListToTextProperty(x11->display, (char **)&t, 1,
1344 XStdICCTextStyle, &prop) == Success)
1345 {
1346 XSetTextProperty(x11->display, x11->window, &prop, name);
1347 } else {
1348 // Strictly speaking this violates the ICCCM, but there's no way we
1349 // can do this correctly.
1350 vo_x11_set_property_utf8(vo, name, t);
1351 }
1352
1353 if (prop.value)
1354 XFree(prop.value);
1355 }
1356
vo_x11_update_window_title(struct vo * vo)1357 static void vo_x11_update_window_title(struct vo *vo)
1358 {
1359 struct vo_x11_state *x11 = vo->x11;
1360
1361 if (!x11->window || !x11->window_title)
1362 return;
1363
1364 vo_x11_set_property_string(vo, XA_WM_NAME, x11->window_title);
1365 vo_x11_set_property_string(vo, XA_WM_ICON_NAME, x11->window_title);
1366 vo_x11_set_property_utf8(vo, XA(x11, _NET_WM_NAME), x11->window_title);
1367 vo_x11_set_property_utf8(vo, XA(x11, _NET_WM_ICON_NAME), x11->window_title);
1368 }
1369
vo_x11_xembed_update(struct vo_x11_state * x11,int flags)1370 static void vo_x11_xembed_update(struct vo_x11_state *x11, int flags)
1371 {
1372 if (!x11->window || !x11->parent)
1373 return;
1374
1375 long xembed_info[] = {XEMBED_VERSION, flags};
1376 Atom name = XA(x11, _XEMBED_INFO);
1377 XChangeProperty(x11->display, x11->window, name, name, 32,
1378 PropModeReplace, (char *)xembed_info, 2);
1379 }
1380
vo_x11_xembed_handle_message(struct vo * vo,XClientMessageEvent * ce)1381 static void vo_x11_xembed_handle_message(struct vo *vo, XClientMessageEvent *ce)
1382 {
1383 struct vo_x11_state *x11 = vo->x11;
1384 if (!x11->window || !x11->parent || ce->message_type != XA(x11, _XEMBED))
1385 return;
1386
1387 long msg = ce->data.l[1];
1388 if (msg == XEMBED_EMBEDDED_NOTIFY)
1389 MP_VERBOSE(x11, "Parent windows supports XEmbed.\n");
1390 }
1391
vo_x11_xembed_send_message(struct vo_x11_state * x11,long m[4])1392 static void vo_x11_xembed_send_message(struct vo_x11_state *x11, long m[4])
1393 {
1394 if (!x11->window || !x11->parent)
1395 return;
1396 XEvent ev = {.xclient = {
1397 .type = ClientMessage,
1398 .window = x11->parent,
1399 .message_type = XA(x11, _XEMBED),
1400 .format = 32,
1401 .data = {.l = { CurrentTime, m[0], m[1], m[2], m[3] }},
1402 } };
1403 XSendEvent(x11->display, x11->parent, False, NoEventMask, &ev);
1404 }
1405
vo_x11_set_wm_icon(struct vo_x11_state * x11)1406 static void vo_x11_set_wm_icon(struct vo_x11_state *x11)
1407 {
1408 int icon_size = 0;
1409 long *icon = talloc_array(NULL, long, 0);
1410
1411 for (int n = 0; x11_icons[n].start; n++) {
1412 struct mp_image *img =
1413 load_image_png_buf(x11_icons[n].start, x11_icons[n].len, IMGFMT_RGBA);
1414 if (!img)
1415 continue;
1416 int new_size = 2 + img->w * img->h;
1417 MP_RESIZE_ARRAY(NULL, icon, icon_size + new_size);
1418 long *cur = icon + icon_size;
1419 icon_size += new_size;
1420 *cur++ = img->w;
1421 *cur++ = img->h;
1422 for (int y = 0; y < img->h; y++) {
1423 uint8_t *s = (uint8_t *)img->planes[0] + img->stride[0] * y;
1424 for (int x = 0; x < img->w; x++) {
1425 *cur++ = s[x * 4 + 0] | (s[x * 4 + 1] << 8) |
1426 (s[x * 4 + 2] << 16) | ((unsigned)s[x * 4 + 3] << 24);
1427 }
1428 }
1429 talloc_free(img);
1430 }
1431
1432 XChangeProperty(x11->display, x11->window, XA(x11, _NET_WM_ICON),
1433 XA_CARDINAL, 32, PropModeReplace,
1434 (unsigned char *)icon, icon_size);
1435 talloc_free(icon);
1436 }
1437
vo_x11_create_window(struct vo * vo,XVisualInfo * vis,struct mp_rect rc)1438 static void vo_x11_create_window(struct vo *vo, XVisualInfo *vis,
1439 struct mp_rect rc)
1440 {
1441 struct vo_x11_state *x11 = vo->x11;
1442
1443 assert(x11->window == None);
1444 assert(!x11->xic);
1445
1446 XVisualInfo vinfo_storage;
1447 if (!vis) {
1448 vis = &vinfo_storage;
1449 XWindowAttributes att;
1450 XGetWindowAttributes(x11->display, x11->rootwin, &att);
1451 XMatchVisualInfo(x11->display, x11->screen, att.depth, TrueColor, vis);
1452 }
1453
1454 if (x11->colormap == None) {
1455 x11->colormap = XCreateColormap(x11->display, x11->rootwin,
1456 vis->visual, AllocNone);
1457 }
1458
1459 unsigned long xswamask = CWBorderPixel | CWColormap;
1460 XSetWindowAttributes xswa = {
1461 .border_pixel = 0,
1462 .colormap = x11->colormap,
1463 };
1464
1465 Window parent = x11->parent;
1466 if (!parent)
1467 parent = x11->rootwin;
1468
1469 x11->window =
1470 XCreateWindow(x11->display, parent, rc.x0, rc.y0, RC_W(rc), RC_H(rc), 0,
1471 vis->depth, CopyFromParent, vis->visual, xswamask, &xswa);
1472 Atom protos[1] = {XA(x11, WM_DELETE_WINDOW)};
1473 XSetWMProtocols(x11->display, x11->window, protos, 1);
1474
1475 x11->mouse_cursor_set = false;
1476 x11->mouse_cursor_visible = true;
1477 vo_update_cursor(vo);
1478
1479 if (x11->xim) {
1480 x11->xic = XCreateIC(x11->xim,
1481 XNInputStyle, XIMPreeditNone | XIMStatusNone,
1482 XNClientWindow, x11->window,
1483 XNFocusWindow, x11->window,
1484 NULL);
1485 }
1486
1487 if (!x11->parent) {
1488 vo_x11_update_composition_hint(vo);
1489 vo_x11_set_wm_icon(x11);
1490 vo_x11_update_window_title(vo);
1491 vo_x11_dnd_init_window(vo);
1492 vo_x11_set_property_utf8(vo, XA(x11, _GTK_THEME_VARIANT), "dark");
1493 }
1494 vo_x11_xembed_update(x11, 0);
1495 }
1496
vo_x11_map_window(struct vo * vo,struct mp_rect rc)1497 static void vo_x11_map_window(struct vo *vo, struct mp_rect rc)
1498 {
1499 struct vo_x11_state *x11 = vo->x11;
1500
1501 vo_x11_move_resize(vo, true, true, rc);
1502 vo_x11_decoration(vo, x11->opts->border);
1503
1504 if (x11->opts->fullscreen && (x11->wm_type & vo_wm_FULLSCREEN)) {
1505 Atom state = XA(x11, _NET_WM_STATE_FULLSCREEN);
1506 XChangeProperty(x11->display, x11->window, XA(x11, _NET_WM_STATE), XA_ATOM,
1507 32, PropModeAppend, (unsigned char *)&state, 1);
1508 x11->fs = 1;
1509 // The "saved" positions are bogus, so reset them when leaving FS again.
1510 x11->size_changed_during_fs = true;
1511 x11->pos_changed_during_fs = true;
1512 }
1513
1514 if (x11->opts->fsscreen_id != -1) {
1515 long params[5] = {0};
1516 if (x11->opts->fsscreen_id >= 0) {
1517 for (int n = 0; n < 4; n++)
1518 params[n] = x11->opts->fsscreen_id;
1519 } else {
1520 vo_x11_get_bounding_monitors(x11, ¶ms[0]);
1521 }
1522 params[4] = 1; // source indication: normal
1523 x11_send_ewmh_msg(x11, "_NET_WM_FULLSCREEN_MONITORS", params);
1524 }
1525
1526 if (x11->opts->all_workspaces || x11->opts->geometry.ws > 0) {
1527 long v = x11->opts->all_workspaces
1528 ? 0xFFFFFFFF : x11->opts->geometry.ws - 1;
1529 XChangeProperty(x11->display, x11->window, XA(x11, _NET_WM_DESKTOP),
1530 XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&v, 1);
1531 }
1532
1533 vo_x11_update_composition_hint(vo);
1534
1535 // map window
1536 int events = StructureNotifyMask | ExposureMask | PropertyChangeMask |
1537 LeaveWindowMask | EnterWindowMask | FocusChangeMask;
1538 if (mp_input_mouse_enabled(x11->input_ctx))
1539 events |= PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
1540 if (mp_input_vo_keyboard_enabled(x11->input_ctx))
1541 events |= KeyPressMask | KeyReleaseMask;
1542 vo_x11_selectinput_witherr(vo, x11->display, x11->window, events);
1543 XMapWindow(x11->display, x11->window);
1544
1545 if (x11->opts->window_maximized) // don't override WM default on "no"
1546 vo_x11_maximize(vo);
1547 if (x11->opts->window_minimized) // don't override WM default on "no"
1548 vo_x11_minimize(vo);
1549
1550 if (x11->opts->fullscreen && (x11->wm_type & vo_wm_FULLSCREEN))
1551 x11_set_ewmh_state(x11, "_NET_WM_STATE_FULLSCREEN", 1);
1552
1553 vo_x11_xembed_update(x11, XEMBED_MAPPED);
1554 }
1555
vo_x11_highlevel_resize(struct vo * vo,struct mp_rect rc)1556 static void vo_x11_highlevel_resize(struct vo *vo, struct mp_rect rc)
1557 {
1558 struct vo_x11_state *x11 = vo->x11;
1559 struct mp_vo_opts *opts = x11->opts;
1560
1561 bool reset_pos = opts->force_window_position;
1562 if (reset_pos) {
1563 x11->nofsrc = rc;
1564 } else {
1565 x11->nofsrc.x1 = x11->nofsrc.x0 + RC_W(rc);
1566 x11->nofsrc.y1 = x11->nofsrc.y0 + RC_H(rc);
1567 }
1568
1569 if (opts->fullscreen) {
1570 x11->size_changed_during_fs = true;
1571 x11->pos_changed_during_fs = reset_pos;
1572 vo_x11_sizehint(vo, rc, false);
1573 } else {
1574 vo_x11_move_resize(vo, reset_pos, true, rc);
1575 }
1576 }
1577
wait_until_mapped(struct vo * vo)1578 static void wait_until_mapped(struct vo *vo)
1579 {
1580 struct vo_x11_state *x11 = vo->x11;
1581 if (!x11->pseudo_mapped)
1582 x11_send_ewmh_msg(x11, "_NET_REQUEST_FRAME_EXTENTS", (long[5]){0});
1583 while (!x11->pseudo_mapped && x11->window) {
1584 XWindowAttributes att;
1585 XGetWindowAttributes(x11->display, x11->window, &att);
1586 if (att.map_state != IsUnmapped) {
1587 x11->pseudo_mapped = true;
1588 break;
1589 }
1590 XEvent unused;
1591 XPeekEvent(x11->display, &unused);
1592 vo_x11_check_events(vo);
1593 }
1594 }
1595
1596 // Create the X11 window. There is only 1, and it must be created before
1597 // vo_x11_config_vo_window() is called. vis can be NULL for default.
vo_x11_create_vo_window(struct vo * vo,XVisualInfo * vis,const char * classname)1598 bool vo_x11_create_vo_window(struct vo *vo, XVisualInfo *vis,
1599 const char *classname)
1600 {
1601 struct vo_x11_state *x11 = vo->x11;
1602 assert(!x11->window);
1603
1604 if (x11->parent) {
1605 if (x11->parent == x11->rootwin) {
1606 x11->window = x11->rootwin;
1607 x11->pseudo_mapped = true;
1608 XSelectInput(x11->display, x11->window, StructureNotifyMask);
1609 } else {
1610 XSelectInput(x11->display, x11->parent, StructureNotifyMask);
1611 }
1612 }
1613 if (x11->window == None) {
1614 vo_x11_create_window(vo, vis, (struct mp_rect){.x1 = 320, .y1 = 200 });
1615 vo_x11_classhint(vo, x11->window, classname);
1616 vo_x11_wm_hints(vo, x11->window);
1617 x11->window_hidden = true;
1618 }
1619
1620 return !!x11->window;
1621 }
1622
1623 // Resize the window (e.g. new file, or video resolution change)
vo_x11_config_vo_window(struct vo * vo)1624 void vo_x11_config_vo_window(struct vo *vo)
1625 {
1626 struct vo_x11_state *x11 = vo->x11;
1627 struct mp_vo_opts *opts = x11->opts;
1628
1629 assert(x11->window);
1630
1631 vo_x11_update_screeninfo(vo);
1632
1633 struct vo_win_geometry geo;
1634 vo_calc_window_geometry2(vo, &x11->screenrc, x11->dpi_scale, &geo);
1635 vo_apply_window_geometry(vo, &geo);
1636
1637 struct mp_rect rc = geo.win;
1638
1639 if (x11->parent) {
1640 vo_x11_update_geometry(vo);
1641 rc = (struct mp_rect){0, 0, RC_W(x11->winrc), RC_H(x11->winrc)};
1642 }
1643
1644 bool reset_size = x11->old_dw != RC_W(rc) || x11->old_dh != RC_H(rc);
1645 x11->old_dw = RC_W(rc);
1646 x11->old_dh = RC_H(rc);
1647
1648 if (x11->window_hidden) {
1649 x11->nofsrc = rc;
1650 vo_x11_map_window(vo, rc);
1651 } else if (reset_size) {
1652 vo_x11_highlevel_resize(vo, rc);
1653 }
1654
1655 if (opts->ontop)
1656 vo_x11_setlayer(vo, opts->ontop);
1657
1658 vo_x11_fullscreen(vo);
1659
1660 wait_until_mapped(vo);
1661 vo_x11_update_geometry(vo);
1662 update_vo_size(vo);
1663 x11->pending_vo_events &= ~VO_EVENT_RESIZE; // implicitly done by the VO
1664 }
1665
vo_x11_setlayer(struct vo * vo,bool ontop)1666 static void vo_x11_setlayer(struct vo *vo, bool ontop)
1667 {
1668 struct vo_x11_state *x11 = vo->x11;
1669 if (x11->parent || !x11->window)
1670 return;
1671
1672 if (x11->wm_type & (vo_wm_STAYS_ON_TOP | vo_wm_ABOVE)) {
1673 char *state = "_NET_WM_STATE_ABOVE";
1674
1675 // Not in EWMH - but the old code preferred this (maybe it is "better")
1676 if (x11->wm_type & vo_wm_STAYS_ON_TOP)
1677 state = "_NET_WM_STATE_STAYS_ON_TOP";
1678
1679 x11_set_ewmh_state(x11, state, ontop);
1680
1681 MP_VERBOSE(x11, "NET style stay on top (%d). Using state %s.\n",
1682 ontop, state);
1683 } else if (x11->wm_type & vo_wm_LAYER) {
1684 if (!x11->orig_layer) {
1685 x11->orig_layer = WIN_LAYER_NORMAL;
1686 x11_get_property_copy(x11, x11->window, XA(x11, _WIN_LAYER),
1687 XA_CARDINAL, 32, &x11->orig_layer, sizeof(long));
1688 MP_VERBOSE(x11, "original window layer is %ld.\n", x11->orig_layer);
1689 }
1690
1691 long params[5] = {0};
1692 // if not fullscreen, stay on default layer
1693 params[0] = ontop ? WIN_LAYER_ABOVE_DOCK : x11->orig_layer;
1694 params[1] = CurrentTime;
1695 MP_VERBOSE(x11, "Layered style stay on top (layer %ld).\n", params[0]);
1696 x11_send_ewmh_msg(x11, "_WIN_LAYER", params);
1697 }
1698 }
1699
rc_overlaps(struct mp_rect rc1,struct mp_rect rc2)1700 static bool rc_overlaps(struct mp_rect rc1, struct mp_rect rc2)
1701 {
1702 return mp_rect_intersection(&rc1, &rc2); // changes the first argument
1703 }
1704
1705 // which screen's ICC profile we're going to use
get_icc_screen(struct vo * vo)1706 static int get_icc_screen(struct vo *vo)
1707 {
1708 struct vo_x11_state *x11 = vo->x11;
1709 int cx = x11->winrc.x0 + (x11->winrc.x1 - x11->winrc.x0)/2,
1710 cy = x11->winrc.y0 + (x11->winrc.y1 - x11->winrc.y0)/2;
1711 int screen = x11->current_icc_screen; // xinerama screen number
1712 for (int n = 0; n < x11->num_displays; n++) {
1713 struct xrandr_display *disp = &x11->displays[n];
1714 if (mp_rect_contains(&disp->rc, cx, cy)) {
1715 screen = n;
1716 break;
1717 }
1718 }
1719 return screen;
1720 }
1721
1722 // update x11->winrc with current boundaries of vo->x11->window
vo_x11_update_geometry(struct vo * vo)1723 static void vo_x11_update_geometry(struct vo *vo)
1724 {
1725 struct vo_x11_state *x11 = vo->x11;
1726 int x = 0, y = 0;
1727 unsigned w, h, dummy_uint;
1728 int dummy_int;
1729 Window dummy_win;
1730 Window win = x11->parent ? x11->parent : x11->window;
1731 x11->winrc = (struct mp_rect){0, 0, 0, 0};
1732 if (win) {
1733 XGetGeometry(x11->display, win, &dummy_win, &dummy_int, &dummy_int,
1734 &w, &h, &dummy_int, &dummy_uint);
1735 if (w > INT_MAX || h > INT_MAX)
1736 w = h = 0;
1737 XTranslateCoordinates(x11->display, win, x11->rootwin, 0, 0,
1738 &x, &y, &dummy_win);
1739 x11->winrc = (struct mp_rect){x, y, x + w, y + h};
1740 }
1741 double fps = 1000.0;
1742 for (int n = 0; n < x11->num_displays; n++) {
1743 struct xrandr_display *disp = &x11->displays[n];
1744 disp->overlaps = rc_overlaps(disp->rc, x11->winrc);
1745 if (disp->overlaps)
1746 fps = MPMIN(fps, disp->fps);
1747 }
1748 double fallback = x11->num_displays > 0 ? x11->displays[0].fps : 0;
1749 fps = fps < 1000.0 ? fps : fallback;
1750 if (fps != x11->current_display_fps)
1751 MP_VERBOSE(x11, "Current display FPS: %f\n", fps);
1752 x11->current_display_fps = fps;
1753 // might have changed displays
1754 x11->pending_vo_events |= VO_EVENT_WIN_STATE;
1755 int icc_screen = get_icc_screen(vo);
1756 if (x11->current_icc_screen != icc_screen) {
1757 x11->current_icc_screen = icc_screen;
1758 x11->pending_vo_events |= VO_EVENT_ICC_PROFILE_CHANGED;
1759 }
1760 }
1761
vo_x11_fullscreen(struct vo * vo)1762 static void vo_x11_fullscreen(struct vo *vo)
1763 {
1764 struct vo_x11_state *x11 = vo->x11;
1765 struct mp_vo_opts *opts = x11->opts;
1766
1767 if (opts->fullscreen == x11->fs)
1768 return;
1769 x11->fs = opts->fullscreen; // x11->fs now contains the new state
1770 if (x11->parent || !x11->window)
1771 return;
1772
1773 // Save old state before entering fullscreen
1774 if (x11->fs) {
1775 vo_x11_update_geometry(vo);
1776 x11->nofsrc = x11->winrc;
1777 }
1778
1779 struct mp_rect rc = x11->nofsrc;
1780
1781 if (x11->wm_type & vo_wm_FULLSCREEN) {
1782 x11_set_ewmh_state(x11, "_NET_WM_STATE_FULLSCREEN", x11->fs);
1783 if (!x11->fs && (x11->pos_changed_during_fs ||
1784 x11->size_changed_during_fs))
1785 {
1786 if (x11->screenrc.x0 == rc.x0 && x11->screenrc.x1 == rc.x1 &&
1787 x11->screenrc.y0 == rc.y0 && x11->screenrc.y1 == rc.y1)
1788 {
1789 // Workaround for some WMs switching back to FS in this case.
1790 MP_VERBOSE(x11, "avoiding triggering old-style fullscreen\n");
1791 rc.x1 -= 1;
1792 rc.y1 -= 1;
1793 }
1794 vo_x11_move_resize(vo, x11->pos_changed_during_fs,
1795 x11->size_changed_during_fs, rc);
1796 }
1797 } else {
1798 if (x11->fs) {
1799 vo_x11_update_screeninfo(vo);
1800 rc = x11->screenrc;
1801 }
1802
1803 vo_x11_decoration(vo, opts->border && !x11->fs);
1804 vo_x11_sizehint(vo, rc, true);
1805
1806 XMoveResizeWindow(x11->display, x11->window, rc.x0, rc.y0,
1807 RC_W(rc), RC_H(rc));
1808
1809 vo_x11_setlayer(vo, x11->fs || opts->ontop);
1810
1811 XRaiseWindow(x11->display, x11->window);
1812 XFlush(x11->display);
1813 }
1814
1815 x11->size_changed_during_fs = false;
1816 x11->pos_changed_during_fs = false;
1817
1818 vo_x11_update_composition_hint(vo);
1819 }
1820
vo_x11_maximize(struct vo * vo)1821 static void vo_x11_maximize(struct vo *vo)
1822 {
1823 struct vo_x11_state *x11 = vo->x11;
1824
1825 long params[5] = {
1826 x11->opts->window_maximized ? NET_WM_STATE_ADD : NET_WM_STATE_REMOVE,
1827 XA(x11, _NET_WM_STATE_MAXIMIZED_VERT),
1828 XA(x11, _NET_WM_STATE_MAXIMIZED_HORZ),
1829 1, // source indication: normal
1830 };
1831 x11_send_ewmh_msg(x11, "_NET_WM_STATE", params);
1832 }
1833
vo_x11_minimize(struct vo * vo)1834 static void vo_x11_minimize(struct vo *vo)
1835 {
1836 struct vo_x11_state *x11 = vo->x11;
1837
1838 if (x11->opts->window_minimized) {
1839 XIconifyWindow(x11->display, x11->window, x11->screen);
1840 } else {
1841 long params[5] = {0};
1842 x11_send_ewmh_msg(x11, "_NET_ACTIVE_WINDOW", params);
1843 }
1844 }
1845
vo_x11_set_geometry(struct vo * vo)1846 static void vo_x11_set_geometry(struct vo *vo)
1847 {
1848 struct vo_x11_state *x11 = vo->x11;
1849
1850 if (!x11->window)
1851 return;
1852
1853 if (x11->opts->window_maximized) {
1854 x11->pending_geometry_change = true;
1855 } else {
1856 vo_x11_config_vo_window(vo);
1857 }
1858 }
1859
vo_x11_control(struct vo * vo,int * events,int request,void * arg)1860 int vo_x11_control(struct vo *vo, int *events, int request, void *arg)
1861 {
1862 struct vo_x11_state *x11 = vo->x11;
1863 struct mp_vo_opts *opts = x11->opts;
1864 switch (request) {
1865 case VOCTRL_CHECK_EVENTS:
1866 vo_x11_check_events(vo);
1867 *events |= x11->pending_vo_events;
1868 x11->pending_vo_events = 0;
1869 return VO_TRUE;
1870 case VOCTRL_VO_OPTS_CHANGED: {
1871 void *opt;
1872 while (m_config_cache_get_next_changed(x11->opts_cache, &opt)) {
1873 if (opt == &opts->fullscreen)
1874 vo_x11_fullscreen(vo);
1875 if (opt == &opts->ontop)
1876 vo_x11_setlayer(vo, opts->ontop);
1877 if (opt == &opts->border)
1878 vo_x11_decoration(vo, opts->border);
1879 if (opt == &opts->all_workspaces) {
1880 long params[5] = {0xFFFFFFFF, 1};
1881 if (!opts->all_workspaces) {
1882 x11_get_property_copy(x11, x11->rootwin,
1883 XA(x11, _NET_CURRENT_DESKTOP),
1884 XA_CARDINAL, 32, ¶ms[0],
1885 sizeof(params[0]));
1886 }
1887 x11_send_ewmh_msg(x11, "_NET_WM_DESKTOP", params);
1888 }
1889 if (opt == &opts->window_minimized)
1890 vo_x11_minimize(vo);
1891 if (opt == &opts->window_maximized)
1892 vo_x11_maximize(vo);
1893 if (opt == &opts->geometry || opt == &opts->autofit ||
1894 opt == &opts->autofit_smaller || opt == &opts->autofit_larger)
1895 {
1896 vo_x11_set_geometry(vo);
1897 }
1898 }
1899 return VO_TRUE;
1900 }
1901 case VOCTRL_GET_UNFS_WINDOW_SIZE: {
1902 int *s = arg;
1903 if (!x11->window || x11->parent)
1904 return VO_FALSE;
1905 s[0] = (x11->fs ? RC_W(x11->nofsrc) : RC_W(x11->winrc)) / x11->dpi_scale;
1906 s[1] = (x11->fs ? RC_H(x11->nofsrc) : RC_H(x11->winrc)) / x11->dpi_scale;
1907 return VO_TRUE;
1908 }
1909 case VOCTRL_SET_UNFS_WINDOW_SIZE: {
1910 int *s = arg;
1911 if (!x11->window || x11->parent)
1912 return VO_FALSE;
1913 int w = s[0] * x11->dpi_scale;
1914 int h = s[1] * x11->dpi_scale;
1915 struct mp_rect rc = x11->winrc;
1916 rc.x1 = rc.x0 + w;
1917 rc.y1 = rc.y0 + h;
1918 if (x11->opts->window_maximized) {
1919 x11->opts->window_maximized = false;
1920 m_config_cache_write_opt(x11->opts_cache,
1921 &x11->opts->window_maximized);
1922 vo_x11_maximize(vo);
1923 }
1924 vo_x11_highlevel_resize(vo, rc);
1925 if (!x11->fs) { // guess new window size, instead of waiting for X
1926 x11->winrc.x1 = x11->winrc.x0 + w;
1927 x11->winrc.y1 = x11->winrc.y0 + h;
1928 }
1929 return VO_TRUE;
1930 }
1931 case VOCTRL_GET_FOCUSED: {
1932 *(bool *)arg = x11->has_focus;
1933 return VO_TRUE;
1934 }
1935 case VOCTRL_GET_DISPLAY_NAMES: {
1936 if (!x11->pseudo_mapped)
1937 return VO_FALSE;
1938 char **names = NULL;
1939 int displays_spanned = 0;
1940 for (int n = 0; n < x11->num_displays; n++) {
1941 if (rc_overlaps(x11->displays[n].rc, x11->winrc))
1942 MP_TARRAY_APPEND(NULL, names, displays_spanned,
1943 talloc_strdup(NULL, x11->displays[n].name));
1944 }
1945 MP_TARRAY_APPEND(NULL, names, displays_spanned, NULL);
1946 *(char ***)arg = names;
1947 return VO_TRUE;
1948 }
1949 case VOCTRL_GET_ICC_PROFILE: {
1950 if (!x11->pseudo_mapped)
1951 return VO_NOTAVAIL;
1952 int screen = get_icc_screen(vo);
1953 int atom_id = x11->displays[screen].atom_id;
1954 char prop[80];
1955 snprintf(prop, sizeof(prop), "_ICC_PROFILE");
1956 if (atom_id > 0)
1957 mp_snprintf_cat(prop, sizeof(prop), "_%d", atom_id);
1958 x11->icc_profile_property = XAs(x11, prop);
1959 int len;
1960 MP_VERBOSE(x11, "Retrieving ICC profile for display: %d\n", screen);
1961 void *icc = x11_get_property(x11, x11->rootwin, x11->icc_profile_property,
1962 XA_CARDINAL, 8, &len);
1963 if (!icc)
1964 return VO_FALSE;
1965 *(bstr *)arg = bstrdup(NULL, (bstr){icc, len});
1966 XFree(icc);
1967 // Watch x11->icc_profile_property
1968 XSelectInput(x11->display, x11->rootwin, PropertyChangeMask);
1969 return VO_TRUE;
1970 }
1971 case VOCTRL_SET_CURSOR_VISIBILITY:
1972 x11->mouse_cursor_visible = *(bool *)arg;
1973 vo_update_cursor(vo);
1974 return VO_TRUE;
1975 case VOCTRL_KILL_SCREENSAVER:
1976 set_screensaver(x11, false);
1977 return VO_TRUE;
1978 case VOCTRL_RESTORE_SCREENSAVER:
1979 set_screensaver(x11, true);
1980 return VO_TRUE;
1981 case VOCTRL_UPDATE_WINDOW_TITLE:
1982 talloc_free(x11->window_title);
1983 x11->window_title = talloc_strdup(x11, (char *)arg);
1984 if (!x11->parent)
1985 vo_x11_update_window_title(vo);
1986 return VO_TRUE;
1987 case VOCTRL_GET_DISPLAY_FPS: {
1988 double fps = x11->current_display_fps;
1989 if (fps <= 0)
1990 break;
1991 *(double *)arg = fps;
1992 return VO_TRUE;
1993 }
1994 case VOCTRL_GET_DISPLAY_RES: {
1995 if (!x11->window || x11->parent)
1996 return VO_NOTAVAIL;
1997 ((int *)arg)[0] = x11->screenrc.x1;
1998 ((int *)arg)[1] = x11->screenrc.y1;
1999 return VO_TRUE;
2000 }
2001 case VOCTRL_GET_HIDPI_SCALE:
2002 *(double *)arg = x11->dpi_scale;
2003 return VO_TRUE;
2004 }
2005 return VO_NOTIMPL;
2006 }
2007
vo_x11_wakeup(struct vo * vo)2008 void vo_x11_wakeup(struct vo *vo)
2009 {
2010 struct vo_x11_state *x11 = vo->x11;
2011
2012 (void)write(x11->wakeup_pipe[1], &(char){0}, 1);
2013 }
2014
vo_x11_wait_events(struct vo * vo,int64_t until_time_us)2015 void vo_x11_wait_events(struct vo *vo, int64_t until_time_us)
2016 {
2017 struct vo_x11_state *x11 = vo->x11;
2018
2019 struct pollfd fds[2] = {
2020 { .fd = x11->event_fd, .events = POLLIN },
2021 { .fd = x11->wakeup_pipe[0], .events = POLLIN },
2022 };
2023 int64_t wait_us = until_time_us - mp_time_us();
2024 int timeout_ms = MPCLAMP((wait_us + 999) / 1000, 0, 10000);
2025
2026 poll(fds, 2, timeout_ms);
2027
2028 if (fds[1].revents & POLLIN)
2029 mp_flush_wakeup_pipe(x11->wakeup_pipe[0]);
2030 }
2031
xscreensaver_heartbeat(struct vo_x11_state * x11)2032 static void xscreensaver_heartbeat(struct vo_x11_state *x11)
2033 {
2034 double time = mp_time_sec();
2035
2036 if (x11->display && !x11->screensaver_enabled &&
2037 (time - x11->screensaver_time_last) >= 10)
2038 {
2039 x11->screensaver_time_last = time;
2040 XResetScreenSaver(x11->display);
2041 }
2042 }
2043
xss_suspend(Display * mDisplay,Bool suspend)2044 static int xss_suspend(Display *mDisplay, Bool suspend)
2045 {
2046 int event, error, major, minor;
2047 if (XScreenSaverQueryExtension(mDisplay, &event, &error) != True ||
2048 XScreenSaverQueryVersion(mDisplay, &major, &minor) != True)
2049 return 0;
2050 if (major < 1 || (major == 1 && minor < 1))
2051 return 0;
2052 XScreenSaverSuspend(mDisplay, suspend);
2053 return 1;
2054 }
2055
set_screensaver(struct vo_x11_state * x11,bool enabled)2056 static void set_screensaver(struct vo_x11_state *x11, bool enabled)
2057 {
2058 Display *mDisplay = x11->display;
2059 if (!mDisplay || x11->screensaver_enabled == enabled)
2060 return;
2061 MP_VERBOSE(x11, "%s screensaver.\n", enabled ? "Enabling" : "Disabling");
2062 x11->screensaver_enabled = enabled;
2063 if (xss_suspend(mDisplay, !enabled))
2064 return;
2065 int nothing;
2066 if (DPMSQueryExtension(mDisplay, ¬hing, ¬hing)) {
2067 BOOL onoff = 0;
2068 CARD16 state;
2069 DPMSInfo(mDisplay, &state, &onoff);
2070 if (!x11->dpms_touched && enabled)
2071 return; // enable DPMS only we we disabled it before
2072 if (enabled != !!onoff) {
2073 MP_VERBOSE(x11, "Setting DMPS: %s.\n", enabled ? "on" : "off");
2074 if (enabled) {
2075 DPMSEnable(mDisplay);
2076 } else {
2077 DPMSDisable(mDisplay);
2078 x11->dpms_touched = true;
2079 }
2080 DPMSInfo(mDisplay, &state, &onoff);
2081 if (enabled != !!onoff)
2082 MP_WARN(x11, "DPMS state could not be set.\n");
2083 }
2084 }
2085 }
2086
vo_x11_selectinput_witherr(struct vo * vo,Display * display,Window w,long event_mask)2087 static void vo_x11_selectinput_witherr(struct vo *vo,
2088 Display *display,
2089 Window w,
2090 long event_mask)
2091 {
2092 XSelectInput(display, w, NoEventMask);
2093
2094 // NOTE: this can raise BadAccess, which should be ignored by the X error
2095 // handler; also see below
2096 XSelectInput(display, w, event_mask);
2097
2098 // Test whether setting the event mask failed (with a BadAccess X error,
2099 // although we don't know whether this really happened).
2100 // This is needed for obscure situations like using --rootwin with a window
2101 // manager active.
2102 XWindowAttributes a;
2103 if (XGetWindowAttributes(display, w, &a)) {
2104 long bad = ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
2105 if ((event_mask & bad) && (a.all_event_masks & bad) &&
2106 ((a.your_event_mask & bad) != (event_mask & bad)))
2107 {
2108 MP_ERR(vo->x11, "X11 error: error during XSelectInput "
2109 "call, trying without mouse events\n");
2110 XSelectInput(display, w, event_mask & ~bad);
2111 }
2112 }
2113 }
2114
vo_x11_screen_is_composited(struct vo * vo)2115 bool vo_x11_screen_is_composited(struct vo *vo)
2116 {
2117 struct vo_x11_state *x11 = vo->x11;
2118 char buf[50];
2119 sprintf(buf, "_NET_WM_CM_S%d", x11->screen);
2120 Atom NET_WM_CM = XInternAtom(x11->display, buf, False);
2121 return XGetSelectionOwner(x11->display, NET_WM_CM) != None;
2122 }
2123
2124 // Return whether the given visual has alpha (when compositing is used).
vo_x11_is_rgba_visual(XVisualInfo * v)2125 bool vo_x11_is_rgba_visual(XVisualInfo *v)
2126 {
2127 // This is a heuristic at best. Note that normal 8 bit Visuals use
2128 // a depth of 24, even if the pixels are padded to 32 bit. If the
2129 // depth is higher than 24, the remaining bits must be alpha.
2130 // Note: vinfo->bits_per_rgb appears to be useless (is always 8).
2131 unsigned long mask = v->depth == sizeof(unsigned long) * 8 ?
2132 (unsigned long)-1 : (1UL << v->depth) - 1;
2133 return mask & ~(v->red_mask | v->green_mask | v->blue_mask);
2134 }
2135