Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1309 lines
39KB

  1. /*
  2. * Carla Plugin UI
  3. * Copyright (C) 2014-2018 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaJuceUtils.hpp"
  18. #include "CarlaPluginUI.hpp"
  19. #ifdef HAVE_X11
  20. # include <sys/types.h>
  21. # include <X11/Xatom.h>
  22. # include <X11/Xlib.h>
  23. # include <X11/Xutil.h>
  24. # include "CarlaPluginUI_X11Icon.hpp"
  25. #endif
  26. #ifdef CARLA_OS_MAC
  27. # include "CarlaMacUtils.hpp"
  28. # import <Cocoa/Cocoa.h>
  29. #endif
  30. #ifdef CARLA_OS_WIN
  31. # include <ctime>
  32. # include "water/common.hpp"
  33. #endif
  34. #ifndef CARLA_PLUGIN_UI_CLASS_PREFIX
  35. # error CARLA_PLUGIN_UI_CLASS_PREFIX undefined
  36. #endif
  37. // ---------------------------------------------------------------------------------------------------------------------
  38. // X11
  39. #ifdef HAVE_X11
  40. typedef void (*EventProcPtr)(XEvent* ev);
  41. static const uint X11Key_Escape = 9;
  42. static bool gErrorTriggered = false;
  43. static int temporaryErrorHandler(Display*, XErrorEvent*)
  44. {
  45. gErrorTriggered = true;
  46. return 0;
  47. }
  48. class X11PluginUI : public CarlaPluginUI
  49. {
  50. public:
  51. X11PluginUI(Callback* const cb, const uintptr_t parentId, const bool isResizable) noexcept
  52. : CarlaPluginUI(cb, isResizable),
  53. fDisplay(nullptr),
  54. fHostWindow(0),
  55. fChildWindow(0),
  56. fChildWindowConfigured(false),
  57. fIsVisible(false),
  58. fFirstShow(true),
  59. fSetSizeCalledAtLeastOnce(false),
  60. fEventProc(nullptr)
  61. {
  62. fDisplay = XOpenDisplay(nullptr);
  63. CARLA_SAFE_ASSERT_RETURN(fDisplay != nullptr,);
  64. const int screen = DefaultScreen(fDisplay);
  65. XSetWindowAttributes attr;
  66. carla_zeroStruct(attr);
  67. attr.border_pixel = 0;
  68. attr.event_mask = KeyPressMask|KeyReleaseMask;
  69. if (fIsResizable)
  70. attr.event_mask |= StructureNotifyMask;
  71. fHostWindow = XCreateWindow(fDisplay, RootWindow(fDisplay, screen),
  72. 0, 0, 300, 300, 0,
  73. DefaultDepth(fDisplay, screen),
  74. InputOutput,
  75. DefaultVisual(fDisplay, screen),
  76. CWBorderPixel|CWEventMask, &attr);
  77. CARLA_SAFE_ASSERT_RETURN(fHostWindow != 0,);
  78. XGrabKey(fDisplay, X11Key_Escape, AnyModifier, fHostWindow, 1, GrabModeAsync, GrabModeAsync);
  79. Atom wmDelete = XInternAtom(fDisplay, "WM_DELETE_WINDOW", True);
  80. XSetWMProtocols(fDisplay, fHostWindow, &wmDelete, 1);
  81. const pid_t pid = getpid();
  82. const Atom _nwp = XInternAtom(fDisplay, "_NET_WM_PID", False);
  83. XChangeProperty(fDisplay, fHostWindow, _nwp, XA_CARDINAL, 32, PropModeReplace, (const uchar*)&pid, 1);
  84. const Atom _nwi = XInternAtom(fDisplay, "_NET_WM_ICON", False);
  85. XChangeProperty(fDisplay, fHostWindow, _nwi, XA_CARDINAL, 32, PropModeReplace, (const uchar*)sCarlaX11Icon, sCarlaX11IconSize);
  86. const Atom _wt = XInternAtom(fDisplay, "_NET_WM_WINDOW_TYPE", False);
  87. // Setting the window to both dialog and normal will produce a decorated floating dialog
  88. // Order is important: DIALOG needs to come before NORMAL
  89. const Atom _wts[2] = {
  90. XInternAtom(fDisplay, "_NET_WM_WINDOW_TYPE_DIALOG", False),
  91. XInternAtom(fDisplay, "_NET_WM_WINDOW_TYPE_NORMAL", False)
  92. };
  93. XChangeProperty(fDisplay, fHostWindow, _wt, XA_ATOM, 32, PropModeReplace, (const uchar*)&_wts, 2);
  94. if (parentId != 0)
  95. setTransientWinId(parentId);
  96. }
  97. ~X11PluginUI() override
  98. {
  99. CARLA_SAFE_ASSERT(! fIsVisible);
  100. if (fIsVisible)
  101. {
  102. XUnmapWindow(fDisplay, fHostWindow);
  103. fIsVisible = false;
  104. }
  105. if (fHostWindow != 0)
  106. {
  107. XDestroyWindow(fDisplay, fHostWindow);
  108. fHostWindow = 0;
  109. }
  110. if (fDisplay != nullptr)
  111. {
  112. XCloseDisplay(fDisplay);
  113. fDisplay = nullptr;
  114. }
  115. }
  116. void show() override
  117. {
  118. CARLA_SAFE_ASSERT_RETURN(fDisplay != nullptr,);
  119. CARLA_SAFE_ASSERT_RETURN(fHostWindow != 0,);
  120. if (fFirstShow)
  121. {
  122. if (const Window childWindow = getChildWindow())
  123. {
  124. if (! fSetSizeCalledAtLeastOnce)
  125. {
  126. XSizeHints hints;
  127. carla_zeroStruct(hints);
  128. if (XGetNormalHints(fDisplay, childWindow, &hints) && hints.width > 0 && hints.height > 0)
  129. {
  130. setSize(static_cast<uint>(hints.width),
  131. static_cast<uint>(hints.height), false);
  132. }
  133. }
  134. const Atom _xevp = XInternAtom(fDisplay, "_XEventProc", False);
  135. gErrorTriggered = false;
  136. const XErrorHandler oldErrorHandler(XSetErrorHandler(temporaryErrorHandler));
  137. Atom actualType;
  138. int actualFormat;
  139. ulong nitems, bytesAfter;
  140. uchar* data = nullptr;
  141. XGetWindowProperty(fDisplay, childWindow, _xevp, 0, 1, False, AnyPropertyType, &actualType, &actualFormat, &nitems, &bytesAfter, &data);
  142. XSetErrorHandler(oldErrorHandler);
  143. if (nitems == 1 && ! gErrorTriggered)
  144. {
  145. fEventProc = *reinterpret_cast<EventProcPtr*>(data);
  146. XMapRaised(fDisplay, childWindow);
  147. }
  148. }
  149. }
  150. fIsVisible = true;
  151. fFirstShow = false;
  152. XMapRaised(fDisplay, fHostWindow);
  153. XSync(fDisplay, False);
  154. }
  155. void hide() override
  156. {
  157. CARLA_SAFE_ASSERT_RETURN(fDisplay != nullptr,);
  158. CARLA_SAFE_ASSERT_RETURN(fHostWindow != 0,);
  159. fIsVisible = false;
  160. XUnmapWindow(fDisplay, fHostWindow);
  161. XFlush(fDisplay);
  162. }
  163. void idle() override
  164. {
  165. // prevent recursion
  166. if (fIsIdling) return;
  167. fIsIdling = true;
  168. for (XEvent event; XPending(fDisplay) > 0;)
  169. {
  170. XNextEvent(fDisplay, &event);
  171. if (! fIsVisible)
  172. continue;
  173. char* type = nullptr;
  174. switch (event.type)
  175. {
  176. case ConfigureNotify:
  177. CARLA_SAFE_ASSERT_CONTINUE(fCallback != nullptr);
  178. CARLA_SAFE_ASSERT_CONTINUE(event.xconfigure.width > 0);
  179. CARLA_SAFE_ASSERT_CONTINUE(event.xconfigure.height > 0);
  180. {
  181. const uint width = static_cast<uint>(event.xconfigure.width);
  182. const uint height = static_cast<uint>(event.xconfigure.height);
  183. if (fChildWindow != 0)
  184. {
  185. if (! fChildWindowConfigured)
  186. {
  187. gErrorTriggered = false;
  188. const XErrorHandler oldErrorHandler = XSetErrorHandler(temporaryErrorHandler);
  189. XSizeHints sizeHints;
  190. carla_zeroStruct(sizeHints);
  191. if (XGetNormalHints(fDisplay, fChildWindow, &sizeHints) && !gErrorTriggered)
  192. XSetNormalHints(fDisplay, fHostWindow, &sizeHints);
  193. else
  194. fChildWindow = 0;
  195. fChildWindowConfigured = true;
  196. XSetErrorHandler(oldErrorHandler);
  197. }
  198. if (fChildWindow != 0)
  199. XResizeWindow(fDisplay, fChildWindow, width, height);
  200. }
  201. fCallback->handlePluginUIResized(width, height);
  202. }
  203. break;
  204. case ClientMessage:
  205. type = XGetAtomName(fDisplay, event.xclient.message_type);
  206. CARLA_SAFE_ASSERT_CONTINUE(type != nullptr);
  207. if (std::strcmp(type, "WM_PROTOCOLS") == 0)
  208. {
  209. fIsVisible = false;
  210. CARLA_SAFE_ASSERT_CONTINUE(fCallback != nullptr);
  211. fCallback->handlePluginUIClosed();
  212. }
  213. break;
  214. case KeyRelease:
  215. if (event.xkey.keycode == X11Key_Escape)
  216. {
  217. fIsVisible = false;
  218. CARLA_SAFE_ASSERT_CONTINUE(fCallback != nullptr);
  219. fCallback->handlePluginUIClosed();
  220. }
  221. break;
  222. }
  223. if (type != nullptr)
  224. XFree(type);
  225. else if (fEventProc != nullptr)
  226. fEventProc(&event);
  227. }
  228. fIsIdling = false;
  229. }
  230. void focus() override
  231. {
  232. CARLA_SAFE_ASSERT_RETURN(fDisplay != nullptr,);
  233. CARLA_SAFE_ASSERT_RETURN(fHostWindow != 0,);
  234. XWindowAttributes wa;
  235. carla_zeroStruct(wa);
  236. CARLA_SAFE_ASSERT_RETURN(XGetWindowAttributes(fDisplay, fHostWindow, &wa),);
  237. if (wa.map_state == IsViewable)
  238. {
  239. XRaiseWindow(fDisplay, fHostWindow);
  240. XSetInputFocus(fDisplay, fHostWindow, RevertToPointerRoot, CurrentTime);
  241. XSync(fDisplay, False);
  242. }
  243. }
  244. void setSize(const uint width, const uint height, const bool forceUpdate) override
  245. {
  246. CARLA_SAFE_ASSERT_RETURN(fDisplay != nullptr,);
  247. CARLA_SAFE_ASSERT_RETURN(fHostWindow != 0,);
  248. fSetSizeCalledAtLeastOnce = true;
  249. XResizeWindow(fDisplay, fHostWindow, width, height);
  250. if (fChildWindow != 0)
  251. XResizeWindow(fDisplay, fChildWindow, width, height);
  252. if (! fIsResizable)
  253. {
  254. XSizeHints sizeHints;
  255. carla_zeroStruct(sizeHints);
  256. sizeHints.flags = PSize|PMinSize|PMaxSize;
  257. sizeHints.width = static_cast<int>(width);
  258. sizeHints.height = static_cast<int>(height);
  259. sizeHints.min_width = static_cast<int>(width);
  260. sizeHints.min_height = static_cast<int>(height);
  261. sizeHints.max_width = static_cast<int>(width);
  262. sizeHints.max_height = static_cast<int>(height);
  263. XSetNormalHints(fDisplay, fHostWindow, &sizeHints);
  264. }
  265. if (forceUpdate)
  266. XSync(fDisplay, False);
  267. }
  268. void setTitle(const char* const title) override
  269. {
  270. CARLA_SAFE_ASSERT_RETURN(fDisplay != nullptr,);
  271. CARLA_SAFE_ASSERT_RETURN(fHostWindow != 0,);
  272. XStoreName(fDisplay, fHostWindow, title);
  273. }
  274. void setTransientWinId(const uintptr_t winId) override
  275. {
  276. CARLA_SAFE_ASSERT_RETURN(fDisplay != nullptr,);
  277. CARLA_SAFE_ASSERT_RETURN(fHostWindow != 0,);
  278. XSetTransientForHint(fDisplay, fHostWindow, static_cast<Window>(winId));
  279. }
  280. void setChildWindow(void* const winId) override
  281. {
  282. CARLA_SAFE_ASSERT_RETURN(winId != nullptr,);
  283. fChildWindow = (Window)winId;
  284. }
  285. void* getPtr() const noexcept override
  286. {
  287. return (void*)fHostWindow;
  288. }
  289. void* getDisplay() const noexcept override
  290. {
  291. return fDisplay;
  292. }
  293. protected:
  294. Window getChildWindow() const
  295. {
  296. CARLA_SAFE_ASSERT_RETURN(fDisplay != nullptr, 0);
  297. CARLA_SAFE_ASSERT_RETURN(fHostWindow != 0, 0);
  298. Window rootWindow, parentWindow, ret = 0;
  299. Window* childWindows = nullptr;
  300. uint numChildren = 0;
  301. XQueryTree(fDisplay, fHostWindow, &rootWindow, &parentWindow, &childWindows, &numChildren);
  302. if (numChildren > 0 && childWindows != nullptr)
  303. {
  304. ret = childWindows[0];
  305. XFree(childWindows);
  306. }
  307. return ret;
  308. }
  309. private:
  310. Display* fDisplay;
  311. Window fHostWindow;
  312. Window fChildWindow;
  313. bool fChildWindowConfigured;
  314. bool fIsVisible;
  315. bool fFirstShow;
  316. bool fSetSizeCalledAtLeastOnce;
  317. EventProcPtr fEventProc;
  318. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(X11PluginUI)
  319. };
  320. #endif // HAVE_X11
  321. // ---------------------------------------------------------------------------------------------------------------------
  322. // MacOS / Cocoa
  323. #ifdef CARLA_OS_MAC
  324. #if defined(BUILD_BRIDGE_ALTERNATIVE_ARCH)
  325. # define CarlaPluginWindow CARLA_JOIN_MACRO(CarlaPluginWindowBridgedArch, CARLA_PLUGIN_UI_CLASS_PREFIX)
  326. #elif defined(BUILD_BRIDGE)
  327. # define CarlaPluginWindow CARLA_JOIN_MACRO(CarlaPluginWindowBridged, CARLA_PLUGIN_UI_CLASS_PREFIX)
  328. #else
  329. # define CarlaPluginWindow CARLA_JOIN_MACRO(CarlaPluginWindow, CARLA_PLUGIN_UI_CLASS_PREFIX)
  330. #endif
  331. @interface CarlaPluginWindow : NSWindow
  332. {
  333. @public
  334. CarlaPluginUI::Callback* callback;
  335. }
  336. - (id) initWithContentRect:(NSRect)contentRect
  337. styleMask:(unsigned int)aStyle
  338. backing:(NSBackingStoreType)bufferingType
  339. defer:(BOOL)flag;
  340. - (void) setCallback:(CarlaPluginUI::Callback*)cb;
  341. - (BOOL) acceptsFirstResponder;
  342. - (BOOL) canBecomeKeyWindow;
  343. - (BOOL) canBecomeMainWindow;
  344. - (BOOL) windowShouldClose:(id)sender;
  345. - (NSSize) windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize;
  346. @end
  347. @implementation CarlaPluginWindow
  348. - (id)initWithContentRect:(NSRect)contentRect
  349. styleMask:(unsigned int)aStyle
  350. backing:(NSBackingStoreType)bufferingType
  351. defer:(BOOL)flag
  352. {
  353. callback = nil;
  354. NSWindow* result = [super initWithContentRect:contentRect
  355. styleMask:aStyle
  356. backing:bufferingType
  357. defer:flag];
  358. [result setAcceptsMouseMovedEvents:YES];
  359. return (CarlaPluginWindow*)result;
  360. // unused
  361. (void)flag;
  362. }
  363. - (void)setCallback:(CarlaPluginUI::Callback*)cb
  364. {
  365. callback = cb;
  366. }
  367. - (BOOL)acceptsFirstResponder
  368. {
  369. return YES;
  370. }
  371. - (BOOL)canBecomeKeyWindow
  372. {
  373. return YES;
  374. }
  375. - (BOOL)canBecomeMainWindow
  376. {
  377. return NO;
  378. }
  379. - (BOOL)windowShouldClose:(id)sender
  380. {
  381. if (callback != nil)
  382. callback->handlePluginUIClosed();
  383. return NO;
  384. // unused
  385. (void)sender;
  386. }
  387. - (NSSize) windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize
  388. {
  389. if (callback != nil)
  390. callback->handlePluginUIResized(frameSize.width, frameSize.height);
  391. return frameSize;
  392. // unused
  393. (void)sender;
  394. }
  395. @end
  396. class CocoaPluginUI : public CarlaPluginUI
  397. {
  398. public:
  399. CocoaPluginUI(Callback* const cb, const uintptr_t parentId, const bool isResizable) noexcept
  400. : CarlaPluginUI(cb, isResizable),
  401. fView(nullptr),
  402. fParentWindow(nullptr),
  403. fWindow(nullptr)
  404. {
  405. carla_debug("CocoaPluginUI::CocoaPluginUI(%p, " P_UINTPTR, "%s)", cb, parentId, bool2str(isResizable));
  406. const CarlaBackend::AutoNSAutoreleasePool arp;
  407. [NSApplication sharedApplication];
  408. fView = [[NSView new]retain];
  409. CARLA_SAFE_ASSERT_RETURN(fView != nullptr,)
  410. uint style = NSClosableWindowMask | NSTitledWindowMask;
  411. /*
  412. if (isResizable)
  413. style |= NSResizableWindowMask;
  414. */
  415. NSRect frame = NSMakeRect(0, 0, 100, 100);
  416. fWindow = [[[CarlaPluginWindow alloc]
  417. initWithContentRect:frame
  418. styleMask:style
  419. backing:NSBackingStoreBuffered
  420. defer:NO
  421. ] retain];
  422. if (fWindow == nullptr)
  423. {
  424. [fView release];
  425. fView = nullptr;
  426. return;
  427. }
  428. //if (! isResizable)
  429. {
  430. [fView setAutoresizingMask:NSViewNotSizable];
  431. [[fWindow standardWindowButton:NSWindowZoomButton] setHidden:YES];
  432. }
  433. [fWindow setCallback:cb];
  434. [fWindow setContentView:fView];
  435. [fWindow makeFirstResponder:fView];
  436. [fView setHidden:NO];
  437. if (parentId != 0)
  438. setTransientWinId(parentId);
  439. }
  440. ~CocoaPluginUI() override
  441. {
  442. carla_debug("CocoaPluginUI::~CocoaPluginUI()");
  443. if (fView == nullptr)
  444. return;
  445. [fView setHidden:YES];
  446. [fView removeFromSuperview];
  447. [fWindow close];
  448. [fView release];
  449. [fWindow release];
  450. }
  451. void show() override
  452. {
  453. carla_debug("CocoaPluginUI::show()");
  454. CARLA_SAFE_ASSERT_RETURN(fView != nullptr,);
  455. if (fParentWindow != nullptr)
  456. {
  457. [fParentWindow addChildWindow:fWindow
  458. ordered:NSWindowAbove];
  459. }
  460. else
  461. {
  462. [fWindow setIsVisible:YES];
  463. }
  464. }
  465. void hide() override
  466. {
  467. carla_debug("CocoaPluginUI::hide()");
  468. CARLA_SAFE_ASSERT_RETURN(fView != nullptr,);
  469. [fWindow setIsVisible:NO];
  470. if (fParentWindow != nullptr)
  471. [fParentWindow removeChildWindow:fWindow];
  472. }
  473. void idle() override
  474. {
  475. // carla_debug("CocoaPluginUI::idle()");
  476. }
  477. void focus() override
  478. {
  479. carla_debug("CocoaPluginUI::focus()");
  480. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  481. [fWindow makeKeyAndOrderFront:fWindow];
  482. [NSApp activateIgnoringOtherApps:YES];
  483. }
  484. void setSize(const uint width, const uint height, const bool forceUpdate) override
  485. {
  486. carla_debug("CocoaPluginUI::setSize(%u, %u, %s)", width, height, bool2str(forceUpdate));
  487. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  488. CARLA_SAFE_ASSERT_RETURN(fView != nullptr,);
  489. [fView setFrame:NSMakeRect(0, 0, width, height)];
  490. for (NSView* subview in [fView subviews])
  491. {
  492. [subview setFrame:NSMakeRect(0, 0, width, height)];
  493. break;
  494. }
  495. const NSSize size = NSMakeSize(width, height);
  496. [fWindow setContentSize:size];
  497. /*
  498. if (fIsResizable)
  499. {
  500. [fWindow setContentMinSize:NSMakeSize(1, 1)];
  501. [fWindow setContentMaxSize:NSMakeSize(99999, 99999)];
  502. }
  503. else
  504. {
  505. [fWindow setContentMinSize:size];
  506. [fWindow setContentMaxSize:size];
  507. }
  508. */
  509. if (forceUpdate)
  510. {
  511. // FIXME, not enough
  512. [fView setNeedsDisplay:YES];
  513. }
  514. }
  515. void setTitle(const char* const title) override
  516. {
  517. carla_debug("CocoaPluginUI::setTitle(\"%s\")", title);
  518. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  519. NSString* titleString = [[NSString alloc]
  520. initWithBytes:title
  521. length:strlen(title)
  522. encoding:NSUTF8StringEncoding];
  523. [fWindow setTitle:titleString];
  524. }
  525. void setTransientWinId(const uintptr_t winId) override
  526. {
  527. carla_debug("CocoaPluginUI::setTransientWinId(" P_UINTPTR ")", winId);
  528. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  529. NSWindow* const parentWindow = [NSApp windowWithWindowNumber:winId];
  530. CARLA_SAFE_ASSERT_RETURN(parentWindow != nullptr,);
  531. fParentWindow = parentWindow;
  532. if ([fWindow isVisible])
  533. [fParentWindow addChildWindow:fWindow
  534. ordered:NSWindowAbove];
  535. }
  536. void setChildWindow(void* const window) override
  537. {
  538. carla_debug("CocoaPluginUI::setChildWindow(%p)", window);
  539. CARLA_SAFE_ASSERT_RETURN(window != nullptr,);
  540. }
  541. void* getPtr() const noexcept override
  542. {
  543. carla_debug("CocoaPluginUI::getPtr()");
  544. return (void*)fView;
  545. }
  546. void* getDisplay() const noexcept
  547. {
  548. carla_debug("CocoaPluginUI::getDisplay()");
  549. return (void*)fWindow;
  550. }
  551. private:
  552. NSView* fView;
  553. NSWindow* fParentWindow;
  554. CarlaPluginWindow* fWindow;
  555. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CocoaPluginUI)
  556. };
  557. #endif // CARLA_OS_MAC
  558. // ---------------------------------------------------------------------------------------------------------------------
  559. // Windows
  560. #ifdef CARLA_OS_WIN
  561. #define PUGL_LOCAL_CLOSE_MSG (WM_USER + 50)
  562. static LRESULT CALLBACK wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
  563. class WindowsPluginUI : public CarlaPluginUI
  564. {
  565. public:
  566. WindowsPluginUI(Callback* const cb, const uintptr_t parentId, const bool isResizable) noexcept
  567. : CarlaPluginUI(cb, isResizable),
  568. fWindow(nullptr),
  569. fChildWindow(nullptr),
  570. fParentWindow(nullptr),
  571. fIsVisible(false),
  572. fFirstShow(true)
  573. {
  574. // FIXME
  575. static int wc_count = 0;
  576. char classNameBuf[32];
  577. std::srand((std::time(nullptr)));
  578. std::snprintf(classNameBuf, 32, "CarlaWin-%d-%d", ++wc_count, std::rand());
  579. classNameBuf[31] = '\0';
  580. const HINSTANCE hInstance = water::getCurrentModuleInstanceHandle();
  581. carla_zeroStruct(fWindowClass);
  582. fWindowClass.style = CS_OWNDC;
  583. fWindowClass.lpfnWndProc = wndProc;
  584. fWindowClass.hInstance = hInstance;
  585. fWindowClass.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
  586. fWindowClass.hCursor = LoadCursor(hInstance, IDC_ARROW);
  587. fWindowClass.lpszClassName = strdup(classNameBuf);
  588. if (!RegisterClass(&fWindowClass)) {
  589. free((void*)fWindowClass.lpszClassName);
  590. return;
  591. }
  592. int winFlags = WS_POPUPWINDOW | WS_CAPTION;
  593. if (isResizable)
  594. {
  595. // not supported right now
  596. // winFlags |= WS_SIZEBOX;
  597. }
  598. fWindow = CreateWindowEx(WS_EX_TOPMOST,
  599. classNameBuf, "Carla Plugin UI", winFlags,
  600. CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
  601. nullptr, nullptr, hInstance, nullptr);
  602. if (fWindow == nullptr) {
  603. const DWORD errorCode = ::GetLastError();
  604. carla_stderr2("CreateWindowEx failed with error code 0x%x, class name was '%s'",
  605. errorCode, fWindowClass.lpszClassName);
  606. UnregisterClass(fWindowClass.lpszClassName, nullptr);
  607. free((void*)fWindowClass.lpszClassName);
  608. return;
  609. }
  610. SetWindowLongPtr(fWindow, GWLP_USERDATA, (LONG_PTR)this);
  611. if (parentId != 0)
  612. setTransientWinId(parentId);
  613. }
  614. ~WindowsPluginUI() override
  615. {
  616. CARLA_SAFE_ASSERT(! fIsVisible);
  617. if (fWindow != 0)
  618. {
  619. if (fIsVisible)
  620. ShowWindow(fWindow, SW_HIDE);
  621. DestroyWindow(fWindow);
  622. fWindow = 0;
  623. }
  624. // FIXME
  625. UnregisterClass(fWindowClass.lpszClassName, nullptr);
  626. free((void*)fWindowClass.lpszClassName);
  627. }
  628. void show() override
  629. {
  630. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  631. if (fFirstShow)
  632. {
  633. fFirstShow = false;
  634. RECT rectChild, rectParent;
  635. if (fParentWindow != nullptr &&
  636. GetWindowRect(fWindow, &rectChild) &&
  637. GetWindowRect(fParentWindow, &rectParent))
  638. {
  639. SetWindowPos(fWindow, fParentWindow,
  640. rectParent.left + (rectChild.right-rectChild.left)/2,
  641. rectParent.top + (rectChild.bottom-rectChild.top)/2,
  642. 0, 0, SWP_SHOWWINDOW|SWP_NOSIZE);
  643. }
  644. else
  645. {
  646. ShowWindow(fWindow, SW_SHOWNORMAL);
  647. }
  648. }
  649. else
  650. {
  651. ShowWindow(fWindow, SW_RESTORE);
  652. }
  653. fIsVisible = true;
  654. UpdateWindow(fWindow);
  655. }
  656. void hide() override
  657. {
  658. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  659. ShowWindow(fWindow, SW_HIDE);
  660. fIsVisible = false;
  661. UpdateWindow(fWindow);
  662. }
  663. void idle() override
  664. {
  665. if (fIsIdling || fWindow == nullptr)
  666. return;
  667. MSG msg;
  668. fIsIdling = true;
  669. while (::PeekMessage(&msg, fWindow, 0, 0, PM_REMOVE))
  670. {
  671. switch (msg.message)
  672. {
  673. case WM_QUIT:
  674. case PUGL_LOCAL_CLOSE_MSG:
  675. fIsVisible = false;
  676. CARLA_SAFE_ASSERT_BREAK(fCallback != nullptr);
  677. fCallback->handlePluginUIClosed();
  678. break;
  679. }
  680. DispatchMessageA(&msg);
  681. }
  682. fIsIdling = false;
  683. }
  684. LRESULT checkAndHandleMessage(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  685. {
  686. if (fWindow == hwnd)
  687. {
  688. switch (message)
  689. {
  690. case WM_QUIT:
  691. case PUGL_LOCAL_CLOSE_MSG:
  692. fIsVisible = false;
  693. CARLA_SAFE_ASSERT_BREAK(fCallback != nullptr);
  694. fCallback->handlePluginUIClosed();
  695. break;
  696. }
  697. }
  698. return DefWindowProcA(hwnd, message, wParam, lParam);
  699. }
  700. void focus() override
  701. {
  702. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  703. SetForegroundWindow(fWindow);
  704. SetActiveWindow(fWindow);
  705. SetFocus(fWindow);
  706. }
  707. void setSize(const uint width, const uint height, const bool forceUpdate) override
  708. {
  709. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  710. const int winFlags = WS_POPUPWINDOW | WS_CAPTION | (fIsResizable ? WS_SIZEBOX : 0x0);
  711. RECT wr = { 0, 0, static_cast<long>(width), static_cast<long>(height) };
  712. AdjustWindowRectEx(&wr, winFlags, FALSE, WS_EX_TOPMOST);
  713. SetWindowPos(fWindow, 0, 0, 0, wr.right-wr.left, wr.bottom-wr.top,
  714. SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOOWNERZORDER|SWP_NOZORDER);
  715. if (forceUpdate)
  716. UpdateWindow(fWindow);
  717. }
  718. void setTitle(const char* const title) override
  719. {
  720. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  721. SetWindowTextA(fWindow, title);
  722. }
  723. void setTransientWinId(const uintptr_t winId) override
  724. {
  725. CARLA_SAFE_ASSERT_RETURN(fWindow != nullptr,);
  726. fParentWindow = (HWND)winId;
  727. SetWindowLongPtr(fWindow, GWLP_HWNDPARENT, (LONG_PTR)winId);
  728. }
  729. void setChildWindow(void* const winId) override
  730. {
  731. CARLA_SAFE_ASSERT_RETURN(winId != nullptr,);
  732. fChildWindow = (HWND)fChildWindow;
  733. }
  734. void* getPtr() const noexcept override
  735. {
  736. return (void*)fWindow;
  737. }
  738. void* getDisplay() const noexcept
  739. {
  740. return nullptr;
  741. }
  742. private:
  743. HWND fWindow;
  744. HWND fChildWindow;
  745. HWND fParentWindow;
  746. WNDCLASS fWindowClass;
  747. bool fIsVisible;
  748. bool fFirstShow;
  749. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(WindowsPluginUI)
  750. };
  751. LRESULT CALLBACK wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  752. {
  753. switch (message)
  754. {
  755. case WM_CLOSE:
  756. PostMessage(hwnd, PUGL_LOCAL_CLOSE_MSG, wParam, lParam);
  757. return 0;
  758. #if 0
  759. case WM_CREATE:
  760. PostMessage(hwnd, WM_SHOWWINDOW, TRUE, 0);
  761. return 0;
  762. case WM_DESTROY:
  763. return 0;
  764. #endif
  765. default:
  766. if (WindowsPluginUI* const ui = (WindowsPluginUI*)GetWindowLongPtr(hwnd, GWLP_USERDATA))
  767. return ui->checkAndHandleMessage(hwnd, message, wParam, lParam);
  768. return DefWindowProcA(hwnd, message, wParam, lParam);
  769. }
  770. }
  771. #endif // CARLA_OS_WIN
  772. // -----------------------------------------------------
  773. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  774. bool CarlaPluginUI::tryTransientWinIdMatch(const uintptr_t pid, const char* const uiTitle, const uintptr_t winId, const bool centerUI)
  775. {
  776. CARLA_SAFE_ASSERT_RETURN(uiTitle != nullptr && uiTitle[0] != '\0', true);
  777. CARLA_SAFE_ASSERT_RETURN(winId != 0, true);
  778. #if defined(HAVE_X11)
  779. struct ScopedDisplay {
  780. Display* display;
  781. ScopedDisplay() : display(XOpenDisplay(nullptr)) {}
  782. ~ScopedDisplay() { if (display!=nullptr) XCloseDisplay(display); }
  783. // c++ compat stuff
  784. CARLA_PREVENT_HEAP_ALLOCATION
  785. CARLA_DECLARE_NON_COPY_CLASS(ScopedDisplay)
  786. };
  787. struct ScopedFreeData {
  788. union {
  789. char* data;
  790. uchar* udata;
  791. };
  792. ScopedFreeData(char* d) : data(d) {}
  793. ScopedFreeData(uchar* d) : udata(d) {}
  794. ~ScopedFreeData() { XFree(data); }
  795. // c++ compat stuff
  796. CARLA_PREVENT_HEAP_ALLOCATION
  797. CARLA_DECLARE_NON_COPY_CLASS(ScopedFreeData)
  798. };
  799. const ScopedDisplay sd;
  800. CARLA_SAFE_ASSERT_RETURN(sd.display != nullptr, true);
  801. const Window rootWindow(DefaultRootWindow(sd.display));
  802. const Atom _ncl = XInternAtom(sd.display, "_NET_CLIENT_LIST" , False);
  803. const Atom _nwn = XInternAtom(sd.display, "_NET_WM_NAME", False);
  804. const Atom _nwp = XInternAtom(sd.display, "_NET_WM_PID", False);
  805. const Atom utf8 = XInternAtom(sd.display, "UTF8_STRING", True);
  806. Atom actualType;
  807. int actualFormat;
  808. ulong numWindows, bytesAfter;
  809. uchar* data = nullptr;
  810. int status = XGetWindowProperty(sd.display, rootWindow, _ncl, 0L, (~0L), False, AnyPropertyType, &actualType, &actualFormat, &numWindows, &bytesAfter, &data);
  811. CARLA_SAFE_ASSERT_RETURN(data != nullptr, true);
  812. const ScopedFreeData sfd(data);
  813. CARLA_SAFE_ASSERT_RETURN(status == Success, true);
  814. CARLA_SAFE_ASSERT_RETURN(actualFormat == 32, true);
  815. CARLA_SAFE_ASSERT_RETURN(numWindows != 0, true);
  816. Window* windows = (Window*)data;
  817. Window lastGoodWindowPID = 0, lastGoodWindowNameSimple = 0, lastGoodWindowNameUTF8 = 0;
  818. for (ulong i = 0; i < numWindows; i++)
  819. {
  820. const Window window(windows[i]);
  821. CARLA_SAFE_ASSERT_CONTINUE(window != 0);
  822. // ------------------------------------------------
  823. // try using pid
  824. if (pid != 0)
  825. {
  826. ulong pidSize;
  827. uchar* pidData = nullptr;
  828. status = XGetWindowProperty(sd.display, window, _nwp, 0L, (~0L), False, XA_CARDINAL, &actualType, &actualFormat, &pidSize, &bytesAfter, &pidData);
  829. if (pidData != nullptr)
  830. {
  831. const ScopedFreeData sfd2(pidData);
  832. CARLA_SAFE_ASSERT_CONTINUE(status == Success);
  833. CARLA_SAFE_ASSERT_CONTINUE(pidSize != 0);
  834. if (*(ulong*)pidData == static_cast<ulong>(pid))
  835. lastGoodWindowPID = window;
  836. }
  837. }
  838. // ------------------------------------------------
  839. // try using name (UTF-8)
  840. ulong nameSize;
  841. uchar* nameData = nullptr;
  842. status = XGetWindowProperty(sd.display, window, _nwn, 0L, (~0L), False, utf8, &actualType, &actualFormat, &nameSize, &bytesAfter, &nameData);
  843. if (nameData != nullptr)
  844. {
  845. const ScopedFreeData sfd2(nameData);
  846. CARLA_SAFE_ASSERT_CONTINUE(status == Success);
  847. if (nameSize != 0 && std::strstr((const char*)nameData, uiTitle) != nullptr)
  848. lastGoodWindowNameUTF8 = window;
  849. }
  850. // ------------------------------------------------
  851. // try using name (simple)
  852. char* wmName = nullptr;
  853. status = XFetchName(sd.display, window, &wmName);
  854. if (wmName != nullptr)
  855. {
  856. const ScopedFreeData sfd2(wmName);
  857. CARLA_SAFE_ASSERT_CONTINUE(status != 0);
  858. if (std::strstr(wmName, uiTitle) != nullptr)
  859. lastGoodWindowNameSimple = window;
  860. }
  861. }
  862. if (lastGoodWindowPID == 0 && lastGoodWindowNameSimple == 0 && lastGoodWindowNameUTF8 == 0)
  863. return false;
  864. Window windowToMap;
  865. if (lastGoodWindowPID != 0)
  866. {
  867. if (lastGoodWindowPID == lastGoodWindowNameSimple && lastGoodWindowPID == lastGoodWindowNameUTF8)
  868. {
  869. carla_stdout("Match found using pid, simple and UTF-8 name all at once, nice!");
  870. windowToMap = lastGoodWindowPID;
  871. }
  872. else if (lastGoodWindowPID == lastGoodWindowNameUTF8)
  873. {
  874. carla_stdout("Match found using pid and UTF-8 name");
  875. windowToMap = lastGoodWindowPID;
  876. }
  877. else if (lastGoodWindowPID == lastGoodWindowNameSimple)
  878. {
  879. carla_stdout("Match found using pid and simple name");
  880. windowToMap = lastGoodWindowPID;
  881. }
  882. else if (lastGoodWindowNameUTF8 != 0)
  883. {
  884. if (lastGoodWindowNameUTF8 == lastGoodWindowNameSimple)
  885. {
  886. carla_stdout("Match found using simple and UTF-8 name (ignoring pid)");
  887. windowToMap = lastGoodWindowNameUTF8;
  888. }
  889. else
  890. {
  891. carla_stdout("Match found using UTF-8 name (ignoring pid)");
  892. windowToMap = lastGoodWindowNameUTF8;
  893. }
  894. }
  895. else
  896. {
  897. carla_stdout("Match found using pid");
  898. windowToMap = lastGoodWindowPID;
  899. }
  900. }
  901. else if (lastGoodWindowNameUTF8 != 0)
  902. {
  903. if (lastGoodWindowNameUTF8 == lastGoodWindowNameSimple)
  904. {
  905. carla_stdout("Match found using simple and UTF-8 name");
  906. windowToMap = lastGoodWindowNameUTF8;
  907. }
  908. else
  909. {
  910. carla_stdout("Match found using UTF-8 name");
  911. windowToMap = lastGoodWindowNameUTF8;
  912. }
  913. }
  914. else
  915. {
  916. carla_stdout("Match found using simple name");
  917. windowToMap = lastGoodWindowNameSimple;
  918. }
  919. const Atom _nwt = XInternAtom(sd.display ,"_NET_WM_STATE", False);
  920. const Atom _nws[2] = {
  921. XInternAtom(sd.display, "_NET_WM_STATE_SKIP_TASKBAR", False),
  922. XInternAtom(sd.display, "_NET_WM_STATE_SKIP_PAGER", False)
  923. };
  924. XChangeProperty(sd.display, windowToMap, _nwt, XA_ATOM, 32, PropModeAppend, (const uchar*)_nws, 2);
  925. const Atom _nwi = XInternAtom(sd.display, "_NET_WM_ICON", False);
  926. XChangeProperty(sd.display, windowToMap, _nwi, XA_CARDINAL, 32, PropModeReplace, (const uchar*)sCarlaX11Icon, sCarlaX11IconSize);
  927. const Window hostWinId((Window)winId);
  928. XSetTransientForHint(sd.display, windowToMap, hostWinId);
  929. if (centerUI && false /* moving the window after being shown isn't pretty... */)
  930. {
  931. int hostX, hostY, pluginX, pluginY;
  932. uint hostWidth, hostHeight, pluginWidth, pluginHeight, border, depth;
  933. Window retWindow;
  934. if (XGetGeometry(sd.display, hostWinId, &retWindow, &hostX, &hostY, &hostWidth, &hostHeight, &border, &depth) != 0 &&
  935. XGetGeometry(sd.display, windowToMap, &retWindow, &pluginX, &pluginY, &pluginWidth, &pluginHeight, &border, &depth) != 0)
  936. {
  937. if (XTranslateCoordinates(sd.display, hostWinId, rootWindow, hostX, hostY, &hostX, &hostY, &retWindow) == True &&
  938. XTranslateCoordinates(sd.display, windowToMap, rootWindow, pluginX, pluginY, &pluginX, &pluginY, &retWindow) == True)
  939. {
  940. const int newX = hostX + int(hostWidth/2 - pluginWidth/2);
  941. const int newY = hostY + int(hostHeight/2 - pluginHeight/2);
  942. XMoveWindow(sd.display, windowToMap, newX, newY);
  943. }
  944. }
  945. }
  946. // focusing the host UI and then the plugin UI forces the WM to repaint the plugin window icon
  947. XRaiseWindow(sd.display, hostWinId);
  948. XSetInputFocus(sd.display, hostWinId, RevertToPointerRoot, CurrentTime);
  949. XRaiseWindow(sd.display, windowToMap);
  950. XSetInputFocus(sd.display, windowToMap, RevertToPointerRoot, CurrentTime);
  951. XFlush(sd.display);
  952. return true;
  953. #endif
  954. #ifdef CARLA_OS_MAC
  955. uint const hints = kCGWindowListOptionOnScreenOnly|kCGWindowListExcludeDesktopElements;
  956. CFArrayRef const windowListRef = CGWindowListCopyWindowInfo(hints, kCGNullWindowID);
  957. const NSArray* const windowList = (const NSArray*)windowListRef;
  958. int windowToMap, windowWithPID = 0, windowWithNameAndPID = 0;
  959. const NSDictionary* entry;
  960. for (entry in windowList)
  961. {
  962. // FIXME: is this needed? is old version safe?
  963. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  964. if ([entry[(id)kCGWindowSharingState] intValue] == kCGWindowSharingNone)
  965. continue;
  966. NSString* const windowName = entry[(id)kCGWindowName];
  967. int const windowNumber = [entry[(id)kCGWindowNumber] intValue];
  968. uintptr_t const windowPID = [entry[(id)kCGWindowOwnerPID] intValue];
  969. #else
  970. if ([[entry objectForKey:(id)kCGWindowSharingState] intValue] == kCGWindowSharingNone)
  971. continue;
  972. NSString* const windowName = [entry objectForKey:(id)kCGWindowName];
  973. int const windowNumber = [[entry objectForKey:(id)kCGWindowNumber] intValue];
  974. uintptr_t const windowPID = [[entry objectForKey:(id)kCGWindowOwnerPID] intValue];
  975. #endif
  976. if (windowPID != pid)
  977. continue;
  978. windowWithPID = windowNumber;
  979. if (windowName != nullptr && std::strcmp([windowName UTF8String], uiTitle) == 0)
  980. windowWithNameAndPID = windowNumber;
  981. }
  982. CFRelease(windowListRef);
  983. if (windowWithNameAndPID != 0)
  984. {
  985. carla_stdout("Match found using pid and name");
  986. windowToMap = windowWithNameAndPID;
  987. }
  988. else if (windowWithPID != 0)
  989. {
  990. carla_stdout("Match found using pid");
  991. windowToMap = windowWithPID;
  992. }
  993. else
  994. {
  995. return false;
  996. }
  997. NSWindow* const parentWindow = [NSApp windowWithWindowNumber:winId];
  998. CARLA_SAFE_ASSERT_RETURN(parentWindow != nullptr, false);
  999. [parentWindow orderWindow:NSWindowBelow
  1000. relativeTo:windowToMap];
  1001. return true;
  1002. #endif
  1003. #ifdef CARLA_OS_WIN
  1004. if (HWND const childWindow = FindWindowA(nullptr, uiTitle))
  1005. {
  1006. HWND const parentWindow = (HWND)winId;
  1007. SetWindowLongPtr(childWindow, GWLP_HWNDPARENT, (LONG_PTR)parentWindow);
  1008. if (centerUI)
  1009. {
  1010. RECT rectChild, rectParent;
  1011. if (GetWindowRect(childWindow, &rectChild) && GetWindowRect(parentWindow, &rectParent))
  1012. {
  1013. SetWindowPos(childWindow, parentWindow,
  1014. rectParent.left + (rectChild.right-rectChild.left)/2,
  1015. rectParent.top + (rectChild.bottom-rectChild.top)/2,
  1016. 0, 0, SWP_NOSIZE);
  1017. }
  1018. }
  1019. carla_stdout("Match found using window name");
  1020. return true;
  1021. }
  1022. return false;
  1023. #endif
  1024. // fallback, may be unused
  1025. return true;
  1026. (void)pid; (void)centerUI;
  1027. }
  1028. #endif // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1029. // -----------------------------------------------------
  1030. #ifdef HAVE_X11
  1031. CarlaPluginUI* CarlaPluginUI::newX11(Callback* cb, uintptr_t parentId, bool isResizable)
  1032. {
  1033. return new X11PluginUI(cb, parentId, isResizable);
  1034. }
  1035. #endif
  1036. #ifdef CARLA_OS_MAC
  1037. CarlaPluginUI* CarlaPluginUI::newCocoa(Callback* cb, uintptr_t parentId, bool isResizable)
  1038. {
  1039. return new CocoaPluginUI(cb, parentId, isResizable);
  1040. }
  1041. #endif
  1042. #ifdef CARLA_OS_WIN
  1043. CarlaPluginUI* CarlaPluginUI::newWindows(Callback* cb, uintptr_t parentId, bool isResizable)
  1044. {
  1045. return new WindowsPluginUI(cb, parentId, isResizable);
  1046. }
  1047. #endif
  1048. // -----------------------------------------------------