iPlug2 - C++ Audio Plug-in Framework
Loading...
Searching...
No Matches
IGraphicsLinux.cpp
1/*
2 ==============================================================================
3
4 This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers.
5
6 See LICENSE.txt for more info.
7
8 ==============================================================================
9*/
10
11#include <pthread.h>
12#include <unistd.h>
13#include <sys/time.h>
14#include <sys/wait.h>
15#include <mutex>
16#include <cstring>
17#include <cstdlib>
18#include <cstdio>
19#include <dlfcn.h>
20#include <poll.h>
21#include <cerrno>
22#include <climits>
23#include <limits>
24#include <chrono>
25#include <string>
26// Fontconfig is loaded via dlopen so the plugin works without it installed.
27// Only the font-by-name lookup (LoadPlatformFont) needs it; embedded fonts work regardless.
28
29// X11 headers first — they define macros (None, Bool, True, False, Status, Complex...)
30// that conflict with C++ identifiers. IGraphicsLinux.h undefines them.
31#include <X11/Xlib.h>
32#include <X11/Xlib-xcb.h>
33#include <X11/Xutil.h>
34#include <X11/cursorfont.h>
35#include <X11/Xatom.h>
36#include <X11/keysym.h>
37
38// glad must come before GL/glx.h: glad sets __gl_h_ so that glx.h's own
39// #include <GL/gl.h> is skipped. If glx.h included gl.h first, glad would
40// detect __gl_h_ and throw a compile-time error.
41// Note: IGRAPHICS_GL is defined inside IGraphics_select.h (not yet processed here),
42// so we use the CMake-passed IGRAPHICS_GL2/GL3 defines directly.
43#if defined(IGRAPHICS_GL2) || defined(IGRAPHICS_GL3)
44 #include <glad/glad.h>
45 // After glad, Bool is still defined (= int from X11/Xlib.h) so GLX
46 // function declarations that use Bool compile correctly.
47 #include <GL/glx.h>
48#endif
49
50// IGraphicsLinux.h undefs the conflicting X11 macros (None, Bool, etc.) and
51// then includes IGraphics_select.h. The glad and GLX_H guards prevent those
52// headers from being re-included.
53#include "IGraphicsLinux.h"
54#include "IGraphicsStructs.h"
55#include "IControl.h"
56#include "wdlutf8.h"
57
58#if defined APP_API || defined REAPER_EXT_API
59 #include "IPlugSWELLTimer.h"
60#endif
61
62#ifdef APP_API
63// Implemented by the standalone app (IPlugAPP_dialog.cpp): carries out the menu item
64// whose keyboard shortcut is the key pressed, returning true if there is one
65extern bool IPlugAPPHandleKeyboardShortcut(const iplug::IKeyPress& key);
66#endif
67
68using namespace iplug;
69using namespace igraphics;
70
71#ifdef IGRAPHICS_ACCESSKIT
73
74BEGIN_IPLUG_NAMESPACE
75BEGIN_IGRAPHICS_NAMESPACE
76
82class IGraphicsAccessibilityLinux : public IGraphicsAccessibility
83{
84public:
85 IGraphicsAccessibilityLinux(IGraphics& graphics, Display* pDisplay, Window wnd)
86 : IGraphicsAccessibility(graphics)
87 , mDisplay(pDisplay)
88 , mWnd(wnd)
89 {
90 Registry& registry = GetRegistry();
91 void* pId = nullptr;
92
93 {
94 std::lock_guard<std::mutex> lock(registry.mutex);
95 mId = registry.nextId++;
96 registry.instances[mId] = this;
97 pId = reinterpret_cast<void*>(mId);
98 }
99
100 mAdapter = accesskit_unix_adapter_new(OnActivate, pId, OnAction, pId, OnDeactivate, pId);
101 }
102
103 ~IGraphicsAccessibilityLinux()
104 {
105 {
106 // Once this lock is released, no handler can be using this object
107 Registry& registry = GetRegistry();
108 std::lock_guard<std::mutex> lock(registry.mutex);
109 registry.instances.erase(mId);
110 }
111
112 accesskit_unix_adapter_free(mAdapter);
113 }
114
115 void SetWindowFocused(bool focused)
116 {
117 accesskit_unix_adapter_update_window_focus_state(mAdapter, focused);
118 }
119
122 void UpdateWindowBounds()
123 {
124 if (!mWantsBounds)
125 return;
126
127 const auto now = std::chrono::steady_clock::now();
128
129 if (!mBoundsRequested.exchange(false) && now - mBoundsTime < std::chrono::milliseconds(250))
130 return;
131
132 mBoundsTime = now;
133
134 // XCB is used so that an error (e.g. a window manager frame that was just destroyed) is returned, instead of reaching the Xlib error handler
135 xcb_connection_t* pConnection = XGetXCBConnection(mDisplay);
136
137 if (!pConnection)
138 return;
139
140 accesskit_rect inner;
141
142 if (!GetScreenRect(pConnection, static_cast<xcb_window_t>(mWnd), inner))
143 return;
144
145 // The outer bounds are those of the top level window, including the window manager's frame if there is one
146 accesskit_rect outer = inner;
147 xcb_window_t topLevel = static_cast<xcb_window_t>(mWnd);
148
149 for (int depth = 0; depth < 64; depth++)
150 {
151 xcb_query_tree_reply_t* pTree = xcb_query_tree_reply(pConnection, xcb_query_tree(pConnection, topLevel), nullptr);
152
153 if (!pTree)
154 return;
155
156 const xcb_window_t parent = pTree->parent;
157 const bool parentIsRoot = !parent || parent == pTree->root;
158 free(pTree);
159
160 if (parentIsRoot)
161 break;
162
163 topLevel = parent;
164 }
165
166 if (topLevel != mWnd && !GetScreenRect(pConnection, topLevel, outer))
167 return;
168
169 if (RectsEqual(inner, mInnerBounds) && RectsEqual(outer, mOuterBounds))
170 return;
171
172 mInnerBounds = inner;
173 mOuterBounds = outer;
174 accesskit_unix_adapter_set_root_window_bounds(mAdapter, outer, inner);
175 }
176
177protected:
178 void UpdateIfActive(accesskit_tree_update_factory factory, void* pUserData) override
179 {
180 accesskit_unix_adapter_update_if_active(mAdapter, factory, pUserData);
181 }
182
183private:
184 struct Registry
185 {
186 std::mutex mutex;
187 std::unordered_map<uintptr_t, IGraphicsAccessibilityLinux*> instances;
188 uintptr_t nextId = 1;
189 };
190
191 static Registry& GetRegistry()
192 {
193 // Never deleted, because AccessKit's thread can outlive static destruction
194 static Registry* sRegistry = new Registry();
195 return *sRegistry;
196 }
197
199 static IGraphicsAccessibilityLinux* GetInstance(void* pUserData)
200 {
201 Registry& registry = GetRegistry();
202 auto itr = registry.instances.find(reinterpret_cast<uintptr_t>(pUserData));
203 return itr != registry.instances.end() ? itr->second : nullptr;
204 }
205
206 static accesskit_tree_update* OnActivate(void* pUserData)
207 {
208 std::lock_guard<std::mutex> lock(GetRegistry().mutex);
209
210 if (auto* pThis = GetInstance(pUserData))
211 {
212 pThis->mWantsBounds = true;
213 pThis->mBoundsRequested = true;
214 pThis->RequestFullUpdate();
215 }
216
217 return nullptr;
218 }
219
220 static void OnDeactivate(void* pUserData)
221 {
222 std::lock_guard<std::mutex> lock(GetRegistry().mutex);
223
224 if (auto* pThis = GetInstance(pUserData))
225 {
226 pThis->mWantsBounds = false;
227 pThis->SetInactive();
228 }
229 }
230
231 static void OnAction(accesskit_action_request* pRequest, void* pUserData)
232 {
233 std::lock_guard<std::mutex> lock(GetRegistry().mutex);
234
235 if (auto* pThis = GetInstance(pUserData))
236 ActionHandler(pRequest, static_cast<IGraphicsAccessibility*>(pThis));
237 else
238 accesskit_action_request_free(pRequest);
239 }
240
241 static bool RectsEqual(const accesskit_rect& a, const accesskit_rect& b)
242 {
243 return a.x0 == b.x0 && a.y0 == b.y0 && a.x1 == b.x1 && a.y1 == b.y1;
244 }
245
247 static bool GetScreenRect(xcb_connection_t* pConnection, xcb_window_t wnd, accesskit_rect& rect)
248 {
249 xcb_get_geometry_reply_t* pGeometry = xcb_get_geometry_reply(pConnection, xcb_get_geometry(pConnection, wnd), nullptr);
250
251 if (!pGeometry)
252 return false;
253
254 const int border = pGeometry->border_width;
255 const int w = pGeometry->width + 2 * border;
256 const int h = pGeometry->height + 2 * border;
257 xcb_translate_coordinates_reply_t* pOrigin = xcb_translate_coordinates_reply(pConnection, xcb_translate_coordinates(pConnection, wnd, pGeometry->root, -border, -border), nullptr);
258 free(pGeometry);
259
260 if (!pOrigin)
261 return false;
262
263 rect.x0 = pOrigin->dst_x;
264 rect.y0 = pOrigin->dst_y;
265 rect.x1 = rect.x0 + w;
266 rect.y1 = rect.y0 + h;
267 free(pOrigin);
268
269 return true;
270 }
271
272 accesskit_unix_adapter* mAdapter = nullptr;
273 uintptr_t mId = 0;
274 Display* mDisplay;
275 Window mWnd;
276 std::atomic<bool> mWantsBounds { false };
277 std::atomic<bool> mBoundsRequested { false };
278 std::chrono::steady_clock::time_point mBoundsTime;
279 accesskit_rect mInnerBounds { 0., 0., 0., 0. };
280 accesskit_rect mOuterBounds { 0., 0., 0., 0. };
281};
282
283END_IGRAPHICS_NAMESPACE
284END_IPLUG_NAMESPACE
285#endif
286
287namespace
288{
289// Match WindowWidth()/WindowHeight() followed by the X11/display-scale conversion.
290double PhysicalWindowDimension(int designDimension, float drawScale, float screenScale)
291{
292 // Probe large candidates without overflowing int; actual window sizes fit in int.
293 const float logical = std::trunc(designDimension * drawScale);
294 return std::trunc(logical * screenScale);
295}
296
297unsigned long HoverMillis() { return static_cast<unsigned long>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()); }
298
299std::vector<std::string> ParseDroppedFiles(const unsigned char* data, size_t length)
300{
301 std::vector<std::string> paths;
302 const std::string list(reinterpret_cast<const char*>(data), length);
303 for (size_t start = 0; start < list.size();)
304 {
305 const size_t end = list.find('\n', start);
306 const std::string line = list.substr(start, end == std::string::npos ? end : end - start);
307 start = end == std::string::npos ? list.size() : end + 1;
308 if (line.empty() || line[0] == '#')
309 continue;
310 const std::string uri = line.back() == '\r' ? line.substr(0, line.size() - 1) : line;
311 if (uri.compare(0, 7, "file://") != 0)
312 continue;
313 size_t pathStart = 7;
314 if (uri.compare(pathStart, 10, "localhost/") == 0)
315 pathStart += 9;
316 if (pathStart >= uri.size() || uri[pathStart] != '/')
317 continue;
318 std::string path;
319 bool valid = true;
320 for (size_t i = pathStart; i < uri.size(); ++i)
321 {
322 if (uri[i] != '%')
323 {
324 path += uri[i];
325 continue;
326 }
327 if (i + 2 >= uri.size())
328 {
329 valid = false;
330 break;
331 }
332 auto hex = [](char c) -> int {
333 if (c >= '0' && c <= '9')
334 return c - '0';
335 if (c >= 'a' && c <= 'f')
336 return c - 'a' + 10;
337 if (c >= 'A' && c <= 'F')
338 return c - 'A' + 10;
339 return -1;
340 };
341 const int hi = hex(uri[i + 1]), lo = hex(uri[i + 2]);
342 if (hi < 0 || lo < 0 || (hi == 0 && lo == 0))
343 {
344 valid = false;
345 break;
346 }
347 path += static_cast<char>((hi << 4) | lo);
348 i += 2;
349 }
350 if (valid && path.find('\0') == std::string::npos)
351 paths.push_back(std::move(path));
352 }
353 return paths;
354}
355
356class LinuxClipboard
357{
358public:
359 ~LinuxClipboard()
360 {
361 mRunning = false;
362 if (mThread)
363 pthread_join(mThread, nullptr);
364 if (mDisplay)
365 {
366 XDestroyWindow(mDisplay, mWindow);
367 XCloseDisplay(mDisplay);
368 }
369 }
370
371 bool SetText(const char* text, const char* displayName)
372 {
373 std::lock_guard<std::mutex> lock(mMutex);
374 if (!mDisplay)
375 {
376 mDisplay = XOpenDisplay(displayName);
377 if (!mDisplay)
378 {
379 fprintf(stderr, "Could not open the X11 clipboard display\n");
380 return false;
381 }
382 mConnection = XGetXCBConnection(mDisplay);
383 if (!mConnection)
384 {
385 fprintf(stderr, "Could not access the XCB clipboard connection\n");
386 XCloseDisplay(mDisplay);
387 mDisplay = nullptr;
388 return false;
389 }
390 mWindow = XCreateSimpleWindow(mDisplay, DefaultRootWindow(mDisplay), 0, 0, 1, 1, 0, 0, 0);
391 mClipboard = XInternAtom(mDisplay, "CLIPBOARD", 0);
392 mUTF8 = XInternAtom(mDisplay, "UTF8_STRING", 0);
393 mTargets = XInternAtom(mDisplay, "TARGETS", 0);
394 mRunning = true;
395 const int error = pthread_create(&mThread, nullptr, Run, this);
396 if (error)
397 {
398 fprintf(stderr, "Could not start the X11 clipboard service: %s\n", strerror(error));
399 mRunning = false;
400 mThread = 0;
401 XDestroyWindow(mDisplay, mWindow);
402 XCloseDisplay(mDisplay);
403 mDisplay = nullptr;
404 mConnection = nullptr;
405 return false;
406 }
407 }
408 if (strcmp(DisplayString(mDisplay), displayName) != 0)
409 {
410 fprintf(stderr, "The clipboard service is already connected to another X11 display\n");
411 return false;
412 }
413 mText.Set(text);
414 XSetSelectionOwner(mDisplay, mClipboard, mWindow, 0);
415 XSync(mDisplay, 0);
416 return XGetSelectionOwner(mDisplay, mClipboard) == mWindow;
417 }
418
419 bool GetOwnedText(Window owner, const char* displayName, WDL_String& text)
420 {
421 std::lock_guard<std::mutex> lock(mMutex);
422 if (!mDisplay || owner != mWindow || strcmp(DisplayString(mDisplay), displayName) != 0)
423 return false;
424 text.Set(mText.Get());
425 return true;
426 }
427
428private:
429 static void* Run(void* context)
430 {
431 auto* self = static_cast<LinuxClipboard*>(context);
432 while (self->mRunning)
433 {
434 {
435 std::lock_guard<std::mutex> lock(self->mMutex);
436 while (XPending(self->mDisplay))
437 {
438 XEvent event;
439 XNextEvent(self->mDisplay, &event);
440 if (event.type == SelectionRequest)
441 self->Reply(event.xselectionrequest);
442 else if (event.type == SelectionClear && XGetSelectionOwner(self->mDisplay, self->mClipboard) != self->mWindow)
443 self->mText.Set("");
444 }
445 }
446 pollfd fd{XConnectionNumber(self->mDisplay), POLLIN, 0};
447 const int result = poll(&fd, 1, 20);
448 if (result < 0 && errno != EINTR)
449 {
450 fprintf(stderr, "Could not poll the X11 clipboard display: %s\n", strerror(errno));
451 break;
452 }
453 }
454 return nullptr;
455 }
456
457 void Reply(const XSelectionRequestEvent& request)
458 {
459 XFlush(mDisplay);
460 xcb_selection_notify_event_t response{};
461 response.response_type = XCB_SELECTION_NOTIFY;
462 response.requestor = request.requestor;
463 response.selection = request.selection;
464 response.target = request.target;
465 response.time = request.time;
466 const Atom property = request.property ? request.property : request.target;
467 if (request.target == mTargets)
468 {
469 const xcb_atom_t targets[] = {static_cast<xcb_atom_t>(mTargets), static_cast<xcb_atom_t>(mUTF8), XCB_ATOM_STRING};
470 if (!CheckReply(xcb_change_property_checked(mConnection, XCB_PROP_MODE_REPLACE, request.requestor, property, XCB_ATOM_ATOM, 32, 3, targets), "property write"))
471 return;
472 response.property = property;
473 }
474 else if (request.target == mUTF8 || request.target == XA_STRING)
475 {
476 if (!CheckReply(xcb_change_property_checked(mConnection, XCB_PROP_MODE_REPLACE, request.requestor, property, request.target, 8, mText.GetLength(), mText.Get()), "property write"))
477 return;
478 response.property = property;
479 }
480 char event[32]{};
481 static_assert(sizeof(response) <= sizeof(event), "X11 selection event must fit the wire event");
482 memcpy(event, &response, sizeof(response));
483 CheckReply(xcb_send_event_checked(mConnection, 0, request.requestor, XCB_EVENT_MASK_NO_EVENT, event), "selection notification");
484 }
485
486 bool CheckReply(xcb_void_cookie_t cookie, const char* operation)
487 {
488 xcb_generic_error_t* error = xcb_request_check(mConnection, cookie);
489 if (error)
490 {
491 fprintf(stderr, "X11 clipboard %s failed (error %u, resource 0x%x)\n", operation, error->error_code, error->resource_id);
492 free(error);
493 return false;
494 }
495 if (xcb_connection_has_error(mConnection))
496 {
497 fprintf(stderr, "The XCB clipboard connection failed during %s\n", operation);
498 return false;
499 }
500 return true;
501 }
502
503 Display* mDisplay = nullptr;
504 xcb_connection_t* mConnection = nullptr;
505 Window mWindow = 0;
506 Atom mClipboard = 0;
507 Atom mUTF8 = 0;
508 Atom mTargets = 0;
509 WDL_String mText;
510 std::mutex mMutex;
511 std::atomic<bool> mRunning{false};
512 pthread_t mThread = 0;
513};
514
515static LinuxClipboard& GetLinuxClipboard()
516{
517 // A separate connection serves selections even while the host UI thread waits for a paste.
518 static LinuxClipboard clipboard;
519 return clipboard;
520}
521} // namespace
522
523// ---- Font helpers -----------------------------------------------------------
524
526class LinuxFileFont final : public PlatformFont
527{
528public:
529 LinuxFileFont(const char* filePath, bool isSystem)
530 : PlatformFont(isSystem)
531 {
532 mPath.Set(filePath);
533 }
534
535 IFontDataPtr GetFontData() override
536 {
537 IFontDataPtr fontData(new IFontData());
538 FILE* fp = fopen(mPath.Get(), "rb");
539 if (!fp)
540 return fontData;
541
542 fseek(fp, 0, SEEK_END);
543 long fileSize = ftell(fp);
544 if (fileSize <= 0)
545 {
546 fclose(fp);
547 return fontData;
548 }
549 fontData = std::make_unique<IFontData>((int)fileSize);
550
551 if (!fontData->GetSize())
552 {
553 fclose(fp);
554 return fontData;
555 }
556
557 fseek(fp, 0, SEEK_SET);
558 size_t readSize = fread(fontData->Get(), 1, fontData->GetSize(), fp);
559 fclose(fp);
560
561 if (readSize && readSize == (size_t)fontData->GetSize())
562 fontData->SetFaceIdx(0);
563
564 return fontData;
565 }
566
567private:
568 WDL_String mPath;
569};
570
572class LinuxMemFont final : public PlatformFont
573{
574public:
575 LinuxMemFont(const void* pData, int dataSize)
576 : PlatformFont(false)
577 {
578 mData.Set((const unsigned char*)pData, dataSize);
579 }
580
581 IFontDataPtr GetFontData() override { return IFontDataPtr(new IFontData(mData.Get(), mData.GetSize(), 0)); }
582
583private:
584 WDL_TypedBuf<unsigned char> mData;
585};
586
587// ---- Runtime GTK3 (optional — loaded via dlopen so the plugin works without GTK) ----
588
590{
591 double red, green, blue, alpha;
592};
594{
595 int x, y, width, height;
596};
597
598// GdkGravity values for gtk_menu_popup_at_rect anchoring
599static constexpr int kGDK_GRAVITY_NORTH_WEST = 1;
600static constexpr int kGDK_GRAVITY_SOUTH_WEST = 7;
601
602// Opaque GTK/GDK types — only used as void* through the function pointers below.
603struct _GtkWidget;
604
605// GTK response codes (subset we need)
606static constexpr int kGTK_RESPONSE_OK = -5;
607static constexpr int kGTK_RESPONSE_CANCEL = -6;
608static constexpr int kGTK_RESPONSE_YES = -8;
609static constexpr int kGTK_RESPONSE_NO = -9;
610static constexpr int kGTK_RESPONSE_RETRY = 1;
611
612// GTK file-chooser action codes
613static constexpr int kGTK_FILE_CHOOSER_ACTION_OPEN = 0;
614static constexpr int kGTK_FILE_CHOOSER_ACTION_SAVE = 1;
615static constexpr int kGTK_FILE_CHOOSER_ACTION_SELECT_FOLDER = 2;
616
617// GTK button presets used by message dialogs
618static constexpr int kGTK_BUTTONS_NONE = 0;
619static constexpr int kGTK_BUTTONS_OK = 1;
620static constexpr int kGTK_BUTTONS_YES_NO = 4;
621static constexpr int kGTK_BUTTONS_OK_CANCEL = 5;
622
623// GTK message-dialog icon types
624static constexpr int kGTK_MESSAGE_INFO = 0;
625static constexpr int kGTK_MESSAGE_QUESTION = 3;
626
627struct GTK3
628{
629 void* handle = nullptr;
630
631 // Core
632 using fn_init_check = int (*)(int*, char***);
633 using fn_events_pending = int (*)();
634 using fn_main_iteration_do = int (*)(int);
635 // Dialogs
636 using fn_dialog_run = int (*)(void*);
637 using fn_dialog_add_button = void* (*)(void*, const char*, int);
638 using fn_widget_destroy = void (*)(void*);
639 using fn_window_set_title = void (*)(void*, const char*);
640 // File chooser
641 using fn_file_chooser_dialog_new = void* (*)(const char*, void*, int, const char*, ...);
642 using fn_file_chooser_get_filename = char* (*)(void*);
643 using fn_file_chooser_set_current_folder = int (*)(void*, const char*);
644 using fn_file_chooser_set_current_name = void (*)(void*, const char*);
645 using fn_file_filter_new = void* (*)();
646 using fn_file_filter_set_name = void (*)(void*, const char*);
647 using fn_file_filter_add_pattern = void (*)(void*, const char*);
648 using fn_file_chooser_add_filter = void (*)(void*, void*);
649 // Color chooser
650 using fn_color_chooser_dialog_new = void* (*)(const char*, void*);
651 using fn_color_chooser_get_rgba = void (*)(void*, GdkRGBA*);
652 using fn_color_chooser_set_rgba = void (*)(void*, const GdkRGBA*);
653 // Message dialog
654 using fn_message_dialog_new = void* (*)(void*, int, int, int, const char*, ...);
655 // Popup menu
656 using fn_menu_new = void* (*)();
657 using fn_menu_item_new_with_label = void* (*)(const char*);
658 using fn_check_menu_item_new_with_label = void* (*)(const char*);
659 using fn_separator_menu_item_new = void* (*)();
660 using fn_menu_shell_append = void (*)(void*, void*);
661 using fn_menu_item_set_submenu = void (*)(void*, void*);
662 using fn_check_menu_item_set_active = void (*)(void*, int);
663 using fn_widget_set_sensitive = void (*)(void*, int);
664 using fn_widget_show_all = void (*)(void*);
665 using fn_widget_get_mapped = int (*)(void*);
666 using fn_menu_popup_at_pointer = void (*)(void*, void*);
667 // gtk_menu_popup_at_rect: positions menu relative to a GdkWindow rectangle.
668 // args: menu, rect_window, rect(GdkRectangle*), rect_anchor, menu_anchor, trigger_event
669 using fn_menu_popup_at_rect = void (*)(void*, void*, const void*, int, int, void*);
670 using fn_main = void (*)();
671 using fn_main_quit = void (*)();
672 // g_signal_connect is a macro over g_signal_connect_data in GObject
673 using fn_signal_connect_data = unsigned long (*)(void*, const char*, void*, void*, void*, int);
674 // Window management (for dialog parenting)
675 using fn_window_set_modal = void (*)(void*, int);
676 using fn_window_present = void (*)(void*);
677 using fn_window_set_position = void (*)(void*, int);
678 // GDK helpers for popup menu positioning
679 using fn_gdk_display_get_default = void* (*)();
680 using fn_gdk_x11_window_foreign = void* (*)(void*, unsigned long);
681 using fn_g_object_unref = void (*)(void*);
682 // Entry dialog
683 using fn_entry_new = void* (*)();
684 using fn_entry_set_text = void (*)(void*, const char*);
685 using fn_entry_get_text = const char* (*)(void*);
686 using fn_entry_set_max_length = void (*)(void*, int);
687 using fn_dialog_new_with_buttons = void* (*)(const char*, void*, int, const char*, ...);
688 using fn_dialog_get_content_area = void* (*)(void*);
689 using fn_dialog_response = void (*)(void*, int);
690 using fn_box_pack_start = void (*)(void*, void*, int, int, unsigned);
691
692 fn_init_check init_check = nullptr;
693 fn_events_pending events_pending = nullptr;
694 fn_main_iteration_do main_iteration_do = nullptr;
695 fn_dialog_run dialog_run = nullptr;
696 fn_dialog_add_button dialog_add_button = nullptr;
697 fn_widget_destroy widget_destroy = nullptr;
698 fn_window_set_title window_set_title = nullptr;
699 fn_file_chooser_dialog_new file_chooser_dialog_new = nullptr;
700 fn_file_chooser_get_filename file_chooser_get_filename = nullptr;
701 fn_file_chooser_set_current_folder file_chooser_set_current_folder = nullptr;
702 fn_file_chooser_set_current_name file_chooser_set_current_name = nullptr;
703 fn_file_filter_new file_filter_new = nullptr;
704 fn_file_filter_set_name file_filter_set_name = nullptr;
705 fn_file_filter_add_pattern file_filter_add_pattern = nullptr;
706 fn_file_chooser_add_filter file_chooser_add_filter = nullptr;
707 fn_color_chooser_dialog_new color_chooser_dialog_new = nullptr;
708 fn_color_chooser_get_rgba color_chooser_get_rgba = nullptr;
709 fn_color_chooser_set_rgba color_chooser_set_rgba = nullptr;
710 fn_message_dialog_new message_dialog_new = nullptr;
711 fn_menu_new menu_new = nullptr;
712 fn_menu_item_new_with_label menu_item_new_with_label = nullptr;
713 fn_check_menu_item_new_with_label check_menu_item_new_with_label = nullptr;
714 fn_separator_menu_item_new separator_menu_item_new = nullptr;
715 fn_menu_shell_append menu_shell_append = nullptr;
716 fn_menu_item_set_submenu menu_item_set_submenu = nullptr;
717 fn_check_menu_item_set_active check_menu_item_set_active = nullptr;
718 fn_widget_set_sensitive widget_set_sensitive = nullptr;
719 fn_widget_show_all widget_show_all = nullptr;
720 fn_widget_get_mapped widget_get_mapped = nullptr;
721 fn_menu_popup_at_pointer menu_popup_at_pointer = nullptr;
722 fn_menu_popup_at_rect menu_popup_at_rect = nullptr;
723 fn_main main = nullptr;
724 fn_main_quit main_quit = nullptr;
725 fn_signal_connect_data signal_connect_data = nullptr;
726 fn_entry_new entry_new = nullptr;
727 fn_entry_set_text entry_set_text = nullptr;
728 fn_entry_get_text entry_get_text = nullptr;
729 fn_entry_set_max_length entry_set_max_length = nullptr;
730 fn_window_set_modal window_set_modal = nullptr;
731 fn_window_present window_present = nullptr;
732 fn_window_set_position window_set_position = nullptr;
733 fn_gdk_display_get_default gdk_display_get_default = nullptr;
734 fn_gdk_x11_window_foreign gdk_x11_window_foreign = nullptr;
735 fn_g_object_unref g_object_unref = nullptr;
736 fn_dialog_new_with_buttons dialog_new_with_buttons = nullptr;
737 fn_dialog_get_content_area dialog_get_content_area = nullptr;
738 fn_dialog_response dialog_response = nullptr;
739 fn_box_pack_start box_pack_start = nullptr;
740};
741
742#define LOAD_GTK_SYM(g, name) g.name = (GTK3::fn_##name)dlsym(g.handle, "gtk_" #name)
743
744static GTK3* LoadGTK3()
745{
746 static GTK3 gtk;
747 static bool sTried = false;
748 if (sTried)
749 return gtk.handle ? &gtk : nullptr;
750 sTried = true;
751
752 // GTK 3 aborts the process if it is initialised alongside GTK 2, so do
753 // without native dialogs in a host that has already loaded GTK 2.
754 if (dlsym(RTLD_DEFAULT, "gtk_progress_get_type"))
755 return nullptr;
756
757 // RTLD_LOCAL keeps GTK's symbols out of the host's global namespace; all
758 // GTK calls go through the explicit function-pointer table below.
759 gtk.handle = dlopen("libgtk-3.so.0", RTLD_NOW | RTLD_LOCAL);
760 if (!gtk.handle)
761 return nullptr;
762
763 LOAD_GTK_SYM(gtk, init_check);
764 LOAD_GTK_SYM(gtk, events_pending);
765 LOAD_GTK_SYM(gtk, main_iteration_do);
766 LOAD_GTK_SYM(gtk, dialog_run);
767 LOAD_GTK_SYM(gtk, dialog_add_button);
768 LOAD_GTK_SYM(gtk, widget_destroy);
769 LOAD_GTK_SYM(gtk, window_set_title);
770 LOAD_GTK_SYM(gtk, file_chooser_dialog_new);
771 LOAD_GTK_SYM(gtk, file_chooser_get_filename);
772 LOAD_GTK_SYM(gtk, file_chooser_set_current_folder);
773 LOAD_GTK_SYM(gtk, file_chooser_set_current_name);
774 LOAD_GTK_SYM(gtk, file_filter_new);
775 LOAD_GTK_SYM(gtk, file_filter_set_name);
776 LOAD_GTK_SYM(gtk, file_filter_add_pattern);
777 LOAD_GTK_SYM(gtk, file_chooser_add_filter);
778 LOAD_GTK_SYM(gtk, color_chooser_dialog_new);
779 LOAD_GTK_SYM(gtk, color_chooser_get_rgba);
780 LOAD_GTK_SYM(gtk, color_chooser_set_rgba);
781 LOAD_GTK_SYM(gtk, message_dialog_new);
782 LOAD_GTK_SYM(gtk, menu_new);
783 LOAD_GTK_SYM(gtk, menu_item_new_with_label);
784 LOAD_GTK_SYM(gtk, check_menu_item_new_with_label);
785 LOAD_GTK_SYM(gtk, separator_menu_item_new);
786 LOAD_GTK_SYM(gtk, menu_shell_append);
787 LOAD_GTK_SYM(gtk, menu_item_set_submenu);
788 LOAD_GTK_SYM(gtk, check_menu_item_set_active);
789 LOAD_GTK_SYM(gtk, widget_set_sensitive);
790 LOAD_GTK_SYM(gtk, widget_show_all);
791 LOAD_GTK_SYM(gtk, widget_get_mapped);
792 LOAD_GTK_SYM(gtk, menu_popup_at_pointer);
793 LOAD_GTK_SYM(gtk, menu_popup_at_rect);
794 LOAD_GTK_SYM(gtk, main);
795 LOAD_GTK_SYM(gtk, main_quit);
796 // g_signal_connect_data is in libgobject, but GTK re-exports it
797 gtk.signal_connect_data = (GTK3::fn_signal_connect_data)dlsym(gtk.handle, "g_signal_connect_data");
798 LOAD_GTK_SYM(gtk, entry_new);
799 LOAD_GTK_SYM(gtk, entry_set_text);
800 LOAD_GTK_SYM(gtk, entry_get_text);
801 LOAD_GTK_SYM(gtk, entry_set_max_length);
802 LOAD_GTK_SYM(gtk, window_set_modal);
803 LOAD_GTK_SYM(gtk, window_present);
804 LOAD_GTK_SYM(gtk, window_set_position);
805 // GDK/GLib symbols (not gtk_ prefixed — load directly)
806 gtk.gdk_display_get_default = (GTK3::fn_gdk_display_get_default)dlsym(gtk.handle, "gdk_display_get_default");
807 gtk.gdk_x11_window_foreign = (GTK3::fn_gdk_x11_window_foreign)dlsym(gtk.handle, "gdk_x11_window_foreign_new_for_display");
808 gtk.g_object_unref = (GTK3::fn_g_object_unref)dlsym(gtk.handle, "g_object_unref");
809 LOAD_GTK_SYM(gtk, dialog_new_with_buttons);
810 LOAD_GTK_SYM(gtk, dialog_get_content_area);
811 LOAD_GTK_SYM(gtk, dialog_response);
812 LOAD_GTK_SYM(gtk, box_pack_start);
813
814 if (!gtk.init_check || !gtk.dialog_run || !gtk.widget_destroy || !gtk.file_chooser_dialog_new || !gtk.file_chooser_get_filename)
815 {
816 dlclose(gtk.handle);
817 gtk.handle = nullptr;
818 return nullptr;
819 }
820
821 // gtk_init_check() would otherwise call setlocale(LC_ALL, ""), changing
822 // e.g. the decimal separator for the host and every other plugin.
823 if (auto disableSetLocale = reinterpret_cast<void (*)()>(dlsym(gtk.handle, "gtk_disable_setlocale")))
824 disableSetLocale();
825
826 // IGraphics windows are X11 windows (XWayland on a Wayland session). GTK must use
827 // the same X display, or its menus can't be anchored to them and its dialogs
828 // and menus don't get focus/grabs. No effect if a host already initialised GTK.
829 if (auto setAllowedBackends = reinterpret_cast<void (*)(const char*)>(dlsym(gtk.handle, "gdk_set_allowed_backends")))
830 setAllowedBackends("x11");
831
832 if (!gtk.init_check(nullptr, nullptr))
833 {
834 dlclose(gtk.handle);
835 gtk.handle = nullptr;
836 return nullptr;
837 }
838
839 // The standalone runs GDK at window scale 1 (SWELL draws its own HiDPI UI),
840 // so GTK dialogs would be drawn at 1x. Scale their fonts by the remaining
841 // factor instead; in plugin hosts GDK already applies the monitor scale.
842 using fn_screen_get_default = void* (*)();
843 using fn_monitor_scale = int (*)(void*, int);
844 using fn_settings_get_default = void* (*)();
845 using fn_object_get = void (*)(void*, const char*, ...);
846 using fn_object_set = void (*)(void*, const char*, ...);
847 auto screen_get_default = (fn_screen_get_default)dlsym(gtk.handle, "gdk_screen_get_default");
848 auto monitor_scale = (fn_monitor_scale)dlsym(gtk.handle, "gdk_screen_get_monitor_scale_factor");
849 auto settings_get_default = (fn_settings_get_default)dlsym(gtk.handle, "gtk_settings_get_default");
850 auto object_get = (fn_object_get)dlsym(gtk.handle, "g_object_get");
851 auto object_set = (fn_object_set)dlsym(gtk.handle, "g_object_set");
852 const char* str = getenv("IPLUG2_SCREEN_SCALE");
853 char* pEnd = nullptr;
854 const double screenScale = str ? strtod(str, &pEnd) : 0.;
855 void* pScreen = screen_get_default ? screen_get_default() : nullptr;
856 void* pSettings = settings_get_default ? settings_get_default() : nullptr;
857 if (str && pEnd != str && *pEnd == '\0' && screenScale >= 1. && screenScale <= 8. && pScreen && pSettings && monitor_scale && object_get && object_set)
858 {
859 const double remaining = screenScale / std::max(1, monitor_scale(pScreen, 0));
860 if (remaining > 1.01)
861 {
862 int dpi = -1; // in 1/1024ths of a dot per inch; -1 when unset
863 object_get(pSettings, "gtk-xft-dpi", &dpi, nullptr);
864 if (dpi <= 0)
865 dpi = 96 * 1024;
866 object_set(pSettings, "gtk-xft-dpi", static_cast<int>(std::lround(dpi * remaining)), nullptr);
867 }
868 }
869 return &gtk;
870}
871
872static void GtkDrainEvents(GTK3* pGTK)
873{
874 if (pGTK->events_pending && pGTK->main_iteration_do)
875 while (pGTK->events_pending())
876 pGTK->main_iteration_do(0 /* non-blocking */);
877}
878
879// Present a GTK dialog as modal so the WM grants it focus and input grabs.
880// Without this, file-chooser dropdowns and color-picker sub-dialogs fail
881// on compositing WMs (Mutter, KWin) because GTK can't acquire a GDK grab.
882static constexpr int kGTK_WIN_POS_MOUSE = 2;
883
884static void GtkPresentDialog(GTK3* pGTK, void* dialog)
885{
886 if (pGTK->window_set_modal)
887 pGTK->window_set_modal(dialog, 1);
888 // The dialog has no GTK parent to be placed relative to, so without a hint
889 // it opens at the screen origin. Open it at the pointer, where the user clicked.
890 if (pGTK->window_set_position)
891 pGTK->window_set_position(dialog, kGTK_WIN_POS_MOUSE);
892 if (pGTK->window_present)
893 pGTK->window_present(dialog);
894}
895
896// Launch a detached external process. Double-forks so the grandchild is
897// reparented to init and the intermediate child is reaped here — neither
898// becomes a zombie. Returns true if the launch was initiated.
899static bool LaunchDetached(const char* program, const char* arg)
900{
901 pid_t pid = fork();
902 if (pid == 0)
903 {
904 pid_t grandchild = fork();
905 if (grandchild == 0)
906 {
907 execlp(program, program, arg, (char*)nullptr);
908 _exit(127);
909 }
910 _exit(grandchild > 0 ? 0 : 1);
911 }
912 if (pid > 0)
913 {
914 int status;
915 while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
916 {
917 }
918 return true;
919 }
920 return false;
921}
922
923static bool GtkAddFileFilters(GTK3* pGTK, void* dialog, const char* ext)
924{
925 WDL_String extensions(ext ? ext : "");
926 char* context = nullptr;
927 char* token = strtok_r(extensions.Get(), " \t\r\n", &context);
928 if (!token)
929 return true;
930
931 if (!pGTK->file_filter_new || !pGTK->file_filter_add_pattern || !pGTK->file_chooser_add_filter)
932 {
933 fprintf(stderr, "Cannot apply file dialog filters: required GTK functions are unavailable\n");
934 return false;
935 }
936
937 void* filter = pGTK->file_filter_new();
938 if (!filter)
939 {
940 fprintf(stderr, "Could not create the file extension filter\n");
941 return false;
942 }
943 if (pGTK->file_filter_set_name)
944 pGTK->file_filter_set_name(filter, ext);
945 do
946 {
947 WDL_String pattern;
948 if (token[0] == '*')
949 pattern.Set(token);
950 else
951 {
952 pattern.Set("*.");
953 pattern.Append(token[0] == '.' ? token + 1 : token);
954 }
955 pGTK->file_filter_add_pattern(filter, pattern.Get());
956 token = strtok_r(nullptr, " \t\r\n", &context);
957 } while (token);
958 pGTK->file_chooser_add_filter(dialog, filter);
959
960 void* all = pGTK->file_filter_new();
961 if (!all)
962 {
963 fprintf(stderr, "Could not create the all-files filter\n");
964 return false;
965 }
966 if (pGTK->file_filter_set_name)
967 pGTK->file_filter_set_name(all, "All Files");
968 pGTK->file_filter_add_pattern(all, "*");
969 pGTK->file_chooser_add_filter(dialog, all);
970 return true;
971}
972
973// ---- Runtime fontconfig (optional — loaded via dlopen so plugins work without it) ----
974
975// Fontconfig opaque types — only used through function pointers below.
976struct _FcPattern;
977struct _FcConfig;
978
979// Fontconfig constants we need (match the enum values from fontconfig.h)
980static constexpr int kFC_WEIGHT_REGULAR = 80;
981static constexpr int kFC_WEIGHT_BOLD = 200;
982static constexpr int kFC_SLANT_ROMAN = 0;
983static constexpr int kFC_SLANT_ITALIC = 100;
984static constexpr int kFC_MatchPattern = 0; // FcMatchKind
985static constexpr int kFC_ResultMatch = 0; // FcResult
986
988{
989 void* handle = nullptr;
990
991 using fn_PatternCreate = _FcPattern* (*)();
992 using fn_PatternAddString = int (*)(_FcPattern*, const char*, const unsigned char*);
993 using fn_PatternAddInteger = int (*)(_FcPattern*, const char*, int);
994 using fn_ConfigSubstitute = int (*)(_FcConfig*, _FcPattern*, int);
995 using fn_DefaultSubstitute = void (*)(_FcPattern*);
996 using fn_FontMatch = _FcPattern* (*)(_FcConfig*, _FcPattern*, int*);
997 using fn_PatternDestroy = void (*)(_FcPattern*);
998 using fn_PatternGetString = int (*)(_FcPattern*, const char*, int, unsigned char**);
999
1000 fn_PatternCreate PatternCreate = nullptr;
1001 fn_PatternAddString PatternAddString = nullptr;
1002 fn_PatternAddInteger PatternAddInteger = nullptr;
1003 fn_ConfigSubstitute ConfigSubstitute = nullptr;
1004 fn_DefaultSubstitute DefaultSubstitute = nullptr;
1005 fn_FontMatch FontMatch = nullptr;
1006 fn_PatternDestroy PatternDestroy = nullptr;
1007 fn_PatternGetString PatternGetString = nullptr;
1008};
1009
1010#define LOAD_FC_SYM(fc, name) fc.name = (Fontconfig::fn_##name)dlsym(fc.handle, "Fc" #name)
1011
1012static Fontconfig* LoadFontconfig()
1013{
1014 static Fontconfig fc;
1015 static bool sTried = false;
1016
1017 if (sTried)
1018 return fc.handle ? &fc : nullptr;
1019
1020 sTried = true;
1021 fc.handle = dlopen("libfontconfig.so.1", RTLD_NOW);
1022 if (!fc.handle)
1023 return nullptr;
1024
1025 LOAD_FC_SYM(fc, PatternCreate);
1026 LOAD_FC_SYM(fc, PatternAddString);
1027 LOAD_FC_SYM(fc, PatternAddInteger);
1028 LOAD_FC_SYM(fc, ConfigSubstitute);
1029 LOAD_FC_SYM(fc, DefaultSubstitute);
1030 LOAD_FC_SYM(fc, FontMatch);
1031 LOAD_FC_SYM(fc, PatternDestroy);
1032 LOAD_FC_SYM(fc, PatternGetString);
1033
1034 if (!fc.PatternCreate || !fc.FontMatch || !fc.PatternGetString)
1035 {
1036 dlclose(fc.handle);
1037 fc.handle = nullptr;
1038 return nullptr;
1039 }
1040
1041 return &fc;
1042}
1043
1044IGraphicsLinux::IGraphicsLinux(IGEditorDelegate& dlg, int w, int h, int fps, float scale)
1045 : IGRAPHICS_DRAW_CLASS(dlg, w, h, fps, scale)
1046{
1047#if defined VST3_API || defined VST3C_API || defined CLAP_API
1048 mHostDriven = true;
1049#endif
1050 // Required before any Xlib calls from multiple threads
1051 XInitThreads();
1052}
1053
1054IGraphicsLinux::~IGraphicsLinux() { CloseWindow(); }
1055
1056void* IGraphicsLinux::OpenWindow(void* pParent)
1057{
1058 StopTimer();
1059 mCloseRequested = false;
1060 mDisplay = XOpenDisplay(nullptr);
1061 if (!mDisplay)
1062 return nullptr;
1063
1064 int screen = DefaultScreen(mDisplay);
1065 Window root = RootWindow(mDisplay, screen);
1066
1067 mParentWnd = root;
1068 if (pParent)
1069 {
1070 auto* connection = XGetXCBConnection(mDisplay);
1071 if (!connection)
1072 {
1073 fprintf(stderr, "Could not access the XCB connection to validate the editor parent\n");
1074 XCloseDisplay(mDisplay);
1075 mDisplay = nullptr;
1076 return nullptr;
1077 }
1078 const uintptr_t parent = reinterpret_cast<uintptr_t>(pParent);
1079 xcb_generic_error_t* error = nullptr;
1080 xcb_get_window_attributes_reply_t* attributes = nullptr;
1081 if (parent <= UINT32_MAX)
1082 attributes = xcb_get_window_attributes_reply(connection, xcb_get_window_attributes(connection, static_cast<xcb_window_t>(parent)), &error);
1083 if (attributes && !error)
1084 mParentWnd = static_cast<Window>(parent);
1085 else
1086 fprintf(stderr, "Invalid X11 editor parent 0x%lx; using a top-level window\n", static_cast<unsigned long>(parent));
1087 free(attributes);
1088 free(error);
1089 if (xcb_connection_has_error(connection))
1090 {
1091 fprintf(stderr, "The XCB connection failed while validating the editor parent\n");
1092 XCloseDisplay(mDisplay);
1093 mDisplay = nullptr;
1094 return nullptr;
1095 }
1096 }
1097
1098 // Detect HiDPI scale factor. The standalone APP sets IPLUG2_SCREEN_SCALE after
1099 // querying gdk_window_get_scale_factor(). Plugin hosts may set GDK_SCALE.
1100 // Note: on Xwayland the X11 coordinate space uses physical pixels, not logical
1101 // pixels, so XDisplayWidth returns the logical (scaled-down) extent. Do NOT
1102 // compare physW against XDisplayWidth — it will always exceed the logical extent
1103 // on HiDPI displays. Trust gdk_window_get_scale_factor instead.
1104 {
1105 float gdkScale = 1.f;
1106 const char* s = getenv("IPLUG2_SCREEN_SCALE");
1107 if (!s)
1108 s = getenv("GDK_SCALE");
1109 if (s)
1110 {
1111 char* end = nullptr;
1112 const float parsed = strtof(s, &end);
1113 if (end != s && *end == '\0' && std::isfinite(parsed) && parsed >= 1.f && parsed <= 8.f)
1114 gdkScale = parsed;
1115 }
1116 if (gdkScale > 1.f && !GetDelegate()->HasHostScreenScale())
1117 SetScreenScale(gdkScale);
1118 // SetScreenScale is safe here: mPlugWnd==0 so PlatformResize skips,
1119 // and mVG==nullptr so DrawResize skips.
1120 }
1121
1122 // In standalone mode the parent window is SWELL's GDK window which includes
1123 // the non-client area (menu bar). IPlugAPP_host exports the menu bar height
1124 // so we can offset the plugin window below it. Querying XGetWindowAttributes
1125 // on a separate Display connection returns stale geometry, so we use the env
1126 // var set by the host instead.
1127 int clientOffY = 0;
1128 {
1129 const char* menuOff = getenv("IPLUG2_MENU_OFFSET");
1130 if (menuOff)
1131 clientOffY = std::clamp(atoi(menuOff), 0, 100);
1132 }
1133
1134#ifdef IGRAPHICS_GL
1135 XVisualInfo* pVisualInfo = CreateGLContext();
1136 if (!mGLContext)
1137 {
1138 XCloseDisplay(mDisplay);
1139 mDisplay = nullptr;
1140 return nullptr;
1141 }
1142 // Create a colormap compatible with the GL visual so the window and context
1143 // share the same visual — required for glXMakeCurrent to succeed.
1144 mGLColormap = XCreateColormap(mDisplay, root, pVisualInfo->visual, AllocNone);
1145
1146 XSetWindowAttributes attrs = {};
1147 attrs.event_mask = ExposureMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | KeyPressMask | KeyReleaseMask | EnterWindowMask | LeaveWindowMask | FocusChangeMask
1148 | PropertyChangeMask;
1149 attrs.colormap = mGLColormap;
1150 // Required when the GL visual's depth differs from the parent's: without a
1151 // border pixel XCreateWindow fails with BadMatch, which is fatal by default.
1152 attrs.border_pixel = 0;
1153
1154 // X11 window must be in physical pixels (WindowWidth/Height are logical).
1155 const auto physW = (unsigned)(WindowWidth() * GetScreenScale());
1156 const auto physH = (unsigned)(WindowHeight() * GetScreenScale());
1157
1158 mPlugWnd = XCreateWindow(mDisplay, mParentWnd, 0, clientOffY, physW, physH, 0, pVisualInfo->depth, InputOutput, pVisualInfo->visual, CWColormap | CWBorderPixel | CWEventMask, &attrs);
1159 XFree(pVisualInfo);
1160#else
1161 XSetWindowAttributes attrs = {};
1162 attrs.event_mask = ExposureMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | KeyPressMask | KeyReleaseMask | EnterWindowMask | LeaveWindowMask | FocusChangeMask
1163 | PropertyChangeMask;
1164 attrs.background_pixel = BlackPixel(mDisplay, screen);
1165
1166 const auto physW = (unsigned)(WindowWidth() * GetScreenScale());
1167 const auto physH = (unsigned)(WindowHeight() * GetScreenScale());
1168
1169 mPlugWnd = XCreateWindow(mDisplay, mParentWnd, 0, clientOffY, physW, physH, 0, CopyFromParent, InputOutput, CopyFromParent, CWEventMask | CWBackPixel, &attrs);
1170#endif
1171
1172 if (!mPlugWnd)
1173 {
1174#ifdef IGRAPHICS_GL
1175 DestroyGLContext();
1176 if (mGLColormap)
1177 {
1178 XFreeColormap(mDisplay, mGLColormap);
1179 mGLColormap = 0;
1180 }
1181#endif
1182 XCloseDisplay(mDisplay);
1183 mDisplay = nullptr;
1184 return nullptr;
1185 }
1186
1187 mWMDeleteMessage = XInternAtom(mDisplay, "WM_DELETE_WINDOW", 0 /* False */);
1188 mClipboardAtom = XInternAtom(mDisplay, "CLIPBOARD", 0 /* False */);
1189 mUTF8StringAtom = XInternAtom(mDisplay, "UTF8_STRING", 0 /* False */);
1190 mSelDataAtom = XInternAtom(mDisplay, "IPLUG2_SEL_DATA", 0 /* False */);
1191 mXdndAware = XInternAtom(mDisplay, "XdndAware", 0);
1192 mXdndEnter = XInternAtom(mDisplay, "XdndEnter", 0);
1193 mXdndPosition = XInternAtom(mDisplay, "XdndPosition", 0);
1194 mXdndStatus = XInternAtom(mDisplay, "XdndStatus", 0);
1195 mXdndLeave = XInternAtom(mDisplay, "XdndLeave", 0);
1196 mXdndDrop = XInternAtom(mDisplay, "XdndDrop", 0);
1197 mXdndFinished = XInternAtom(mDisplay, "XdndFinished", 0);
1198 mXdndSelection = XInternAtom(mDisplay, "XdndSelection", 0);
1199 mXdndTypeList = XInternAtom(mDisplay, "XdndTypeList", 0);
1200 mXdndActionCopy = XInternAtom(mDisplay, "XdndActionCopy", 0);
1201 mUriList = XInternAtom(mDisplay, "text/uri-list", 0);
1202 mDropProperty = XInternAtom(mDisplay, "IPLUG2_DROP_DATA", 0);
1203 const unsigned long xdndVersion = 5;
1204 XChangeProperty(mDisplay, mPlugWnd, mXdndAware, XA_ATOM, 32, PropModeReplace, reinterpret_cast<const unsigned char*>(&xdndVersion), 1);
1205
1206 // WM protocols and size hints are only appropriate for top-level windows.
1207 // When embedded in a host parent, setting them causes the window manager to
1208 // adopt and reparent the plugin window, making it appear as a second window.
1209 bool isTopLevel = (mParentWnd == (Window)XRootWindow(mDisplay, DefaultScreen(mDisplay)));
1210 if (isTopLevel)
1211 {
1212 XSetWMProtocols(mDisplay, mPlugWnd, &mWMDeleteMessage, 1);
1213
1214 // Tell the WM the fixed (or resizable) size range so it doesn't arbitrarily
1215 // resize the plugin window to the screen dimensions on first map.
1216 XSizeHints hints = {};
1217 hints.flags = PSize | PMinSize;
1218 hints.width = WindowWidth();
1219 hints.height = WindowHeight();
1220 hints.min_width = WindowWidth();
1221 hints.min_height = WindowHeight();
1222 XSetWMNormalHints(mDisplay, mPlugWnd, &hints);
1223 }
1224
1225 XMapWindow(mDisplay, mPlugWnd);
1226 XFlush(mDisplay);
1227
1228#ifdef IGRAPHICS_GL
1229 bool initialized = false;
1230 {
1231 ScopedGLContext scopedGLCtx{this};
1232 if (glXGetCurrentContext() == mGLContext && glXGetCurrentDrawable() == mPlugWnd)
1233 {
1234 gladLoadGL();
1235 OnViewInitialized(nullptr);
1236 GetDelegate()->LayoutUI(this);
1237 SetAllControlsDirty();
1238 DrawResize();
1239 initialized = true;
1240 }
1241 }
1242 if (!initialized)
1243 {
1244 DestroyGLContext();
1245 if (mGLColormap)
1246 {
1247 XFreeColormap(mDisplay, mGLColormap);
1248 mGLColormap = 0;
1249 }
1250 XDestroyWindow(mDisplay, mPlugWnd);
1251 mPlugWnd = 0;
1252 XCloseDisplay(mDisplay);
1253 mDisplay = nullptr;
1254 return nullptr;
1255 }
1256#else
1257 OnViewInitialized(nullptr);
1258 GetDelegate()->LayoutUI(this);
1259 SetAllControlsDirty();
1260 DrawResize();
1261#endif
1262
1263 CreateInputContext();
1264 UpdateTooltips();
1265
1266#ifdef IGRAPHICS_ACCESSKIT
1267 mAccessibility = std::make_unique<IGraphicsAccessibilityLinux>(*this, mDisplay, mPlugWnd);
1268#endif
1269
1270 GetDelegate()->OnUIOpen();
1271
1272 // Mark dirty so the first timer tick renders immediately, even if no
1273 // Expose event arrives before the initial frame.
1274 mNeedsRedraw = true;
1275 if (!StartTimer())
1276 return nullptr;
1277
1278 return (void*)(uintptr_t)mPlugWnd;
1279}
1280
1281void IGraphicsLinux::CloseWindow()
1282{
1283 if (IsInPlatformCallback())
1284 {
1285 RequestWindowClose();
1286 return;
1287 }
1288 StopTimer();
1289 ResetDrag();
1290 HideTooltip();
1291#ifdef IGRAPHICS_ACCESSKIT
1292 mAccessibility = nullptr;
1293#endif
1294 if (!mDisplay)
1295 return;
1296
1297 {
1298 ScopedGLContext scopedGLCtx{this};
1299 OnViewDestroyed();
1300 }
1301
1302#ifdef IGRAPHICS_GL
1303 DestroyGLContext();
1304#endif
1305
1306 if (mBlankCursor)
1307 {
1308 XFreeCursor(mDisplay, mBlankCursor);
1309 mBlankCursor = 0;
1310 }
1311
1312#if defined IGRAPHICS_SKIA && defined IGRAPHICS_CPU
1313 DestroyCPUImage();
1314 if (mCPUGC)
1315 {
1316 XFreeGC(mDisplay, mCPUGC);
1317 mCPUGC = nullptr;
1318 }
1319#endif
1320
1321 DestroyInputContext();
1322 if (mTooltipFont)
1323 {
1324 XFreeFontSet(mDisplay, mTooltipFont);
1325 mTooltipFont = nullptr;
1326 }
1327 if (mPlugWnd)
1328 {
1329 XDestroyWindow(mDisplay, mPlugWnd);
1330 mPlugWnd = 0;
1331 }
1332
1333#ifdef IGRAPHICS_GL
1334 if (mGLColormap)
1335 {
1336 XFreeColormap(mDisplay, mGLColormap);
1337 mGLColormap = 0;
1338 }
1339#endif
1340
1341 XCloseDisplay(mDisplay);
1342 mDisplay = nullptr;
1343}
1344
1345void IGraphicsLinux::ResetDrag()
1346{
1347 mDragSource = 0;
1348 mDragSupported = false;
1349}
1350
1351void IGraphicsLinux::HideTooltip()
1352{
1353 if (mDisplay && mTooltipWindow)
1354 {
1355 XDestroyWindow(mDisplay, mTooltipWindow);
1356 mTooltipWindow = 0;
1357 }
1358}
1359
1360void IGraphicsLinux::UpdateTooltips()
1361{
1362 HideTooltip();
1363 mTooltipControl = -1;
1364 mTooltipHoverTime = HoverMillis();
1365}
1366
1367void IGraphicsLinux::ShowTooltip(float x, float y)
1368{
1369 if (!mDisplay || !mPlugWnd || !TooltipsEnabled() || mTooltipControl < 0 || mTooltipWindow)
1370 return;
1371 IControl* pControl = GetControl(mTooltipControl);
1372 if (!pControl || pControl->IsHidden() || !pControl->GetTooltip() || !*pControl->GetTooltip())
1373 return;
1374 if (!mTooltipFont)
1375 {
1376 char** missing = nullptr;
1377 int count = 0;
1378 char* defaultString = nullptr;
1379 mTooltipFont = XCreateFontSet(mDisplay, "-*-sans-medium-r-normal--14-*-*-*-*-*-*-*", &missing, &count, &defaultString);
1380 if (missing)
1381 XFreeStringList(missing);
1382 // Minimal Xvfb installations (and some desktops) have no "sans" XLFD.
1383 // The core fixed font is present with the standard X11 font packages.
1384 if (!mTooltipFont)
1385 {
1386 missing = nullptr;
1387 mTooltipFont = XCreateFontSet(mDisplay, "fixed", &missing, &count, &defaultString);
1388 if (missing)
1389 XFreeStringList(missing);
1390 }
1391 }
1392 if (!mTooltipFont)
1393 return;
1394 const char* label = pControl->GetTooltip();
1395 const int len = static_cast<int>(strlen(label));
1396 XRectangle ink{}, logical{};
1397 Xutf8TextExtents(mTooltipFont, label, len, &ink, &logical);
1398 const int width = std::max(20, static_cast<int>(logical.width) + 12);
1399 const int height = std::max(20, static_cast<int>(logical.height) + 8);
1400 int rootX = 0, rootY = 0;
1401 Window child = 0;
1402 XTranslateCoordinates(mDisplay, mPlugWnd, DefaultRootWindow(mDisplay), static_cast<int>(x * GetTotalScale()) + 12, static_cast<int>(y * GetTotalScale()) + 20, &rootX, &rootY, &child);
1403 const int screen = DefaultScreen(mDisplay);
1404 rootX = std::max(0, std::min(rootX, DisplayWidth(mDisplay, screen) - width));
1405 rootY = std::max(0, std::min(rootY, DisplayHeight(mDisplay, screen) - height));
1406 XSetWindowAttributes attrs{};
1407 attrs.override_redirect = 1;
1408 attrs.background_pixel = WhitePixel(mDisplay, screen);
1409 attrs.event_mask = ExposureMask;
1410 mTooltipWindow =
1411 XCreateWindow(mDisplay, DefaultRootWindow(mDisplay), rootX, rootY, width, height, 1, CopyFromParent, InputOutput, CopyFromParent, CWOverrideRedirect | CWBackPixel | CWEventMask, &attrs);
1412 if (mTooltipWindow)
1413 XMapRaised(mDisplay, mTooltipWindow);
1414}
1415
1416void IGraphicsLinux::DrawTooltip()
1417{
1418 if (!mTooltipWindow || mTooltipControl < 0 || !mTooltipFont)
1419 return;
1420 IControl* pControl = GetControl(mTooltipControl);
1421 if (!pControl || !pControl->GetTooltip())
1422 return;
1423 const char* label = pControl->GetTooltip();
1424 XRectangle ink{}, logical{};
1425 Xutf8TextExtents(mTooltipFont, label, static_cast<int>(strlen(label)), &ink, &logical);
1426 XWindowAttributes attrs{};
1427 if (!XGetWindowAttributes(mDisplay, mTooltipWindow, &attrs))
1428 return;
1429 GC gc = XCreateGC(mDisplay, mTooltipWindow, 0, nullptr);
1430 XSetForeground(mDisplay, gc, BlackPixel(mDisplay, DefaultScreen(mDisplay)));
1431 XDrawRectangle(mDisplay, mTooltipWindow, gc, 0, 0, attrs.width - 1, attrs.height - 1);
1432 Xutf8DrawString(mDisplay, mTooltipWindow, mTooltipFont, gc, 6, 4 - logical.y, label, static_cast<int>(strlen(label)));
1433 XFreeGC(mDisplay, gc);
1434}
1435
1436void IGraphicsLinux::PlatformResize(bool parentHasResized)
1437{
1438 // When handling a ConfigureNotify, the X server already sized our window.
1439 // Calling XResizeWindow here would create an oscillation.
1440 if (mInConfigureNotify)
1441 return;
1442
1443 if (mDisplay && mPlugWnd)
1444 {
1445 // X11 window must be in physical pixels (WindowWidth/Height are logical).
1446 auto w = (unsigned)(WindowWidth() * GetScreenScale());
1447 auto h = (unsigned)(WindowHeight() * GetScreenScale());
1448 XResizeWindow(mDisplay, mPlugWnd, w, h);
1449 }
1450}
1451
1453{
1454 if (scale == GetScreenScale())
1455 return;
1456 if (mDisplay && mPlugWnd)
1457 {
1458 // Complete older native resize requests before changing the coordinate
1459 // conversion. Their ConfigureNotify events describe the previous scale.
1460 XSync(mDisplay, 0);
1461 XEvent event;
1462 while (XCheckTypedWindowEvent(mDisplay, mPlugWnd, ConfigureNotify, &event))
1463 {
1464 }
1465 }
1466 SetScreenScale(scale);
1467}
1468
1469#if defined IGRAPHICS_SKIA && defined IGRAPHICS_CPU
1470void IGraphicsLinux::DestroyCPUImage()
1471{
1472 if (mCPUImage)
1473 {
1474 // XDestroyImage also frees the separately allocated pixel buffer.
1475 XDestroyImage(mCPUImage);
1476 mCPUImage = nullptr;
1477 }
1478}
1479
1480void IGraphicsLinux::PresentCPUFrame(const SkPixmap& pixels)
1481{
1482 if (!mDisplay || !mPlugWnd || pixels.width() <= 0 || pixels.height() <= 0)
1483 return;
1484
1485 if (mCPUImage && (mCPUImage->width != pixels.width() || mCPUImage->height != pixels.height()))
1486 DestroyCPUImage();
1487
1488 if (!mCPUImage)
1489 {
1490 XWindowAttributes attributes{};
1491 if (!XGetWindowAttributes(mDisplay, mPlugWnd, &attributes) || attributes.visual->c_class != TrueColor)
1492 return;
1493 mCPUImage = XCreateImage(mDisplay, attributes.visual, attributes.depth, ZPixmap,
1494 0, nullptr, pixels.width(), pixels.height(), 32, 0);
1495 if (!mCPUImage)
1496 return;
1497 const size_t stride = static_cast<size_t>(mCPUImage->bytes_per_line);
1498 if (mCPUImage->bytes_per_line <= 0 || static_cast<size_t>(pixels.height()) > std::numeric_limits<size_t>::max() / stride)
1499 {
1500 DestroyCPUImage();
1501 return;
1502 }
1503 mCPUImage->data = static_cast<char*>(calloc(pixels.height(), stride));
1504 if (!mCPUImage->data)
1505 {
1506 DestroyCPUImage();
1507 return;
1508 }
1509 }
1510
1511 // The usual X11 visual is 24-bit RGB in a 32-bit little-endian pixel.
1512 // Ask Skia for an explicit format instead of assuming its native N32 order.
1513 if (mCPUImage->bits_per_pixel == 32 && mCPUImage->byte_order == LSBFirst &&
1514 mCPUImage->red_mask == 0xff0000 && mCPUImage->green_mask == 0xff00 &&
1515 mCPUImage->blue_mask == 0xff && mCPUImage->depth == 24)
1516 {
1517 const auto info = SkImageInfo::Make(pixels.width(), pixels.height(),
1518 kBGRA_8888_SkColorType, kPremul_SkAlphaType);
1519 if (!pixels.readPixels(info, mCPUImage->data, mCPUImage->bytes_per_line))
1520 return;
1521 }
1522 else
1523 {
1524 // Respect the server's visual masks and byte order (including RGB565 and
1525 // 30-bit displays). XPutPixel handles the XImage's storage layout.
1526 const auto channel = [](unsigned value, unsigned long mask) -> unsigned long {
1527 if (!mask)
1528 return 0;
1529 unsigned shift = 0;
1530 while (!(mask & 1))
1531 {
1532 mask >>= 1;
1533 ++shift;
1534 }
1535 return ((static_cast<unsigned long>(value) * mask + 127) / 255) << shift;
1536 };
1537 for (int y = 0; y < pixels.height(); ++y)
1538 {
1539 for (int x = 0; x < pixels.width(); ++x)
1540 {
1541 const SkColor color = pixels.getColor(x, y);
1542 const unsigned alpha = SkColorGetA(color);
1543 const auto premul = [alpha](unsigned value) { return (value * alpha + 127) / 255; };
1544 const unsigned long rgb = channel(premul(SkColorGetR(color)), mCPUImage->red_mask) |
1545 channel(premul(SkColorGetG(color)), mCPUImage->green_mask) |
1546 channel(premul(SkColorGetB(color)), mCPUImage->blue_mask);
1547 // A depth-32 X11 window may be composited; present an opaque UI.
1548 const unsigned long opaque = mCPUImage->depth == 32 ?
1549 (0xffffffffUL & ~(mCPUImage->red_mask | mCPUImage->green_mask | mCPUImage->blue_mask)) : 0;
1550 XPutPixel(mCPUImage, x, y, rgb | opaque);
1551 }
1552 }
1553 }
1554
1555 if (!mCPUGC)
1556 mCPUGC = XCreateGC(mDisplay, mPlugWnd, 0, nullptr);
1557 if (!mCPUGC)
1558 return;
1559 XPutImage(mDisplay, mPlugWnd, mCPUGC, mCPUImage, 0, 0, 0, 0, pixels.width(), pixels.height());
1560 XFlush(mDisplay);
1561}
1562#endif
1563
1564void IGraphicsLinux::ResizeFromHost(int width, int height)
1565{
1566 if (width <= 0 || height <= 0)
1567 return;
1568
1569 int designWidth, designHeight;
1570 float scale;
1571 CalculateHostResize(width, height, designWidth, designHeight, scale);
1572 Resize(designWidth, designHeight, scale, false);
1573}
1574
1575void IGraphicsLinux::CalculateHostResize(int width, int height, int& designWidth, int& designHeight, float& scale)
1576{
1577 const float screenScale = GetScreenScale();
1578 const auto pixels = [screenScale](int dimension, float candidateScale) { return PhysicalWindowDimension(dimension, candidateScale, screenScale); };
1579 if (GetResizerMode() == EUIResizerMode::Scale)
1580 {
1581 designWidth = Width();
1582 designHeight = Height();
1583 GetDelegate()->ConstrainEditorResize(designWidth, designHeight);
1584
1585 const auto fits = [&](float candidateScale) { return pixels(designWidth, candidateScale) <= width && pixels(designHeight, candidateScale) <= height; };
1586 float lo = ConstrainDrawScale(0.f);
1587 float hi = ConstrainDrawScale(std::numeric_limits<float>::max());
1588 if (fits(hi))
1589 lo = hi;
1590 else if (fits(lo))
1591 {
1592 // Find the last representable scale that fits the requested pixel bounds.
1593 // Inverting their lower edges loses a pixel at each integer conversion.
1594 // Querying the resulting dimensions admits this same scale again.
1595 for (;;)
1596 {
1597 const float mid = lo + (hi - lo) * .5f;
1598 if (mid == lo || mid == hi)
1599 break;
1600 if (fits(mid))
1601 lo = mid;
1602 else
1603 hi = mid;
1604 }
1605 }
1606 scale = lo;
1607 // Keep exact scales such as 1.5 when they produce the same pixel dimensions.
1608 const float nominalScale = ConstrainDrawScale(std::min(width / screenScale / designWidth, height / screenScale / designHeight));
1609 if (pixels(designWidth, nominalScale) == pixels(designWidth, scale) && pixels(designHeight, nominalScale) == pixels(designHeight, scale))
1610 scale = nominalScale;
1611 }
1612 else
1613 {
1614 scale = ConstrainDrawScale(GetDrawScale());
1615 // Use the same upper-bound search for integer design pixels in Size mode.
1616 const auto fitDimension = [&](int requested, int maximum) {
1617 int lo = 0, hi = maximum;
1618 while (lo < hi)
1619 {
1620 const int mid = hi - (hi - lo) / 2;
1621 if (pixels(mid, scale) <= requested)
1622 lo = mid;
1623 else
1624 hi = mid - 1;
1625 }
1626 const int nominal = static_cast<int>(std::lround(std::min<double>(maximum, requested / screenScale / scale)));
1627 return pixels(nominal, scale) == pixels(lo, scale) ? nominal : lo;
1628 };
1629 designWidth = fitDimension(width, GetDelegate()->GetMaxWidth());
1630 designHeight = fitDimension(height, GetDelegate()->GetMaxHeight());
1631 // Editor constraints describe dimensions before drawing/display scaling.
1632 GetDelegate()->ConstrainEditorResize(designWidth, designHeight);
1633 }
1634}
1635
1636void IGraphicsLinux::ConstrainHostResize(int& width, int& height)
1637{
1638 int designWidth, designHeight;
1639 float scale;
1640 CalculateHostResize(width, height, designWidth, designHeight, scale);
1641 width = static_cast<int>(PhysicalWindowDimension(designWidth, scale, GetScreenScale()));
1642 height = static_cast<int>(PhysicalWindowDimension(designHeight, scale, GetScreenScale()));
1643}
1644
1645void IGraphicsLinux::ForceEndUserEdit() {}
1646
1647void IGraphicsLinux::HideMouseCursor(bool hide, bool lock)
1648{
1649 if (!mDisplay || !mPlugWnd)
1650 return;
1651
1652 if (hide)
1653 {
1654 if (!mBlankCursor)
1655 {
1656 static const char emptyData[] = {0, 0, 0, 0, 0, 0, 0, 0};
1657 XColor black = {};
1658 Pixmap emptyBitmap = XCreateBitmapFromData(mDisplay, mPlugWnd, emptyData, 8, 8);
1659 mBlankCursor = XCreatePixmapCursor(mDisplay, emptyBitmap, emptyBitmap, &black, &black, 0, 0);
1660 XFreePixmap(mDisplay, emptyBitmap);
1661 }
1662 XDefineCursor(mDisplay, mPlugWnd, mBlankCursor);
1663 mCursorHidden = true;
1664 mCursorLock = lock;
1665 if (lock)
1666 {
1667 mHiddenCursorX = mCursorX;
1668 mHiddenCursorY = mCursorY;
1669 }
1670 }
1671 else
1672 {
1673 XUndefineCursor(mDisplay, mPlugWnd);
1674 if (mCursorLock)
1675 MoveMouseCursor(mHiddenCursorX, mHiddenCursorY);
1676 mCursorHidden = false;
1677 mCursorLock = false;
1678 }
1679}
1680
1681void IGraphicsLinux::MoveMouseCursor(float x, float y)
1682{
1683 if (mDisplay && mPlugWnd)
1684 {
1685 const float scale = GetTotalScale();
1686 XWarpPointer(mDisplay, 0 /* None */, mPlugWnd, 0, 0, 0, 0, (int)(x * scale), (int)(y * scale));
1687 }
1688}
1689
1690ECursor IGraphicsLinux::SetMouseCursor(ECursor cursorType)
1691{
1692 if (!mDisplay || !mPlugWnd)
1693 return cursorType;
1694
1695 unsigned int shape = XC_left_ptr;
1696 switch (cursorType)
1697 {
1698 case ECursor::ARROW:
1699 shape = XC_left_ptr;
1700 break;
1701 case ECursor::IBEAM:
1702 shape = XC_xterm;
1703 break;
1704 case ECursor::WAIT:
1705 shape = XC_watch;
1706 break;
1707 case ECursor::CROSS:
1708 shape = XC_crosshair;
1709 break;
1710 case ECursor::UPARROW:
1711 shape = XC_sb_up_arrow;
1712 break;
1713 case ECursor::SIZENWSE:
1714 shape = XC_sizing;
1715 break;
1716 case ECursor::SIZENESW:
1717 shape = XC_sizing;
1718 break;
1719 case ECursor::SIZEWE:
1720 shape = XC_sb_h_double_arrow;
1721 break;
1722 case ECursor::SIZENS:
1723 shape = XC_sb_v_double_arrow;
1724 break;
1725 case ECursor::SIZEALL:
1726 shape = XC_fleur;
1727 break;
1728 case ECursor::INO:
1729 shape = XC_X_cursor;
1730 break;
1731 case ECursor::HAND:
1732 shape = XC_hand2;
1733 break;
1734 case ECursor::APPSTARTING:
1735 shape = XC_watch;
1736 break;
1737 case ECursor::HELP:
1738 shape = XC_question_arrow;
1739 break;
1740 default:
1741 shape = XC_left_ptr;
1742 break;
1743 }
1744
1745 Cursor cursor = XCreateFontCursor(mDisplay, shape);
1746 XDefineCursor(mDisplay, mPlugWnd, cursor);
1747 XFreeCursor(mDisplay, cursor);
1748 return IGraphics::SetMouseCursor(cursorType);
1749}
1750
1751void IGraphicsLinux::GetMouseLocation(float& x, float& y) const
1752{
1753 if (!mDisplay || !mPlugWnd)
1754 {
1755 x = y = 0.f;
1756 return;
1757 }
1758
1759 Window root, child;
1760 int rootX, rootY, winX, winY;
1761 unsigned int mask;
1762 if (!XQueryPointer(mDisplay, mPlugWnd, &root, &child, &rootX, &rootY, &winX, &winY, &mask))
1763 {
1764 x = y = 0.f;
1765 return;
1766 }
1767 const float scale = GetTotalScale();
1768 x = winX / scale;
1769 y = winY / scale;
1770}
1771
1772EMsgBoxResult IGraphicsLinux::ShowMessageBox(const char* str, const char* title, EMsgBoxType type, IMsgBoxCompletionHandlerFunc completionHandler)
1773{
1774 auto complete = [&](EMsgBoxResult result) {
1775 if (completionHandler)
1776 completionHandler(result);
1777 return result;
1778 };
1779 GTK3* pGTK = LoadGTK3();
1780 const bool customButtons = type == kMB_YESNOCANCEL || type == kMB_RETRYCANCEL;
1781 if (!pGTK || !pGTK->message_dialog_new || (customButtons && !pGTK->dialog_add_button))
1782 {
1783 fprintf(stderr, "Cannot show message box: required GTK functions are unavailable\n");
1784 return complete(kCANCEL);
1785 }
1786
1787 int gtkMsgType = kGTK_MESSAGE_INFO;
1788 int gtkBtnType = kGTK_BUTTONS_OK;
1789 switch (type)
1790 {
1791 case kMB_OK:
1792 break;
1793 case kMB_OKCANCEL:
1794 gtkMsgType = kGTK_MESSAGE_QUESTION;
1795 gtkBtnType = kGTK_BUTTONS_OK_CANCEL;
1796 break;
1797 case kMB_YESNO:
1798 gtkMsgType = kGTK_MESSAGE_QUESTION;
1799 gtkBtnType = kGTK_BUTTONS_YES_NO;
1800 break;
1801 case kMB_YESNOCANCEL:
1802 case kMB_RETRYCANCEL:
1803 gtkMsgType = kGTK_MESSAGE_QUESTION;
1804 gtkBtnType = kGTK_BUTTONS_NONE;
1805 break;
1806 default:
1807 fprintf(stderr, "Cannot show message box: unsupported button type %d\n", type);
1808 return complete(kCANCEL);
1809 }
1810
1811 void* dialog = pGTK->message_dialog_new(nullptr, 0, gtkMsgType, gtkBtnType, "%s", str ? str : "");
1812 if (!dialog)
1813 {
1814 fprintf(stderr, "Could not create the message box\n");
1815 return complete(kCANCEL);
1816 }
1817 if (type == kMB_YESNOCANCEL)
1818 {
1819 pGTK->dialog_add_button(dialog, "_Cancel", kGTK_RESPONSE_CANCEL);
1820 pGTK->dialog_add_button(dialog, "_No", kGTK_RESPONSE_NO);
1821 pGTK->dialog_add_button(dialog, "_Yes", kGTK_RESPONSE_YES);
1822 }
1823 else if (type == kMB_RETRYCANCEL)
1824 {
1825 pGTK->dialog_add_button(dialog, "_Cancel", kGTK_RESPONSE_CANCEL);
1826 pGTK->dialog_add_button(dialog, "_Retry", kGTK_RESPONSE_RETRY);
1827 }
1828 if (title && pGTK->window_set_title)
1829 pGTK->window_set_title(dialog, title);
1830 GtkPresentDialog(pGTK, dialog);
1831
1832 int resp = pGTK->dialog_run(dialog);
1833 pGTK->widget_destroy(dialog);
1834 GtkDrainEvents(pGTK);
1835
1836 EMsgBoxResult result = kCANCEL;
1837 switch (resp)
1838 {
1839 case kGTK_RESPONSE_OK:
1840 result = kOK;
1841 break;
1842 case kGTK_RESPONSE_YES:
1843 result = kYES;
1844 break;
1845 case kGTK_RESPONSE_NO:
1846 result = kNO;
1847 break;
1848 case kGTK_RESPONSE_CANCEL:
1849 result = kCANCEL;
1850 break;
1851 case kGTK_RESPONSE_RETRY:
1852 result = kRETRY;
1853 break;
1854 default:
1855 result = kCANCEL;
1856 break;
1857 }
1858
1859 return complete(result);
1860}
1861
1862bool IGraphicsLinux::RevealPathInExplorerOrFinder(WDL_String& path, bool select)
1863{
1864 // Open parent directory with xdg-open
1865 WDL_String dir(path);
1866 if (select)
1867 {
1868 // Truncate to the parent dir via WDL_String, not by writing '\0' through
1869 // Get() — that desyncs the cached length and is UB on the const buffer.
1870 if (strrchr(dir.Get(), '/'))
1871 dir.remove_filepart(false);
1872 }
1873
1874 return LaunchDetached("xdg-open", dir.Get());
1875}
1876
1877void IGraphicsLinux::PromptForFile(WDL_String& fileName, WDL_String& path, EFileAction action, const char* ext, IFileDialogCompletionHandlerFunc completionHandler)
1878{
1879 WDL_String outFile, outPath;
1880 auto complete = [&]() {
1881 fileName.Set(outFile.Get());
1882 path.Set(outPath.Get());
1883 if (completionHandler)
1884 completionHandler(fileName, path);
1885 };
1886 GTK3* pGTK = LoadGTK3();
1887 if (!pGTK)
1888 {
1889 fprintf(stderr, "Cannot show file dialog: GTK is unavailable\n");
1890 complete();
1891 return;
1892 }
1893
1894 const bool isSave = (action == EFileAction::Save);
1895 const int gtkAction = isSave ? kGTK_FILE_CHOOSER_ACTION_SAVE : kGTK_FILE_CHOOSER_ACTION_OPEN;
1896 const char* acceptBtn = isSave ? "_Save" : "_Open";
1897
1898 void* dialog = pGTK->file_chooser_dialog_new(isSave ? "Save File" : "Open File", nullptr, gtkAction, "_Cancel", kGTK_RESPONSE_CANCEL, acceptBtn, kGTK_RESPONSE_OK, nullptr);
1899
1900 if (!dialog)
1901 {
1902 fprintf(stderr, "Could not create the file dialog\n");
1903 complete();
1904 return;
1905 }
1906 if (!GtkAddFileFilters(pGTK, dialog, ext))
1907 {
1908 pGTK->widget_destroy(dialog);
1909 GtkDrainEvents(pGTK);
1910 complete();
1911 return;
1912 }
1913
1914 // Set initial directory
1915 if (path.GetLength() && pGTK->file_chooser_set_current_folder)
1916 pGTK->file_chooser_set_current_folder(dialog, path.Get());
1917
1918 // For save dialogs, suggest filename
1919 if (isSave && fileName.GetLength() && pGTK->file_chooser_set_current_name)
1920 pGTK->file_chooser_set_current_name(dialog, fileName.Get());
1921 GtkPresentDialog(pGTK, dialog);
1922
1923 if (pGTK->dialog_run(dialog) == kGTK_RESPONSE_OK)
1924 {
1925 char* chosen = pGTK->file_chooser_get_filename(dialog);
1926 if (chosen)
1927 {
1928 outFile.Set(chosen);
1929 const char* slash = strrchr(chosen, '/');
1930 if (slash)
1931 outPath.Set(chosen, (int)(slash - chosen + 1));
1932 free(chosen);
1933 }
1934 else
1935 fprintf(stderr, "File dialog accepted without a selected file\n");
1936 }
1937
1938 pGTK->widget_destroy(dialog);
1939 GtkDrainEvents(pGTK);
1940
1941 complete();
1942}
1943
1944void IGraphicsLinux::PromptForDirectory(WDL_String& dir, IFileDialogCompletionHandlerFunc completionHandler)
1945{
1946 WDL_String outDir;
1947 auto complete = [&]() {
1948 dir.Set(outDir.Get());
1949 if (completionHandler)
1950 completionHandler(WDL_String{}, dir);
1951 };
1952 GTK3* pGTK = LoadGTK3();
1953 if (!pGTK)
1954 {
1955 fprintf(stderr, "Cannot show directory dialog: GTK is unavailable\n");
1956 complete();
1957 return;
1958 }
1959
1960 void* dialog = pGTK->file_chooser_dialog_new("Select Folder", nullptr, kGTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, "_Cancel", kGTK_RESPONSE_CANCEL, "_Select", kGTK_RESPONSE_OK, nullptr);
1961
1962 if (!dialog)
1963 {
1964 fprintf(stderr, "Could not create the directory dialog\n");
1965 complete();
1966 return;
1967 }
1968
1969 if (dir.GetLength() && pGTK->file_chooser_set_current_folder)
1970 pGTK->file_chooser_set_current_folder(dialog, dir.Get());
1971 GtkPresentDialog(pGTK, dialog);
1972
1973 if (pGTK->dialog_run(dialog) == kGTK_RESPONSE_OK)
1974 {
1975 char* chosen = pGTK->file_chooser_get_filename(dialog);
1976 if (chosen)
1977 {
1978 outDir.Set(chosen);
1979 if (outDir.GetLength() && outDir.Get()[outDir.GetLength() - 1] != '/')
1980 outDir.Append("/");
1981 free(chosen);
1982 }
1983 else
1984 fprintf(stderr, "Directory dialog accepted without a selected directory\n");
1985 }
1986
1987 pGTK->widget_destroy(dialog);
1988 GtkDrainEvents(pGTK);
1989
1990 complete();
1991}
1992
1993bool IGraphicsLinux::PromptForColor(IColor& color, const char* str, IColorPickerHandlerFunc func)
1994{
1995 GTK3* pGTK = LoadGTK3();
1996 if (!pGTK || !pGTK->color_chooser_dialog_new)
1997 return false;
1998
1999 void* dialog = pGTK->color_chooser_dialog_new(str ? str : "Choose Color", nullptr);
2000
2001 if (pGTK->color_chooser_set_rgba)
2002 {
2003 GdkRGBA rgba = {color.R / 255.0, color.G / 255.0, color.B / 255.0, color.A / 255.0};
2004 pGTK->color_chooser_set_rgba(dialog, &rgba);
2005 }
2006 GtkPresentDialog(pGTK, dialog);
2007
2008 const bool accepted = (pGTK->dialog_run(dialog) == kGTK_RESPONSE_OK);
2009
2010 if (accepted && pGTK->color_chooser_get_rgba)
2011 {
2012 GdkRGBA rgba = {};
2013 pGTK->color_chooser_get_rgba(dialog, &rgba);
2014 color.R = (int)(rgba.red * 255.0 + 0.5);
2015 color.G = (int)(rgba.green * 255.0 + 0.5);
2016 color.B = (int)(rgba.blue * 255.0 + 0.5);
2017 color.A = (int)(rgba.alpha * 255.0 + 0.5);
2018 if (func)
2019 func(color);
2020 }
2021
2022 pGTK->widget_destroy(dialog);
2023 GtkDrainEvents(pGTK);
2024 return accepted;
2025}
2026
2027bool IGraphicsLinux::OpenURL(const char* url, const char* msgWindowTitle, const char* confirmMsg, const char* errMsgOnFailure) { return LaunchDetached("xdg-open", url); }
2028
2029bool IGraphicsLinux::GetTextFromClipboard(WDL_String& str)
2030{
2031 if (!mDisplay || !mPlugWnd || !mClipboardAtom)
2032 return false;
2033
2034 const Window owner = XGetSelectionOwner(mDisplay, mClipboardAtom);
2035 if (GetLinuxClipboard().GetOwnedText(owner, DisplayString(mDisplay), str))
2036 return true;
2037 if (!owner)
2038 return false;
2039
2040 // Native clipboard owners in the host may need the same GTK main thread to
2041 // answer. Like modal dialogs, this wait can reenter host callbacks: defer any
2042 // editor teardown until the synchronous paste has returned to its caller.
2043 DispatchScope dispatch(mDispatchDepth);
2044 GTK3* pGTK = LoadGTK3();
2045
2046 // Ask the clipboard owner to convert to UTF-8 and store in our scratch property
2047 XConvertSelection(mDisplay, mClipboardAtom, mUTF8StringAtom, mSelDataAtom, mPlugWnd, 0L /* CurrentTime */);
2048 XFlush(mDisplay);
2049
2050 // Keep the event consumer locked out until we have read SelectionNotify.
2051 for (int i = 0; i < 50; ++i)
2052 {
2053 if (pGTK && pGTK->events_pending && pGTK->main_iteration_do && pGTK->events_pending())
2054 pGTK->main_iteration_do(0);
2055 if (mCloseRequested)
2056 return false;
2057 usleep(10000); // 10 ms
2058
2059 XEvent ev;
2060 if (XCheckTypedWindowEvent(mDisplay, mPlugWnd, SelectionNotify, &ev))
2061 {
2062 if (ev.xselection.selection != mClipboardAtom)
2063 continue;
2064
2065 if (ev.xselection.property == 0 /* None */)
2066 return false; // owner couldn't convert
2067
2068 Atom type;
2069 int fmt;
2070 unsigned long nitems, remaining;
2071 unsigned char* data = nullptr;
2072
2073 const int status = XGetWindowProperty(mDisplay, mPlugWnd, mSelDataAtom, 0, 65536, 1 /* delete after read */, AnyPropertyType, &type, &fmt, &nitems, &remaining, &data);
2074 // Require remaining == 0 so we never report success on a truncated
2075 // read, and bound nitems before the int cast to avoid UB.
2076 if (status == 0 && fmt == 8 && (type == mUTF8StringAtom || type == XA_STRING) && data && remaining == 0 && nitems <= 0x7FFFFFFFUL)
2077 {
2078 str.Set((const char*)data, (int)nitems);
2079 XFree(data);
2080 return true;
2081 }
2082 if (data)
2083 XFree(data);
2084 return false;
2085 }
2086 }
2087 fprintf(stderr, "Timed out waiting for the X11 clipboard owner\n");
2088 return false;
2089}
2090
2091bool IGraphicsLinux::SetTextInClipboard(const char* str)
2092{
2093 if (!mDisplay || !mPlugWnd || !mClipboardAtom)
2094 return false;
2095
2096 return GetLinuxClipboard().SetText(str, DisplayString(mDisplay));
2097}
2098
2099// State passed through GTK menu-item activation callbacks.
2101{
2102 IPopupMenu* pMenu = nullptr;
2103 int chosenIdx = -1;
2104};
2105
2108static void* BuildGtkMenu(GTK3* pGTK, IPopupMenu& menu, GtkMenuState* pState)
2109{
2110 void* gtkMenu = pGTK->menu_new();
2111
2112 for (int i = 0; i < menu.NItems(); ++i)
2113 {
2114 IPopupMenu::Item* pItem = menu.GetItem(i);
2115 void* gtkItem = nullptr;
2116
2117 if (pItem->GetIsSeparator())
2118 {
2119 gtkItem = pGTK->separator_menu_item_new();
2120 }
2121 else if (pItem->GetChecked() && pGTK->check_menu_item_new_with_label)
2122 {
2123 gtkItem = pGTK->check_menu_item_new_with_label(pItem->GetText());
2124 if (pGTK->check_menu_item_set_active)
2125 pGTK->check_menu_item_set_active(gtkItem, 1);
2126 }
2127 else
2128 {
2129 gtkItem = pGTK->menu_item_new_with_label(pItem->GetText());
2130 }
2131
2132 if (!gtkItem)
2133 continue;
2134
2135 // Disabled or title items are insensitive
2136 if (!pItem->GetEnabled() || pItem->GetIsTitle())
2137 {
2138 if (pGTK->widget_set_sensitive)
2139 pGTK->widget_set_sensitive(gtkItem, 0);
2140 }
2141
2142 // Submenus
2143 if (pItem->GetSubmenu() && pGTK->menu_item_set_submenu)
2144 {
2145 void* sub = BuildGtkMenu(pGTK, *pItem->GetSubmenu(), pState);
2146 pGTK->menu_item_set_submenu(gtkItem, sub);
2147 }
2148 else if (pItem->GetEnabled() && !pItem->GetIsTitle() && !pItem->GetIsSeparator() && pGTK->signal_connect_data)
2149 {
2150 // Store the menu pointer and index in the state for the callback.
2151 // We use a small lambda-like static function with user data.
2152 struct ActivateData
2153 {
2154 GtkMenuState* state;
2155 IPopupMenu* menu;
2156 int idx;
2157 };
2158 auto* ad = new ActivateData{pState, &menu, i};
2159
2160 // GCallback signature: void callback(GtkMenuItem*, gpointer)
2161 auto activateCb = +[](void*, void* userData) {
2162 auto* d = static_cast<ActivateData*>(userData);
2163 d->state->pMenu = d->menu;
2164 d->state->chosenIdx = d->idx;
2165 };
2166
2167 // GDestroyNotify frees the ActivateData when the signal is disconnected.
2168 auto destroyCb = +[](void* userData) { delete static_cast<ActivateData*>(userData); };
2169
2170 pGTK->signal_connect_data(gtkItem, "activate", (void*)activateCb, ad, (void*)destroyCb, 0);
2171 }
2172
2173 pGTK->menu_shell_append(gtkMenu, gtkItem);
2174 }
2175
2176 if (pGTK->widget_show_all)
2177 pGTK->widget_show_all(gtkMenu);
2178
2179 return gtkMenu;
2180}
2181
2182// GTK3's GdkEventButton (stable ABI), used to fill in a synthetic trigger event
2184{
2185 int type;
2186 void* window;
2187 int8_t send_event;
2188 uint32_t time;
2189 double x, y;
2190 double* axes;
2191 unsigned int state;
2192 unsigned int button;
2193 void* device;
2194 double x_root, y_root;
2195};
2196
2197// A GTK menu opened without the button press that triggered it treats the
2198// release of that click as a click outside the menu, and closes at once.
2199// Rebuild the press from the X event so GTK knows to ignore its release.
2200void* IGraphicsLinux::CreateGdkButtonPressEvent(void* gtkHandle, void* gdkDisplay, void* gdkWindow, int gdkScale)
2201{
2202 static constexpr int kGDK_BUTTON_PRESS = 4;
2203 auto event_new = reinterpret_cast<void* (*)(int)>(dlsym(gtkHandle, "gdk_event_new"));
2204 auto event_set_device = reinterpret_cast<void (*)(void*, void*)>(dlsym(gtkHandle, "gdk_event_set_device"));
2205 auto get_default_seat = reinterpret_cast<void* (*)(void*)>(dlsym(gtkHandle, "gdk_display_get_default_seat"));
2206 auto seat_get_pointer = reinterpret_cast<void* (*)(void*)>(dlsym(gtkHandle, "gdk_seat_get_pointer"));
2207 auto object_ref = reinterpret_cast<void* (*)(void*)>(dlsym(gtkHandle, "g_object_ref"));
2208 if (!mLastPressTime || !event_new || !event_set_device || !get_default_seat || !seat_get_pointer || !object_ref || !dlsym(gtkHandle, "gdk_event_free"))
2209 return nullptr;
2210
2211 void* pSeat = get_default_seat(gdkDisplay);
2212 void* pPointer = pSeat ? seat_get_pointer(pSeat) : nullptr;
2213 if (!pPointer)
2214 return nullptr;
2215
2216 auto* pEvent = static_cast<GdkEventButtonABI*>(event_new(kGDK_BUTTON_PRESS));
2217 pEvent->window = object_ref(gdkWindow); // gdk_event_free() unrefs it
2218 pEvent->send_event = 0;
2219 pEvent->time = static_cast<uint32_t>(mLastPressTime);
2220 pEvent->x = static_cast<double>(mLastPressX) / gdkScale;
2221 pEvent->y = static_cast<double>(mLastPressY) / gdkScale;
2222 pEvent->button = mLastPressButton;
2223 pEvent->x_root = static_cast<double>(mLastPressRootX) / gdkScale;
2224 pEvent->y_root = static_cast<double>(mLastPressRootY) / gdkScale;
2225 event_set_device(pEvent, pPointer);
2226 return pEvent;
2227}
2228
2229void IGraphicsLinux::ReleaseX11PointerGrab()
2230{
2231 if (mDisplay)
2232 {
2233 XUngrabPointer(mDisplay, 0L /* CurrentTime */);
2234 XFlush(mDisplay);
2235 }
2236}
2237
2238IPopupMenu* IGraphicsLinux::CreatePlatformPopupMenu(IPopupMenu& menu, const IRECT bounds, bool& isAsync)
2239{
2240 isAsync = false;
2241
2242 GTK3* pGTK = LoadGTK3();
2243 if (!pGTK || !pGTK->menu_new || !pGTK->menu_item_new_with_label || !pGTK->menu_shell_append || !pGTK->main || !pGTK->main_quit)
2244 return nullptr;
2245
2246 // Menus open on mouse down, while the press's implicit pointer grab belongs to our
2247 // X connection. GTK uses its own connection, so its menu grab would fail and the
2248 // menu would close as soon as it opened. Hand the pointer over first.
2249 ReleaseX11PointerGrab();
2250
2251 GtkMenuState state;
2252 void* gtkMenu = BuildGtkMenu(pGTK, menu, &state);
2253
2254 // Quit the GTK main loop when the menu is dismissed (deactivate signal).
2255 if (pGTK->signal_connect_data)
2256 {
2257 auto deactivateCb = +[](void*, void*) {
2258 // LoadGTK3() returns cached pointer; safe to call again
2259 GTK3* pGTK = LoadGTK3();
2260 if (pGTK && pGTK->main_quit)
2261 pGTK->main_quit();
2262 };
2263 pGTK->signal_connect_data(gtkMenu, "deactivate", (void*)deactivateCb, nullptr, nullptr, 0);
2264 }
2265
2266 // The button press that opened the menu holds an implicit pointer grab on
2267 // our X connection. GTK needs its own grab to show the menu and silently
2268 // abandons the popup when it cannot get one, so release ours first.
2269 if (mDisplay)
2270 {
2271 XUngrabPointer(mDisplay, 0 /* CurrentTime */);
2272 XSync(mDisplay, 0);
2273 }
2274
2275 // Position the popup menu anchored to the control's bounding rectangle.
2276 // gtk_menu_popup_at_rect is the non-deprecated GTK3 API (since 3.22).
2277 // It needs a GdkWindow — we create a "foreign" wrapper around mPlugWnd.
2278 // Falls back to gtk_menu_popup_at_pointer(NULL) on older GTK or if the
2279 // foreign window can't be created (e.g. Wayland without X11 backend).
2280 bool popped = false;
2281
2282 if (pGTK->menu_popup_at_rect && pGTK->gdk_display_get_default && pGTK->gdk_x11_window_foreign && mPlugWnd)
2283 {
2284 void* gdkDisplay = pGTK->gdk_display_get_default();
2285 if (gdkDisplay)
2286 {
2287 void* gdkWindow = pGTK->gdk_x11_window_foreign(gdkDisplay, static_cast<unsigned long>(mPlugWnd));
2288
2289 if (gdkWindow)
2290 {
2291 // Control coordinates to window pixels (draw and screen scale), then
2292 // to GDK units, which GDK multiplies by its own window scale.
2293 using fn_window_scale = int (*)(void*);
2294 auto window_scale = (fn_window_scale)dlsym(pGTK->handle, "gdk_window_get_scale_factor");
2295 float s = GetTotalScale() / static_cast<float>(window_scale ? std::max(1, window_scale(gdkWindow)) : 1);
2296 GdkRectangle rect;
2297 rect.x = static_cast<int>(bounds.L * s);
2298 rect.y = static_cast<int>(bounds.B * s);
2299 rect.width = static_cast<int>(bounds.W() * s);
2300 rect.height = 1;
2301
2302 void* triggerEvent = CreateGdkButtonPressEvent(pGTK->handle, gdkDisplay, gdkWindow, window_scale ? std::max(1, window_scale(gdkWindow)) : 1);
2303 pGTK->menu_popup_at_rect(gtkMenu, gdkWindow, &rect, kGDK_GRAVITY_NORTH_WEST, kGDK_GRAVITY_NORTH_WEST, triggerEvent);
2304 popped = true;
2305 if (triggerEvent)
2306 reinterpret_cast<void (*)(void*)>(dlsym(pGTK->handle, "gdk_event_free"))(triggerEvent);
2307
2308 if (pGTK->g_object_unref)
2309 pGTK->g_object_unref(gdkWindow);
2310 }
2311 }
2312 }
2313
2314 if (!popped && pGTK->menu_popup_at_pointer)
2315 pGTK->menu_popup_at_pointer(gtkMenu, nullptr);
2316
2317 // Run a nested GTK main loop — blocks until the menu closes. If GTK did not
2318 // show the menu (e.g. its pointer grab failed) "deactivate" never fires, and
2319 // the loop would block the application forever, so skip it.
2320 if (!pGTK->widget_get_mapped || pGTK->widget_get_mapped(gtkMenu))
2321 pGTK->main();
2322 else
2323 fprintf(stderr, "IGraphicsLinux: GTK did not show the popup menu\n");
2324
2325 // GTK owns the menu widget tree; destroy it.
2326 pGTK->widget_destroy(gtkMenu);
2327 GtkDrainEvents(pGTK);
2328
2329 if (state.pMenu && state.chosenIdx >= 0)
2330 {
2331 state.pMenu->SetChosenItemIdx(state.chosenIdx);
2332
2333 if (state.pMenu->GetFunction())
2334 state.pMenu->ExecFunction();
2335
2336 return state.pMenu;
2337 }
2338
2339 return nullptr;
2340}
2341
2342void IGraphicsLinux::CreatePlatformTextEntry(int paramIdx, const IText& text, const IRECT& bounds, int length, const char* str)
2343{
2344 // GTK dialog flags: GTK_DIALOG_MODAL = 1, GTK_DIALOG_DESTROY_WITH_PARENT = 2
2345 static constexpr int kGTK_DIALOG_MODAL = 1;
2346
2347 GTK3* pGTK = LoadGTK3();
2348 if (!pGTK || !pGTK->dialog_new_with_buttons || !pGTK->dialog_get_content_area || !pGTK->entry_new || !pGTK->entry_get_text || !pGTK->box_pack_start)
2349 {
2350 ClearInTextEntryControl();
2351 return;
2352 }
2353
2354 // As for popup menus: free the pointer from the click that opened this, and end
2355 // the click in IGraphics too, since its button release will go to the dialog.
2356 ReleaseX11PointerGrab();
2357 ReleaseMouseCapture();
2358
2359 void* dialog = pGTK->dialog_new_with_buttons("Edit Value", nullptr, kGTK_DIALOG_MODAL, "_Cancel", kGTK_RESPONSE_CANCEL, "_OK", kGTK_RESPONSE_OK, nullptr);
2360
2361 void* entry = pGTK->entry_new();
2362 if (pGTK->entry_set_text && str)
2363 pGTK->entry_set_text(entry, str);
2364 if (pGTK->entry_set_max_length && length > 0)
2365 pGTK->entry_set_max_length(entry, length);
2366
2367 // Wire Enter key in the entry to trigger the OK response
2368 if (pGTK->signal_connect_data && pGTK->dialog_response)
2369 {
2370 auto activateCb = +[](void*, void* userData) {
2371 GTK3* pGTK = LoadGTK3();
2372 if (pGTK && pGTK->dialog_response)
2373 pGTK->dialog_response(userData, kGTK_RESPONSE_OK);
2374 };
2375 pGTK->signal_connect_data(entry, "activate", (void*)activateCb, dialog, nullptr, 0);
2376 }
2377
2378 void* contentArea = pGTK->dialog_get_content_area(dialog);
2379 pGTK->box_pack_start(contentArea, entry, 1, 1, 0);
2380
2381 // Open the dialog just below the control being edited. This must happen before it
2382 // is shown: GtkPresentDialog's position hint only applies when a window first maps.
2383 auto window_move = reinterpret_cast<void (*)(void*, int, int)>(dlsym(pGTK->handle, "gtk_window_move"));
2384 auto widget_scale = reinterpret_cast<int (*)(void*)>(dlsym(pGTK->handle, "gtk_widget_get_scale_factor"));
2385 if (window_move && mDisplay && mPlugWnd)
2386 {
2387 const float scale = GetTotalScale();
2388 int rootX = 0, rootY = 0;
2389 Window child;
2390 if (XTranslateCoordinates(mDisplay, mPlugWnd, DefaultRootWindow(mDisplay), static_cast<int>(bounds.L * scale), static_cast<int>(bounds.B * scale), &rootX, &rootY, &child))
2391 {
2392 const int gdkScale = widget_scale ? std::max(1, widget_scale(dialog)) : 1;
2393 window_move(dialog, rootX / gdkScale, rootY / gdkScale);
2394 }
2395 }
2396
2397 if (pGTK->widget_show_all)
2398 pGTK->widget_show_all(dialog);
2399 GtkPresentDialog(pGTK, dialog);
2400
2401 int response = pGTK->dialog_run(dialog);
2402
2403 if (response == kGTK_RESPONSE_OK)
2404 {
2405 const char* result = pGTK->entry_get_text(entry);
2406 SetControlValueAfterTextEdit(result ? result : "");
2407 }
2408 else
2409 {
2410 ClearInTextEntryControl();
2411 }
2412
2413 pGTK->widget_destroy(dialog);
2414 GtkDrainEvents(pGTK);
2415}
2416
2417PlatformFontPtr IGraphicsLinux::LoadPlatformFont(const char* fontID, const char* fileNameOrResID)
2418{
2419 WDL_String fullPath;
2420 const EResourceLocation loc = LocateResource(fileNameOrResID, "ttf", fullPath, GetBundleID(), nullptr, nullptr);
2421 if (loc == EResourceLocation::kNotFound)
2422 return nullptr;
2423
2424 return PlatformFontPtr(new LinuxFileFont(fullPath.Get(), false));
2425}
2426
2427PlatformFontPtr IGraphicsLinux::LoadPlatformFont(const char* fontID, const char* fontName, ETextStyle style)
2428{
2429 Fontconfig* pFontconfig = LoadFontconfig();
2430 if (!pFontconfig)
2431 return nullptr;
2432
2433 _FcPattern* pattern = pFontconfig->PatternCreate();
2434 if (!pattern)
2435 return nullptr;
2436
2437 pFontconfig->PatternAddString(pattern, "family", (const unsigned char*)fontName);
2438 pFontconfig->PatternAddInteger(pattern, "weight", style == ETextStyle::Bold ? kFC_WEIGHT_BOLD : kFC_WEIGHT_REGULAR);
2439 pFontconfig->PatternAddInteger(pattern, "slant", style == ETextStyle::Italic ? kFC_SLANT_ITALIC : kFC_SLANT_ROMAN);
2440
2441 pFontconfig->ConfigSubstitute(nullptr, pattern, kFC_MatchPattern);
2442 pFontconfig->DefaultSubstitute(pattern);
2443
2444 int result = 1; // FcResultNoMatch
2445 _FcPattern* matched = pFontconfig->FontMatch(nullptr, pattern, &result);
2446 pFontconfig->PatternDestroy(pattern);
2447
2448 if (!matched)
2449 return nullptr;
2450
2451 PlatformFontPtr ret;
2452 unsigned char* path = nullptr;
2453 if (pFontconfig->PatternGetString(matched, "file", 0, &path) == kFC_ResultMatch && path)
2454 ret = PlatformFontPtr(new LinuxFileFont((const char*)path, true));
2455
2456 pFontconfig->PatternDestroy(matched);
2457 return ret;
2458}
2459
2460PlatformFontPtr IGraphicsLinux::LoadPlatformFont(const char* fontID, void* pData, int dataSize) { return PlatformFontPtr(new LinuxMemFont(pData, dataSize)); }
2461
2462void IGraphicsLinux::CachePlatformFont(const char* fontID, const PlatformFontPtr& font)
2463{
2464 // NanoVG caches loaded fonts in its own atlas; no additional platform cache needed.
2465}
2466
2467void IGraphicsLinux::ActivateGLContext()
2468{
2469#ifdef IGRAPHICS_GL
2470 mGLContextStack.push_back({glXGetCurrentDisplay(), glXGetCurrentContext(), glXGetCurrentDrawable(), glXGetCurrentReadDrawable()});
2471 if (!mDisplay || !mGLContext)
2472 return;
2473 if (!glXMakeCurrent(mDisplay, mPlugWnd, (GLXContext)mGLContext))
2474 fprintf(stderr, "Could not activate the Linux graphics GLX context\n");
2475#endif
2476}
2477
2478void IGraphicsLinux::DeactivateGLContext()
2479{
2480#ifdef IGRAPHICS_GL
2481 assert(!mGLContextStack.empty());
2482 const auto state = mGLContextStack.back();
2483 mGLContextStack.pop_back();
2484 if (glXGetCurrentDisplay() == state.display && glXGetCurrentContext() == state.context && glXGetCurrentDrawable() == state.drawable && glXGetCurrentReadDrawable() == state.readDrawable)
2485 return;
2486
2487 Display* display = state.context ? state.display : glXGetCurrentDisplay();
2488 if (display && !glXMakeContextCurrent(display, state.drawable, state.readDrawable, static_cast<GLXContext>(state.context)))
2489 fprintf(stderr, "Could not restore the previous GLX context\n");
2490#endif
2491}
2492
2493#ifdef IGRAPHICS_GL
2494XVisualInfo* IGraphicsLinux::CreateGLContext()
2495{
2496 // Classic GLX 1.2 API — compatible with all Mesa drivers including software
2497 // renderers (llvmpipe, softpipe) on Xwayland where the GLX 1.3 FBConfig +
2498 // glXCreateNewContext path fails to create DRI drawables.
2499 int screen = DefaultScreen(mDisplay);
2500
2501 int attribs[] = {
2502 GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_DEPTH_SIZE, 24, 0 /* None */
2503 };
2504
2505 XVisualInfo* pVisualInfo = glXChooseVisual(mDisplay, screen, attribs);
2506 if (!pVisualInfo)
2507 return nullptr;
2508
2509 mGLContext = (void*)glXCreateContext(mDisplay, pVisualInfo, nullptr, GL_TRUE);
2510 if (!mGLContext)
2511 {
2512 XFree(pVisualInfo);
2513 return nullptr;
2514 }
2515 // Caller owns pVisualInfo and must XFree() it after creating the X window
2516 return pVisualInfo;
2517}
2518
2519void IGraphicsLinux::DestroyGLContext()
2520{
2521 if (mDisplay && mGLContext)
2522 {
2523 if (glXGetCurrentContext() == mGLContext)
2524 if (!glXMakeCurrent(mDisplay, 0, nullptr))
2525 fprintf(stderr, "Could not release the Linux graphics GLX context\n");
2526 glXDestroyContext(mDisplay, (GLXContext)mGLContext);
2527 mGLContext = nullptr;
2528 }
2529}
2530#endif
2531
2532// Map X11 keysym to Windows virtual key code (used by IKeyPress).
2533// Covers the subset that iPlug2 controls actually handle.
2534static int KeysymToVK(KeySym ks)
2535{
2536 switch (ks)
2537 {
2538 case XK_BackSpace:
2539 return kVK_BACK;
2540 case XK_Tab:
2541 return kVK_TAB;
2542 case XK_Return:
2543 return kVK_RETURN;
2544 case XK_Escape:
2545 return kVK_ESCAPE;
2546 case XK_space:
2547 return kVK_SPACE;
2548 case XK_Prior:
2549 return kVK_PRIOR;
2550 case XK_Next:
2551 return kVK_NEXT;
2552 case XK_End:
2553 return kVK_END;
2554 case XK_Home:
2555 return kVK_HOME;
2556 case XK_Left:
2557 return kVK_LEFT;
2558 case XK_Up:
2559 return kVK_UP;
2560 case XK_Right:
2561 return kVK_RIGHT;
2562 case XK_Down:
2563 return kVK_DOWN;
2564 case XK_Insert:
2565 return kVK_INSERT;
2566 case XK_Delete:
2567 return kVK_DELETE;
2568 case XK_F1:
2569 return kVK_F1;
2570 case XK_F2:
2571 return kVK_F2;
2572 case XK_F3:
2573 return kVK_F3;
2574 case XK_F4:
2575 return kVK_F4;
2576 case XK_F5:
2577 return kVK_F5;
2578 case XK_F6:
2579 return kVK_F6;
2580 case XK_F7:
2581 return kVK_F7;
2582 case XK_F8:
2583 return kVK_F8;
2584 case XK_F9:
2585 return kVK_F9;
2586 case XK_F10:
2587 return kVK_F10;
2588 case XK_F11:
2589 return kVK_F11;
2590 case XK_F12:
2591 return kVK_F12;
2592 case XK_Shift_L:
2593 case XK_Shift_R:
2594 return kVK_SHIFT;
2595 case XK_Control_L:
2596 case XK_Control_R:
2597 return kVK_CONTROL;
2598 case XK_Alt_L:
2599 case XK_Alt_R:
2600 return kVK_MENU;
2601 default:
2602 if (ks >= XK_0 && ks <= XK_9)
2603 return kVK_0 + (int)(ks - XK_0);
2604 if (ks >= XK_a && ks <= XK_z)
2605 return kVK_A + (int)(ks - XK_a);
2606 if (ks >= XK_A && ks <= XK_Z)
2607 return kVK_A + (int)(ks - XK_A);
2608 return kVK_NONE;
2609 }
2610}
2611
2612void IGraphicsLinux::CreateInputContext()
2613{
2614 mInputMethodDisconnected = false;
2615 // Use the host's locale/modifiers; changing them here would affect every plugin.
2616 mInputMethod = XOpenIM(mDisplay, nullptr, nullptr, nullptr);
2617 if (mInputMethod)
2618 {
2619 XIMCallback destroyed{};
2620 destroyed.client_data = reinterpret_cast<XPointer>(this);
2621 destroyed.callback = [](XIM, XPointer data, XPointer) {
2622 auto* graphics = reinterpret_cast<IGraphicsLinux*>(data);
2623 graphics->mInputContext = nullptr;
2624 graphics->mInputMethod = nullptr;
2625 graphics->mInputMethodDisconnected = true;
2626 fprintf(stderr, "The Linux input method disconnected; Compose and IME input are unavailable\n");
2627 };
2628 if (XSetIMValues(mInputMethod, XNDestroyCallback, &destroyed, nullptr))
2629 {
2630 fprintf(stderr, "Could not register the Linux input method disconnect callback; Compose and IME input are unavailable\n");
2631 DestroyInputContext();
2632 return;
2633 }
2634 mInputContext = XCreateIC(mInputMethod, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, mPlugWnd, XNFocusWindow, mPlugWnd, nullptr);
2635 }
2636 if (!mInputContext)
2637 {
2638 fprintf(stderr, "Could not create the Linux input context; Compose and IME input are unavailable\n");
2639 DestroyInputContext();
2640 return;
2641 }
2642 long filterEvents = 0;
2643 if (XGetICValues(mInputContext, XNFilterEvents, &filterEvents, nullptr) == nullptr)
2644 {
2645 XWindowAttributes attributes{};
2646 if (XGetWindowAttributes(mDisplay, mPlugWnd, &attributes))
2647 XSelectInput(mDisplay, mPlugWnd, attributes.your_event_mask | filterEvents);
2648 }
2649}
2650
2651void IGraphicsLinux::DestroyInputContext()
2652{
2653 if (mInputContext)
2654 {
2655 XDestroyIC(mInputContext);
2656 mInputContext = nullptr;
2657 }
2658 if (mInputMethod)
2659 {
2660 XCloseIM(mInputMethod);
2661 mInputMethod = nullptr;
2662 }
2663}
2664
2665void IGraphicsLinux::DispatchKeyEvent(XKeyEvent& event)
2666{
2667 KeySym symbol = 0;
2668 WDL_TypedBuf<char> text;
2669 text.Resize(64);
2670 if (!text.Get())
2671 {
2672 fprintf(stderr, "Could not allocate the Linux keyboard input buffer\n");
2673 return;
2674 }
2675 int length = 0;
2676 if (event.type == KeyPress && mInputContext)
2677 {
2678 int status = 0;
2679 length = Xutf8LookupString(mInputContext, &event, text.Get(), text.GetSize() - 1, &symbol, &status);
2680 if (status == XBufferOverflow && length > 0 && length < INT_MAX)
2681 {
2682 text.Resize(length + 1);
2683 if (text.GetSize() != length + 1)
2684 {
2685 fprintf(stderr, "Could not allocate the Linux input method commit buffer\n");
2686 return;
2687 }
2688 length = Xutf8LookupString(mInputContext, &event, text.Get(), text.GetSize() - 1, &symbol, &status);
2689 }
2690 if (status != XLookupChars && status != XLookupKeySym && status != XLookupBoth)
2691 {
2692 if (status != XLookupNone)
2693 fprintf(stderr, "Could not read the Linux input method commit (status %d)\n", status);
2694 return;
2695 }
2696 if (status == XLookupChars)
2697 symbol = 0;
2698 if (status == XLookupKeySym)
2699 length = 0;
2700 }
2701 else
2702 {
2703 // Key releases cannot use Xutf8LookupString. Encode printable keysyms rather
2704 // than assuming XLookupString's locale-dependent bytes are Latin-1 or UTF-8.
2705 length = XLookupString(&event, text.Get(), text.GetSize() - 1, &symbol, nullptr);
2706 const bool ascii = length == 1 && static_cast<unsigned char>(text.Get()[0]) < 0x80;
2707 if (!ascii && symbol >= 0xA0 && symbol <= 0xFF)
2708 length = wdl_utf8_makechar(static_cast<int>(symbol), text.Get(), text.GetSize() - 1);
2709 else if (!ascii && (symbol & 0xFF000000UL) == 0x01000000UL)
2710 {
2711 const auto codepoint = static_cast<int>(symbol & 0xFFFFFFUL);
2712 if (codepoint <= 0x10FFFF && !(codepoint >= 0xD800 && codepoint <= 0xDFFF))
2713 length = wdl_utf8_makechar(codepoint, text.Get(), text.GetSize() - 1);
2714 }
2715 }
2716 if (length < 0 || length >= text.GetSize())
2717 {
2718 fprintf(stderr, "Invalid Linux input method commit length %d\n", length);
2719 return;
2720 }
2721 text.Get()[length] = '\0';
2722 // A phrase commit can accompany the Return keysym used to accept an IME candidate.
2723 if (length > 1)
2724 symbol = 0;
2725
2726 int offset = 0;
2727 do
2728 {
2729 char character[5]{};
2730 int size = 0;
2731 if (offset < length)
2732 {
2733 int codepoint = 0;
2734 size = wdl_utf8_parsechar(text.Get() + offset, &codepoint);
2735 char encoded[4]{};
2736 if (size > 4 || offset + size > length || codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF) || wdl_utf8_makechar(codepoint, encoded, sizeof(encoded)) != size
2737 || memcmp(encoded, text.Get() + offset, size) != 0)
2738 {
2739 fprintf(stderr, "The Linux input method returned invalid UTF-8\n");
2740 return;
2741 }
2742 memcpy(character, text.Get() + offset, size);
2743 }
2744 // IKeyPress holds one UTF-8 code point, while an IME can commit an entire phrase.
2745 IKeyPress key(character, offset == 0 ? KeysymToVK(symbol) : kVK_NONE, (event.state & ShiftMask) != 0, (event.state & ControlMask) != 0, (event.state & Mod1Mask) != 0);
2746#ifdef APP_API
2747 // Menu shortcuts take priority over the editor, as on Windows and macOS
2748 if (event.type == KeyPress && offset == 0 && IPlugAPPHandleKeyboardShortcut(key))
2749 return;
2750#endif
2751 if (event.type == KeyPress)
2752 OnKeyDown(mCursorX, mCursorY, key);
2753 else
2754 OnKeyUp(mCursorX, mCursorY, key);
2755 offset += size;
2756 } while (offset < length && !mCloseRequested);
2757}
2758
2760{
2761 if (IsInPlatformCallback())
2762 return;
2763 DispatchScope dispatch(mDispatchDepth);
2764 DispatchX11Events();
2765}
2766
2767void IGraphicsLinux::DispatchX11Events()
2768{
2769 if (!mDisplay || !mPlugWnd || mCloseRequested)
2770 return;
2771
2772 while (!mCloseRequested && XPending(mDisplay))
2773 {
2774 XEvent ev;
2775 XNextEvent(mDisplay, &ev);
2776 if (ev.type == Expose && ev.xexpose.window == mTooltipWindow)
2777 {
2778 DrawTooltip();
2779 continue;
2780 }
2781 if (XFilterEvent(&ev, mPlugWnd))
2782 continue;
2783
2784 const float scale = GetTotalScale();
2785 switch (ev.type)
2786 {
2787 case Expose: {
2788 // Handled by the render path below; drain duplicate exposures
2789 while (XCheckTypedWindowEvent(mDisplay, mPlugWnd, Expose, &ev))
2790 ;
2791 mNeedsRedraw = true;
2792 break;
2793 }
2794
2795 case ConfigureNotify: {
2796 XConfigureEvent& ce = ev.xconfigure;
2797 if (ce.window != mPlugWnd)
2798 break;
2799
2800 // Drain all pending ConfigureNotify events and use the latest.
2801 // During rapid resizing (corner-resizer drag or host resize),
2802 // multiple ConfigureNotify events queue up. Processing stale
2803 // intermediate sizes would cause unnecessary FBO recreations
2804 // and potential size oscillations. Only the final size matters.
2805 {
2806 XEvent next;
2807 while (XCheckTypedWindowEvent(mDisplay, mPlugWnd, ConfigureNotify, &next))
2808 {
2809 ce = next.xconfigure;
2810 }
2811 }
2812
2813 const int physW = ce.width;
2814 const int physH = ce.height;
2815 // Check if the internal state already matches this physical
2816 // size (e.g. OnParentWindowResize already processed it).
2817 const int curPhysW = static_cast<int>(WindowWidth() * GetScreenScale());
2818 const int curPhysH = static_cast<int>(WindowHeight() * GetScreenScale());
2819 if (physW == curPhysW && physH == curPhysH)
2820 {
2821 break;
2822 }
2823
2824 // The X server resized our window. Suppress PlatformResize to
2825 // avoid a resize oscillation.
2826 mInConfigureNotify = true;
2827
2828 ResizeFromHost(physW, physH);
2829
2830 mInConfigureNotify = false;
2831 // A WM may ignore the aspect ratio or scale limits. Reconcile the child
2832 // once; the resulting ConfigureNotify already matches our state.
2833 if (physW != static_cast<int>(WindowWidth() * GetScreenScale()) || physH != static_cast<int>(WindowHeight() * GetScreenScale()))
2834 PlatformResize(false);
2835 break;
2836 }
2837
2838 case ButtonPress:
2839 case ButtonRelease: {
2840 HideTooltip();
2841 mTooltipControl = -1;
2842 XButtonEvent& be = ev.xbutton;
2843 const float x = be.x / scale;
2844 const float y = be.y / scale;
2845 const bool shift = (be.state & ShiftMask) != 0;
2846 const bool ctrl = (be.state & ControlMask) != 0;
2847 const bool alt = (be.state & Mod1Mask) != 0;
2848
2849 if (be.button == Button4 || be.button == Button5)
2850 {
2851 // Scroll wheel — only fire on press
2852 if (ev.type == ButtonPress)
2853 {
2854 XSetInputFocus(mDisplay, mPlugWnd, RevertToParent, be.time);
2855 const float delta = (be.button == Button4) ? 1.f : -1.f;
2856 IMouseMod mod(false, false, shift, ctrl, alt);
2857 OnMouseWheel(x, y, mod, delta);
2858 }
2859 break;
2860 }
2861
2862 // Buttons 6/7 are horizontal scroll and 8/9 back/forward; they are not clicks.
2863 if (be.button > Button3)
2864 break;
2865
2866 const bool left = (be.button == Button1);
2867 const bool right = (be.button == Button3);
2868 IMouseMod mod(left, right, shift, ctrl, alt);
2869
2870 mCursorX = x;
2871 mCursorY = y;
2872
2873 IMouseInfo info;
2874 info.x = x;
2875 info.y = y;
2876 info.dX = 0.f;
2877 info.dY = 0.f;
2878 info.ms = mod;
2879 std::vector<IMouseInfo> list{info};
2880
2881 if (ev.type == ButtonPress)
2882 {
2883 mLastPressTime = be.time;
2884 mLastPressButton = be.button;
2885 mLastPressX = be.x;
2886 mLastPressY = be.y;
2887 mLastPressRootX = be.x_root;
2888 mLastPressRootY = be.y_root;
2889 // A child of the host's window does not gain focus automatically.
2890 // Only an explicit click transfers focus; mapping/hovering never does.
2891 XSetInputFocus(mDisplay, mPlugWnd, RevertToParent, be.time);
2892 XFlush(mDisplay);
2893 // Measure distance in screen-logical pixels, independent of UI zoom.
2894 static constexpr unsigned long kDblClickTimeoutMs = 400;
2895 static constexpr float kDblClickDistance = 4.f;
2896 const float clickX = be.x / GetScreenScale();
2897 const float clickY = be.y / GetScreenScale();
2898 if (left && mLastLeftClickTime && static_cast<uint32_t>(be.time - mLastLeftClickTime) < kDblClickTimeoutMs && std::fabs(clickX - mLastLeftClickX) <= kDblClickDistance
2899 && std::fabs(clickY - mLastLeftClickY) <= kDblClickDistance)
2900 {
2901 OnMouseDblClick(x, y, mod);
2902 mLastLeftClickTime = 0; // reset so triple-click doesn't fire again
2903 }
2904 else
2905 {
2906 OnMouseDown(list);
2907 mLastLeftClickTime = left ? be.time : 0;
2908 mLastLeftClickX = clickX;
2909 mLastLeftClickY = clickY;
2910 }
2911 }
2912 else
2913 {
2914 OnMouseUp(list);
2915 }
2916 break;
2917 }
2918
2919 case MotionNotify: {
2920 XMotionEvent& me = ev.xmotion;
2921 const float x = me.x / scale;
2922 const float y = me.y / scale;
2923 const bool shift = (me.state & ShiftMask) != 0;
2924 const bool ctrl = (me.state & ControlMask) != 0;
2925 const bool alt = (me.state & Mod1Mask) != 0;
2926 const bool lbtn = (me.state & Button1Mask) != 0;
2927 const bool rbtn = (me.state & Button3Mask) != 0;
2928 IMouseMod mod(lbtn, rbtn, shift, ctrl, alt);
2929
2930 IMouseInfo info;
2931 info.x = x;
2932 info.y = y;
2933 info.dX = x - mCursorX;
2934 info.dY = y - mCursorY;
2935 info.ms = mod;
2936 std::vector<IMouseInfo> list{info};
2937
2938 if (lbtn || rbtn)
2939 {
2940 HideTooltip();
2941 mTooltipControl = -1;
2942 OnMouseDrag(list);
2943 mCursorX = x;
2944 mCursorY = y;
2945 }
2946 else
2947 {
2948 OnMouseOver(x, y, mod);
2949 mCursorX = x;
2950 mCursorY = y;
2951 const int hovered = TooltipsEnabled() ? GetMouseOver() : -1;
2952 if (hovered != mTooltipControl || std::fabs(mTooltipX - x) > 4.f || std::fabs(mTooltipY - y) > 4.f)
2953 {
2954 HideTooltip();
2955 mTooltipControl = hovered;
2956 mTooltipX = x;
2957 mTooltipY = y;
2958 mTooltipHoverTime = HoverMillis();
2959 }
2960 }
2961 break;
2962 }
2963
2964 case LeaveNotify:
2965 HideTooltip();
2966 mTooltipControl = -1;
2967 OnMouseOut();
2968 break;
2969
2970 case FocusIn:
2971 if (mInputMethodDisconnected)
2972 CreateInputContext();
2973 if (mInputContext)
2974 XSetICFocus(mInputContext);
2975#ifdef IGRAPHICS_ACCESSKIT
2976 // NotifyPointer is ignored because there is no matching FocusOut when the pointer leaves the window
2977 if (mAccessibility && ev.xfocus.window == mPlugWnd && ev.xfocus.detail != NotifyPointer && ev.xfocus.detail != NotifyPointerRoot)
2978 static_cast<IGraphicsAccessibilityLinux*>(mAccessibility.get())->SetWindowFocused(true);
2979#endif
2980 break;
2981
2982 case FocusOut:
2983 HideTooltip();
2984 if (mInputContext)
2985 XUnsetICFocus(mInputContext);
2986#ifdef IGRAPHICS_ACCESSKIT
2987 if (mAccessibility && ev.xfocus.window == mPlugWnd && ev.xfocus.detail != NotifyPointer && ev.xfocus.detail != NotifyPointerRoot)
2988 static_cast<IGraphicsAccessibilityLinux*>(mAccessibility.get())->SetWindowFocused(false);
2989#endif
2990 break;
2991
2992 case KeyPress:
2993 case KeyRelease:
2994 DispatchKeyEvent(ev.xkey);
2995 break;
2996
2997 case ClientMessage: {
2998 if (ev.xclient.window == mPlugWnd && ev.xclient.format == 32)
2999 {
3000 auto& msg = ev.xclient;
3001 if (msg.message_type == mXdndEnter)
3002 {
3003 HideTooltip();
3004 mTooltipControl = -1;
3005 ResetDrag();
3006 const int version = (msg.data.l[1] >> 24) & 0xff;
3007 if (version >= 3)
3008 {
3009 mDragSource = static_cast<Window>(msg.data.l[0]);
3010 if (msg.data.l[1] & 1)
3011 {
3012 Atom type = 0;
3013 int format = 0;
3014 unsigned long count = 0, remaining = 0;
3015 unsigned char* data = nullptr;
3016 if (XGetWindowProperty(mDisplay, mDragSource, mXdndTypeList, 0, 1024, 0, XA_ATOM, &type, &format, &count, &remaining, &data) == 0 && type == XA_ATOM && format == 32 && remaining == 0
3017 && data)
3018 {
3019 const auto* types = reinterpret_cast<const Atom*>(data);
3020 for (unsigned long i = 0; i < count; ++i)
3021 if (types[i] == mUriList)
3022 mDragSupported = true;
3023 }
3024 if (data)
3025 XFree(data);
3026 }
3027 else
3028 for (int i = 2; i < 5; ++i)
3029 if (static_cast<Atom>(msg.data.l[i]) == mUriList)
3030 mDragSupported = true;
3031 }
3032 break;
3033 }
3034 if (msg.message_type == mXdndLeave && static_cast<Window>(msg.data.l[0]) == mDragSource)
3035 {
3036 ResetDrag();
3037 break;
3038 }
3039 if (msg.message_type == mXdndPosition && static_cast<Window>(msg.data.l[0]) == mDragSource)
3040 {
3041 int x = 0, y = 0;
3042 Window child = 0;
3043 const int rootX = static_cast<short>(msg.data.l[2] >> 16);
3044 const int rootY = static_cast<short>(msg.data.l[2] & 0xffff);
3045 XTranslateCoordinates(mDisplay, DefaultRootWindow(mDisplay), mPlugWnd, rootX, rootY, &x, &y, &child);
3046 mDropX = x / GetTotalScale();
3047 mDropY = y / GetTotalScale();
3048 XEvent reply{};
3049 reply.xclient.type = ClientMessage;
3050 reply.xclient.display = mDisplay;
3051 reply.xclient.window = mDragSource;
3052 reply.xclient.message_type = mXdndStatus;
3053 reply.xclient.format = 32;
3054 reply.xclient.data.l[0] = mPlugWnd;
3055 reply.xclient.data.l[1] = mDragSupported ? 1 : 0;
3056 reply.xclient.data.l[4] = mDragSupported ? mXdndActionCopy : 0;
3057 XSendEvent(mDisplay, mDragSource, 0, NoEventMask, &reply);
3058 XFlush(mDisplay);
3059 break;
3060 }
3061 if (msg.message_type == mXdndDrop && static_cast<Window>(msg.data.l[0]) == mDragSource)
3062 {
3063 if (mDragSupported)
3064 XConvertSelection(mDisplay, mXdndSelection, mUriList, mDropProperty, mPlugWnd, msg.data.l[2]);
3065 else
3066 {
3067 XEvent reply{};
3068 reply.xclient.type = ClientMessage;
3069 reply.xclient.display = mDisplay;
3070 reply.xclient.window = mDragSource;
3071 reply.xclient.message_type = mXdndFinished;
3072 reply.xclient.format = 32;
3073 reply.xclient.data.l[0] = mPlugWnd;
3074 XSendEvent(mDisplay, mDragSource, 0, NoEventMask, &reply);
3075 ResetDrag();
3076 }
3077 XFlush(mDisplay);
3078 break;
3079 }
3080 }
3081 if (ev.xclient.message_type == XInternAtom(mDisplay, "WM_PROTOCOLS", 0) && ev.xclient.format == 32 && (Atom)ev.xclient.data.l[0] == mWMDeleteMessage)
3082 {
3083 mCloseRequested = true;
3084 mTimerRunning = false;
3085 return;
3086 }
3087 break;
3088 }
3089
3090 case SelectionNotify: {
3091 if (ev.xselection.selection != mXdndSelection || !mDragSource)
3092 break;
3093 bool accepted = false;
3094 const Window dragSource = mDragSource;
3095 const Window targetWindow = mPlugWnd;
3096 if (ev.xselection.property == mDropProperty)
3097 {
3098 Atom type = 0;
3099 int format = 0;
3100 unsigned long count = 0, remaining = 0;
3101 unsigned char* data = nullptr;
3102 if (XGetWindowProperty(mDisplay, mPlugWnd, mDropProperty, 0, 262144, 1, mUriList, &type, &format, &count, &remaining, &data) == 0 && type == mUriList && format == 8 && remaining == 0 && data)
3103 {
3104 const auto paths = ParseDroppedFiles(data, count);
3105 XFree(data);
3106 data = nullptr;
3107 if (!paths.empty())
3108 {
3109 accepted = true;
3110 if (paths.size() == 1)
3111 OnDrop(paths[0].c_str(), mDropX, mDropY);
3112 else
3113 {
3114 std::vector<const char*> pointers;
3115 for (const auto& path : paths)
3116 pointers.push_back(path.c_str());
3117 OnDropMultiple(pointers, mDropX, mDropY);
3118 }
3119 }
3120 }
3121 if (data)
3122 XFree(data);
3123 }
3124 XEvent reply{};
3125 reply.xclient.type = ClientMessage;
3126 reply.xclient.display = mDisplay;
3127 reply.xclient.window = dragSource;
3128 reply.xclient.message_type = mXdndFinished;
3129 reply.xclient.format = 32;
3130 reply.xclient.data.l[0] = targetWindow;
3131 reply.xclient.data.l[1] = accepted ? 1 : 0;
3132 reply.xclient.data.l[2] = accepted ? mXdndActionCopy : 0;
3133 if (mDisplay && mPlugWnd == targetWindow)
3134 {
3135 XSendEvent(mDisplay, dragSource, 0, NoEventMask, &reply);
3136 XFlush(mDisplay);
3137 }
3138 ResetDrag();
3139 break;
3140 }
3141
3142 default:
3143 break;
3144 }
3145 }
3146}
3147
3148bool IGraphicsLinux::StartTimer()
3149{
3150 if (mHostDriven || mTimerRunning)
3151 return true;
3152
3153#if defined APP_API || defined REAPER_EXT_API
3154 mMainLoopTimer.reset(SWELLTimer::Create([this](Timer&) { OnDisplayTimer(); }, std::max(1, 1000 / FPS())));
3155 if (!mMainLoopTimer)
3156 {
3157 fprintf(stderr, "Could not start Linux graphics main-loop timer\n");
3158 return false;
3159 }
3160 mTimerRunning = true;
3161 return true;
3162#else
3163 // Plug-in editors are drawn from the host's run loop (see SetHostDriven).
3164 fprintf(stderr, "The Linux editor needs a host-driven display timer\n");
3165 return false;
3166#endif
3167}
3168
3169void IGraphicsLinux::StopTimer()
3170{
3171 mTimerRunning = false;
3172 mMainLoopTimer.reset();
3173}
3174
3176{
3177 if (IsInPlatformCallback())
3178 return;
3179 DispatchScope dispatch(mDispatchDepth);
3180 if (!mDisplay || !mPlugWnd || mCloseRequested)
3181 return;
3182
3183 DispatchX11Events();
3184 if (!mDisplay || !mPlugWnd || mCloseRequested)
3185 return;
3186
3187 if (!TooltipsEnabled() && mTooltipWindow)
3188 HideTooltip();
3189 if (mTooltipControl >= 0 && !mTooltipWindow && TooltipsEnabled() && HoverMillis() - mTooltipHoverTime >= 700)
3190 ShowTooltip(mTooltipX, mTooltipY);
3191
3192#ifdef IGRAPHICS_ACCESSKIT
3193 if (mAccessibility)
3194 static_cast<IGraphicsAccessibilityLinux*>(mAccessibility.get())->UpdateWindowBounds();
3195#endif
3196
3197 IRECTList rects;
3198 const bool dirty = IsDirty(rects);
3199 if (mNeedsRedraw || dirty)
3200 {
3201 if (mNeedsRedraw)
3202 {
3203 // Full redraw (e.g. from Expose)
3204 mNeedsRedraw = false;
3205 rects.Clear();
3206 rects.Add(GetBounds());
3207 }
3208 ScopedGLContext scopedGLCtx{this};
3209 Draw(rects);
3210#if defined(IGRAPHICS_GL2) || defined(IGRAPHICS_GL3)
3211 glXSwapBuffers(mDisplay, mPlugWnd);
3212#endif
3213 }
3214}
3215
3216#ifndef NO_IGRAPHICS
3217 #if defined IGRAPHICS_NANOVG
3218 // Unity-build the NanoVG drawing backend into the platform translation unit.
3219 // nanovg.c and glad.c are compiled separately via CMake sources.
3220 #include "IGraphicsNanoVG.cpp"
3221 #elif defined IGRAPHICS_SKIA
3222 #include "IGraphicsSkia.cpp"
3223 #else
3224 #error "Either NO_IGRAPHICS or a drawing backend (IGRAPHICS_NANOVG, IGRAPHICS_SKIA) must be defined"
3225 #endif
3226#endif
This file contains the base IControl implementation, along with some base classes for specific types ...
Bridges the IGraphics control hierarchy to platform accessibility APIs, via AccessKit (https://access...
EResourceLocation LocateResource(const char *fileNameOrResID, const char *type, WDL_String &result, const char *bundleID, void *pHInstance, const char *sharedResourcesSubPath)
Find the absolute path of a resource based on it's file name (e.g.
The lowest level base class of an IGraphics control.
Definition: IControl.h:49
const char * GetTooltip() const
Definition: IControl.h:224
bool IsHidden() const
Definition: IControl.h:360
An editor delegate base class that uses IGraphics for the UI.
The lowest level base class of an IGraphics context.
Definition: IGraphics.h:87
virtual ECursor SetMouseCursor(ECursor cursorType=ECursor::ARROW)
Sets the mouse cursor to one of ECursor (implementations should return the result of the base impleme...
Definition: IGraphics.h:829
IGraphics platform class for Linux.
void ProcessX11Events()
Called by CLAP host posix-fd callback to drain pending X11 events.
void SetScreenScaleFromHost(float scale)
Apply a new host scale without interpreting older native sizes at the new scale.
void ResizeFromHost(int width, int height)
Apply a host/X11 size in physical pixels, preserving the configured resize mode.
void ConstrainHostResize(int &width, int &height)
Constrain a proposed host size in physical pixels without resizing the editor.
void OnDisplayTimer()
Called by CLAP host timer callback to advance one display frame.
A class to specify an item of a pop up menu.
A class for setting the contents of a pop up menu.
Used to manage a list of rectangular areas and optimize them for drawing to the screen.
void Clear()
Clear the list.
void Add(const IRECT &rect)
Add a rectangle to the list.
Loads a TTF font from a file path; GetFontData() reads the bytes on demand.
Wraps pre-loaded raw font bytes; takes a copy so the caller can free its buffer.
Used to group mouse coordinates with mouse modifier information.
Used to manage color data, independent of draw class/platform.
Used for key press info, such as ASCII representation, virtual key (mapped to win32 codes) and modifi...
Definition: IPlugStructs.h:615
Used to manage mouse modifiers i.e.
Used to manage a rectangular area, independent of draw class/platform.
float W() const
IText is used to manage font and text/text entry style for a piece of text on the UI,...
Base class for timer.
Definition: IPlugTimer.h:43