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.

1253 lines
37KB

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