32#include <X11/Xlib-xcb.h>
34#include <X11/cursorfont.h>
36#include <X11/keysym.h>
43#if defined(IGRAPHICS_GL2) || defined(IGRAPHICS_GL3)
44 #include <glad/glad.h>
53#include "IGraphicsLinux.h"
54#include "IGraphicsStructs.h"
58#if defined APP_API || defined REAPER_EXT_API
59 #include "IPlugSWELLTimer.h"
65extern bool IPlugAPPHandleKeyboardShortcut(
const iplug::IKeyPress& key);
69using namespace igraphics;
71#ifdef IGRAPHICS_ACCESSKIT
75BEGIN_IGRAPHICS_NAMESPACE
82class IGraphicsAccessibilityLinux :
public IGraphicsAccessibility
85 IGraphicsAccessibilityLinux(
IGraphics& graphics, Display* pDisplay, Window wnd)
86 : IGraphicsAccessibility(graphics)
90 Registry& registry = GetRegistry();
94 std::lock_guard<std::mutex> lock(registry.mutex);
95 mId = registry.nextId++;
96 registry.instances[mId] =
this;
97 pId =
reinterpret_cast<void*
>(mId);
100 mAdapter = accesskit_unix_adapter_new(OnActivate, pId, OnAction, pId, OnDeactivate, pId);
103 ~IGraphicsAccessibilityLinux()
107 Registry& registry = GetRegistry();
108 std::lock_guard<std::mutex> lock(registry.mutex);
109 registry.instances.erase(mId);
112 accesskit_unix_adapter_free(mAdapter);
115 void SetWindowFocused(
bool focused)
117 accesskit_unix_adapter_update_window_focus_state(mAdapter, focused);
122 void UpdateWindowBounds()
127 const auto now = std::chrono::steady_clock::now();
129 if (!mBoundsRequested.exchange(
false) && now - mBoundsTime < std::chrono::milliseconds(250))
135 xcb_connection_t* pConnection = XGetXCBConnection(mDisplay);
140 accesskit_rect inner;
142 if (!GetScreenRect(pConnection,
static_cast<xcb_window_t
>(mWnd), inner))
146 accesskit_rect outer = inner;
147 xcb_window_t topLevel =
static_cast<xcb_window_t
>(mWnd);
149 for (
int depth = 0; depth < 64; depth++)
151 xcb_query_tree_reply_t* pTree = xcb_query_tree_reply(pConnection, xcb_query_tree(pConnection, topLevel),
nullptr);
156 const xcb_window_t parent = pTree->parent;
157 const bool parentIsRoot = !parent || parent == pTree->root;
166 if (topLevel != mWnd && !GetScreenRect(pConnection, topLevel, outer))
169 if (RectsEqual(inner, mInnerBounds) && RectsEqual(outer, mOuterBounds))
172 mInnerBounds = inner;
173 mOuterBounds = outer;
174 accesskit_unix_adapter_set_root_window_bounds(mAdapter, outer, inner);
178 void UpdateIfActive(accesskit_tree_update_factory factory,
void* pUserData)
override
180 accesskit_unix_adapter_update_if_active(mAdapter, factory, pUserData);
187 std::unordered_map<uintptr_t, IGraphicsAccessibilityLinux*> instances;
188 uintptr_t nextId = 1;
191 static Registry& GetRegistry()
194 static Registry* sRegistry =
new Registry();
199 static IGraphicsAccessibilityLinux* GetInstance(
void* pUserData)
201 Registry& registry = GetRegistry();
202 auto itr = registry.instances.find(
reinterpret_cast<uintptr_t
>(pUserData));
203 return itr != registry.instances.end() ? itr->second :
nullptr;
206 static accesskit_tree_update* OnActivate(
void* pUserData)
208 std::lock_guard<std::mutex> lock(GetRegistry().mutex);
210 if (
auto* pThis = GetInstance(pUserData))
212 pThis->mWantsBounds =
true;
213 pThis->mBoundsRequested =
true;
214 pThis->RequestFullUpdate();
220 static void OnDeactivate(
void* pUserData)
222 std::lock_guard<std::mutex> lock(GetRegistry().mutex);
224 if (
auto* pThis = GetInstance(pUserData))
226 pThis->mWantsBounds =
false;
227 pThis->SetInactive();
231 static void OnAction(accesskit_action_request* pRequest,
void* pUserData)
233 std::lock_guard<std::mutex> lock(GetRegistry().mutex);
235 if (
auto* pThis = GetInstance(pUserData))
236 ActionHandler(pRequest,
static_cast<IGraphicsAccessibility*
>(pThis));
238 accesskit_action_request_free(pRequest);
241 static bool RectsEqual(
const accesskit_rect& a,
const accesskit_rect& b)
243 return a.x0 == b.x0 && a.y0 == b.y0 && a.x1 == b.x1 && a.y1 == b.y1;
247 static bool GetScreenRect(xcb_connection_t* pConnection, xcb_window_t wnd, accesskit_rect& rect)
249 xcb_get_geometry_reply_t* pGeometry = xcb_get_geometry_reply(pConnection, xcb_get_geometry(pConnection, wnd),
nullptr);
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);
263 rect.x0 = pOrigin->dst_x;
264 rect.y0 = pOrigin->dst_y;
265 rect.x1 = rect.x0 + w;
266 rect.y1 = rect.y0 + h;
272 accesskit_unix_adapter* mAdapter =
nullptr;
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. };
283END_IGRAPHICS_NAMESPACE
290double PhysicalWindowDimension(
int designDimension,
float drawScale,
float screenScale)
293 const float logical = std::trunc(designDimension * drawScale);
294 return std::trunc(logical * screenScale);
297unsigned long HoverMillis() {
return static_cast<unsigned long>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()); }
299std::vector<std::string> ParseDroppedFiles(
const unsigned char* data,
size_t length)
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();)
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] ==
'#')
310 const std::string uri = line.back() ==
'\r' ? line.substr(0, line.size() - 1) : line;
311 if (uri.compare(0, 7,
"file://") != 0)
313 size_t pathStart = 7;
314 if (uri.compare(pathStart, 10,
"localhost/") == 0)
316 if (pathStart >= uri.size() || uri[pathStart] !=
'/')
320 for (
size_t i = pathStart; i < uri.size(); ++i)
327 if (i + 2 >= uri.size())
332 auto hex = [](
char c) ->
int {
333 if (c >=
'0' && c <=
'9')
335 if (c >=
'a' && c <=
'f')
337 if (c >=
'A' && c <=
'F')
341 const int hi = hex(uri[i + 1]), lo = hex(uri[i + 2]);
342 if (hi < 0 || lo < 0 || (hi == 0 && lo == 0))
347 path +=
static_cast<char>((hi << 4) | lo);
350 if (valid && path.find(
'\0') == std::string::npos)
351 paths.push_back(std::move(path));
363 pthread_join(mThread,
nullptr);
366 XDestroyWindow(mDisplay, mWindow);
367 XCloseDisplay(mDisplay);
371 bool SetText(
const char* text,
const char* displayName)
373 std::lock_guard<std::mutex> lock(mMutex);
376 mDisplay = XOpenDisplay(displayName);
379 fprintf(stderr,
"Could not open the X11 clipboard display\n");
382 mConnection = XGetXCBConnection(mDisplay);
385 fprintf(stderr,
"Could not access the XCB clipboard connection\n");
386 XCloseDisplay(mDisplay);
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);
395 const int error = pthread_create(&mThread,
nullptr, Run,
this);
398 fprintf(stderr,
"Could not start the X11 clipboard service: %s\n", strerror(error));
401 XDestroyWindow(mDisplay, mWindow);
402 XCloseDisplay(mDisplay);
404 mConnection =
nullptr;
408 if (strcmp(DisplayString(mDisplay), displayName) != 0)
410 fprintf(stderr,
"The clipboard service is already connected to another X11 display\n");
414 XSetSelectionOwner(mDisplay, mClipboard, mWindow, 0);
416 return XGetSelectionOwner(mDisplay, mClipboard) == mWindow;
419 bool GetOwnedText(Window owner,
const char* displayName, WDL_String& text)
421 std::lock_guard<std::mutex> lock(mMutex);
422 if (!mDisplay || owner != mWindow || strcmp(DisplayString(mDisplay), displayName) != 0)
424 text.Set(mText.Get());
429 static void* Run(
void* context)
431 auto* self =
static_cast<LinuxClipboard*
>(context);
432 while (self->mRunning)
435 std::lock_guard<std::mutex> lock(self->mMutex);
436 while (XPending(self->mDisplay))
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)
446 pollfd fd{XConnectionNumber(self->mDisplay), POLLIN, 0};
447 const int result = poll(&fd, 1, 20);
448 if (result < 0 && errno != EINTR)
450 fprintf(stderr,
"Could not poll the X11 clipboard display: %s\n", strerror(errno));
457 void Reply(
const XSelectionRequestEvent& request)
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)
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"))
472 response.property = property;
474 else if (request.target == mUTF8 || request.target == XA_STRING)
476 if (!CheckReply(xcb_change_property_checked(mConnection, XCB_PROP_MODE_REPLACE, request.requestor, property, request.target, 8, mText.GetLength(), mText.Get()),
"property write"))
478 response.property = property;
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");
486 bool CheckReply(xcb_void_cookie_t cookie,
const char* operation)
488 xcb_generic_error_t* error = xcb_request_check(mConnection, cookie);
491 fprintf(stderr,
"X11 clipboard %s failed (error %u, resource 0x%x)\n", operation, error->error_code, error->resource_id);
495 if (xcb_connection_has_error(mConnection))
497 fprintf(stderr,
"The XCB clipboard connection failed during %s\n", operation);
503 Display* mDisplay =
nullptr;
504 xcb_connection_t* mConnection =
nullptr;
511 std::atomic<bool> mRunning{
false};
512 pthread_t mThread = 0;
515static LinuxClipboard& GetLinuxClipboard()
518 static LinuxClipboard clipboard;
530 : PlatformFont(isSystem)
535 IFontDataPtr GetFontData()
override
537 IFontDataPtr fontData(
new IFontData());
538 FILE* fp = fopen(mPath.Get(),
"rb");
542 fseek(fp, 0, SEEK_END);
543 long fileSize = ftell(fp);
549 fontData = std::make_unique<IFontData>((
int)fileSize);
551 if (!fontData->GetSize())
557 fseek(fp, 0, SEEK_SET);
558 size_t readSize = fread(fontData->Get(), 1, fontData->GetSize(), fp);
561 if (readSize && readSize == (
size_t)fontData->GetSize())
562 fontData->SetFaceIdx(0);
576 : PlatformFont(
false)
578 mData.Set((
const unsigned char*)pData, dataSize);
581 IFontDataPtr GetFontData()
override {
return IFontDataPtr(
new IFontData(mData.Get(), mData.GetSize(), 0)); }
584 WDL_TypedBuf<unsigned char> mData;
591 double red, green, blue, alpha;
595 int x, y, width, height;
599static constexpr int kGDK_GRAVITY_NORTH_WEST = 1;
600static constexpr int kGDK_GRAVITY_SOUTH_WEST = 7;
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;
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;
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;
624static constexpr int kGTK_MESSAGE_INFO = 0;
625static constexpr int kGTK_MESSAGE_QUESTION = 3;
629 void* handle =
nullptr;
632 using fn_init_check = int (*)(
int*,
char***);
633 using fn_events_pending = int (*)();
634 using fn_main_iteration_do = int (*)(int);
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*);
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*);
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*);
654 using fn_message_dialog_new =
void* (*)(
void*,
int,
int,
int,
const char*, ...);
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*);
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 (*)();
673 using fn_signal_connect_data =
unsigned long (*)(
void*,
const char*,
void*,
void*,
void*, int);
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);
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*);
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);
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;
742#define LOAD_GTK_SYM(g, name) g.name = (GTK3::fn_##name)dlsym(g.handle, "gtk_" #name)
744static GTK3* LoadGTK3()
747 static bool sTried =
false;
749 return gtk.handle ? >k :
nullptr;
754 if (dlsym(RTLD_DEFAULT,
"gtk_progress_get_type"))
759 gtk.handle = dlopen(
"libgtk-3.so.0", RTLD_NOW | RTLD_LOCAL);
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);
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);
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);
814 if (!gtk.init_check || !gtk.dialog_run || !gtk.widget_destroy || !gtk.file_chooser_dialog_new || !gtk.file_chooser_get_filename)
817 gtk.handle =
nullptr;
823 if (
auto disableSetLocale =
reinterpret_cast<void (*)()
>(dlsym(gtk.handle,
"gtk_disable_setlocale")))
829 if (
auto setAllowedBackends =
reinterpret_cast<void (*)(
const char*)
>(dlsym(gtk.handle,
"gdk_set_allowed_backends")))
830 setAllowedBackends(
"x11");
832 if (!gtk.init_check(
nullptr,
nullptr))
835 gtk.handle =
nullptr;
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)
859 const double remaining = screenScale / std::max(1, monitor_scale(pScreen, 0));
860 if (remaining > 1.01)
863 object_get(pSettings,
"gtk-xft-dpi", &dpi,
nullptr);
866 object_set(pSettings,
"gtk-xft-dpi",
static_cast<int>(std::lround(dpi * remaining)),
nullptr);
872static void GtkDrainEvents(
GTK3* pGTK)
874 if (pGTK->events_pending && pGTK->main_iteration_do)
875 while (pGTK->events_pending())
876 pGTK->main_iteration_do(0 );
882static constexpr int kGTK_WIN_POS_MOUSE = 2;
884static void GtkPresentDialog(
GTK3* pGTK,
void* dialog)
886 if (pGTK->window_set_modal)
887 pGTK->window_set_modal(dialog, 1);
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);
899static bool LaunchDetached(
const char* program,
const char* arg)
904 pid_t grandchild = fork();
907 execlp(program, program, arg, (
char*)
nullptr);
910 _exit(grandchild > 0 ? 0 : 1);
915 while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
923static bool GtkAddFileFilters(
GTK3* pGTK,
void* dialog,
const char* ext)
925 WDL_String extensions(ext ? ext :
"");
926 char* context =
nullptr;
927 char* token = strtok_r(extensions.Get(),
" \t\r\n", &context);
931 if (!pGTK->file_filter_new || !pGTK->file_filter_add_pattern || !pGTK->file_chooser_add_filter)
933 fprintf(stderr,
"Cannot apply file dialog filters: required GTK functions are unavailable\n");
937 void* filter = pGTK->file_filter_new();
940 fprintf(stderr,
"Could not create the file extension filter\n");
943 if (pGTK->file_filter_set_name)
944 pGTK->file_filter_set_name(filter, ext);
953 pattern.Append(token[0] ==
'.' ? token + 1 : token);
955 pGTK->file_filter_add_pattern(filter, pattern.Get());
956 token = strtok_r(
nullptr,
" \t\r\n", &context);
958 pGTK->file_chooser_add_filter(dialog, filter);
960 void* all = pGTK->file_filter_new();
963 fprintf(stderr,
"Could not create the all-files filter\n");
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);
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;
985static constexpr int kFC_ResultMatch = 0;
989 void* handle =
nullptr;
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**);
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;
1010#define LOAD_FC_SYM(fc, name) fc.name = (Fontconfig::fn_##name)dlsym(fc.handle, "Fc" #name)
1015 static bool sTried =
false;
1018 return fc.handle ? &fc :
nullptr;
1021 fc.handle = dlopen(
"libfontconfig.so.1", RTLD_NOW);
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);
1034 if (!fc.PatternCreate || !fc.FontMatch || !fc.PatternGetString)
1037 fc.handle =
nullptr;
1044IGraphicsLinux::IGraphicsLinux(
IGEditorDelegate& dlg,
int w,
int h,
int fps,
float scale)
1045 : IGRAPHICS_DRAW_CLASS(dlg, w, h, fps, scale)
1047#if defined VST3_API || defined VST3C_API || defined CLAP_API
1054IGraphicsLinux::~IGraphicsLinux() { CloseWindow(); }
1056void* IGraphicsLinux::OpenWindow(
void* pParent)
1059 mCloseRequested =
false;
1060 mDisplay = XOpenDisplay(
nullptr);
1064 int screen = DefaultScreen(mDisplay);
1065 Window root = RootWindow(mDisplay, screen);
1070 auto* connection = XGetXCBConnection(mDisplay);
1073 fprintf(stderr,
"Could not access the XCB connection to validate the editor parent\n");
1074 XCloseDisplay(mDisplay);
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);
1086 fprintf(stderr,
"Invalid X11 editor parent 0x%lx; using a top-level window\n",
static_cast<unsigned long>(parent));
1089 if (xcb_connection_has_error(connection))
1091 fprintf(stderr,
"The XCB connection failed while validating the editor parent\n");
1092 XCloseDisplay(mDisplay);
1105 float gdkScale = 1.f;
1106 const char* s = getenv(
"IPLUG2_SCREEN_SCALE");
1108 s = getenv(
"GDK_SCALE");
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)
1116 if (gdkScale > 1.f && !GetDelegate()->HasHostScreenScale())
1117 SetScreenScale(gdkScale);
1129 const char* menuOff = getenv(
"IPLUG2_MENU_OFFSET");
1131 clientOffY = std::clamp(atoi(menuOff), 0, 100);
1135 XVisualInfo* pVisualInfo = CreateGLContext();
1138 XCloseDisplay(mDisplay);
1144 mGLColormap = XCreateColormap(mDisplay, root, pVisualInfo->visual, AllocNone);
1146 XSetWindowAttributes attrs = {};
1147 attrs.event_mask = ExposureMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | KeyPressMask | KeyReleaseMask | EnterWindowMask | LeaveWindowMask | FocusChangeMask
1148 | PropertyChangeMask;
1149 attrs.colormap = mGLColormap;
1152 attrs.border_pixel = 0;
1155 const auto physW = (unsigned)(WindowWidth() * GetScreenScale());
1156 const auto physH = (unsigned)(WindowHeight() * GetScreenScale());
1158 mPlugWnd = XCreateWindow(mDisplay, mParentWnd, 0, clientOffY, physW, physH, 0, pVisualInfo->depth, InputOutput, pVisualInfo->visual, CWColormap | CWBorderPixel | CWEventMask, &attrs);
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);
1166 const auto physW = (unsigned)(WindowWidth() * GetScreenScale());
1167 const auto physH = (unsigned)(WindowHeight() * GetScreenScale());
1169 mPlugWnd = XCreateWindow(mDisplay, mParentWnd, 0, clientOffY, physW, physH, 0, CopyFromParent, InputOutput, CopyFromParent, CWEventMask | CWBackPixel, &attrs);
1178 XFreeColormap(mDisplay, mGLColormap);
1182 XCloseDisplay(mDisplay);
1187 mWMDeleteMessage = XInternAtom(mDisplay,
"WM_DELETE_WINDOW", 0 );
1188 mClipboardAtom = XInternAtom(mDisplay,
"CLIPBOARD", 0 );
1189 mUTF8StringAtom = XInternAtom(mDisplay,
"UTF8_STRING", 0 );
1190 mSelDataAtom = XInternAtom(mDisplay,
"IPLUG2_SEL_DATA", 0 );
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);
1209 bool isTopLevel = (mParentWnd == (Window)XRootWindow(mDisplay, DefaultScreen(mDisplay)));
1212 XSetWMProtocols(mDisplay, mPlugWnd, &mWMDeleteMessage, 1);
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);
1225 XMapWindow(mDisplay, mPlugWnd);
1229 bool initialized =
false;
1231 ScopedGLContext scopedGLCtx{
this};
1232 if (glXGetCurrentContext() == mGLContext && glXGetCurrentDrawable() == mPlugWnd)
1235 OnViewInitialized(
nullptr);
1236 GetDelegate()->LayoutUI(
this);
1237 SetAllControlsDirty();
1247 XFreeColormap(mDisplay, mGLColormap);
1250 XDestroyWindow(mDisplay, mPlugWnd);
1252 XCloseDisplay(mDisplay);
1257 OnViewInitialized(
nullptr);
1258 GetDelegate()->LayoutUI(
this);
1259 SetAllControlsDirty();
1263 CreateInputContext();
1266#ifdef IGRAPHICS_ACCESSKIT
1267 mAccessibility = std::make_unique<IGraphicsAccessibilityLinux>(*
this, mDisplay, mPlugWnd);
1270 GetDelegate()->OnUIOpen();
1274 mNeedsRedraw =
true;
1278 return (
void*)(uintptr_t)mPlugWnd;
1281void IGraphicsLinux::CloseWindow()
1283 if (IsInPlatformCallback())
1285 RequestWindowClose();
1291#ifdef IGRAPHICS_ACCESSKIT
1292 mAccessibility =
nullptr;
1298 ScopedGLContext scopedGLCtx{
this};
1308 XFreeCursor(mDisplay, mBlankCursor);
1312#if defined IGRAPHICS_SKIA && defined IGRAPHICS_CPU
1316 XFreeGC(mDisplay, mCPUGC);
1321 DestroyInputContext();
1324 XFreeFontSet(mDisplay, mTooltipFont);
1325 mTooltipFont =
nullptr;
1329 XDestroyWindow(mDisplay, mPlugWnd);
1336 XFreeColormap(mDisplay, mGLColormap);
1341 XCloseDisplay(mDisplay);
1345void IGraphicsLinux::ResetDrag()
1348 mDragSupported =
false;
1351void IGraphicsLinux::HideTooltip()
1353 if (mDisplay && mTooltipWindow)
1355 XDestroyWindow(mDisplay, mTooltipWindow);
1360void IGraphicsLinux::UpdateTooltips()
1363 mTooltipControl = -1;
1364 mTooltipHoverTime = HoverMillis();
1367void IGraphicsLinux::ShowTooltip(
float x,
float y)
1369 if (!mDisplay || !mPlugWnd || !TooltipsEnabled() || mTooltipControl < 0 || mTooltipWindow)
1371 IControl* pControl = GetControl(mTooltipControl);
1376 char** missing =
nullptr;
1378 char* defaultString =
nullptr;
1379 mTooltipFont = XCreateFontSet(mDisplay,
"-*-sans-medium-r-normal--14-*-*-*-*-*-*-*", &missing, &count, &defaultString);
1381 XFreeStringList(missing);
1387 mTooltipFont = XCreateFontSet(mDisplay,
"fixed", &missing, &count, &defaultString);
1389 XFreeStringList(missing);
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;
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;
1411 XCreateWindow(mDisplay, DefaultRootWindow(mDisplay), rootX, rootY, width, height, 1, CopyFromParent, InputOutput, CopyFromParent, CWOverrideRedirect | CWBackPixel | CWEventMask, &attrs);
1413 XMapRaised(mDisplay, mTooltipWindow);
1416void IGraphicsLinux::DrawTooltip()
1418 if (!mTooltipWindow || mTooltipControl < 0 || !mTooltipFont)
1420 IControl* pControl = GetControl(mTooltipControl);
1424 XRectangle ink{}, logical{};
1425 Xutf8TextExtents(mTooltipFont, label,
static_cast<int>(strlen(label)), &ink, &logical);
1426 XWindowAttributes attrs{};
1427 if (!XGetWindowAttributes(mDisplay, mTooltipWindow, &attrs))
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);
1436void IGraphicsLinux::PlatformResize(
bool parentHasResized)
1440 if (mInConfigureNotify)
1443 if (mDisplay && mPlugWnd)
1446 auto w = (unsigned)(WindowWidth() * GetScreenScale());
1447 auto h = (unsigned)(WindowHeight() * GetScreenScale());
1448 XResizeWindow(mDisplay, mPlugWnd, w, h);
1454 if (scale == GetScreenScale())
1456 if (mDisplay && mPlugWnd)
1462 while (XCheckTypedWindowEvent(mDisplay, mPlugWnd, ConfigureNotify, &event))
1466 SetScreenScale(scale);
1469#if defined IGRAPHICS_SKIA && defined IGRAPHICS_CPU
1470void IGraphicsLinux::DestroyCPUImage()
1475 XDestroyImage(mCPUImage);
1476 mCPUImage =
nullptr;
1480void IGraphicsLinux::PresentCPUFrame(
const SkPixmap& pixels)
1482 if (!mDisplay || !mPlugWnd || pixels.width() <= 0 || pixels.height() <= 0)
1485 if (mCPUImage && (mCPUImage->width != pixels.width() || mCPUImage->height != pixels.height()))
1490 XWindowAttributes attributes{};
1491 if (!XGetWindowAttributes(mDisplay, mPlugWnd, &attributes) || attributes.visual->c_class != TrueColor)
1493 mCPUImage = XCreateImage(mDisplay, attributes.visual, attributes.depth, ZPixmap,
1494 0,
nullptr, pixels.width(), pixels.height(), 32, 0);
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)
1503 mCPUImage->data =
static_cast<char*
>(calloc(pixels.height(), stride));
1504 if (!mCPUImage->data)
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)
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))
1526 const auto channel = [](
unsigned value,
unsigned long mask) ->
unsigned long {
1535 return ((
static_cast<unsigned long>(value) * mask + 127) / 255) << shift;
1537 for (
int y = 0; y < pixels.height(); ++y)
1539 for (
int x = 0; x < pixels.width(); ++x)
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);
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);
1556 mCPUGC = XCreateGC(mDisplay, mPlugWnd, 0,
nullptr);
1559 XPutImage(mDisplay, mPlugWnd, mCPUGC, mCPUImage, 0, 0, 0, 0, pixels.width(), pixels.height());
1566 if (width <= 0 || height <= 0)
1569 int designWidth, designHeight;
1571 CalculateHostResize(width, height, designWidth, designHeight, scale);
1572 Resize(designWidth, designHeight, scale,
false);
1575void IGraphicsLinux::CalculateHostResize(
int width,
int height,
int& designWidth,
int& designHeight,
float& scale)
1577 const float screenScale = GetScreenScale();
1578 const auto pixels = [screenScale](
int dimension,
float candidateScale) {
return PhysicalWindowDimension(dimension, candidateScale, screenScale); };
1579 if (GetResizerMode() == EUIResizerMode::Scale)
1581 designWidth = Width();
1582 designHeight = Height();
1583 GetDelegate()->ConstrainEditorResize(designWidth, designHeight);
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());
1597 const float mid = lo + (hi - lo) * .5f;
1598 if (mid == lo || mid == hi)
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;
1614 scale = ConstrainDrawScale(GetDrawScale());
1616 const auto fitDimension = [&](
int requested,
int maximum) {
1617 int lo = 0, hi = maximum;
1620 const int mid = hi - (hi - lo) / 2;
1621 if (pixels(mid, scale) <= requested)
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;
1629 designWidth = fitDimension(width, GetDelegate()->GetMaxWidth());
1630 designHeight = fitDimension(height, GetDelegate()->GetMaxHeight());
1632 GetDelegate()->ConstrainEditorResize(designWidth, designHeight);
1638 int designWidth, designHeight;
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()));
1645void IGraphicsLinux::ForceEndUserEdit() {}
1647void IGraphicsLinux::HideMouseCursor(
bool hide,
bool lock)
1649 if (!mDisplay || !mPlugWnd)
1656 static const char emptyData[] = {0, 0, 0, 0, 0, 0, 0, 0};
1658 Pixmap emptyBitmap = XCreateBitmapFromData(mDisplay, mPlugWnd, emptyData, 8, 8);
1659 mBlankCursor = XCreatePixmapCursor(mDisplay, emptyBitmap, emptyBitmap, &black, &black, 0, 0);
1660 XFreePixmap(mDisplay, emptyBitmap);
1662 XDefineCursor(mDisplay, mPlugWnd, mBlankCursor);
1663 mCursorHidden =
true;
1667 mHiddenCursorX = mCursorX;
1668 mHiddenCursorY = mCursorY;
1673 XUndefineCursor(mDisplay, mPlugWnd);
1675 MoveMouseCursor(mHiddenCursorX, mHiddenCursorY);
1676 mCursorHidden =
false;
1677 mCursorLock =
false;
1681void IGraphicsLinux::MoveMouseCursor(
float x,
float y)
1683 if (mDisplay && mPlugWnd)
1685 const float scale = GetTotalScale();
1686 XWarpPointer(mDisplay, 0 , mPlugWnd, 0, 0, 0, 0, (
int)(x * scale), (
int)(y * scale));
1690ECursor IGraphicsLinux::SetMouseCursor(ECursor cursorType)
1692 if (!mDisplay || !mPlugWnd)
1695 unsigned int shape = XC_left_ptr;
1698 case ECursor::ARROW:
1699 shape = XC_left_ptr;
1701 case ECursor::IBEAM:
1707 case ECursor::CROSS:
1708 shape = XC_crosshair;
1710 case ECursor::UPARROW:
1711 shape = XC_sb_up_arrow;
1713 case ECursor::SIZENWSE:
1716 case ECursor::SIZENESW:
1719 case ECursor::SIZEWE:
1720 shape = XC_sb_h_double_arrow;
1722 case ECursor::SIZENS:
1723 shape = XC_sb_v_double_arrow;
1725 case ECursor::SIZEALL:
1729 shape = XC_X_cursor;
1734 case ECursor::APPSTARTING:
1738 shape = XC_question_arrow;
1741 shape = XC_left_ptr;
1745 Cursor cursor = XCreateFontCursor(mDisplay, shape);
1746 XDefineCursor(mDisplay, mPlugWnd, cursor);
1747 XFreeCursor(mDisplay, cursor);
1751void IGraphicsLinux::GetMouseLocation(
float& x,
float& y)
const
1753 if (!mDisplay || !mPlugWnd)
1760 int rootX, rootY, winX, winY;
1762 if (!XQueryPointer(mDisplay, mPlugWnd, &root, &child, &rootX, &rootY, &winX, &winY, &mask))
1767 const float scale = GetTotalScale();
1772EMsgBoxResult IGraphicsLinux::ShowMessageBox(
const char* str,
const char* title, EMsgBoxType type, IMsgBoxCompletionHandlerFunc completionHandler)
1774 auto complete = [&](EMsgBoxResult result) {
1775 if (completionHandler)
1776 completionHandler(result);
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))
1783 fprintf(stderr,
"Cannot show message box: required GTK functions are unavailable\n");
1784 return complete(kCANCEL);
1787 int gtkMsgType = kGTK_MESSAGE_INFO;
1788 int gtkBtnType = kGTK_BUTTONS_OK;
1794 gtkMsgType = kGTK_MESSAGE_QUESTION;
1795 gtkBtnType = kGTK_BUTTONS_OK_CANCEL;
1798 gtkMsgType = kGTK_MESSAGE_QUESTION;
1799 gtkBtnType = kGTK_BUTTONS_YES_NO;
1801 case kMB_YESNOCANCEL:
1802 case kMB_RETRYCANCEL:
1803 gtkMsgType = kGTK_MESSAGE_QUESTION;
1804 gtkBtnType = kGTK_BUTTONS_NONE;
1807 fprintf(stderr,
"Cannot show message box: unsupported button type %d\n", type);
1808 return complete(kCANCEL);
1811 void* dialog = pGTK->message_dialog_new(
nullptr, 0, gtkMsgType, gtkBtnType,
"%s", str ? str :
"");
1814 fprintf(stderr,
"Could not create the message box\n");
1815 return complete(kCANCEL);
1817 if (type == kMB_YESNOCANCEL)
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);
1823 else if (type == kMB_RETRYCANCEL)
1825 pGTK->dialog_add_button(dialog,
"_Cancel", kGTK_RESPONSE_CANCEL);
1826 pGTK->dialog_add_button(dialog,
"_Retry", kGTK_RESPONSE_RETRY);
1828 if (title && pGTK->window_set_title)
1829 pGTK->window_set_title(dialog, title);
1830 GtkPresentDialog(pGTK, dialog);
1832 int resp = pGTK->dialog_run(dialog);
1833 pGTK->widget_destroy(dialog);
1834 GtkDrainEvents(pGTK);
1836 EMsgBoxResult result = kCANCEL;
1839 case kGTK_RESPONSE_OK:
1842 case kGTK_RESPONSE_YES:
1845 case kGTK_RESPONSE_NO:
1848 case kGTK_RESPONSE_CANCEL:
1851 case kGTK_RESPONSE_RETRY:
1859 return complete(result);
1862bool IGraphicsLinux::RevealPathInExplorerOrFinder(WDL_String& path,
bool select)
1865 WDL_String dir(path);
1870 if (strrchr(dir.Get(),
'/'))
1871 dir.remove_filepart(
false);
1874 return LaunchDetached(
"xdg-open", dir.Get());
1877void IGraphicsLinux::PromptForFile(WDL_String& fileName, WDL_String& path, EFileAction action,
const char* ext, IFileDialogCompletionHandlerFunc completionHandler)
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);
1886 GTK3* pGTK = LoadGTK3();
1889 fprintf(stderr,
"Cannot show file dialog: GTK is unavailable\n");
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";
1898 void* dialog = pGTK->file_chooser_dialog_new(isSave ?
"Save File" :
"Open File",
nullptr, gtkAction,
"_Cancel", kGTK_RESPONSE_CANCEL, acceptBtn, kGTK_RESPONSE_OK,
nullptr);
1902 fprintf(stderr,
"Could not create the file dialog\n");
1906 if (!GtkAddFileFilters(pGTK, dialog, ext))
1908 pGTK->widget_destroy(dialog);
1909 GtkDrainEvents(pGTK);
1915 if (path.GetLength() && pGTK->file_chooser_set_current_folder)
1916 pGTK->file_chooser_set_current_folder(dialog, path.Get());
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);
1923 if (pGTK->dialog_run(dialog) == kGTK_RESPONSE_OK)
1925 char* chosen = pGTK->file_chooser_get_filename(dialog);
1928 outFile.Set(chosen);
1929 const char* slash = strrchr(chosen,
'/');
1931 outPath.Set(chosen, (
int)(slash - chosen + 1));
1935 fprintf(stderr,
"File dialog accepted without a selected file\n");
1938 pGTK->widget_destroy(dialog);
1939 GtkDrainEvents(pGTK);
1944void IGraphicsLinux::PromptForDirectory(WDL_String& dir, IFileDialogCompletionHandlerFunc completionHandler)
1947 auto complete = [&]() {
1948 dir.Set(outDir.Get());
1949 if (completionHandler)
1950 completionHandler(WDL_String{}, dir);
1952 GTK3* pGTK = LoadGTK3();
1955 fprintf(stderr,
"Cannot show directory dialog: GTK is unavailable\n");
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);
1964 fprintf(stderr,
"Could not create the directory dialog\n");
1969 if (dir.GetLength() && pGTK->file_chooser_set_current_folder)
1970 pGTK->file_chooser_set_current_folder(dialog, dir.Get());
1971 GtkPresentDialog(pGTK, dialog);
1973 if (pGTK->dialog_run(dialog) == kGTK_RESPONSE_OK)
1975 char* chosen = pGTK->file_chooser_get_filename(dialog);
1979 if (outDir.GetLength() && outDir.Get()[outDir.GetLength() - 1] !=
'/')
1984 fprintf(stderr,
"Directory dialog accepted without a selected directory\n");
1987 pGTK->widget_destroy(dialog);
1988 GtkDrainEvents(pGTK);
1993bool IGraphicsLinux::PromptForColor(
IColor& color,
const char* str, IColorPickerHandlerFunc func)
1995 GTK3* pGTK = LoadGTK3();
1996 if (!pGTK || !pGTK->color_chooser_dialog_new)
1999 void* dialog = pGTK->color_chooser_dialog_new(str ? str :
"Choose Color",
nullptr);
2001 if (pGTK->color_chooser_set_rgba)
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);
2006 GtkPresentDialog(pGTK, dialog);
2008 const bool accepted = (pGTK->dialog_run(dialog) == kGTK_RESPONSE_OK);
2010 if (accepted && pGTK->color_chooser_get_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);
2022 pGTK->widget_destroy(dialog);
2023 GtkDrainEvents(pGTK);
2027bool IGraphicsLinux::OpenURL(
const char* url,
const char* msgWindowTitle,
const char* confirmMsg,
const char* errMsgOnFailure) {
return LaunchDetached(
"xdg-open", url); }
2029bool IGraphicsLinux::GetTextFromClipboard(WDL_String& str)
2031 if (!mDisplay || !mPlugWnd || !mClipboardAtom)
2034 const Window owner = XGetSelectionOwner(mDisplay, mClipboardAtom);
2035 if (GetLinuxClipboard().GetOwnedText(owner, DisplayString(mDisplay), str))
2043 DispatchScope dispatch(mDispatchDepth);
2044 GTK3* pGTK = LoadGTK3();
2047 XConvertSelection(mDisplay, mClipboardAtom, mUTF8StringAtom, mSelDataAtom, mPlugWnd, 0L );
2051 for (
int i = 0; i < 50; ++i)
2053 if (pGTK && pGTK->events_pending && pGTK->main_iteration_do && pGTK->events_pending())
2054 pGTK->main_iteration_do(0);
2055 if (mCloseRequested)
2060 if (XCheckTypedWindowEvent(mDisplay, mPlugWnd, SelectionNotify, &ev))
2062 if (ev.xselection.selection != mClipboardAtom)
2065 if (ev.xselection.property == 0 )
2070 unsigned long nitems, remaining;
2071 unsigned char* data =
nullptr;
2073 const int status = XGetWindowProperty(mDisplay, mPlugWnd, mSelDataAtom, 0, 65536, 1 , AnyPropertyType, &type, &fmt, &nitems, &remaining, &data);
2076 if (status == 0 && fmt == 8 && (type == mUTF8StringAtom || type == XA_STRING) && data && remaining == 0 && nitems <= 0x7FFFFFFFUL)
2078 str.Set((
const char*)data, (
int)nitems);
2087 fprintf(stderr,
"Timed out waiting for the X11 clipboard owner\n");
2091bool IGraphicsLinux::SetTextInClipboard(
const char* str)
2093 if (!mDisplay || !mPlugWnd || !mClipboardAtom)
2096 return GetLinuxClipboard().SetText(str, DisplayString(mDisplay));
2110 void* gtkMenu = pGTK->menu_new();
2112 for (
int i = 0; i < menu.NItems(); ++i)
2115 void* gtkItem =
nullptr;
2117 if (pItem->GetIsSeparator())
2119 gtkItem = pGTK->separator_menu_item_new();
2121 else if (pItem->GetChecked() && pGTK->check_menu_item_new_with_label)
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);
2129 gtkItem = pGTK->menu_item_new_with_label(pItem->GetText());
2136 if (!pItem->GetEnabled() || pItem->GetIsTitle())
2138 if (pGTK->widget_set_sensitive)
2139 pGTK->widget_set_sensitive(gtkItem, 0);
2143 if (pItem->GetSubmenu() && pGTK->menu_item_set_submenu)
2145 void* sub = BuildGtkMenu(pGTK, *pItem->GetSubmenu(), pState);
2146 pGTK->menu_item_set_submenu(gtkItem, sub);
2148 else if (pItem->GetEnabled() && !pItem->GetIsTitle() && !pItem->GetIsSeparator() && pGTK->signal_connect_data)
2158 auto* ad =
new ActivateData{pState, &menu, i};
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;
2168 auto destroyCb = +[](
void* userData) {
delete static_cast<ActivateData*
>(userData); };
2170 pGTK->signal_connect_data(gtkItem,
"activate", (
void*)activateCb, ad, (
void*)destroyCb, 0);
2173 pGTK->menu_shell_append(gtkMenu, gtkItem);
2176 if (pGTK->widget_show_all)
2177 pGTK->widget_show_all(gtkMenu);
2192 unsigned int button;
2194 double x_root, y_root;
2200void* IGraphicsLinux::CreateGdkButtonPressEvent(
void* gtkHandle,
void* gdkDisplay,
void* gdkWindow,
int gdkScale)
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"))
2211 void* pSeat = get_default_seat(gdkDisplay);
2212 void* pPointer = pSeat ? seat_get_pointer(pSeat) : nullptr;
2217 pEvent->window = object_ref(gdkWindow);
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);
2229void IGraphicsLinux::ReleaseX11PointerGrab()
2233 XUngrabPointer(mDisplay, 0L );
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)
2249 ReleaseX11PointerGrab();
2252 void* gtkMenu = BuildGtkMenu(pGTK, menu, &state);
2255 if (pGTK->signal_connect_data)
2257 auto deactivateCb = +[](
void*,
void*) {
2259 GTK3* pGTK = LoadGTK3();
2260 if (pGTK && pGTK->main_quit)
2263 pGTK->signal_connect_data(gtkMenu,
"deactivate", (
void*)deactivateCb,
nullptr,
nullptr, 0);
2271 XUngrabPointer(mDisplay, 0 );
2280 bool popped =
false;
2282 if (pGTK->menu_popup_at_rect && pGTK->gdk_display_get_default && pGTK->gdk_x11_window_foreign && mPlugWnd)
2284 void* gdkDisplay = pGTK->gdk_display_get_default();
2287 void* gdkWindow = pGTK->gdk_x11_window_foreign(gdkDisplay,
static_cast<unsigned long>(mPlugWnd));
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);
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);
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);
2306 reinterpret_cast<void (*)(
void*)
>(dlsym(pGTK->handle,
"gdk_event_free"))(triggerEvent);
2308 if (pGTK->g_object_unref)
2309 pGTK->g_object_unref(gdkWindow);
2314 if (!popped && pGTK->menu_popup_at_pointer)
2315 pGTK->menu_popup_at_pointer(gtkMenu,
nullptr);
2320 if (!pGTK->widget_get_mapped || pGTK->widget_get_mapped(gtkMenu))
2323 fprintf(stderr,
"IGraphicsLinux: GTK did not show the popup menu\n");
2326 pGTK->widget_destroy(gtkMenu);
2327 GtkDrainEvents(pGTK);
2329 if (state.pMenu && state.chosenIdx >= 0)
2331 state.pMenu->SetChosenItemIdx(state.chosenIdx);
2333 if (state.pMenu->GetFunction())
2334 state.pMenu->ExecFunction();
2342void IGraphicsLinux::CreatePlatformTextEntry(
int paramIdx,
const IText& text,
const IRECT& bounds,
int length,
const char* str)
2345 static constexpr int kGTK_DIALOG_MODAL = 1;
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)
2350 ClearInTextEntryControl();
2356 ReleaseX11PointerGrab();
2357 ReleaseMouseCapture();
2359 void* dialog = pGTK->dialog_new_with_buttons(
"Edit Value",
nullptr, kGTK_DIALOG_MODAL,
"_Cancel", kGTK_RESPONSE_CANCEL,
"_OK", kGTK_RESPONSE_OK,
nullptr);
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);
2368 if (pGTK->signal_connect_data && pGTK->dialog_response)
2370 auto activateCb = +[](
void*,
void* userData) {
2371 GTK3* pGTK = LoadGTK3();
2372 if (pGTK && pGTK->dialog_response)
2373 pGTK->dialog_response(userData, kGTK_RESPONSE_OK);
2375 pGTK->signal_connect_data(entry,
"activate", (
void*)activateCb, dialog,
nullptr, 0);
2378 void* contentArea = pGTK->dialog_get_content_area(dialog);
2379 pGTK->box_pack_start(contentArea, entry, 1, 1, 0);
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)
2387 const float scale = GetTotalScale();
2388 int rootX = 0, rootY = 0;
2390 if (XTranslateCoordinates(mDisplay, mPlugWnd, DefaultRootWindow(mDisplay),
static_cast<int>(bounds.L * scale),
static_cast<int>(bounds.B * scale), &rootX, &rootY, &child))
2392 const int gdkScale = widget_scale ? std::max(1, widget_scale(dialog)) : 1;
2393 window_move(dialog, rootX / gdkScale, rootY / gdkScale);
2397 if (pGTK->widget_show_all)
2398 pGTK->widget_show_all(dialog);
2399 GtkPresentDialog(pGTK, dialog);
2401 int response = pGTK->dialog_run(dialog);
2403 if (response == kGTK_RESPONSE_OK)
2405 const char* result = pGTK->entry_get_text(entry);
2406 SetControlValueAfterTextEdit(result ? result :
"");
2410 ClearInTextEntryControl();
2413 pGTK->widget_destroy(dialog);
2414 GtkDrainEvents(pGTK);
2417PlatformFontPtr IGraphicsLinux::LoadPlatformFont(
const char* fontID,
const char* fileNameOrResID)
2419 WDL_String fullPath;
2420 const EResourceLocation loc =
LocateResource(fileNameOrResID,
"ttf", fullPath, GetBundleID(),
nullptr,
nullptr);
2421 if (loc == EResourceLocation::kNotFound)
2424 return PlatformFontPtr(
new LinuxFileFont(fullPath.Get(),
false));
2427PlatformFontPtr IGraphicsLinux::LoadPlatformFont(
const char* fontID,
const char* fontName, ETextStyle style)
2433 _FcPattern* pattern = pFontconfig->PatternCreate();
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);
2441 pFontconfig->ConfigSubstitute(
nullptr, pattern, kFC_MatchPattern);
2442 pFontconfig->DefaultSubstitute(pattern);
2445 _FcPattern* matched = pFontconfig->FontMatch(
nullptr, pattern, &result);
2446 pFontconfig->PatternDestroy(pattern);
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));
2456 pFontconfig->PatternDestroy(matched);
2460PlatformFontPtr IGraphicsLinux::LoadPlatformFont(
const char* fontID,
void* pData,
int dataSize) {
return PlatformFontPtr(
new LinuxMemFont(pData, dataSize)); }
2462void IGraphicsLinux::CachePlatformFont(
const char* fontID,
const PlatformFontPtr& font)
2467void IGraphicsLinux::ActivateGLContext()
2470 mGLContextStack.push_back({glXGetCurrentDisplay(), glXGetCurrentContext(), glXGetCurrentDrawable(), glXGetCurrentReadDrawable()});
2471 if (!mDisplay || !mGLContext)
2473 if (!glXMakeCurrent(mDisplay, mPlugWnd, (GLXContext)mGLContext))
2474 fprintf(stderr,
"Could not activate the Linux graphics GLX context\n");
2478void IGraphicsLinux::DeactivateGLContext()
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)
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");
2494XVisualInfo* IGraphicsLinux::CreateGLContext()
2499 int screen = DefaultScreen(mDisplay);
2502 GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_DEPTH_SIZE, 24, 0
2505 XVisualInfo* pVisualInfo = glXChooseVisual(mDisplay, screen, attribs);
2509 mGLContext = (
void*)glXCreateContext(mDisplay, pVisualInfo,
nullptr, GL_TRUE);
2519void IGraphicsLinux::DestroyGLContext()
2521 if (mDisplay && mGLContext)
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;
2534static int KeysymToVK(KeySym ks)
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);
2612void IGraphicsLinux::CreateInputContext()
2614 mInputMethodDisconnected =
false;
2616 mInputMethod = XOpenIM(mDisplay,
nullptr,
nullptr,
nullptr);
2619 XIMCallback destroyed{};
2620 destroyed.client_data =
reinterpret_cast<XPointer
>(
this);
2621 destroyed.callback = [](XIM, XPointer data, XPointer) {
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");
2628 if (XSetIMValues(mInputMethod, XNDestroyCallback, &destroyed,
nullptr))
2630 fprintf(stderr,
"Could not register the Linux input method disconnect callback; Compose and IME input are unavailable\n");
2631 DestroyInputContext();
2634 mInputContext = XCreateIC(mInputMethod, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, mPlugWnd, XNFocusWindow, mPlugWnd,
nullptr);
2638 fprintf(stderr,
"Could not create the Linux input context; Compose and IME input are unavailable\n");
2639 DestroyInputContext();
2642 long filterEvents = 0;
2643 if (XGetICValues(mInputContext, XNFilterEvents, &filterEvents,
nullptr) ==
nullptr)
2645 XWindowAttributes attributes{};
2646 if (XGetWindowAttributes(mDisplay, mPlugWnd, &attributes))
2647 XSelectInput(mDisplay, mPlugWnd, attributes.your_event_mask | filterEvents);
2651void IGraphicsLinux::DestroyInputContext()
2655 XDestroyIC(mInputContext);
2656 mInputContext =
nullptr;
2660 XCloseIM(mInputMethod);
2661 mInputMethod =
nullptr;
2665void IGraphicsLinux::DispatchKeyEvent(XKeyEvent& event)
2668 WDL_TypedBuf<char> text;
2672 fprintf(stderr,
"Could not allocate the Linux keyboard input buffer\n");
2676 if (event.type == KeyPress && mInputContext)
2679 length = Xutf8LookupString(mInputContext, &event, text.Get(), text.GetSize() - 1, &symbol, &status);
2680 if (status == XBufferOverflow && length > 0 && length < INT_MAX)
2682 text.Resize(length + 1);
2683 if (text.GetSize() != length + 1)
2685 fprintf(stderr,
"Could not allocate the Linux input method commit buffer\n");
2688 length = Xutf8LookupString(mInputContext, &event, text.Get(), text.GetSize() - 1, &symbol, &status);
2690 if (status != XLookupChars && status != XLookupKeySym && status != XLookupBoth)
2692 if (status != XLookupNone)
2693 fprintf(stderr,
"Could not read the Linux input method commit (status %d)\n", status);
2696 if (status == XLookupChars)
2698 if (status == XLookupKeySym)
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)
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);
2716 if (length < 0 || length >= text.GetSize())
2718 fprintf(stderr,
"Invalid Linux input method commit length %d\n", length);
2721 text.Get()[length] =
'\0';
2729 char character[5]{};
2731 if (offset < length)
2734 size = wdl_utf8_parsechar(text.Get() + offset, &codepoint);
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)
2739 fprintf(stderr,
"The Linux input method returned invalid UTF-8\n");
2742 memcpy(character, text.Get() + offset, size);
2745 IKeyPress key(character, offset == 0 ? KeysymToVK(symbol) : kVK_NONE, (event.state & ShiftMask) != 0, (event.state & ControlMask) != 0, (event.state & Mod1Mask) != 0);
2748 if (event.type == KeyPress && offset == 0 && IPlugAPPHandleKeyboardShortcut(key))
2751 if (event.type == KeyPress)
2752 OnKeyDown(mCursorX, mCursorY, key);
2754 OnKeyUp(mCursorX, mCursorY, key);
2756 }
while (offset < length && !mCloseRequested);
2761 if (IsInPlatformCallback())
2763 DispatchScope dispatch(mDispatchDepth);
2764 DispatchX11Events();
2767void IGraphicsLinux::DispatchX11Events()
2769 if (!mDisplay || !mPlugWnd || mCloseRequested)
2772 while (!mCloseRequested && XPending(mDisplay))
2775 XNextEvent(mDisplay, &ev);
2776 if (ev.type == Expose && ev.xexpose.window == mTooltipWindow)
2781 if (XFilterEvent(&ev, mPlugWnd))
2784 const float scale = GetTotalScale();
2789 while (XCheckTypedWindowEvent(mDisplay, mPlugWnd, Expose, &ev))
2791 mNeedsRedraw =
true;
2795 case ConfigureNotify: {
2796 XConfigureEvent& ce = ev.xconfigure;
2797 if (ce.window != mPlugWnd)
2807 while (XCheckTypedWindowEvent(mDisplay, mPlugWnd, ConfigureNotify, &next))
2809 ce = next.xconfigure;
2813 const int physW = ce.width;
2814 const int physH = ce.height;
2817 const int curPhysW =
static_cast<int>(WindowWidth() * GetScreenScale());
2818 const int curPhysH =
static_cast<int>(WindowHeight() * GetScreenScale());
2819 if (physW == curPhysW && physH == curPhysH)
2826 mInConfigureNotify =
true;
2830 mInConfigureNotify =
false;
2833 if (physW !=
static_cast<int>(WindowWidth() * GetScreenScale()) || physH !=
static_cast<int>(WindowHeight() * GetScreenScale()))
2834 PlatformResize(
false);
2839 case ButtonRelease: {
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;
2849 if (be.button == Button4 || be.button == Button5)
2852 if (ev.type == ButtonPress)
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);
2863 if (be.button > Button3)
2866 const bool left = (be.button == Button1);
2867 const bool right = (be.button == Button3);
2868 IMouseMod mod(left, right, shift, ctrl, alt);
2879 std::vector<IMouseInfo> list{info};
2881 if (ev.type == ButtonPress)
2883 mLastPressTime = be.time;
2884 mLastPressButton = be.button;
2887 mLastPressRootX = be.x_root;
2888 mLastPressRootY = be.y_root;
2891 XSetInputFocus(mDisplay, mPlugWnd, RevertToParent, be.time);
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)
2901 OnMouseDblClick(x, y, mod);
2902 mLastLeftClickTime = 0;
2907 mLastLeftClickTime = left ? be.time : 0;
2908 mLastLeftClickX = clickX;
2909 mLastLeftClickY = clickY;
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);
2933 info.dX = x - mCursorX;
2934 info.dY = y - mCursorY;
2936 std::vector<IMouseInfo> list{info};
2941 mTooltipControl = -1;
2948 OnMouseOver(x, y, mod);
2951 const int hovered = TooltipsEnabled() ? GetMouseOver() : -1;
2952 if (hovered != mTooltipControl || std::fabs(mTooltipX - x) > 4.f || std::fabs(mTooltipY - y) > 4.f)
2955 mTooltipControl = hovered;
2958 mTooltipHoverTime = HoverMillis();
2966 mTooltipControl = -1;
2971 if (mInputMethodDisconnected)
2972 CreateInputContext();
2974 XSetICFocus(mInputContext);
2975#ifdef IGRAPHICS_ACCESSKIT
2977 if (mAccessibility && ev.xfocus.window == mPlugWnd && ev.xfocus.detail != NotifyPointer && ev.xfocus.detail != NotifyPointerRoot)
2978 static_cast<IGraphicsAccessibilityLinux*
>(mAccessibility.get())->SetWindowFocused(
true);
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);
2994 DispatchKeyEvent(ev.xkey);
2997 case ClientMessage: {
2998 if (ev.xclient.window == mPlugWnd && ev.xclient.format == 32)
3000 auto& msg = ev.xclient;
3001 if (msg.message_type == mXdndEnter)
3004 mTooltipControl = -1;
3006 const int version = (msg.data.l[1] >> 24) & 0xff;
3009 mDragSource =
static_cast<Window
>(msg.data.l[0]);
3010 if (msg.data.l[1] & 1)
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
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;
3028 for (
int i = 2; i < 5; ++i)
3029 if (
static_cast<Atom
>(msg.data.l[i]) == mUriList)
3030 mDragSupported =
true;
3034 if (msg.message_type == mXdndLeave &&
static_cast<Window
>(msg.data.l[0]) == mDragSource)
3039 if (msg.message_type == mXdndPosition &&
static_cast<Window
>(msg.data.l[0]) == mDragSource)
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();
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);
3061 if (msg.message_type == mXdndDrop &&
static_cast<Window
>(msg.data.l[0]) == mDragSource)
3064 XConvertSelection(mDisplay, mXdndSelection, mUriList, mDropProperty, mPlugWnd, msg.data.l[2]);
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);
3081 if (ev.xclient.message_type == XInternAtom(mDisplay,
"WM_PROTOCOLS", 0) && ev.xclient.format == 32 && (Atom)ev.xclient.data.l[0] == mWMDeleteMessage)
3083 mCloseRequested =
true;
3084 mTimerRunning =
false;
3090 case SelectionNotify: {
3091 if (ev.xselection.selection != mXdndSelection || !mDragSource)
3093 bool accepted =
false;
3094 const Window dragSource = mDragSource;
3095 const Window targetWindow = mPlugWnd;
3096 if (ev.xselection.property == mDropProperty)
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)
3104 const auto paths = ParseDroppedFiles(data, count);
3110 if (paths.size() == 1)
3111 OnDrop(paths[0].c_str(), mDropX, mDropY);
3114 std::vector<const char*> pointers;
3115 for (
const auto& path : paths)
3116 pointers.push_back(path.c_str());
3117 OnDropMultiple(pointers, mDropX, mDropY);
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)
3135 XSendEvent(mDisplay, dragSource, 0, NoEventMask, &reply);
3148bool IGraphicsLinux::StartTimer()
3150 if (mHostDriven || mTimerRunning)
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)
3157 fprintf(stderr,
"Could not start Linux graphics main-loop timer\n");
3160 mTimerRunning =
true;
3164 fprintf(stderr,
"The Linux editor needs a host-driven display timer\n");
3169void IGraphicsLinux::StopTimer()
3171 mTimerRunning =
false;
3172 mMainLoopTimer.reset();
3177 if (IsInPlatformCallback())
3179 DispatchScope dispatch(mDispatchDepth);
3180 if (!mDisplay || !mPlugWnd || mCloseRequested)
3183 DispatchX11Events();
3184 if (!mDisplay || !mPlugWnd || mCloseRequested)
3187 if (!TooltipsEnabled() && mTooltipWindow)
3189 if (mTooltipControl >= 0 && !mTooltipWindow && TooltipsEnabled() && HoverMillis() - mTooltipHoverTime >= 700)
3190 ShowTooltip(mTooltipX, mTooltipY);
3192#ifdef IGRAPHICS_ACCESSKIT
3194 static_cast<IGraphicsAccessibilityLinux*
>(mAccessibility.get())->UpdateWindowBounds();
3198 const bool dirty = IsDirty(rects);
3199 if (mNeedsRedraw || dirty)
3204 mNeedsRedraw =
false;
3206 rects.
Add(GetBounds());
3208 ScopedGLContext scopedGLCtx{
this};
3210#if defined(IGRAPHICS_GL2) || defined(IGRAPHICS_GL3)
3211 glXSwapBuffers(mDisplay, mPlugWnd);
3217 #if defined IGRAPHICS_NANOVG
3220 #include "IGraphicsNanoVG.cpp"
3221 #elif defined IGRAPHICS_SKIA
3222 #include "IGraphicsSkia.cpp"
3224 #error "Either NO_IGRAPHICS or a drawing backend (IGRAPHICS_NANOVG, IGRAPHICS_SKIA) must be defined"
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.
const char * GetTooltip() const
An editor delegate base class that uses IGraphics for the UI.
The lowest level base class of an IGraphics context.
virtual ECursor SetMouseCursor(ECursor cursorType=ECursor::ARROW)
Sets the mouse cursor to one of ECursor (implementations should return the result of the base impleme...
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.
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...
Used to manage mouse modifiers i.e.
Used to manage a rectangular area, independent of draw class/platform.
IText is used to manage font and text/text entry style for a piece of text on the UI,...