The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

4937 lines
175KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  19. #include <juce_audio_plugin_client/AAX/juce_AAX_Modifier_Injector.h>
  20. #endif
  21. #if JUCE_MODULE_AVAILABLE_juce_gui_extra
  22. #include <juce_gui_extra/embedding/juce_ScopedDPIAwarenessDisabler.h>
  23. #endif
  24. namespace juce
  25. {
  26. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wcast-function-type")
  27. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  28. // these are in the windows SDK, but need to be repeated here for GCC..
  29. #ifndef GET_APPCOMMAND_LPARAM
  30. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  31. #define FAPPCOMMAND_MASK 0xF000
  32. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  33. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  34. #define APPCOMMAND_MEDIA_STOP 13
  35. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  36. #endif
  37. #ifndef WM_APPCOMMAND
  38. #define WM_APPCOMMAND 0x0319
  39. #endif
  40. void juce_repeatLastProcessPriority();
  41. bool juce_isRunningInWine();
  42. using CheckEventBlockedByModalComps = bool (*) (const MSG&);
  43. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  44. static bool shouldDeactivateTitleBar = true;
  45. void* getUser32Function (const char*);
  46. namespace WindowsAccessibility
  47. {
  48. void initialiseUIAWrapper();
  49. long getUiaRootObjectId();
  50. bool handleWmGetObject (AccessibilityHandler*, WPARAM, LPARAM, LRESULT*);
  51. void revokeUIAMapEntriesForWindow (HWND);
  52. }
  53. #if JUCE_DEBUG
  54. int numActiveScopedDpiAwarenessDisablers = 0;
  55. bool isInScopedDPIAwarenessDisabler() { return numActiveScopedDpiAwarenessDisablers > 0; }
  56. extern HWND juce_messageWindowHandle;
  57. #endif
  58. struct ScopedDeviceContext
  59. {
  60. explicit ScopedDeviceContext (HWND h)
  61. : hwnd (h), dc (GetDC (hwnd))
  62. {
  63. }
  64. ~ScopedDeviceContext()
  65. {
  66. ReleaseDC (hwnd, dc);
  67. }
  68. HWND hwnd;
  69. HDC dc;
  70. JUCE_DECLARE_NON_COPYABLE (ScopedDeviceContext)
  71. JUCE_DECLARE_NON_MOVEABLE (ScopedDeviceContext)
  72. };
  73. //==============================================================================
  74. #ifndef WM_TOUCH
  75. enum
  76. {
  77. WM_TOUCH = 0x0240,
  78. TOUCHEVENTF_MOVE = 0x0001,
  79. TOUCHEVENTF_DOWN = 0x0002,
  80. TOUCHEVENTF_UP = 0x0004
  81. };
  82. typedef HANDLE HTOUCHINPUT;
  83. typedef HANDLE HGESTUREINFO;
  84. struct TOUCHINPUT
  85. {
  86. LONG x;
  87. LONG y;
  88. HANDLE hSource;
  89. DWORD dwID;
  90. DWORD dwFlags;
  91. DWORD dwMask;
  92. DWORD dwTime;
  93. ULONG_PTR dwExtraInfo;
  94. DWORD cxContact;
  95. DWORD cyContact;
  96. };
  97. struct GESTUREINFO
  98. {
  99. UINT cbSize;
  100. DWORD dwFlags;
  101. DWORD dwID;
  102. HWND hwndTarget;
  103. POINTS ptsLocation;
  104. DWORD dwInstanceID;
  105. DWORD dwSequenceID;
  106. ULONGLONG ullArguments;
  107. UINT cbExtraArgs;
  108. };
  109. #endif
  110. #ifndef WM_NCPOINTERUPDATE
  111. enum
  112. {
  113. WM_NCPOINTERUPDATE = 0x241,
  114. WM_NCPOINTERDOWN = 0x242,
  115. WM_NCPOINTERUP = 0x243,
  116. WM_POINTERUPDATE = 0x245,
  117. WM_POINTERDOWN = 0x246,
  118. WM_POINTERUP = 0x247,
  119. WM_POINTERENTER = 0x249,
  120. WM_POINTERLEAVE = 0x24A,
  121. WM_POINTERACTIVATE = 0x24B,
  122. WM_POINTERCAPTURECHANGED = 0x24C,
  123. WM_TOUCHHITTESTING = 0x24D,
  124. WM_POINTERWHEEL = 0x24E,
  125. WM_POINTERHWHEEL = 0x24F,
  126. WM_POINTERHITTEST = 0x250
  127. };
  128. enum
  129. {
  130. PT_TOUCH = 0x00000002,
  131. PT_PEN = 0x00000003
  132. };
  133. enum POINTER_BUTTON_CHANGE_TYPE
  134. {
  135. POINTER_CHANGE_NONE,
  136. POINTER_CHANGE_FIRSTBUTTON_DOWN,
  137. POINTER_CHANGE_FIRSTBUTTON_UP,
  138. POINTER_CHANGE_SECONDBUTTON_DOWN,
  139. POINTER_CHANGE_SECONDBUTTON_UP,
  140. POINTER_CHANGE_THIRDBUTTON_DOWN,
  141. POINTER_CHANGE_THIRDBUTTON_UP,
  142. POINTER_CHANGE_FOURTHBUTTON_DOWN,
  143. POINTER_CHANGE_FOURTHBUTTON_UP,
  144. POINTER_CHANGE_FIFTHBUTTON_DOWN,
  145. POINTER_CHANGE_FIFTHBUTTON_UP
  146. };
  147. enum
  148. {
  149. PEN_MASK_NONE = 0x00000000,
  150. PEN_MASK_PRESSURE = 0x00000001,
  151. PEN_MASK_ROTATION = 0x00000002,
  152. PEN_MASK_TILT_X = 0x00000004,
  153. PEN_MASK_TILT_Y = 0x00000008
  154. };
  155. enum
  156. {
  157. TOUCH_MASK_NONE = 0x00000000,
  158. TOUCH_MASK_CONTACTAREA = 0x00000001,
  159. TOUCH_MASK_ORIENTATION = 0x00000002,
  160. TOUCH_MASK_PRESSURE = 0x00000004
  161. };
  162. enum
  163. {
  164. POINTER_FLAG_NONE = 0x00000000,
  165. POINTER_FLAG_NEW = 0x00000001,
  166. POINTER_FLAG_INRANGE = 0x00000002,
  167. POINTER_FLAG_INCONTACT = 0x00000004,
  168. POINTER_FLAG_FIRSTBUTTON = 0x00000010,
  169. POINTER_FLAG_SECONDBUTTON = 0x00000020,
  170. POINTER_FLAG_THIRDBUTTON = 0x00000040,
  171. POINTER_FLAG_FOURTHBUTTON = 0x00000080,
  172. POINTER_FLAG_FIFTHBUTTON = 0x00000100,
  173. POINTER_FLAG_PRIMARY = 0x00002000,
  174. POINTER_FLAG_CONFIDENCE = 0x00004000,
  175. POINTER_FLAG_CANCELED = 0x00008000,
  176. POINTER_FLAG_DOWN = 0x00010000,
  177. POINTER_FLAG_UPDATE = 0x00020000,
  178. POINTER_FLAG_UP = 0x00040000,
  179. POINTER_FLAG_WHEEL = 0x00080000,
  180. POINTER_FLAG_HWHEEL = 0x00100000,
  181. POINTER_FLAG_CAPTURECHANGED = 0x00200000,
  182. POINTER_FLAG_HASTRANSFORM = 0x00400000
  183. };
  184. typedef DWORD POINTER_INPUT_TYPE;
  185. typedef UINT32 POINTER_FLAGS;
  186. typedef UINT32 PEN_FLAGS;
  187. typedef UINT32 PEN_MASK;
  188. typedef UINT32 TOUCH_FLAGS;
  189. typedef UINT32 TOUCH_MASK;
  190. struct POINTER_INFO
  191. {
  192. POINTER_INPUT_TYPE pointerType;
  193. UINT32 pointerId;
  194. UINT32 frameId;
  195. POINTER_FLAGS pointerFlags;
  196. HANDLE sourceDevice;
  197. HWND hwndTarget;
  198. POINT ptPixelLocation;
  199. POINT ptHimetricLocation;
  200. POINT ptPixelLocationRaw;
  201. POINT ptHimetricLocationRaw;
  202. DWORD dwTime;
  203. UINT32 historyCount;
  204. INT32 InputData;
  205. DWORD dwKeyStates;
  206. UINT64 PerformanceCount;
  207. POINTER_BUTTON_CHANGE_TYPE ButtonChangeType;
  208. };
  209. struct POINTER_TOUCH_INFO
  210. {
  211. POINTER_INFO pointerInfo;
  212. TOUCH_FLAGS touchFlags;
  213. TOUCH_MASK touchMask;
  214. RECT rcContact;
  215. RECT rcContactRaw;
  216. UINT32 orientation;
  217. UINT32 pressure;
  218. };
  219. struct POINTER_PEN_INFO
  220. {
  221. POINTER_INFO pointerInfo;
  222. PEN_FLAGS penFlags;
  223. PEN_MASK penMask;
  224. UINT32 pressure;
  225. UINT32 rotation;
  226. INT32 tiltX;
  227. INT32 tiltY;
  228. };
  229. #define GET_POINTERID_WPARAM(wParam) (LOWORD(wParam))
  230. #endif
  231. #ifndef MONITOR_DPI_TYPE
  232. enum Monitor_DPI_Type
  233. {
  234. MDT_Effective_DPI = 0,
  235. MDT_Angular_DPI = 1,
  236. MDT_Raw_DPI = 2,
  237. MDT_Default = MDT_Effective_DPI
  238. };
  239. #endif
  240. #ifndef DPI_AWARENESS
  241. enum DPI_Awareness
  242. {
  243. DPI_Awareness_Invalid = -1,
  244. DPI_Awareness_Unaware = 0,
  245. DPI_Awareness_System_Aware = 1,
  246. DPI_Awareness_Per_Monitor_Aware = 2
  247. };
  248. #endif
  249. #ifndef USER_DEFAULT_SCREEN_DPI
  250. #define USER_DEFAULT_SCREEN_DPI 96
  251. #endif
  252. #ifndef _DPI_AWARENESS_CONTEXTS_
  253. typedef HANDLE DPI_AWARENESS_CONTEXT;
  254. #define DPI_AWARENESS_CONTEXT_UNAWARE ((DPI_AWARENESS_CONTEXT) - 1)
  255. #define DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ((DPI_AWARENESS_CONTEXT) - 2)
  256. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ((DPI_AWARENESS_CONTEXT) - 3)
  257. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT) - 4)
  258. #endif
  259. // Some versions of the Windows 10 SDK define _DPI_AWARENESS_CONTEXTS_ but not
  260. // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  261. #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  262. #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ((DPI_AWARENESS_CONTEXT) - 4)
  263. #endif
  264. //==============================================================================
  265. using RegisterTouchWindowFunc = BOOL (WINAPI*) (HWND, ULONG);
  266. using GetTouchInputInfoFunc = BOOL (WINAPI*) (HTOUCHINPUT, UINT, TOUCHINPUT*, int);
  267. using CloseTouchInputHandleFunc = BOOL (WINAPI*) (HTOUCHINPUT);
  268. using GetGestureInfoFunc = BOOL (WINAPI*) (HGESTUREINFO, GESTUREINFO*);
  269. static RegisterTouchWindowFunc registerTouchWindow = nullptr;
  270. static GetTouchInputInfoFunc getTouchInputInfo = nullptr;
  271. static CloseTouchInputHandleFunc closeTouchInputHandle = nullptr;
  272. static GetGestureInfoFunc getGestureInfo = nullptr;
  273. static bool hasCheckedForMultiTouch = false;
  274. static bool canUseMultiTouch()
  275. {
  276. if (registerTouchWindow == nullptr && ! hasCheckedForMultiTouch)
  277. {
  278. hasCheckedForMultiTouch = true;
  279. registerTouchWindow = (RegisterTouchWindowFunc) getUser32Function ("RegisterTouchWindow");
  280. getTouchInputInfo = (GetTouchInputInfoFunc) getUser32Function ("GetTouchInputInfo");
  281. closeTouchInputHandle = (CloseTouchInputHandleFunc) getUser32Function ("CloseTouchInputHandle");
  282. getGestureInfo = (GetGestureInfoFunc) getUser32Function ("GetGestureInfo");
  283. }
  284. return registerTouchWindow != nullptr;
  285. }
  286. //==============================================================================
  287. using GetPointerTypeFunc = BOOL (WINAPI*) (UINT32, POINTER_INPUT_TYPE*);
  288. using GetPointerTouchInfoFunc = BOOL (WINAPI*) (UINT32, POINTER_TOUCH_INFO*);
  289. using GetPointerPenInfoFunc = BOOL (WINAPI*) (UINT32, POINTER_PEN_INFO*);
  290. static GetPointerTypeFunc getPointerTypeFunction = nullptr;
  291. static GetPointerTouchInfoFunc getPointerTouchInfo = nullptr;
  292. static GetPointerPenInfoFunc getPointerPenInfo = nullptr;
  293. static bool canUsePointerAPI = false;
  294. static void checkForPointerAPI()
  295. {
  296. getPointerTypeFunction = (GetPointerTypeFunc) getUser32Function ("GetPointerType");
  297. getPointerTouchInfo = (GetPointerTouchInfoFunc) getUser32Function ("GetPointerTouchInfo");
  298. getPointerPenInfo = (GetPointerPenInfoFunc) getUser32Function ("GetPointerPenInfo");
  299. canUsePointerAPI = (getPointerTypeFunction != nullptr
  300. && getPointerTouchInfo != nullptr
  301. && getPointerPenInfo != nullptr);
  302. }
  303. //==============================================================================
  304. using SetProcessDPIAwareFunc = BOOL (WINAPI*) ();
  305. using SetProcessDPIAwarenessContextFunc = BOOL (WINAPI*) (DPI_AWARENESS_CONTEXT);
  306. using SetProcessDPIAwarenessFunc = BOOL (WINAPI*) (DPI_Awareness);
  307. using SetThreadDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) (DPI_AWARENESS_CONTEXT);
  308. using GetDPIForWindowFunc = UINT (WINAPI*) (HWND);
  309. using GetDPIForMonitorFunc = HRESULT (WINAPI*) (HMONITOR, Monitor_DPI_Type, UINT*, UINT*);
  310. using GetProcessDPIAwarenessFunc = HRESULT (WINAPI*) (HANDLE, DPI_Awareness*);
  311. using GetWindowDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) (HWND);
  312. using GetThreadDPIAwarenessContextFunc = DPI_AWARENESS_CONTEXT (WINAPI*) ();
  313. using GetAwarenessFromDpiAwarenessContextFunc = DPI_Awareness (WINAPI*) (DPI_AWARENESS_CONTEXT);
  314. using EnableNonClientDPIScalingFunc = BOOL (WINAPI*) (HWND);
  315. static SetProcessDPIAwareFunc setProcessDPIAware = nullptr;
  316. static SetProcessDPIAwarenessContextFunc setProcessDPIAwarenessContext = nullptr;
  317. static SetProcessDPIAwarenessFunc setProcessDPIAwareness = nullptr;
  318. static SetThreadDPIAwarenessContextFunc setThreadDPIAwarenessContext = nullptr;
  319. static GetDPIForMonitorFunc getDPIForMonitor = nullptr;
  320. static GetDPIForWindowFunc getDPIForWindow = nullptr;
  321. static GetProcessDPIAwarenessFunc getProcessDPIAwareness = nullptr;
  322. static GetWindowDPIAwarenessContextFunc getWindowDPIAwarenessContext = nullptr;
  323. static GetThreadDPIAwarenessContextFunc getThreadDPIAwarenessContext = nullptr;
  324. static GetAwarenessFromDpiAwarenessContextFunc getAwarenessFromDPIAwarenessContext = nullptr;
  325. static EnableNonClientDPIScalingFunc enableNonClientDPIScaling = nullptr;
  326. static bool hasCheckedForDPIAwareness = false;
  327. static void setDPIAwareness()
  328. {
  329. if (hasCheckedForDPIAwareness)
  330. return;
  331. hasCheckedForDPIAwareness = true;
  332. if (! JUCEApplicationBase::isStandaloneApp())
  333. return;
  334. const auto shcore = "SHCore.dll";
  335. LoadLibraryA (shcore);
  336. const auto shcoreModule = GetModuleHandleA (shcore);
  337. if (shcoreModule != nullptr)
  338. {
  339. getDPIForMonitor = (GetDPIForMonitorFunc) GetProcAddress (shcoreModule, "GetDpiForMonitor");
  340. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  341. getDPIForWindow = (GetDPIForWindowFunc) getUser32Function ("GetDpiForWindow");
  342. getProcessDPIAwareness = (GetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "GetProcessDpiAwareness");
  343. getWindowDPIAwarenessContext = (GetWindowDPIAwarenessContextFunc) getUser32Function ("GetWindowDpiAwarenessContext");
  344. setThreadDPIAwarenessContext = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
  345. getThreadDPIAwarenessContext = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
  346. getAwarenessFromDPIAwarenessContext = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
  347. setProcessDPIAwareness = (SetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "SetProcessDpiAwareness");
  348. setProcessDPIAwarenessContext = (SetProcessDPIAwarenessContextFunc) getUser32Function ("SetProcessDpiAwarenessContext");
  349. if (setProcessDPIAwarenessContext != nullptr
  350. && SUCCEEDED (setProcessDPIAwarenessContext (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)))
  351. return;
  352. enableNonClientDPIScaling = (EnableNonClientDPIScalingFunc) getUser32Function ("EnableNonClientDpiScaling");
  353. if (setProcessDPIAwareness != nullptr && enableNonClientDPIScaling != nullptr
  354. && SUCCEEDED (setProcessDPIAwareness (DPI_Awareness::DPI_Awareness_Per_Monitor_Aware)))
  355. return;
  356. #endif
  357. if (setProcessDPIAwareness == nullptr)
  358. setProcessDPIAwareness = (SetProcessDPIAwarenessFunc) GetProcAddress (shcoreModule, "SetProcessDpiAwareness");
  359. if (setProcessDPIAwareness != nullptr && getDPIForMonitor != nullptr
  360. && SUCCEEDED (setProcessDPIAwareness (DPI_Awareness::DPI_Awareness_System_Aware)))
  361. return;
  362. }
  363. // fallback for pre Windows 8.1 - equivalent to Process_System_DPI_Aware
  364. setProcessDPIAware = (SetProcessDPIAwareFunc) getUser32Function ("SetProcessDPIAware");
  365. if (setProcessDPIAware != nullptr)
  366. setProcessDPIAware();
  367. }
  368. static bool isPerMonitorDPIAwareProcess()
  369. {
  370. #if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  371. return false;
  372. #else
  373. static bool dpiAware = []() -> bool
  374. {
  375. setDPIAwareness();
  376. if (getProcessDPIAwareness == nullptr)
  377. return false;
  378. DPI_Awareness context;
  379. getProcessDPIAwareness (nullptr, &context);
  380. return context == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware;
  381. }();
  382. return dpiAware;
  383. #endif
  384. }
  385. static bool isPerMonitorDPIAwareWindow (HWND nativeWindow)
  386. {
  387. #if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  388. ignoreUnused (nativeWindow);
  389. return false;
  390. #else
  391. setDPIAwareness();
  392. if (getWindowDPIAwarenessContext != nullptr
  393. && getAwarenessFromDPIAwarenessContext != nullptr)
  394. {
  395. return (getAwarenessFromDPIAwarenessContext (getWindowDPIAwarenessContext (nativeWindow))
  396. == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
  397. }
  398. return isPerMonitorDPIAwareProcess();
  399. #endif
  400. }
  401. static bool isPerMonitorDPIAwareThread()
  402. {
  403. #if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  404. return false;
  405. #else
  406. setDPIAwareness();
  407. if (getThreadDPIAwarenessContext != nullptr
  408. && getAwarenessFromDPIAwarenessContext != nullptr)
  409. {
  410. return (getAwarenessFromDPIAwarenessContext (getThreadDPIAwarenessContext())
  411. == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
  412. }
  413. return isPerMonitorDPIAwareProcess();
  414. #endif
  415. }
  416. static double getGlobalDPI()
  417. {
  418. setDPIAwareness();
  419. ScopedDeviceContext deviceContext { nullptr };
  420. return (GetDeviceCaps (deviceContext.dc, LOGPIXELSX) + GetDeviceCaps (deviceContext.dc, LOGPIXELSY)) / 2.0;
  421. }
  422. //==============================================================================
  423. class ScopedThreadDPIAwarenessSetter::NativeImpl
  424. {
  425. public:
  426. explicit NativeImpl (HWND nativeWindow)
  427. {
  428. ignoreUnused (nativeWindow);
  429. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  430. if (auto* functionSingleton = FunctionSingleton::getInstance())
  431. {
  432. if (! functionSingleton->isLoaded())
  433. return;
  434. auto dpiAwareWindow = (functionSingleton->getAwarenessFromContext (functionSingleton->getWindowAwareness (nativeWindow))
  435. == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
  436. auto dpiAwareThread = (functionSingleton->getAwarenessFromContext (functionSingleton->getThreadAwareness())
  437. == DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
  438. if (dpiAwareWindow && ! dpiAwareThread)
  439. oldContext = functionSingleton->setThreadAwareness (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
  440. else if (! dpiAwareWindow && dpiAwareThread)
  441. oldContext = functionSingleton->setThreadAwareness (DPI_AWARENESS_CONTEXT_UNAWARE);
  442. }
  443. #endif
  444. }
  445. ~NativeImpl()
  446. {
  447. if (oldContext != nullptr)
  448. if (auto* functionSingleton = FunctionSingleton::getInstance())
  449. functionSingleton->setThreadAwareness (oldContext);
  450. }
  451. private:
  452. struct FunctionSingleton : public DeletedAtShutdown
  453. {
  454. FunctionSingleton() = default;
  455. ~FunctionSingleton() override { clearSingletonInstance(); }
  456. SetThreadDPIAwarenessContextFunc setThreadAwareness = (SetThreadDPIAwarenessContextFunc) getUser32Function ("SetThreadDpiAwarenessContext");
  457. GetWindowDPIAwarenessContextFunc getWindowAwareness = (GetWindowDPIAwarenessContextFunc) getUser32Function ("GetWindowDpiAwarenessContext");
  458. GetThreadDPIAwarenessContextFunc getThreadAwareness = (GetThreadDPIAwarenessContextFunc) getUser32Function ("GetThreadDpiAwarenessContext");
  459. GetAwarenessFromDpiAwarenessContextFunc getAwarenessFromContext = (GetAwarenessFromDpiAwarenessContextFunc) getUser32Function ("GetAwarenessFromDpiAwarenessContext");
  460. bool isLoaded() const noexcept
  461. {
  462. return setThreadAwareness != nullptr
  463. && getWindowAwareness != nullptr
  464. && getThreadAwareness != nullptr
  465. && getAwarenessFromContext != nullptr;
  466. }
  467. JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL (FunctionSingleton)
  468. JUCE_DECLARE_NON_COPYABLE (FunctionSingleton)
  469. JUCE_DECLARE_NON_MOVEABLE (FunctionSingleton)
  470. };
  471. DPI_AWARENESS_CONTEXT oldContext = nullptr;
  472. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeImpl)
  473. JUCE_DECLARE_NON_MOVEABLE (NativeImpl)
  474. };
  475. JUCE_IMPLEMENT_SINGLETON (ScopedThreadDPIAwarenessSetter::NativeImpl::FunctionSingleton)
  476. ScopedThreadDPIAwarenessSetter::ScopedThreadDPIAwarenessSetter (void* nativeWindow)
  477. {
  478. pimpl = std::make_unique<NativeImpl> ((HWND) nativeWindow);
  479. }
  480. ScopedThreadDPIAwarenessSetter::~ScopedThreadDPIAwarenessSetter()
  481. {
  482. }
  483. #if JUCE_MODULE_AVAILABLE_juce_gui_extra
  484. ScopedDPIAwarenessDisabler::ScopedDPIAwarenessDisabler()
  485. {
  486. if (! isPerMonitorDPIAwareThread())
  487. return;
  488. if (setThreadDPIAwarenessContext != nullptr)
  489. {
  490. previousContext = setThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_UNAWARE);
  491. #if JUCE_DEBUG
  492. ++numActiveScopedDpiAwarenessDisablers;
  493. #endif
  494. }
  495. }
  496. ScopedDPIAwarenessDisabler::~ScopedDPIAwarenessDisabler()
  497. {
  498. if (previousContext != nullptr)
  499. {
  500. setThreadDPIAwarenessContext ((DPI_AWARENESS_CONTEXT) previousContext);
  501. #if JUCE_DEBUG
  502. --numActiveScopedDpiAwarenessDisablers;
  503. #endif
  504. }
  505. }
  506. #endif
  507. //==============================================================================
  508. using SettingChangeCallbackFunc = void (*)(void);
  509. extern SettingChangeCallbackFunc settingChangeCallback;
  510. //==============================================================================
  511. static Rectangle<int> rectangleFromRECT (RECT r) noexcept { return { r.left, r.top, r.right - r.left, r.bottom - r.top }; }
  512. static RECT RECTFromRectangle (Rectangle<int> r) noexcept { return { r.getX(), r.getY(), r.getRight(), r.getBottom() }; }
  513. static Point<int> pointFromPOINT (POINT p) noexcept { return { p.x, p.y }; }
  514. static POINT POINTFromPoint (Point<int> p) noexcept { return { p.x, p.y }; }
  515. //==============================================================================
  516. static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd);
  517. template<typename ValueType>
  518. static Rectangle<ValueType> convertPhysicalScreenRectangleToLogical (Rectangle<ValueType> r, HWND h) noexcept
  519. {
  520. if (isPerMonitorDPIAwareWindow (h))
  521. return Desktop::getInstance().getDisplays().physicalToLogical (r, getCurrentDisplayFromScaleFactor (h));
  522. return r;
  523. }
  524. template<typename ValueType>
  525. static Rectangle<ValueType> convertLogicalScreenRectangleToPhysical (Rectangle<ValueType> r, HWND h) noexcept
  526. {
  527. if (isPerMonitorDPIAwareWindow (h))
  528. return Desktop::getInstance().getDisplays().logicalToPhysical (r, getCurrentDisplayFromScaleFactor (h));
  529. return r;
  530. }
  531. static Point<int> convertPhysicalScreenPointToLogical (Point<int> p, HWND h) noexcept
  532. {
  533. if (isPerMonitorDPIAwareWindow (h))
  534. return Desktop::getInstance().getDisplays().physicalToLogical (p, getCurrentDisplayFromScaleFactor (h));
  535. return p;
  536. }
  537. static Point<int> convertLogicalScreenPointToPhysical (Point<int> p, HWND h) noexcept
  538. {
  539. if (isPerMonitorDPIAwareWindow (h))
  540. return Desktop::getInstance().getDisplays().logicalToPhysical (p, getCurrentDisplayFromScaleFactor (h));
  541. return p;
  542. }
  543. JUCE_API double getScaleFactorForWindow (HWND h)
  544. {
  545. // NB. Using a local function here because we need to call this method from the plug-in wrappers
  546. // which don't load the DPI-awareness functions on startup
  547. static GetDPIForWindowFunc localGetDPIForWindow = nullptr;
  548. static bool hasChecked = false;
  549. if (! hasChecked)
  550. {
  551. hasChecked = true;
  552. if (localGetDPIForWindow == nullptr)
  553. localGetDPIForWindow = (GetDPIForWindowFunc) getUser32Function ("GetDpiForWindow");
  554. }
  555. if (localGetDPIForWindow != nullptr)
  556. return (double) localGetDPIForWindow (h) / USER_DEFAULT_SCREEN_DPI;
  557. return 1.0;
  558. }
  559. //==============================================================================
  560. static void setWindowPos (HWND hwnd, Rectangle<int> bounds, UINT flags, bool adjustTopLeft = false)
  561. {
  562. ScopedThreadDPIAwarenessSetter setter { hwnd };
  563. if (isPerMonitorDPIAwareWindow (hwnd))
  564. {
  565. if (adjustTopLeft)
  566. bounds = convertLogicalScreenRectangleToPhysical (bounds, hwnd)
  567. .withPosition (Desktop::getInstance().getDisplays().logicalToPhysical (bounds.getTopLeft()));
  568. else
  569. bounds = convertLogicalScreenRectangleToPhysical (bounds, hwnd);
  570. }
  571. SetWindowPos (hwnd, nullptr, bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), flags);
  572. }
  573. static RECT getWindowScreenRect (HWND hwnd)
  574. {
  575. ScopedThreadDPIAwarenessSetter setter { hwnd };
  576. RECT rect;
  577. GetWindowRect (hwnd, &rect);
  578. return rect;
  579. }
  580. static RECT getWindowClientRect (HWND hwnd)
  581. {
  582. auto rect = getWindowScreenRect (hwnd);
  583. if (auto parentH = GetParent (hwnd))
  584. {
  585. ScopedThreadDPIAwarenessSetter setter { hwnd };
  586. MapWindowPoints (HWND_DESKTOP, parentH, (LPPOINT) &rect, 2);
  587. }
  588. return rect;
  589. }
  590. static void setWindowZOrder (HWND hwnd, HWND insertAfter)
  591. {
  592. SetWindowPos (hwnd, insertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  593. }
  594. //==============================================================================
  595. double Desktop::getDefaultMasterScale()
  596. {
  597. if (! JUCEApplicationBase::isStandaloneApp() || isPerMonitorDPIAwareProcess())
  598. return 1.0;
  599. return getGlobalDPI() / USER_DEFAULT_SCREEN_DPI;
  600. }
  601. bool Desktop::canUseSemiTransparentWindows() noexcept { return true; }
  602. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  603. {
  604. return upright;
  605. }
  606. int64 getMouseEventTime()
  607. {
  608. static int64 eventTimeOffset = 0;
  609. static LONG lastMessageTime = 0;
  610. const LONG thisMessageTime = GetMessageTime();
  611. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  612. {
  613. lastMessageTime = thisMessageTime;
  614. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  615. }
  616. return eventTimeOffset + thisMessageTime;
  617. }
  618. //==============================================================================
  619. const int extendedKeyModifier = 0x10000;
  620. const int KeyPress::spaceKey = VK_SPACE;
  621. const int KeyPress::returnKey = VK_RETURN;
  622. const int KeyPress::escapeKey = VK_ESCAPE;
  623. const int KeyPress::backspaceKey = VK_BACK;
  624. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  625. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  626. const int KeyPress::tabKey = VK_TAB;
  627. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  628. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  629. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  630. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  631. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  632. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  633. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  634. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  635. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  636. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  637. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  638. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  639. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  640. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  641. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  642. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  643. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  644. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  645. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  646. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  647. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  648. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  649. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  650. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  651. const int KeyPress::F17Key = VK_F17 | extendedKeyModifier;
  652. const int KeyPress::F18Key = VK_F18 | extendedKeyModifier;
  653. const int KeyPress::F19Key = VK_F19 | extendedKeyModifier;
  654. const int KeyPress::F20Key = VK_F20 | extendedKeyModifier;
  655. const int KeyPress::F21Key = VK_F21 | extendedKeyModifier;
  656. const int KeyPress::F22Key = VK_F22 | extendedKeyModifier;
  657. const int KeyPress::F23Key = VK_F23 | extendedKeyModifier;
  658. const int KeyPress::F24Key = VK_F24 | extendedKeyModifier;
  659. const int KeyPress::F25Key = 0x31000; // Windows doesn't support F-keys 25 or higher
  660. const int KeyPress::F26Key = 0x31001;
  661. const int KeyPress::F27Key = 0x31002;
  662. const int KeyPress::F28Key = 0x31003;
  663. const int KeyPress::F29Key = 0x31004;
  664. const int KeyPress::F30Key = 0x31005;
  665. const int KeyPress::F31Key = 0x31006;
  666. const int KeyPress::F32Key = 0x31007;
  667. const int KeyPress::F33Key = 0x31008;
  668. const int KeyPress::F34Key = 0x31009;
  669. const int KeyPress::F35Key = 0x3100a;
  670. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  671. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  672. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  673. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  674. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  675. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  676. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  677. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  678. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  679. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  680. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  681. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  682. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  683. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  684. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  685. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  686. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  687. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  688. const int KeyPress::playKey = 0x30000;
  689. const int KeyPress::stopKey = 0x30001;
  690. const int KeyPress::fastForwardKey = 0x30002;
  691. const int KeyPress::rewindKey = 0x30003;
  692. //==============================================================================
  693. class WindowsBitmapImage : public ImagePixelData
  694. {
  695. public:
  696. WindowsBitmapImage (const Image::PixelFormat format,
  697. const int w, const int h, const bool clearImage)
  698. : ImagePixelData (format, w, h)
  699. {
  700. jassert (format == Image::RGB || format == Image::ARGB);
  701. static bool alwaysUse32Bits = isGraphicsCard32Bit(); // NB: for 32-bit cards, it's faster to use a 32-bit image.
  702. pixelStride = (alwaysUse32Bits || format == Image::ARGB) ? 4 : 3;
  703. lineStride = -((w * pixelStride + 3) & ~3);
  704. zerostruct (bitmapInfo);
  705. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  706. bitmapInfo.bV4Width = w;
  707. bitmapInfo.bV4Height = h;
  708. bitmapInfo.bV4Planes = 1;
  709. bitmapInfo.bV4CSType = 1;
  710. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  711. if (format == Image::ARGB)
  712. {
  713. bitmapInfo.bV4AlphaMask = 0xff000000;
  714. bitmapInfo.bV4RedMask = 0xff0000;
  715. bitmapInfo.bV4GreenMask = 0xff00;
  716. bitmapInfo.bV4BlueMask = 0xff;
  717. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  718. }
  719. else
  720. {
  721. bitmapInfo.bV4V4Compression = BI_RGB;
  722. }
  723. {
  724. ScopedDeviceContext deviceContext { nullptr };
  725. hdc = CreateCompatibleDC (deviceContext.dc);
  726. }
  727. SetMapMode (hdc, MM_TEXT);
  728. hBitmap = CreateDIBSection (hdc, (BITMAPINFO*) &(bitmapInfo), DIB_RGB_COLORS,
  729. (void**) &bitmapData, nullptr, 0);
  730. previousBitmap = SelectObject (hdc, hBitmap);
  731. if (format == Image::ARGB && clearImage)
  732. zeromem (bitmapData, (size_t) std::abs (h * lineStride));
  733. imageData = bitmapData - (lineStride * (h - 1));
  734. }
  735. ~WindowsBitmapImage()
  736. {
  737. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  738. DeleteDC (hdc);
  739. DeleteObject (hBitmap);
  740. }
  741. std::unique_ptr<ImageType> createType() const override { return std::make_unique<NativeImageType>(); }
  742. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
  743. {
  744. sendDataChangeMessage();
  745. return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (this));
  746. }
  747. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  748. {
  749. bitmap.data = imageData + x * pixelStride + y * lineStride;
  750. bitmap.pixelFormat = pixelFormat;
  751. bitmap.lineStride = lineStride;
  752. bitmap.pixelStride = pixelStride;
  753. if (mode != Image::BitmapData::readOnly)
  754. sendDataChangeMessage();
  755. }
  756. ImagePixelData::Ptr clone() override
  757. {
  758. auto im = new WindowsBitmapImage (pixelFormat, width, height, false);
  759. for (int i = 0; i < height; ++i)
  760. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, (size_t) lineStride);
  761. return im;
  762. }
  763. void blitToWindow (HWND hwnd, HDC dc, bool transparent, int x, int y, uint8 updateLayeredWindowAlpha) noexcept
  764. {
  765. SetMapMode (dc, MM_TEXT);
  766. if (transparent)
  767. {
  768. auto windowBounds = getWindowScreenRect (hwnd);
  769. POINT p = { -x, -y };
  770. POINT pos = { windowBounds.left, windowBounds.top };
  771. SIZE size = { windowBounds.right - windowBounds.left,
  772. windowBounds.bottom - windowBounds.top };
  773. BLENDFUNCTION bf;
  774. bf.AlphaFormat = 1 /*AC_SRC_ALPHA*/;
  775. bf.BlendFlags = 0;
  776. bf.BlendOp = AC_SRC_OVER;
  777. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  778. UpdateLayeredWindow (hwnd, nullptr, &pos, &size, hdc, &p, 0, &bf, 2 /*ULW_ALPHA*/);
  779. }
  780. else
  781. {
  782. StretchDIBits (dc,
  783. x, y, width, height,
  784. 0, 0, width, height,
  785. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  786. DIB_RGB_COLORS, SRCCOPY);
  787. }
  788. }
  789. HBITMAP hBitmap;
  790. HGDIOBJ previousBitmap;
  791. BITMAPV4HEADER bitmapInfo;
  792. HDC hdc;
  793. uint8* bitmapData;
  794. int pixelStride, lineStride;
  795. uint8* imageData;
  796. private:
  797. static bool isGraphicsCard32Bit()
  798. {
  799. ScopedDeviceContext deviceContext { nullptr };
  800. return GetDeviceCaps (deviceContext.dc, BITSPIXEL) > 24;
  801. }
  802. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage)
  803. };
  804. //==============================================================================
  805. Image createSnapshotOfNativeWindow (void*);
  806. Image createSnapshotOfNativeWindow (void* nativeWindowHandle)
  807. {
  808. auto hwnd = (HWND) nativeWindowHandle;
  809. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)), hwnd);
  810. const auto w = r.getWidth();
  811. const auto h = r.getHeight();
  812. auto nativeBitmap = new WindowsBitmapImage (Image::RGB, w, h, true);
  813. Image bitmap (nativeBitmap);
  814. ScopedDeviceContext deviceContext { hwnd };
  815. if (isPerMonitorDPIAwareProcess())
  816. {
  817. auto scale = getScaleFactorForWindow (hwnd);
  818. auto prevStretchMode = SetStretchBltMode (nativeBitmap->hdc, HALFTONE);
  819. SetBrushOrgEx (nativeBitmap->hdc, 0, 0, NULL);
  820. StretchBlt (nativeBitmap->hdc, 0, 0, w, h,
  821. deviceContext.dc, 0, 0, roundToInt (w * scale), roundToInt (h * scale),
  822. SRCCOPY);
  823. SetStretchBltMode (nativeBitmap->hdc, prevStretchMode);
  824. }
  825. else
  826. {
  827. BitBlt (nativeBitmap->hdc, 0, 0, w, h, deviceContext.dc, 0, 0, SRCCOPY);
  828. }
  829. return SoftwareImageType().convert (bitmap);
  830. }
  831. //==============================================================================
  832. namespace IconConverters
  833. {
  834. Image createImageFromHICON (HICON icon)
  835. {
  836. if (icon == nullptr)
  837. return {};
  838. struct ScopedICONINFO : public ICONINFO
  839. {
  840. ScopedICONINFO()
  841. {
  842. hbmColor = nullptr;
  843. hbmMask = nullptr;
  844. }
  845. ~ScopedICONINFO()
  846. {
  847. if (hbmColor != nullptr)
  848. ::DeleteObject (hbmColor);
  849. if (hbmMask != nullptr)
  850. ::DeleteObject (hbmMask);
  851. }
  852. };
  853. ScopedICONINFO info;
  854. if (! SUCCEEDED (::GetIconInfo (icon, &info)))
  855. return {};
  856. BITMAP bm;
  857. if (! (::GetObject (info.hbmColor, sizeof (BITMAP), &bm)
  858. && bm.bmWidth > 0 && bm.bmHeight > 0))
  859. return {};
  860. ScopedDeviceContext deviceContext { nullptr };
  861. if (auto* dc = ::CreateCompatibleDC (deviceContext.dc))
  862. {
  863. BITMAPV5HEADER header = {};
  864. header.bV5Size = sizeof (BITMAPV5HEADER);
  865. header.bV5Width = bm.bmWidth;
  866. header.bV5Height = -bm.bmHeight;
  867. header.bV5Planes = 1;
  868. header.bV5Compression = BI_RGB;
  869. header.bV5BitCount = 32;
  870. header.bV5RedMask = 0x00FF0000;
  871. header.bV5GreenMask = 0x0000FF00;
  872. header.bV5BlueMask = 0x000000FF;
  873. header.bV5AlphaMask = 0xFF000000;
  874. header.bV5CSType = LCS_WINDOWS_COLOR_SPACE;
  875. header.bV5Intent = LCS_GM_IMAGES;
  876. uint32* bitmapImageData = nullptr;
  877. if (auto* dib = ::CreateDIBSection (deviceContext.dc, (BITMAPINFO*) &header, DIB_RGB_COLORS,
  878. (void**) &bitmapImageData, nullptr, 0))
  879. {
  880. auto oldObject = ::SelectObject (dc, dib);
  881. auto numPixels = bm.bmWidth * bm.bmHeight;
  882. auto numColourComponents = (size_t) numPixels * 4;
  883. // Windows icon data comes as two layers, an XOR mask which contains the bulk
  884. // of the image data and an AND mask which provides the transparency. Annoyingly
  885. // the XOR mask can also contain an alpha channel, in which case the transparency
  886. // mask should not be applied, but there's no way to find out a priori if the XOR
  887. // mask contains an alpha channel.
  888. HeapBlock<bool> opacityMask (numPixels);
  889. memset (bitmapImageData, 0, numColourComponents);
  890. ::DrawIconEx (dc, 0, 0, icon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_MASK);
  891. for (int i = 0; i < numPixels; ++i)
  892. opacityMask[i] = (bitmapImageData[i] == 0);
  893. Image result = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  894. Image::BitmapData imageData (result, Image::BitmapData::readWrite);
  895. memset (bitmapImageData, 0, numColourComponents);
  896. ::DrawIconEx (dc, 0, 0, icon, bm.bmWidth, bm.bmHeight, 0, nullptr, DI_NORMAL);
  897. memcpy (imageData.data, bitmapImageData, numColourComponents);
  898. auto imageHasAlphaChannel = [&imageData, numPixels]()
  899. {
  900. for (int i = 0; i < numPixels; ++i)
  901. if (imageData.data[i * 4] != 0)
  902. return true;
  903. return false;
  904. };
  905. if (! imageHasAlphaChannel())
  906. for (int i = 0; i < numPixels; ++i)
  907. imageData.data[i * 4] = opacityMask[i] ? 0xff : 0x00;
  908. ::SelectObject (dc, oldObject);
  909. ::DeleteObject (dib);
  910. ::DeleteDC (dc);
  911. return result;
  912. }
  913. ::DeleteDC (dc);
  914. }
  915. return {};
  916. }
  917. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  918. {
  919. auto nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  920. Image bitmap (nativeBitmap);
  921. {
  922. Graphics g (bitmap);
  923. g.drawImageAt (image, 0, 0);
  924. }
  925. auto mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, nullptr);
  926. ICONINFO info;
  927. info.fIcon = isIcon;
  928. info.xHotspot = (DWORD) hotspotX;
  929. info.yHotspot = (DWORD) hotspotY;
  930. info.hbmMask = mask;
  931. info.hbmColor = nativeBitmap->hBitmap;
  932. auto hi = CreateIconIndirect (&info);
  933. DeleteObject (mask);
  934. return hi;
  935. }
  936. }
  937. //==============================================================================
  938. JUCE_IUNKNOWNCLASS (ITipInvocation, "37c994e7-432b-4834-a2f7-dce1f13b834b")
  939. {
  940. static CLSID getCLSID() noexcept { return { 0x4ce576fa, 0x83dc, 0x4f88, { 0x95, 0x1c, 0x9d, 0x07, 0x82, 0xb4, 0xe3, 0x76 } }; }
  941. JUCE_COMCALL Toggle (HWND) = 0;
  942. };
  943. struct OnScreenKeyboard : public DeletedAtShutdown,
  944. private Timer
  945. {
  946. void activate()
  947. {
  948. shouldBeActive = true;
  949. startTimer (10);
  950. }
  951. void deactivate()
  952. {
  953. shouldBeActive = false;
  954. startTimer (10);
  955. }
  956. JUCE_DECLARE_SINGLETON_SINGLETHREADED (OnScreenKeyboard, false)
  957. private:
  958. OnScreenKeyboard()
  959. {
  960. tipInvocation.CoCreateInstance (ITipInvocation::getCLSID(), CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER);
  961. }
  962. ~OnScreenKeyboard()
  963. {
  964. clearSingletonInstance();
  965. }
  966. void timerCallback() override
  967. {
  968. stopTimer();
  969. if (reentrant || tipInvocation == nullptr)
  970. return;
  971. const ScopedValueSetter<bool> setter (reentrant, true, false);
  972. auto isActive = isKeyboardVisible();
  973. if (isActive != shouldBeActive)
  974. {
  975. if (! isActive)
  976. {
  977. tipInvocation->Toggle (GetDesktopWindow());
  978. }
  979. else
  980. {
  981. if (auto hwnd = FindWindow (L"IPTip_Main_Window", NULL))
  982. PostMessage (hwnd, WM_SYSCOMMAND, (int) SC_CLOSE, 0);
  983. }
  984. }
  985. }
  986. bool isVisible()
  987. {
  988. if (auto hwnd = FindWindowEx (NULL, NULL, L"ApplicationFrameWindow", NULL))
  989. return FindWindowEx (hwnd, NULL, L"Windows.UI.Core.CoreWindow", L"Microsoft Text Input Application") != NULL;
  990. return false;
  991. }
  992. bool isVisibleLegacy()
  993. {
  994. if (auto hwnd = FindWindow (L"IPTip_Main_Window", NULL))
  995. {
  996. auto style = GetWindowLong (hwnd, GWL_STYLE);
  997. return (style & WS_DISABLED) == 0 && (style & WS_VISIBLE) != 0;
  998. }
  999. return false;
  1000. }
  1001. bool isKeyboardVisible()
  1002. {
  1003. if (isVisible())
  1004. return true;
  1005. // isVisible() may fail on Win10 versions < 1709 so try the old method too
  1006. return isVisibleLegacy();
  1007. }
  1008. bool shouldBeActive = false, reentrant = false;
  1009. ComSmartPtr<ITipInvocation> tipInvocation;
  1010. };
  1011. JUCE_IMPLEMENT_SINGLETON (OnScreenKeyboard)
  1012. //==============================================================================
  1013. struct HSTRING_PRIVATE;
  1014. typedef HSTRING_PRIVATE* HSTRING;
  1015. struct IInspectable : public IUnknown
  1016. {
  1017. JUCE_COMCALL GetIids (ULONG* ,IID**) = 0;
  1018. JUCE_COMCALL GetRuntimeClassName (HSTRING*) = 0;
  1019. JUCE_COMCALL GetTrustLevel (void*) = 0;
  1020. };
  1021. JUCE_COMCLASS (IUIViewSettingsInterop, "3694dbf9-8f68-44be-8ff5-195c98ede8a6") : public IInspectable
  1022. {
  1023. JUCE_COMCALL GetForWindow (HWND, REFIID, void**) = 0;
  1024. };
  1025. JUCE_COMCLASS (IUIViewSettings, "c63657f6-8850-470d-88f8-455e16ea2c26") : public IInspectable
  1026. {
  1027. enum UserInteractionMode
  1028. {
  1029. Mouse = 0,
  1030. Touch = 1
  1031. };
  1032. JUCE_COMCALL GetUserInteractionMode (UserInteractionMode*) = 0;
  1033. };
  1034. struct UWPUIViewSettings
  1035. {
  1036. UWPUIViewSettings()
  1037. {
  1038. ComBaseModule dll (L"api-ms-win-core-winrt-l1-1-0");
  1039. if (dll.h != nullptr)
  1040. {
  1041. roInitialize = (RoInitializeFuncPtr) ::GetProcAddress (dll.h, "RoInitialize");
  1042. roGetActivationFactory = (RoGetActivationFactoryFuncPtr) ::GetProcAddress (dll.h, "RoGetActivationFactory");
  1043. createHString = (WindowsCreateStringFuncPtr) ::GetProcAddress (dll.h, "WindowsCreateString");
  1044. deleteHString = (WindowsDeleteStringFuncPtr) ::GetProcAddress (dll.h, "WindowsDeleteString");
  1045. if (roInitialize == nullptr || roGetActivationFactory == nullptr
  1046. || createHString == nullptr || deleteHString == nullptr)
  1047. return;
  1048. auto status = roInitialize (1);
  1049. if (status != S_OK && status != S_FALSE && (unsigned) status != 0x80010106L)
  1050. return;
  1051. LPCWSTR uwpClassName = L"Windows.UI.ViewManagement.UIViewSettings";
  1052. HSTRING uwpClassId;
  1053. if (createHString (uwpClassName, (::UINT32) wcslen (uwpClassName), &uwpClassId) != S_OK
  1054. || uwpClassId == nullptr)
  1055. return;
  1056. status = roGetActivationFactory (uwpClassId, __uuidof (IUIViewSettingsInterop),
  1057. (void**) viewSettingsInterop.resetAndGetPointerAddress());
  1058. deleteHString (uwpClassId);
  1059. if (status != S_OK || viewSettingsInterop == nullptr)
  1060. return;
  1061. // move dll into member var
  1062. comBaseDLL = std::move (dll);
  1063. }
  1064. }
  1065. bool isTabletModeActivatedForWindow (::HWND hWnd) const
  1066. {
  1067. if (viewSettingsInterop == nullptr)
  1068. return false;
  1069. ComSmartPtr<IUIViewSettings> viewSettings;
  1070. if (viewSettingsInterop->GetForWindow (hWnd, __uuidof (IUIViewSettings),
  1071. (void**) viewSettings.resetAndGetPointerAddress()) == S_OK
  1072. && viewSettings != nullptr)
  1073. {
  1074. IUIViewSettings::UserInteractionMode mode;
  1075. if (viewSettings->GetUserInteractionMode (&mode) == S_OK)
  1076. return mode == IUIViewSettings::Touch;
  1077. }
  1078. return false;
  1079. }
  1080. private:
  1081. //==============================================================================
  1082. struct ComBaseModule
  1083. {
  1084. ComBaseModule() {}
  1085. ComBaseModule (LPCWSTR libraryName) : h (::LoadLibrary (libraryName)) {}
  1086. ComBaseModule (ComBaseModule&& o) : h (o.h) { o.h = nullptr; }
  1087. ~ComBaseModule() { release(); }
  1088. void release() { if (h != nullptr) ::FreeLibrary (h); h = nullptr; }
  1089. ComBaseModule& operator= (ComBaseModule&& o) { release(); h = o.h; o.h = nullptr; return *this; }
  1090. HMODULE h = {};
  1091. };
  1092. using RoInitializeFuncPtr = HRESULT (WINAPI*) (int);
  1093. using RoGetActivationFactoryFuncPtr = HRESULT (WINAPI*) (HSTRING, REFIID, void**);
  1094. using WindowsCreateStringFuncPtr = HRESULT (WINAPI*) (LPCWSTR,UINT32, HSTRING*);
  1095. using WindowsDeleteStringFuncPtr = HRESULT (WINAPI*) (HSTRING);
  1096. ComBaseModule comBaseDLL;
  1097. ComSmartPtr<IUIViewSettingsInterop> viewSettingsInterop;
  1098. RoInitializeFuncPtr roInitialize;
  1099. RoGetActivationFactoryFuncPtr roGetActivationFactory;
  1100. WindowsCreateStringFuncPtr createHString;
  1101. WindowsDeleteStringFuncPtr deleteHString;
  1102. };
  1103. //==============================================================================
  1104. class HWNDComponentPeer : public ComponentPeer,
  1105. private Timer
  1106. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1107. , public ModifierKeyReceiver
  1108. #endif
  1109. {
  1110. public:
  1111. enum RenderingEngineType
  1112. {
  1113. softwareRenderingEngine = 0,
  1114. direct2DRenderingEngine
  1115. };
  1116. //==============================================================================
  1117. HWNDComponentPeer (Component& comp, int windowStyleFlags, HWND parent, bool nonRepainting)
  1118. : ComponentPeer (comp, windowStyleFlags),
  1119. dontRepaint (nonRepainting),
  1120. parentToAddTo (parent),
  1121. currentRenderingEngine (softwareRenderingEngine)
  1122. {
  1123. // make sure that the UIA wrapper singleton is loaded
  1124. WindowsAccessibility::initialiseUIAWrapper();
  1125. callFunctionIfNotLocked (&createWindowCallback, this);
  1126. setTitle (component.getName());
  1127. updateShadower();
  1128. OnScreenKeyboard::getInstance();
  1129. getNativeRealtimeModifiers = []
  1130. {
  1131. HWNDComponentPeer::updateKeyModifiers();
  1132. int mouseMods = 0;
  1133. if (HWNDComponentPeer::isKeyDown (VK_LBUTTON)) mouseMods |= ModifierKeys::leftButtonModifier;
  1134. if (HWNDComponentPeer::isKeyDown (VK_RBUTTON)) mouseMods |= ModifierKeys::rightButtonModifier;
  1135. if (HWNDComponentPeer::isKeyDown (VK_MBUTTON)) mouseMods |= ModifierKeys::middleButtonModifier;
  1136. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1137. return ModifierKeys::currentModifiers;
  1138. };
  1139. }
  1140. ~HWNDComponentPeer()
  1141. {
  1142. // do this first to avoid messages arriving for this window before it's destroyed
  1143. JuceWindowIdentifier::setAsJUCEWindow (hwnd, false);
  1144. if (isAccessibilityActive)
  1145. WindowsAccessibility::revokeUIAMapEntriesForWindow (hwnd);
  1146. shadower = nullptr;
  1147. currentTouches.deleteAllTouchesForPeer (this);
  1148. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  1149. if (currentWindowIcon != nullptr)
  1150. DestroyIcon (currentWindowIcon);
  1151. if (dropTarget != nullptr)
  1152. {
  1153. dropTarget->peerIsDeleted = true;
  1154. dropTarget->Release();
  1155. dropTarget = nullptr;
  1156. }
  1157. #if JUCE_DIRECT2D
  1158. direct2DContext = nullptr;
  1159. #endif
  1160. }
  1161. //==============================================================================
  1162. void* getNativeHandle() const override { return hwnd; }
  1163. void setVisible (bool shouldBeVisible) override
  1164. {
  1165. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  1166. if (shouldBeVisible)
  1167. InvalidateRect (hwnd, nullptr, 0);
  1168. else
  1169. lastPaintTime = 0;
  1170. }
  1171. void setTitle (const String& title) override
  1172. {
  1173. // Unfortunately some ancient bits of win32 mean you can only perform this operation from the message thread.
  1174. JUCE_ASSERT_MESSAGE_THREAD
  1175. SetWindowText (hwnd, title.toWideCharPointer());
  1176. }
  1177. void repaintNowIfTransparent()
  1178. {
  1179. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  1180. handlePaintMessage();
  1181. }
  1182. void updateBorderSize()
  1183. {
  1184. WINDOWINFO info;
  1185. info.cbSize = sizeof (info);
  1186. if (GetWindowInfo (hwnd, &info))
  1187. windowBorder = BorderSize<int> (roundToInt ((info.rcClient.top - info.rcWindow.top) / scaleFactor),
  1188. roundToInt ((info.rcClient.left - info.rcWindow.left) / scaleFactor),
  1189. roundToInt ((info.rcWindow.bottom - info.rcClient.bottom) / scaleFactor),
  1190. roundToInt ((info.rcWindow.right - info.rcClient.right) / scaleFactor));
  1191. #if JUCE_DIRECT2D
  1192. if (direct2DContext != nullptr)
  1193. direct2DContext->resized();
  1194. #endif
  1195. }
  1196. void setBounds (const Rectangle<int>& bounds, bool isNowFullScreen) override
  1197. {
  1198. fullScreen = isNowFullScreen;
  1199. auto newBounds = windowBorder.addedTo (bounds);
  1200. if (isUsingUpdateLayeredWindow())
  1201. {
  1202. if (auto parentHwnd = GetParent (hwnd))
  1203. {
  1204. auto parentRect = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (parentHwnd)), hwnd);
  1205. newBounds.translate (parentRect.getX(), parentRect.getY());
  1206. }
  1207. }
  1208. auto oldBounds = getBounds();
  1209. const bool hasMoved = (oldBounds.getPosition() != bounds.getPosition());
  1210. const bool hasResized = (oldBounds.getWidth() != bounds.getWidth()
  1211. || oldBounds.getHeight() != bounds.getHeight());
  1212. DWORD flags = SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER;
  1213. if (! hasMoved) flags |= SWP_NOMOVE;
  1214. if (! hasResized) flags |= SWP_NOSIZE;
  1215. setWindowPos (hwnd, newBounds, flags, ! isInDPIChange);
  1216. if (hasResized && isValidPeer (this))
  1217. {
  1218. updateBorderSize();
  1219. repaintNowIfTransparent();
  1220. }
  1221. }
  1222. Rectangle<int> getBounds() const override
  1223. {
  1224. auto bounds = [this]
  1225. {
  1226. if (parentToAddTo == nullptr)
  1227. return convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)), hwnd);
  1228. auto localBounds = rectangleFromRECT (getWindowClientRect (hwnd));
  1229. if (isPerMonitorDPIAwareWindow (hwnd))
  1230. return (localBounds.toDouble() / getPlatformScaleFactor()).toNearestInt();
  1231. return localBounds;
  1232. }();
  1233. return windowBorder.subtractedFrom (bounds);
  1234. }
  1235. Point<int> getScreenPosition() const
  1236. {
  1237. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)), hwnd);
  1238. return { r.getX() + windowBorder.getLeft(),
  1239. r.getY() + windowBorder.getTop() };
  1240. }
  1241. Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getScreenPosition().toFloat(); }
  1242. Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getScreenPosition().toFloat(); }
  1243. using ComponentPeer::localToGlobal;
  1244. using ComponentPeer::globalToLocal;
  1245. void setAlpha (float newAlpha) override
  1246. {
  1247. auto intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  1248. if (component.isOpaque())
  1249. {
  1250. if (newAlpha < 1.0f)
  1251. {
  1252. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  1253. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  1254. }
  1255. else
  1256. {
  1257. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  1258. RedrawWindow (hwnd, nullptr, nullptr, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  1259. }
  1260. }
  1261. else
  1262. {
  1263. updateLayeredWindowAlpha = intAlpha;
  1264. component.repaint();
  1265. }
  1266. }
  1267. void setMinimised (bool shouldBeMinimised) override
  1268. {
  1269. if (shouldBeMinimised != isMinimised())
  1270. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  1271. }
  1272. bool isMinimised() const override
  1273. {
  1274. WINDOWPLACEMENT wp;
  1275. wp.length = sizeof (WINDOWPLACEMENT);
  1276. GetWindowPlacement (hwnd, &wp);
  1277. return wp.showCmd == SW_SHOWMINIMIZED;
  1278. }
  1279. void setFullScreen (bool shouldBeFullScreen) override
  1280. {
  1281. setMinimised (false);
  1282. if (isFullScreen() != shouldBeFullScreen)
  1283. {
  1284. if (constrainer != nullptr)
  1285. constrainer->resizeStart();
  1286. fullScreen = shouldBeFullScreen;
  1287. const WeakReference<Component> deletionChecker (&component);
  1288. if (! fullScreen)
  1289. {
  1290. auto boundsCopy = lastNonFullscreenBounds;
  1291. if (hasTitleBar())
  1292. ShowWindow (hwnd, SW_SHOWNORMAL);
  1293. if (! boundsCopy.isEmpty())
  1294. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, boundsCopy), false);
  1295. }
  1296. else
  1297. {
  1298. if (hasTitleBar())
  1299. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  1300. else
  1301. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  1302. }
  1303. if (deletionChecker != nullptr)
  1304. handleMovedOrResized();
  1305. if (constrainer != nullptr)
  1306. constrainer->resizeEnd();
  1307. }
  1308. }
  1309. bool isFullScreen() const override
  1310. {
  1311. if (! hasTitleBar())
  1312. return fullScreen;
  1313. WINDOWPLACEMENT wp;
  1314. wp.length = sizeof (wp);
  1315. GetWindowPlacement (hwnd, &wp);
  1316. return wp.showCmd == SW_SHOWMAXIMIZED;
  1317. }
  1318. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  1319. {
  1320. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)), hwnd);
  1321. if (! r.withZeroOrigin().contains (localPos))
  1322. return false;
  1323. auto w = WindowFromPoint (POINTFromPoint (convertLogicalScreenPointToPhysical (localPos + getScreenPosition(),
  1324. hwnd)));
  1325. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  1326. }
  1327. BorderSize<int> getFrameSize() const override
  1328. {
  1329. return windowBorder;
  1330. }
  1331. bool setAlwaysOnTop (bool alwaysOnTop) override
  1332. {
  1333. const bool oldDeactivate = shouldDeactivateTitleBar;
  1334. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1335. setWindowZOrder (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST);
  1336. shouldDeactivateTitleBar = oldDeactivate;
  1337. if (shadower != nullptr)
  1338. handleBroughtToFront();
  1339. return true;
  1340. }
  1341. void toFront (bool makeActive) override
  1342. {
  1343. setMinimised (false);
  1344. const bool oldDeactivate = shouldDeactivateTitleBar;
  1345. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1346. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  1347. shouldDeactivateTitleBar = oldDeactivate;
  1348. if (! makeActive)
  1349. {
  1350. // in this case a broughttofront call won't have occurred, so do it now..
  1351. handleBroughtToFront();
  1352. }
  1353. }
  1354. void toBehind (ComponentPeer* other) override
  1355. {
  1356. if (auto* otherPeer = dynamic_cast<HWNDComponentPeer*> (other))
  1357. {
  1358. setMinimised (false);
  1359. // Must be careful not to try to put a topmost window behind a normal one, or Windows
  1360. // promotes the normal one to be topmost!
  1361. if (component.isAlwaysOnTop() == otherPeer->getComponent().isAlwaysOnTop())
  1362. setWindowZOrder (hwnd, otherPeer->hwnd);
  1363. else if (otherPeer->getComponent().isAlwaysOnTop())
  1364. setWindowZOrder (hwnd, HWND_TOP);
  1365. }
  1366. else
  1367. {
  1368. jassertfalse; // wrong type of window?
  1369. }
  1370. }
  1371. bool isFocused() const override
  1372. {
  1373. return callFunctionIfNotLocked (&getFocusCallback, nullptr) == (void*) hwnd;
  1374. }
  1375. void grabFocus() override
  1376. {
  1377. const bool oldDeactivate = shouldDeactivateTitleBar;
  1378. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1379. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  1380. shouldDeactivateTitleBar = oldDeactivate;
  1381. }
  1382. void textInputRequired (Point<int>, TextInputTarget&) override
  1383. {
  1384. if (! hasCreatedCaret)
  1385. {
  1386. hasCreatedCaret = true;
  1387. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  1388. }
  1389. ShowCaret (hwnd);
  1390. SetCaretPos (0, 0);
  1391. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  1392. OnScreenKeyboard::getInstance()->activate();
  1393. }
  1394. void dismissPendingTextInput() override
  1395. {
  1396. imeHandler.handleSetContext (hwnd, false);
  1397. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  1398. OnScreenKeyboard::getInstance()->deactivate();
  1399. }
  1400. void repaint (const Rectangle<int>& area) override
  1401. {
  1402. auto r = RECTFromRectangle ((area.toDouble() * getPlatformScaleFactor()).getSmallestIntegerContainer());
  1403. InvalidateRect (hwnd, &r, FALSE);
  1404. }
  1405. void performAnyPendingRepaintsNow() override
  1406. {
  1407. if (component.isVisible())
  1408. {
  1409. WeakReference<Component> localRef (&component);
  1410. MSG m;
  1411. if (isUsingUpdateLayeredWindow() || PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  1412. if (localRef != nullptr) // (the PeekMessage call can dispatch messages, which may delete this comp)
  1413. handlePaintMessage();
  1414. }
  1415. }
  1416. //==============================================================================
  1417. static HWNDComponentPeer* getOwnerOfWindow (HWND h) noexcept
  1418. {
  1419. if (h != nullptr && JuceWindowIdentifier::isJUCEWindow (h))
  1420. return (HWNDComponentPeer*) GetWindowLongPtr (h, 8);
  1421. return nullptr;
  1422. }
  1423. //==============================================================================
  1424. bool isInside (HWND h) const noexcept
  1425. {
  1426. return GetAncestor (hwnd, GA_ROOT) == h;
  1427. }
  1428. //==============================================================================
  1429. static bool isKeyDown (const int key) noexcept { return (GetAsyncKeyState (key) & 0x8000) != 0; }
  1430. static void updateKeyModifiers() noexcept
  1431. {
  1432. int keyMods = 0;
  1433. if (isKeyDown (VK_SHIFT)) keyMods |= ModifierKeys::shiftModifier;
  1434. if (isKeyDown (VK_CONTROL)) keyMods |= ModifierKeys::ctrlModifier;
  1435. if (isKeyDown (VK_MENU)) keyMods |= ModifierKeys::altModifier;
  1436. // workaround: Windows maps AltGr to left-Ctrl + right-Alt.
  1437. if (isKeyDown (VK_RMENU) && !isKeyDown (VK_RCONTROL))
  1438. {
  1439. keyMods = (keyMods & ~ModifierKeys::ctrlModifier) | ModifierKeys::altModifier;
  1440. }
  1441. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1442. }
  1443. static void updateModifiersFromWParam (const WPARAM wParam)
  1444. {
  1445. int mouseMods = 0;
  1446. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  1447. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  1448. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  1449. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1450. updateKeyModifiers();
  1451. }
  1452. //==============================================================================
  1453. bool dontRepaint;
  1454. static ModifierKeys modifiersAtLastCallback;
  1455. //==============================================================================
  1456. struct FileDropTarget : public ComBaseClassHelper<IDropTarget>
  1457. {
  1458. FileDropTarget (HWNDComponentPeer& p) : peer (p) {}
  1459. JUCE_COMRESULT DragEnter (IDataObject* pDataObject, DWORD grfKeyState, POINTL mousePos, DWORD* pdwEffect) override
  1460. {
  1461. auto hr = updateFileList (pDataObject);
  1462. if (FAILED (hr))
  1463. return hr;
  1464. return DragOver (grfKeyState, mousePos, pdwEffect);
  1465. }
  1466. JUCE_COMRESULT DragLeave() override
  1467. {
  1468. if (peerIsDeleted)
  1469. return S_FALSE;
  1470. peer.handleDragExit (dragInfo);
  1471. return S_OK;
  1472. }
  1473. JUCE_COMRESULT DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1474. {
  1475. if (peerIsDeleted)
  1476. return S_FALSE;
  1477. dragInfo.position = getMousePos (mousePos).roundToInt();
  1478. *pdwEffect = peer.handleDragMove (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1479. : (DWORD) DROPEFFECT_NONE;
  1480. return S_OK;
  1481. }
  1482. JUCE_COMRESULT Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1483. {
  1484. auto hr = updateFileList (pDataObject);
  1485. if (FAILED (hr))
  1486. return hr;
  1487. dragInfo.position = getMousePos (mousePos).roundToInt();
  1488. *pdwEffect = peer.handleDragDrop (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1489. : (DWORD) DROPEFFECT_NONE;
  1490. return S_OK;
  1491. }
  1492. HWNDComponentPeer& peer;
  1493. ComponentPeer::DragInfo dragInfo;
  1494. bool peerIsDeleted = false;
  1495. private:
  1496. Point<float> getMousePos (POINTL mousePos) const
  1497. {
  1498. return peer.getComponent().getLocalPoint (nullptr, convertPhysicalScreenPointToLogical (pointFromPOINT ({ mousePos.x, mousePos.y }),
  1499. (HWND) peer.getNativeHandle()).toFloat());
  1500. }
  1501. struct DroppedData
  1502. {
  1503. DroppedData (IDataObject* dataObject, CLIPFORMAT type)
  1504. {
  1505. FORMATETC format = { type, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  1506. if (SUCCEEDED (error = dataObject->GetData (&format, &medium)))
  1507. {
  1508. dataSize = GlobalSize (medium.hGlobal);
  1509. data = GlobalLock (medium.hGlobal);
  1510. }
  1511. }
  1512. ~DroppedData()
  1513. {
  1514. if (data != nullptr)
  1515. GlobalUnlock (medium.hGlobal);
  1516. }
  1517. HRESULT error;
  1518. STGMEDIUM medium { TYMED_HGLOBAL, { nullptr }, nullptr };
  1519. void* data = {};
  1520. SIZE_T dataSize;
  1521. };
  1522. void parseFileList (HDROP dropFiles)
  1523. {
  1524. dragInfo.files.clearQuick();
  1525. std::vector<TCHAR> nameBuffer;
  1526. const auto numFiles = DragQueryFile (dropFiles, ~(UINT) 0, nullptr, 0);
  1527. for (UINT i = 0; i < numFiles; ++i)
  1528. {
  1529. const auto bufferSize = DragQueryFile (dropFiles, i, nullptr, 0);
  1530. nameBuffer.clear();
  1531. nameBuffer.resize (bufferSize + 1, 0); // + 1 for the null terminator
  1532. const auto readCharacters = DragQueryFile (dropFiles, i, nameBuffer.data(), (UINT) nameBuffer.size());
  1533. ignoreUnused (readCharacters);
  1534. jassert (readCharacters == bufferSize);
  1535. dragInfo.files.add (String (nameBuffer.data()));
  1536. }
  1537. }
  1538. HRESULT updateFileList (IDataObject* const dataObject)
  1539. {
  1540. if (peerIsDeleted)
  1541. return S_FALSE;
  1542. dragInfo.clear();
  1543. {
  1544. DroppedData fileData (dataObject, CF_HDROP);
  1545. if (SUCCEEDED (fileData.error))
  1546. {
  1547. parseFileList (static_cast<HDROP> (fileData.data));
  1548. return S_OK;
  1549. }
  1550. }
  1551. DroppedData textData (dataObject, CF_UNICODETEXT);
  1552. if (SUCCEEDED (textData.error))
  1553. {
  1554. dragInfo.text = String (CharPointer_UTF16 ((const WCHAR*) textData.data),
  1555. CharPointer_UTF16 ((const WCHAR*) addBytesToPointer (textData.data, textData.dataSize)));
  1556. return S_OK;
  1557. }
  1558. return textData.error;
  1559. }
  1560. JUCE_DECLARE_NON_COPYABLE (FileDropTarget)
  1561. };
  1562. static bool offerKeyMessageToJUCEWindow (MSG& m)
  1563. {
  1564. if (m.message == WM_KEYDOWN || m.message == WM_KEYUP)
  1565. if (Component::getCurrentlyFocusedComponent() != nullptr)
  1566. if (auto* h = getOwnerOfWindow (m.hwnd))
  1567. return m.message == WM_KEYDOWN ? h->doKeyDown (m.wParam)
  1568. : h->doKeyUp (m.wParam);
  1569. return false;
  1570. }
  1571. double getPlatformScaleFactor() const noexcept override
  1572. {
  1573. #if ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  1574. return 1.0;
  1575. #else
  1576. if (! isPerMonitorDPIAwareWindow (hwnd))
  1577. return 1.0;
  1578. if (auto* parentHWND = GetParent (hwnd))
  1579. {
  1580. if (auto* parentPeer = getOwnerOfWindow (parentHWND))
  1581. return parentPeer->getPlatformScaleFactor();
  1582. if (getDPIForWindow != nullptr)
  1583. return getScaleFactorForWindow (parentHWND);
  1584. }
  1585. return scaleFactor;
  1586. #endif
  1587. }
  1588. private:
  1589. HWND hwnd, parentToAddTo;
  1590. std::unique_ptr<DropShadower> shadower;
  1591. RenderingEngineType currentRenderingEngine;
  1592. #if JUCE_DIRECT2D
  1593. std::unique_ptr<Direct2DLowLevelGraphicsContext> direct2DContext;
  1594. #endif
  1595. uint32 lastPaintTime = 0;
  1596. ULONGLONG lastMagnifySize = 0;
  1597. bool fullScreen = false, isDragging = false, isMouseOver = false,
  1598. hasCreatedCaret = false, constrainerIsResizing = false;
  1599. BorderSize<int> windowBorder;
  1600. HICON currentWindowIcon = nullptr;
  1601. FileDropTarget* dropTarget = nullptr;
  1602. uint8 updateLayeredWindowAlpha = 255;
  1603. UWPUIViewSettings uwpViewSettings;
  1604. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1605. ModifierKeyProvider* modProvider = nullptr;
  1606. #endif
  1607. double scaleFactor = 1.0;
  1608. bool isInDPIChange = false;
  1609. bool isAccessibilityActive = false;
  1610. //==============================================================================
  1611. static MultiTouchMapper<DWORD> currentTouches;
  1612. //==============================================================================
  1613. struct TemporaryImage : private Timer
  1614. {
  1615. TemporaryImage() {}
  1616. Image& getImage (bool transparent, int w, int h)
  1617. {
  1618. auto format = transparent ? Image::ARGB : Image::RGB;
  1619. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  1620. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  1621. startTimer (3000);
  1622. return image;
  1623. }
  1624. void timerCallback() override
  1625. {
  1626. stopTimer();
  1627. image = {};
  1628. }
  1629. private:
  1630. Image image;
  1631. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage)
  1632. };
  1633. TemporaryImage offscreenImageGenerator;
  1634. //==============================================================================
  1635. class WindowClassHolder : private DeletedAtShutdown
  1636. {
  1637. public:
  1638. WindowClassHolder()
  1639. {
  1640. // this name has to be different for each app/dll instance because otherwise poor old Windows can
  1641. // get a bit confused (even despite it not being a process-global window class).
  1642. String windowClassName ("JUCE_");
  1643. windowClassName << String::toHexString (Time::currentTimeMillis());
  1644. auto moduleHandle = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
  1645. TCHAR moduleFile[1024] = {};
  1646. GetModuleFileName (moduleHandle, moduleFile, 1024);
  1647. WORD iconNum = 0;
  1648. WNDCLASSEX wcex = {};
  1649. wcex.cbSize = sizeof (wcex);
  1650. wcex.style = CS_OWNDC;
  1651. wcex.lpfnWndProc = (WNDPROC) windowProc;
  1652. wcex.lpszClassName = windowClassName.toWideCharPointer();
  1653. wcex.cbWndExtra = 32;
  1654. wcex.hInstance = moduleHandle;
  1655. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1656. iconNum = 1;
  1657. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1658. atom = RegisterClassEx (&wcex);
  1659. jassert (atom != 0);
  1660. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  1661. }
  1662. ~WindowClassHolder()
  1663. {
  1664. if (ComponentPeer::getNumPeers() == 0)
  1665. UnregisterClass (getWindowClassName(), (HINSTANCE) Process::getCurrentModuleInstanceHandle());
  1666. clearSingletonInstance();
  1667. }
  1668. LPCTSTR getWindowClassName() const noexcept { return (LPCTSTR) (pointer_sized_uint) atom; }
  1669. JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL (WindowClassHolder)
  1670. private:
  1671. ATOM atom;
  1672. static bool isHWNDBlockedByModalComponents (HWND h)
  1673. {
  1674. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1675. if (auto* c = Desktop::getInstance().getComponent (i))
  1676. if ((! c->isCurrentlyBlockedByAnotherModalComponent())
  1677. && IsChild ((HWND) c->getWindowHandle(), h))
  1678. return false;
  1679. return true;
  1680. }
  1681. static bool checkEventBlockedByModalComps (const MSG& m)
  1682. {
  1683. if (Component::getNumCurrentlyModalComponents() == 0 || JuceWindowIdentifier::isJUCEWindow (m.hwnd))
  1684. return false;
  1685. switch (m.message)
  1686. {
  1687. case WM_MOUSEMOVE:
  1688. case WM_NCMOUSEMOVE:
  1689. case 0x020A: /* WM_MOUSEWHEEL */
  1690. case 0x020E: /* WM_MOUSEHWHEEL */
  1691. case WM_KEYUP:
  1692. case WM_SYSKEYUP:
  1693. case WM_CHAR:
  1694. case WM_APPCOMMAND:
  1695. case WM_LBUTTONUP:
  1696. case WM_MBUTTONUP:
  1697. case WM_RBUTTONUP:
  1698. case WM_MOUSEACTIVATE:
  1699. case WM_NCMOUSEHOVER:
  1700. case WM_MOUSEHOVER:
  1701. case WM_TOUCH:
  1702. case WM_POINTERUPDATE:
  1703. case WM_NCPOINTERUPDATE:
  1704. case WM_POINTERWHEEL:
  1705. case WM_POINTERHWHEEL:
  1706. case WM_POINTERUP:
  1707. case WM_POINTERACTIVATE:
  1708. return isHWNDBlockedByModalComponents(m.hwnd);
  1709. case WM_NCLBUTTONDOWN:
  1710. case WM_NCLBUTTONDBLCLK:
  1711. case WM_NCRBUTTONDOWN:
  1712. case WM_NCRBUTTONDBLCLK:
  1713. case WM_NCMBUTTONDOWN:
  1714. case WM_NCMBUTTONDBLCLK:
  1715. case WM_LBUTTONDOWN:
  1716. case WM_LBUTTONDBLCLK:
  1717. case WM_MBUTTONDOWN:
  1718. case WM_MBUTTONDBLCLK:
  1719. case WM_RBUTTONDOWN:
  1720. case WM_RBUTTONDBLCLK:
  1721. case WM_KEYDOWN:
  1722. case WM_SYSKEYDOWN:
  1723. case WM_NCPOINTERDOWN:
  1724. case WM_POINTERDOWN:
  1725. if (isHWNDBlockedByModalComponents (m.hwnd))
  1726. {
  1727. if (auto* modal = Component::getCurrentlyModalComponent (0))
  1728. modal->inputAttemptWhenModal();
  1729. return true;
  1730. }
  1731. break;
  1732. default:
  1733. break;
  1734. }
  1735. return false;
  1736. }
  1737. JUCE_DECLARE_NON_COPYABLE (WindowClassHolder)
  1738. };
  1739. //==============================================================================
  1740. static void* createWindowCallback (void* userData)
  1741. {
  1742. static_cast<HWNDComponentPeer*> (userData)->createWindow();
  1743. return nullptr;
  1744. }
  1745. void createWindow()
  1746. {
  1747. DWORD exstyle = 0;
  1748. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  1749. if (hasTitleBar())
  1750. {
  1751. type |= WS_OVERLAPPED;
  1752. if ((styleFlags & windowHasCloseButton) != 0)
  1753. {
  1754. type |= WS_SYSMENU;
  1755. }
  1756. else
  1757. {
  1758. // annoyingly, windows won't let you have a min/max button without a close button
  1759. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  1760. }
  1761. if ((styleFlags & windowIsResizable) != 0)
  1762. type |= WS_THICKFRAME;
  1763. }
  1764. else if (parentToAddTo != nullptr)
  1765. {
  1766. type |= WS_CHILD;
  1767. }
  1768. else
  1769. {
  1770. type |= WS_POPUP | WS_SYSMENU;
  1771. }
  1772. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1773. exstyle |= WS_EX_TOOLWINDOW;
  1774. else
  1775. exstyle |= WS_EX_APPWINDOW;
  1776. if ((styleFlags & windowHasMinimiseButton) != 0) type |= WS_MINIMIZEBOX;
  1777. if ((styleFlags & windowHasMaximiseButton) != 0) type |= WS_MAXIMIZEBOX;
  1778. if ((styleFlags & windowIgnoresMouseClicks) != 0) exstyle |= WS_EX_TRANSPARENT;
  1779. if ((styleFlags & windowIsSemiTransparent) != 0) exstyle |= WS_EX_LAYERED;
  1780. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->getWindowClassName(),
  1781. L"", type, 0, 0, 0, 0, parentToAddTo, nullptr,
  1782. (HINSTANCE) Process::getCurrentModuleInstanceHandle(), nullptr);
  1783. #if JUCE_DEBUG
  1784. // The DPI-awareness context of this window and JUCE's hidden message window are different.
  1785. // You normally want these to match otherwise timer events and async messages will happen
  1786. // in a different context to normal HWND messages which can cause issues with UI scaling.
  1787. jassert (isPerMonitorDPIAwareWindow (hwnd) == isPerMonitorDPIAwareWindow (juce_messageWindowHandle)
  1788. || isInScopedDPIAwarenessDisabler());
  1789. #endif
  1790. if (hwnd != nullptr)
  1791. {
  1792. SetWindowLongPtr (hwnd, 0, 0);
  1793. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  1794. JuceWindowIdentifier::setAsJUCEWindow (hwnd, true);
  1795. if (dropTarget == nullptr)
  1796. {
  1797. HWNDComponentPeer* peer = nullptr;
  1798. if (dontRepaint)
  1799. peer = getOwnerOfWindow (parentToAddTo);
  1800. if (peer == nullptr)
  1801. peer = this;
  1802. dropTarget = new FileDropTarget (*peer);
  1803. }
  1804. RegisterDragDrop (hwnd, dropTarget);
  1805. if (canUseMultiTouch())
  1806. registerTouchWindow (hwnd, 0);
  1807. setDPIAwareness();
  1808. if (isPerMonitorDPIAwareThread())
  1809. scaleFactor = getScaleFactorForWindow (hwnd);
  1810. setMessageFilter();
  1811. updateBorderSize();
  1812. checkForPointerAPI();
  1813. // This is needed so that our plugin window gets notified of WM_SETTINGCHANGE messages
  1814. // and can respond to display scale changes
  1815. if (! JUCEApplication::isStandaloneApp())
  1816. settingChangeCallback = ComponentPeer::forceDisplayUpdate;
  1817. // Calling this function here is (for some reason) necessary to make Windows
  1818. // correctly enable the menu items that we specify in the wm_initmenu message.
  1819. GetSystemMenu (hwnd, false);
  1820. auto alpha = component.getAlpha();
  1821. if (alpha < 1.0f)
  1822. setAlpha (alpha);
  1823. }
  1824. else
  1825. {
  1826. jassertfalse;
  1827. }
  1828. }
  1829. static BOOL CALLBACK revokeChildDragDropCallback (HWND hwnd, LPARAM) { RevokeDragDrop (hwnd); return TRUE; }
  1830. static void* destroyWindowCallback (void* handle)
  1831. {
  1832. auto hwnd = reinterpret_cast<HWND> (handle);
  1833. if (IsWindow (hwnd))
  1834. {
  1835. RevokeDragDrop (hwnd);
  1836. // NB: we need to do this before DestroyWindow() as child HWNDs will be invalid after
  1837. EnumChildWindows (hwnd, revokeChildDragDropCallback, 0);
  1838. DestroyWindow (hwnd);
  1839. }
  1840. return nullptr;
  1841. }
  1842. static void* toFrontCallback1 (void* h)
  1843. {
  1844. SetForegroundWindow ((HWND) h);
  1845. return nullptr;
  1846. }
  1847. static void* toFrontCallback2 (void* h)
  1848. {
  1849. setWindowZOrder ((HWND) h, HWND_TOP);
  1850. return nullptr;
  1851. }
  1852. static void* setFocusCallback (void* h)
  1853. {
  1854. SetFocus ((HWND) h);
  1855. return nullptr;
  1856. }
  1857. static void* getFocusCallback (void*)
  1858. {
  1859. return GetFocus();
  1860. }
  1861. bool isUsingUpdateLayeredWindow() const
  1862. {
  1863. return ! component.isOpaque();
  1864. }
  1865. bool hasTitleBar() const noexcept { return (styleFlags & windowHasTitleBar) != 0; }
  1866. void updateShadower()
  1867. {
  1868. if (! component.isCurrentlyModal() && (styleFlags & windowHasDropShadow) != 0
  1869. && ((! hasTitleBar()) || SystemStats::getOperatingSystemType() < SystemStats::WinVista))
  1870. {
  1871. shadower.reset (component.getLookAndFeel().createDropShadowerForComponent (&component));
  1872. if (shadower != nullptr)
  1873. shadower->setOwner (&component);
  1874. }
  1875. }
  1876. void setIcon (const Image& newIcon) override
  1877. {
  1878. if (auto hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0))
  1879. {
  1880. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  1881. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  1882. if (currentWindowIcon != nullptr)
  1883. DestroyIcon (currentWindowIcon);
  1884. currentWindowIcon = hicon;
  1885. }
  1886. }
  1887. void setMessageFilter()
  1888. {
  1889. using ChangeWindowMessageFilterExFunc = BOOL (WINAPI*) (HWND, UINT, DWORD, PVOID);
  1890. if (auto changeMessageFilter = (ChangeWindowMessageFilterExFunc) getUser32Function ("ChangeWindowMessageFilterEx"))
  1891. {
  1892. changeMessageFilter (hwnd, WM_DROPFILES, 1 /*MSGFLT_ALLOW*/, nullptr);
  1893. changeMessageFilter (hwnd, WM_COPYDATA, 1 /*MSGFLT_ALLOW*/, nullptr);
  1894. changeMessageFilter (hwnd, 0x49, 1 /*MSGFLT_ALLOW*/, nullptr);
  1895. }
  1896. }
  1897. struct ChildWindowClippingInfo
  1898. {
  1899. HDC dc;
  1900. HWNDComponentPeer* peer;
  1901. RectangleList<int>* clip;
  1902. Point<int> origin;
  1903. int savedDC;
  1904. };
  1905. static BOOL CALLBACK clipChildWindowCallback (HWND hwnd, LPARAM context)
  1906. {
  1907. if (IsWindowVisible (hwnd))
  1908. {
  1909. auto& info = *(ChildWindowClippingInfo*) context;
  1910. if (GetParent (hwnd) == info.peer->hwnd)
  1911. {
  1912. auto clip = rectangleFromRECT (getWindowClientRect (hwnd));
  1913. info.clip->subtract (clip - info.origin);
  1914. if (info.savedDC == 0)
  1915. info.savedDC = SaveDC (info.dc);
  1916. ExcludeClipRect (info.dc, clip.getX(), clip.getY(), clip.getRight(), clip.getBottom());
  1917. }
  1918. }
  1919. return TRUE;
  1920. }
  1921. //==============================================================================
  1922. void handlePaintMessage()
  1923. {
  1924. #if JUCE_DIRECT2D
  1925. if (direct2DContext != nullptr)
  1926. {
  1927. RECT r;
  1928. if (GetUpdateRect (hwnd, &r, false))
  1929. {
  1930. direct2DContext->start();
  1931. direct2DContext->clipToRectangle (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r), hwnd));
  1932. handlePaint (*direct2DContext);
  1933. direct2DContext->end();
  1934. ValidateRect (hwnd, &r);
  1935. }
  1936. }
  1937. else
  1938. #endif
  1939. {
  1940. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  1941. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  1942. PAINTSTRUCT paintStruct;
  1943. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  1944. // message and become re-entrant, but that's OK
  1945. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  1946. // corrupt the image it's using to paint into, so do a check here.
  1947. static bool reentrant = false;
  1948. if (! reentrant)
  1949. {
  1950. const ScopedValueSetter<bool> setter (reentrant, true, false);
  1951. if (dontRepaint)
  1952. component.handleCommandMessage (0); // (this triggers a repaint in the openGL context)
  1953. else
  1954. performPaint (dc, rgn, regionType, paintStruct);
  1955. }
  1956. DeleteObject (rgn);
  1957. EndPaint (hwnd, &paintStruct);
  1958. #if JUCE_MSVC
  1959. _fpreset(); // because some graphics cards can unmask FP exceptions
  1960. #endif
  1961. }
  1962. lastPaintTime = Time::getMillisecondCounter();
  1963. }
  1964. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  1965. {
  1966. int x = paintStruct.rcPaint.left;
  1967. int y = paintStruct.rcPaint.top;
  1968. int w = paintStruct.rcPaint.right - x;
  1969. int h = paintStruct.rcPaint.bottom - y;
  1970. const bool transparent = isUsingUpdateLayeredWindow();
  1971. if (transparent)
  1972. {
  1973. // it's not possible to have a transparent window with a title bar at the moment!
  1974. jassert (! hasTitleBar());
  1975. auto r = getWindowScreenRect (hwnd);
  1976. x = y = 0;
  1977. w = r.right - r.left;
  1978. h = r.bottom - r.top;
  1979. }
  1980. if (w > 0 && h > 0)
  1981. {
  1982. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  1983. RectangleList<int> contextClip;
  1984. const Rectangle<int> clipBounds (w, h);
  1985. bool needToPaintAll = true;
  1986. if (regionType == COMPLEXREGION && ! transparent)
  1987. {
  1988. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  1989. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  1990. DeleteObject (clipRgn);
  1991. char rgnData[8192];
  1992. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  1993. if (res > 0 && res <= sizeof (rgnData))
  1994. {
  1995. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  1996. if (hdr->iType == RDH_RECTANGLES
  1997. && hdr->rcBound.right - hdr->rcBound.left >= w
  1998. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  1999. {
  2000. needToPaintAll = false;
  2001. auto rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  2002. for (int i = (int) ((RGNDATA*) rgnData)->rdh.nCount; --i >= 0;)
  2003. {
  2004. if (rects->right <= x + w && rects->bottom <= y + h)
  2005. {
  2006. const int cx = jmax (x, (int) rects->left);
  2007. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  2008. rects->right - cx, rects->bottom - rects->top)
  2009. .getIntersection (clipBounds));
  2010. }
  2011. else
  2012. {
  2013. needToPaintAll = true;
  2014. break;
  2015. }
  2016. ++rects;
  2017. }
  2018. }
  2019. }
  2020. }
  2021. if (needToPaintAll)
  2022. {
  2023. contextClip.clear();
  2024. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  2025. }
  2026. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  2027. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  2028. if (! contextClip.isEmpty())
  2029. {
  2030. if (transparent)
  2031. for (auto& i : contextClip)
  2032. offscreenImage.clear (i);
  2033. {
  2034. auto context = component.getLookAndFeel()
  2035. .createGraphicsContext (offscreenImage, { -x, -y }, contextClip);
  2036. context->addTransform (AffineTransform::scale ((float) getPlatformScaleFactor()));
  2037. handlePaint (*context);
  2038. }
  2039. static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData())
  2040. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  2041. }
  2042. if (childClipInfo.savedDC != 0)
  2043. RestoreDC (dc, childClipInfo.savedDC);
  2044. }
  2045. }
  2046. //==============================================================================
  2047. void doMouseEvent (Point<float> position, float pressure, float orientation = 0.0f, ModifierKeys mods = ModifierKeys::currentModifiers)
  2048. {
  2049. handleMouseEvent (MouseInputSource::InputSourceType::mouse, position, mods, pressure, orientation, getMouseEventTime());
  2050. }
  2051. StringArray getAvailableRenderingEngines() override
  2052. {
  2053. StringArray s ("Software Renderer");
  2054. #if JUCE_DIRECT2D
  2055. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  2056. s.add ("Direct2D");
  2057. #endif
  2058. return s;
  2059. }
  2060. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  2061. #if JUCE_DIRECT2D
  2062. void updateDirect2DContext()
  2063. {
  2064. if (currentRenderingEngine != direct2DRenderingEngine)
  2065. direct2DContext = nullptr;
  2066. else if (direct2DContext == nullptr)
  2067. direct2DContext.reset (new Direct2DLowLevelGraphicsContext (hwnd));
  2068. }
  2069. #endif
  2070. void setCurrentRenderingEngine (int index) override
  2071. {
  2072. ignoreUnused (index);
  2073. #if JUCE_DIRECT2D
  2074. if (getAvailableRenderingEngines().size() > 1)
  2075. {
  2076. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  2077. updateDirect2DContext();
  2078. repaint (component.getLocalBounds());
  2079. }
  2080. #endif
  2081. }
  2082. static uint32 getMinTimeBetweenMouseMoves()
  2083. {
  2084. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  2085. return 0;
  2086. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  2087. }
  2088. bool isTouchEvent() noexcept
  2089. {
  2090. if (registerTouchWindow == nullptr)
  2091. return false;
  2092. // Relevant info about touch/pen detection flags:
  2093. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
  2094. // http://www.petertissen.de/?p=4
  2095. return (GetMessageExtraInfo() & 0xFFFFFF80 /*SIGNATURE_MASK*/) == 0xFF515780 /*MI_WP_SIGNATURE*/;
  2096. }
  2097. static bool areOtherTouchSourcesActive()
  2098. {
  2099. for (auto& ms : Desktop::getInstance().getMouseSources())
  2100. if (ms.isDragging() && (ms.getType() == MouseInputSource::InputSourceType::touch
  2101. || ms.getType() == MouseInputSource::InputSourceType::pen))
  2102. return true;
  2103. return false;
  2104. }
  2105. void doMouseMove (Point<float> position, bool isMouseDownEvent)
  2106. {
  2107. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2108. // this will be handled by WM_TOUCH
  2109. if (isTouchEvent() || areOtherTouchSourcesActive())
  2110. return;
  2111. if (! isMouseOver)
  2112. {
  2113. isMouseOver = true;
  2114. // This avoids a rare stuck-button problem when focus is lost unexpectedly, but must
  2115. // not be called as part of a move, in case it's actually a mouse-drag from another
  2116. // app which ends up here when we get focus before the mouse is released..
  2117. if (isMouseDownEvent && getNativeRealtimeModifiers != nullptr)
  2118. getNativeRealtimeModifiers();
  2119. updateKeyModifiers();
  2120. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2121. if (modProvider != nullptr)
  2122. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2123. #endif
  2124. TRACKMOUSEEVENT tme;
  2125. tme.cbSize = sizeof (tme);
  2126. tme.dwFlags = TME_LEAVE;
  2127. tme.hwndTrack = hwnd;
  2128. tme.dwHoverTime = 0;
  2129. if (! TrackMouseEvent (&tme))
  2130. jassertfalse;
  2131. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  2132. }
  2133. else if (! isDragging)
  2134. {
  2135. if (! contains (position.roundToInt(), false))
  2136. return;
  2137. }
  2138. static uint32 lastMouseTime = 0;
  2139. static auto minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  2140. auto now = Time::getMillisecondCounter();
  2141. if (! Desktop::getInstance().getMainMouseSource().isDragging())
  2142. modsToSend = modsToSend.withoutMouseButtons();
  2143. if (now >= lastMouseTime + minTimeBetweenMouses)
  2144. {
  2145. lastMouseTime = now;
  2146. doMouseEvent (position, MouseInputSource::invalidPressure,
  2147. MouseInputSource::invalidOrientation, modsToSend);
  2148. }
  2149. }
  2150. void doMouseDown (Point<float> position, const WPARAM wParam)
  2151. {
  2152. // this will be handled by WM_TOUCH
  2153. if (isTouchEvent() || areOtherTouchSourcesActive())
  2154. return;
  2155. if (GetCapture() != hwnd)
  2156. SetCapture (hwnd);
  2157. doMouseMove (position, true);
  2158. if (isValidPeer (this))
  2159. {
  2160. updateModifiersFromWParam (wParam);
  2161. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2162. if (modProvider != nullptr)
  2163. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2164. #endif
  2165. isDragging = true;
  2166. doMouseEvent (position, MouseInputSource::invalidPressure);
  2167. }
  2168. }
  2169. void doMouseUp (Point<float> position, const WPARAM wParam)
  2170. {
  2171. // this will be handled by WM_TOUCH
  2172. if (isTouchEvent() || areOtherTouchSourcesActive())
  2173. return;
  2174. updateModifiersFromWParam (wParam);
  2175. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2176. if (modProvider != nullptr)
  2177. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2178. #endif
  2179. const bool wasDragging = isDragging;
  2180. isDragging = false;
  2181. // release the mouse capture if the user has released all buttons
  2182. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  2183. ReleaseCapture();
  2184. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  2185. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  2186. if (wasDragging)
  2187. doMouseEvent (position, MouseInputSource::invalidPressure);
  2188. }
  2189. void doCaptureChanged()
  2190. {
  2191. if (constrainerIsResizing)
  2192. {
  2193. if (constrainer != nullptr)
  2194. constrainer->resizeEnd();
  2195. constrainerIsResizing = false;
  2196. }
  2197. if (isDragging)
  2198. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  2199. }
  2200. void doMouseExit()
  2201. {
  2202. isMouseOver = false;
  2203. if (! areOtherTouchSourcesActive())
  2204. doMouseEvent (getCurrentMousePos(), MouseInputSource::invalidPressure);
  2205. }
  2206. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  2207. {
  2208. auto currentMousePos = getPOINTFromLParam (GetMessagePos());
  2209. // Because Windows stupidly sends all wheel events to the window with the keyboard
  2210. // focus, we have to redirect them here according to the mouse pos..
  2211. auto* peer = getOwnerOfWindow (WindowFromPoint (currentMousePos));
  2212. if (peer == nullptr)
  2213. peer = this;
  2214. localPos = peer->globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (currentMousePos), hwnd).toFloat());
  2215. return peer;
  2216. }
  2217. static MouseInputSource::InputSourceType getPointerType (WPARAM wParam)
  2218. {
  2219. if (getPointerTypeFunction != nullptr)
  2220. {
  2221. POINTER_INPUT_TYPE pointerType;
  2222. if (getPointerTypeFunction (GET_POINTERID_WPARAM (wParam), &pointerType))
  2223. {
  2224. if (pointerType == 2)
  2225. return MouseInputSource::InputSourceType::touch;
  2226. if (pointerType == 3)
  2227. return MouseInputSource::InputSourceType::pen;
  2228. }
  2229. }
  2230. return MouseInputSource::InputSourceType::mouse;
  2231. }
  2232. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  2233. {
  2234. updateKeyModifiers();
  2235. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  2236. MouseWheelDetails wheel;
  2237. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  2238. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  2239. wheel.isReversed = false;
  2240. wheel.isSmooth = false;
  2241. wheel.isInertial = false;
  2242. Point<float> localPos;
  2243. if (auto* peer = findPeerUnderMouse (localPos))
  2244. peer->handleMouseWheel (getPointerType (wParam), localPos, getMouseEventTime(), wheel);
  2245. }
  2246. bool doGestureEvent (LPARAM lParam)
  2247. {
  2248. GESTUREINFO gi;
  2249. zerostruct (gi);
  2250. gi.cbSize = sizeof (gi);
  2251. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  2252. {
  2253. updateKeyModifiers();
  2254. Point<float> localPos;
  2255. if (auto* peer = findPeerUnderMouse (localPos))
  2256. {
  2257. switch (gi.dwID)
  2258. {
  2259. case 3: /*GID_ZOOM*/
  2260. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  2261. peer->handleMagnifyGesture (MouseInputSource::InputSourceType::touch, localPos, getMouseEventTime(),
  2262. (float) (gi.ullArguments / (double) lastMagnifySize));
  2263. lastMagnifySize = gi.ullArguments;
  2264. return true;
  2265. case 4: /*GID_PAN*/
  2266. case 5: /*GID_ROTATE*/
  2267. case 6: /*GID_TWOFINGERTAP*/
  2268. case 7: /*GID_PRESSANDTAP*/
  2269. default:
  2270. break;
  2271. }
  2272. }
  2273. }
  2274. return false;
  2275. }
  2276. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  2277. {
  2278. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2279. if (auto* parent = getOwnerOfWindow (GetParent (hwnd)))
  2280. if (parent != this)
  2281. return parent->doTouchEvent (numInputs, eventHandle);
  2282. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  2283. if (getTouchInputInfo (eventHandle, (UINT) numInputs, inputInfo, sizeof (TOUCHINPUT)))
  2284. {
  2285. for (int i = 0; i < numInputs; ++i)
  2286. {
  2287. auto flags = inputInfo[i].dwFlags;
  2288. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  2289. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  2290. return 0; // abandon method if this window was deleted by the callback
  2291. }
  2292. }
  2293. closeTouchInputHandle (eventHandle);
  2294. return 0;
  2295. }
  2296. bool handleTouchInput (const TOUCHINPUT& touch, const bool isDown, const bool isUp,
  2297. const float touchPressure = MouseInputSource::invalidPressure,
  2298. const float orientation = 0.0f)
  2299. {
  2300. auto isCancel = false;
  2301. const auto touchIndex = currentTouches.getIndexOfTouch (this, touch.dwID);
  2302. const auto time = getMouseEventTime();
  2303. const auto pos = globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT ({ roundToInt (touch.x / 100.0f),
  2304. roundToInt (touch.y / 100.0f) }), hwnd).toFloat());
  2305. const auto pressure = touchPressure;
  2306. auto modsToSend = ModifierKeys::currentModifiers;
  2307. if (isDown)
  2308. {
  2309. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2310. modsToSend = ModifierKeys::currentModifiers;
  2311. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2312. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  2313. pressure, orientation, time, {}, touchIndex);
  2314. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2315. return false;
  2316. }
  2317. else if (isUp)
  2318. {
  2319. modsToSend = modsToSend.withoutMouseButtons();
  2320. ModifierKeys::currentModifiers = modsToSend;
  2321. currentTouches.clearTouch (touchIndex);
  2322. if (! currentTouches.areAnyTouchesActive())
  2323. isCancel = true;
  2324. }
  2325. else
  2326. {
  2327. modsToSend = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2328. }
  2329. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend,
  2330. pressure, orientation, time, {}, touchIndex);
  2331. if (! isValidPeer (this))
  2332. return false;
  2333. if (isUp)
  2334. {
  2335. handleMouseEvent (MouseInputSource::InputSourceType::touch, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers.withoutMouseButtons(),
  2336. pressure, orientation, time, {}, touchIndex);
  2337. if (! isValidPeer (this))
  2338. return false;
  2339. if (isCancel)
  2340. {
  2341. currentTouches.clear();
  2342. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2343. }
  2344. }
  2345. return true;
  2346. }
  2347. bool handlePointerInput (WPARAM wParam, LPARAM lParam, const bool isDown, const bool isUp)
  2348. {
  2349. if (! canUsePointerAPI)
  2350. return false;
  2351. auto pointerType = getPointerType (wParam);
  2352. if (pointerType == MouseInputSource::InputSourceType::touch)
  2353. {
  2354. POINTER_TOUCH_INFO touchInfo;
  2355. if (! getPointerTouchInfo (GET_POINTERID_WPARAM (wParam), &touchInfo))
  2356. return false;
  2357. const auto pressure = touchInfo.touchMask & TOUCH_MASK_PRESSURE ? touchInfo.pressure
  2358. : MouseInputSource::invalidPressure;
  2359. const auto orientation = touchInfo.touchMask & TOUCH_MASK_ORIENTATION ? degreesToRadians (static_cast<float> (touchInfo.orientation))
  2360. : MouseInputSource::invalidOrientation;
  2361. if (! handleTouchInput (emulateTouchEventFromPointer (touchInfo.pointerInfo.ptPixelLocationRaw, wParam),
  2362. isDown, isUp, pressure, orientation))
  2363. return false;
  2364. }
  2365. else if (pointerType == MouseInputSource::InputSourceType::pen)
  2366. {
  2367. POINTER_PEN_INFO penInfo;
  2368. if (! getPointerPenInfo (GET_POINTERID_WPARAM (wParam), &penInfo))
  2369. return false;
  2370. const auto pressure = (penInfo.penMask & PEN_MASK_PRESSURE) ? penInfo.pressure / 1024.0f : MouseInputSource::invalidPressure;
  2371. if (! handlePenInput (penInfo, globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (lParam)), hwnd).toFloat()),
  2372. pressure, isDown, isUp))
  2373. return false;
  2374. }
  2375. else
  2376. {
  2377. return false;
  2378. }
  2379. return true;
  2380. }
  2381. TOUCHINPUT emulateTouchEventFromPointer (POINT p, WPARAM wParam)
  2382. {
  2383. TOUCHINPUT touchInput;
  2384. touchInput.dwID = GET_POINTERID_WPARAM (wParam);
  2385. touchInput.x = p.x * 100;
  2386. touchInput.y = p.y * 100;
  2387. return touchInput;
  2388. }
  2389. bool handlePenInput (POINTER_PEN_INFO penInfo, Point<float> pos, const float pressure, bool isDown, bool isUp)
  2390. {
  2391. const auto time = getMouseEventTime();
  2392. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2393. PenDetails penDetails;
  2394. penDetails.rotation = (penInfo.penMask & PEN_MASK_ROTATION) ? degreesToRadians (static_cast<float> (penInfo.rotation)) : MouseInputSource::invalidRotation;
  2395. penDetails.tiltX = (penInfo.penMask & PEN_MASK_TILT_X) ? penInfo.tiltX / 90.0f : MouseInputSource::invalidTiltX;
  2396. penDetails.tiltY = (penInfo.penMask & PEN_MASK_TILT_Y) ? penInfo.tiltY / 90.0f : MouseInputSource::invalidTiltY;
  2397. auto pInfoFlags = penInfo.pointerInfo.pointerFlags;
  2398. if ((pInfoFlags & POINTER_FLAG_FIRSTBUTTON) != 0)
  2399. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2400. else if ((pInfoFlags & POINTER_FLAG_SECONDBUTTON) != 0)
  2401. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::rightButtonModifier);
  2402. if (isDown)
  2403. {
  2404. modsToSend = ModifierKeys::currentModifiers;
  2405. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2406. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend.withoutMouseButtons(),
  2407. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2408. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2409. return false;
  2410. }
  2411. else if (isUp || ! (pInfoFlags & POINTER_FLAG_INCONTACT))
  2412. {
  2413. modsToSend = modsToSend.withoutMouseButtons();
  2414. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2415. }
  2416. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend, pressure,
  2417. MouseInputSource::invalidOrientation, time, penDetails);
  2418. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2419. return false;
  2420. if (isUp)
  2421. {
  2422. handleMouseEvent (MouseInputSource::InputSourceType::pen, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  2423. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2424. if (! isValidPeer (this))
  2425. return false;
  2426. }
  2427. return true;
  2428. }
  2429. //==============================================================================
  2430. void sendModifierKeyChangeIfNeeded()
  2431. {
  2432. if (modifiersAtLastCallback != ModifierKeys::currentModifiers)
  2433. {
  2434. modifiersAtLastCallback = ModifierKeys::currentModifiers;
  2435. handleModifierKeysChange();
  2436. }
  2437. }
  2438. bool doKeyUp (const WPARAM key)
  2439. {
  2440. updateKeyModifiers();
  2441. switch (key)
  2442. {
  2443. case VK_SHIFT:
  2444. case VK_CONTROL:
  2445. case VK_MENU:
  2446. case VK_CAPITAL:
  2447. case VK_LWIN:
  2448. case VK_RWIN:
  2449. case VK_APPS:
  2450. case VK_NUMLOCK:
  2451. case VK_SCROLL:
  2452. case VK_LSHIFT:
  2453. case VK_RSHIFT:
  2454. case VK_LCONTROL:
  2455. case VK_LMENU:
  2456. case VK_RCONTROL:
  2457. case VK_RMENU:
  2458. sendModifierKeyChangeIfNeeded();
  2459. }
  2460. return handleKeyUpOrDown (false)
  2461. || Component::getCurrentlyModalComponent() != nullptr;
  2462. }
  2463. bool doKeyDown (const WPARAM key)
  2464. {
  2465. updateKeyModifiers();
  2466. bool used = false;
  2467. switch (key)
  2468. {
  2469. case VK_SHIFT:
  2470. case VK_LSHIFT:
  2471. case VK_RSHIFT:
  2472. case VK_CONTROL:
  2473. case VK_LCONTROL:
  2474. case VK_RCONTROL:
  2475. case VK_MENU:
  2476. case VK_LMENU:
  2477. case VK_RMENU:
  2478. case VK_LWIN:
  2479. case VK_RWIN:
  2480. case VK_CAPITAL:
  2481. case VK_NUMLOCK:
  2482. case VK_SCROLL:
  2483. case VK_APPS:
  2484. used = handleKeyUpOrDown (true);
  2485. sendModifierKeyChangeIfNeeded();
  2486. break;
  2487. case VK_LEFT:
  2488. case VK_RIGHT:
  2489. case VK_UP:
  2490. case VK_DOWN:
  2491. case VK_PRIOR:
  2492. case VK_NEXT:
  2493. case VK_HOME:
  2494. case VK_END:
  2495. case VK_DELETE:
  2496. case VK_INSERT:
  2497. case VK_F1:
  2498. case VK_F2:
  2499. case VK_F3:
  2500. case VK_F4:
  2501. case VK_F5:
  2502. case VK_F6:
  2503. case VK_F7:
  2504. case VK_F8:
  2505. case VK_F9:
  2506. case VK_F10:
  2507. case VK_F11:
  2508. case VK_F12:
  2509. case VK_F13:
  2510. case VK_F14:
  2511. case VK_F15:
  2512. case VK_F16:
  2513. case VK_F17:
  2514. case VK_F18:
  2515. case VK_F19:
  2516. case VK_F20:
  2517. case VK_F21:
  2518. case VK_F22:
  2519. case VK_F23:
  2520. case VK_F24:
  2521. used = handleKeyUpOrDown (true);
  2522. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  2523. break;
  2524. default:
  2525. used = handleKeyUpOrDown (true);
  2526. {
  2527. MSG msg;
  2528. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  2529. {
  2530. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  2531. // manually generate the key-press event that matches this key-down.
  2532. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  2533. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  2534. BYTE keyState[256];
  2535. GetKeyboardState (keyState);
  2536. WCHAR text[16] = { 0 };
  2537. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  2538. text[0] = 0;
  2539. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  2540. }
  2541. }
  2542. break;
  2543. }
  2544. return used || (Component::getCurrentlyModalComponent() != nullptr);
  2545. }
  2546. bool doKeyChar (int key, const LPARAM flags)
  2547. {
  2548. updateKeyModifiers();
  2549. auto textChar = (juce_wchar) key;
  2550. const int virtualScanCode = (flags >> 16) & 0xff;
  2551. if (key >= '0' && key <= '9')
  2552. {
  2553. switch (virtualScanCode) // check for a numeric keypad scan-code
  2554. {
  2555. case 0x52:
  2556. case 0x4f:
  2557. case 0x50:
  2558. case 0x51:
  2559. case 0x4b:
  2560. case 0x4c:
  2561. case 0x4d:
  2562. case 0x47:
  2563. case 0x48:
  2564. case 0x49:
  2565. key = (key - '0') + KeyPress::numberPad0;
  2566. break;
  2567. default:
  2568. break;
  2569. }
  2570. }
  2571. else
  2572. {
  2573. // convert the scan code to an unmodified character code..
  2574. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  2575. UINT keyChar = MapVirtualKey (virtualKey, 2);
  2576. keyChar = LOWORD (keyChar);
  2577. if (keyChar != 0)
  2578. key = (int) keyChar;
  2579. // avoid sending junk text characters for some control-key combinations
  2580. if (textChar < ' ' && ModifierKeys::currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  2581. textChar = 0;
  2582. }
  2583. return handleKeyPress (key, textChar);
  2584. }
  2585. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  2586. {
  2587. if (HWND parentH = GetParent (hwnd))
  2588. PostMessage (parentH, message, wParam, lParam);
  2589. }
  2590. bool doAppCommand (const LPARAM lParam)
  2591. {
  2592. int key = 0;
  2593. switch (GET_APPCOMMAND_LPARAM (lParam))
  2594. {
  2595. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  2596. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  2597. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  2598. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  2599. default: break;
  2600. }
  2601. if (key != 0)
  2602. {
  2603. updateKeyModifiers();
  2604. if (hwnd == GetActiveWindow())
  2605. return handleKeyPress (key, 0);
  2606. }
  2607. return false;
  2608. }
  2609. bool isConstrainedNativeWindow() const
  2610. {
  2611. return constrainer != nullptr
  2612. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  2613. && ! isKioskMode();
  2614. }
  2615. Rectangle<int> getCurrentScaledBounds() const
  2616. {
  2617. return ScalingHelpers::unscaledScreenPosToScaled (component, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (component, component.getBounds())));
  2618. }
  2619. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  2620. {
  2621. if (isConstrainedNativeWindow())
  2622. {
  2623. const auto logicalBounds = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r).toFloat(), hwnd);
  2624. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, logicalBounds).toNearestInt();
  2625. const auto original = getCurrentScaledBounds();
  2626. constrainer->checkBounds (pos, original,
  2627. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2628. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  2629. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  2630. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  2631. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  2632. r = RECTFromRectangle (convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos.toFloat()).toNearestInt(), hwnd));
  2633. }
  2634. return TRUE;
  2635. }
  2636. LRESULT handlePositionChanging (WINDOWPOS& wp)
  2637. {
  2638. if (isConstrainedNativeWindow())
  2639. {
  2640. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  2641. && (wp.x > -32000 && wp.y > -32000)
  2642. && ! Component::isMouseButtonDownAnywhere())
  2643. {
  2644. const auto logicalBounds = convertPhysicalScreenRectangleToLogical (rectangleFromRECT ({ wp.x, wp.y, wp.x + wp.cx, wp.y + wp.cy }).toFloat(), hwnd);
  2645. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, logicalBounds).toNearestInt();
  2646. const auto original = getCurrentScaledBounds();
  2647. constrainer->checkBounds (pos, original,
  2648. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2649. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  2650. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  2651. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  2652. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  2653. auto physicalBounds = convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos.toFloat()), hwnd);
  2654. auto getNewPositionIfNotRoundingError = [] (int pos, float newPos)
  2655. {
  2656. return (std::abs ((float) pos - newPos) >= 1.0f) ? roundToInt (newPos) : pos;
  2657. };
  2658. wp.x = getNewPositionIfNotRoundingError (wp.x, physicalBounds.getX());
  2659. wp.y = getNewPositionIfNotRoundingError (wp.y, physicalBounds.getY());
  2660. wp.cx = getNewPositionIfNotRoundingError (wp.cx, physicalBounds.getWidth());
  2661. wp.cy = getNewPositionIfNotRoundingError (wp.cy, physicalBounds.getHeight());
  2662. }
  2663. }
  2664. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  2665. component.setVisible (true);
  2666. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  2667. component.setVisible (false);
  2668. return 0;
  2669. }
  2670. bool handlePositionChanged()
  2671. {
  2672. auto pos = getCurrentMousePos();
  2673. if (contains (pos.roundToInt(), false))
  2674. {
  2675. if (! areOtherTouchSourcesActive())
  2676. doMouseEvent (pos, MouseInputSource::invalidPressure);
  2677. if (! isValidPeer (this))
  2678. return true;
  2679. }
  2680. handleMovedOrResized();
  2681. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly..
  2682. }
  2683. //==============================================================================
  2684. struct ChildWindowCallbackData
  2685. {
  2686. std::map<HWND, RECT> windowRectsMap;
  2687. float scaleRatio;
  2688. };
  2689. LRESULT handleDPIChanging (int newDPI, RECT newRect)
  2690. {
  2691. auto newScale = (double) newDPI / USER_DEFAULT_SCREEN_DPI;
  2692. if (! approximatelyEqual (scaleFactor, newScale))
  2693. {
  2694. auto oldScale = scaleFactor;
  2695. scaleFactor = newScale;
  2696. {
  2697. const ScopedValueSetter<bool> setter (isInDPIChange, true);
  2698. setBounds (windowBorder.subtractedFrom (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (newRect), hwnd)), fullScreen);
  2699. }
  2700. updateShadower();
  2701. InvalidateRect (hwnd, nullptr, FALSE);
  2702. ChildWindowCallbackData callbackData;
  2703. callbackData.scaleRatio = (float) (scaleFactor / oldScale);
  2704. EnumChildWindows (hwnd, getChildWindowRectCallback, (LPARAM) &callbackData);
  2705. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  2706. EnumChildWindows (hwnd, scaleChildWindowCallback, (LPARAM) &callbackData);
  2707. }
  2708. return 0;
  2709. }
  2710. static BOOL CALLBACK getChildWindowRectCallback (HWND hwnd, LPARAM data)
  2711. {
  2712. auto& callbackData = *(reinterpret_cast<ChildWindowCallbackData*> (data));
  2713. callbackData.windowRectsMap[hwnd] = getWindowClientRect (hwnd);
  2714. return TRUE;
  2715. }
  2716. static BOOL CALLBACK scaleChildWindowCallback (HWND hwnd, LPARAM data)
  2717. {
  2718. auto& callbackData = *(reinterpret_cast<ChildWindowCallbackData*> (data));
  2719. auto originalBounds = rectangleFromRECT (callbackData.windowRectsMap[hwnd]);
  2720. auto scaledBounds = (originalBounds.toFloat() * callbackData.scaleRatio).toNearestInt();
  2721. auto currentBounds = rectangleFromRECT (getWindowClientRect (hwnd));
  2722. if (scaledBounds != currentBounds)
  2723. {
  2724. SetWindowPos (hwnd,
  2725. nullptr,
  2726. scaledBounds.getX(),
  2727. scaledBounds.getY(),
  2728. scaledBounds.getWidth(),
  2729. scaledBounds.getHeight(),
  2730. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  2731. }
  2732. if (auto* peer = getOwnerOfWindow (hwnd))
  2733. peer->handleChildDPIChanging();
  2734. return TRUE;
  2735. }
  2736. void handleChildDPIChanging()
  2737. {
  2738. scaleFactor = getScaleFactorForWindow (parentToAddTo);
  2739. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  2740. updateShadower();
  2741. InvalidateRect (hwnd, nullptr, FALSE);
  2742. }
  2743. //==============================================================================
  2744. void handleAppActivation (const WPARAM wParam)
  2745. {
  2746. modifiersAtLastCallback = -1;
  2747. updateKeyModifiers();
  2748. if (isMinimised())
  2749. {
  2750. component.repaint();
  2751. handleMovedOrResized();
  2752. if (! isValidPeer (this))
  2753. return;
  2754. }
  2755. auto* underMouse = component.getComponentAt (component.getMouseXYRelative());
  2756. if (underMouse == nullptr)
  2757. underMouse = &component;
  2758. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  2759. {
  2760. if (LOWORD (wParam) == WA_CLICKACTIVE)
  2761. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  2762. else
  2763. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  2764. }
  2765. else
  2766. {
  2767. handleBroughtToFront();
  2768. }
  2769. }
  2770. void handlePowerBroadcast (WPARAM wParam)
  2771. {
  2772. if (auto* app = JUCEApplicationBase::getInstance())
  2773. {
  2774. switch (wParam)
  2775. {
  2776. case PBT_APMSUSPEND: app->suspended(); break;
  2777. case PBT_APMQUERYSUSPENDFAILED:
  2778. case PBT_APMRESUMECRITICAL:
  2779. case PBT_APMRESUMESUSPEND:
  2780. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  2781. default: break;
  2782. }
  2783. }
  2784. }
  2785. void handleLeftClickInNCArea (WPARAM wParam)
  2786. {
  2787. if (! sendInputAttemptWhenModalMessage())
  2788. {
  2789. switch (wParam)
  2790. {
  2791. case HTBOTTOM:
  2792. case HTBOTTOMLEFT:
  2793. case HTBOTTOMRIGHT:
  2794. case HTGROWBOX:
  2795. case HTLEFT:
  2796. case HTRIGHT:
  2797. case HTTOP:
  2798. case HTTOPLEFT:
  2799. case HTTOPRIGHT:
  2800. if (isConstrainedNativeWindow())
  2801. {
  2802. constrainerIsResizing = true;
  2803. constrainer->resizeStart();
  2804. }
  2805. break;
  2806. default:
  2807. break;
  2808. }
  2809. }
  2810. }
  2811. void initialiseSysMenu (HMENU menu) const
  2812. {
  2813. if (! hasTitleBar())
  2814. {
  2815. if (isFullScreen())
  2816. {
  2817. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  2818. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  2819. }
  2820. else if (! isMinimised())
  2821. {
  2822. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  2823. }
  2824. }
  2825. }
  2826. void doSettingChange()
  2827. {
  2828. forceDisplayUpdate();
  2829. if (fullScreen && ! isMinimised())
  2830. setWindowPos (hwnd, ScalingHelpers::scaledScreenPosToUnscaled (component, Desktop::getInstance().getDisplays()
  2831. .getDisplayForRect (component.getScreenBounds())->userArea),
  2832. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  2833. }
  2834. //==============================================================================
  2835. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2836. void setModifierKeyProvider (ModifierKeyProvider* provider) override
  2837. {
  2838. modProvider = provider;
  2839. }
  2840. void removeModifierKeyProvider() override
  2841. {
  2842. modProvider = nullptr;
  2843. }
  2844. #endif
  2845. public:
  2846. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2847. {
  2848. // Ensure that non-client areas are scaled for per-monitor DPI awareness v1 - can't
  2849. // do this in peerWindowProc as we have no window at this point
  2850. if (message == WM_NCCREATE && enableNonClientDPIScaling != nullptr)
  2851. enableNonClientDPIScaling (h);
  2852. if (auto* peer = getOwnerOfWindow (h))
  2853. {
  2854. jassert (isValidPeer (peer));
  2855. return peer->peerWindowProc (h, message, wParam, lParam);
  2856. }
  2857. return DefWindowProcW (h, message, wParam, lParam);
  2858. }
  2859. private:
  2860. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  2861. {
  2862. auto& mm = *MessageManager::getInstance();
  2863. if (mm.currentThreadHasLockedMessageManager())
  2864. return callback (userData);
  2865. return mm.callFunctionOnMessageThread (callback, userData);
  2866. }
  2867. static POINT getPOINTFromLParam (LPARAM lParam) noexcept
  2868. {
  2869. return { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
  2870. }
  2871. Point<float> getPointFromLocalLParam (LPARAM lParam) noexcept
  2872. {
  2873. auto p = pointFromPOINT (getPOINTFromLParam (lParam));
  2874. if (isPerMonitorDPIAwareWindow (hwnd))
  2875. {
  2876. // LPARAM is relative to this window's top-left but may be on a different monitor so we need to calculate the
  2877. // physical screen position and then convert this to local logical coordinates
  2878. auto r = getWindowScreenRect (hwnd);
  2879. return globalToLocal (Desktop::getInstance().getDisplays().physicalToLogical (pointFromPOINT ({ r.left + p.x + roundToInt (windowBorder.getLeft() * scaleFactor),
  2880. r.top + p.y + roundToInt (windowBorder.getTop() * scaleFactor) })).toFloat());
  2881. }
  2882. return p.toFloat();
  2883. }
  2884. Point<float> getCurrentMousePos() noexcept
  2885. {
  2886. return globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (GetMessagePos())), hwnd).toFloat());
  2887. }
  2888. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2889. {
  2890. switch (message)
  2891. {
  2892. //==============================================================================
  2893. case WM_NCHITTEST:
  2894. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2895. return HTTRANSPARENT;
  2896. if (! hasTitleBar())
  2897. return HTCLIENT;
  2898. break;
  2899. //==============================================================================
  2900. case WM_PAINT:
  2901. handlePaintMessage();
  2902. return 0;
  2903. case WM_NCPAINT:
  2904. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  2905. if (hasTitleBar())
  2906. break; // let the DefWindowProc handle drawing the frame.
  2907. return 0;
  2908. case WM_ERASEBKGND:
  2909. case WM_NCCALCSIZE:
  2910. if (hasTitleBar())
  2911. break;
  2912. return 1;
  2913. //==============================================================================
  2914. case WM_POINTERUPDATE:
  2915. if (handlePointerInput (wParam, lParam, false, false))
  2916. return 0;
  2917. break;
  2918. case WM_POINTERDOWN:
  2919. if (handlePointerInput (wParam, lParam, true, false))
  2920. return 0;
  2921. break;
  2922. case WM_POINTERUP:
  2923. if (handlePointerInput (wParam, lParam, false, true))
  2924. return 0;
  2925. break;
  2926. //==============================================================================
  2927. case WM_MOUSEMOVE: doMouseMove (getPointFromLocalLParam (lParam), false); return 0;
  2928. case WM_POINTERLEAVE:
  2929. case WM_MOUSELEAVE: doMouseExit(); return 0;
  2930. case WM_LBUTTONDOWN:
  2931. case WM_MBUTTONDOWN:
  2932. case WM_RBUTTONDOWN: doMouseDown (getPointFromLocalLParam (lParam), wParam); return 0;
  2933. case WM_LBUTTONUP:
  2934. case WM_MBUTTONUP:
  2935. case WM_RBUTTONUP: doMouseUp (getPointFromLocalLParam (lParam), wParam); return 0;
  2936. case WM_POINTERWHEEL:
  2937. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  2938. case WM_POINTERHWHEEL:
  2939. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  2940. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  2941. case WM_NCPOINTERUPDATE:
  2942. case WM_NCMOUSEMOVE:
  2943. if (hasTitleBar())
  2944. break;
  2945. return 0;
  2946. case WM_TOUCH:
  2947. if (getTouchInputInfo != nullptr)
  2948. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  2949. break;
  2950. case 0x119: /* WM_GESTURE */
  2951. if (doGestureEvent (lParam))
  2952. return 0;
  2953. break;
  2954. //==============================================================================
  2955. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  2956. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  2957. case 0x2e0: /* WM_DPICHANGED */ return handleDPIChanging ((int) HIWORD (wParam), *(RECT*) lParam);
  2958. case WM_WINDOWPOSCHANGED:
  2959. {
  2960. const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
  2961. if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
  2962. startTimer (100);
  2963. else
  2964. if (handlePositionChanged())
  2965. return 0;
  2966. }
  2967. break;
  2968. //==============================================================================
  2969. case WM_KEYDOWN:
  2970. case WM_SYSKEYDOWN:
  2971. if (doKeyDown (wParam))
  2972. return 0;
  2973. forwardMessageToParent (message, wParam, lParam);
  2974. break;
  2975. case WM_KEYUP:
  2976. case WM_SYSKEYUP:
  2977. if (doKeyUp (wParam))
  2978. return 0;
  2979. forwardMessageToParent (message, wParam, lParam);
  2980. break;
  2981. case WM_CHAR:
  2982. if (doKeyChar ((int) wParam, lParam))
  2983. return 0;
  2984. forwardMessageToParent (message, wParam, lParam);
  2985. break;
  2986. case WM_APPCOMMAND:
  2987. if (doAppCommand (lParam))
  2988. return TRUE;
  2989. break;
  2990. case WM_MENUCHAR: // triggered when alt+something is pressed
  2991. return MNC_CLOSE << 16; // (avoids making the default system beep)
  2992. //==============================================================================
  2993. case WM_SETFOCUS:
  2994. updateKeyModifiers();
  2995. handleFocusGain();
  2996. break;
  2997. case WM_KILLFOCUS:
  2998. if (hasCreatedCaret)
  2999. {
  3000. hasCreatedCaret = false;
  3001. DestroyCaret();
  3002. }
  3003. handleFocusLoss();
  3004. break;
  3005. case WM_ACTIVATEAPP:
  3006. // Windows does weird things to process priority when you swap apps,
  3007. // so this forces an update when the app is brought to the front
  3008. if (wParam != FALSE)
  3009. juce_repeatLastProcessPriority();
  3010. else
  3011. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  3012. juce_checkCurrentlyFocusedTopLevelWindow();
  3013. modifiersAtLastCallback = -1;
  3014. return 0;
  3015. case WM_ACTIVATE:
  3016. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  3017. {
  3018. handleAppActivation (wParam);
  3019. return 0;
  3020. }
  3021. break;
  3022. case WM_NCACTIVATE:
  3023. // while a temporary window is being shown, prevent Windows from deactivating the
  3024. // title bars of our main windows.
  3025. if (wParam == 0 && ! shouldDeactivateTitleBar)
  3026. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  3027. break;
  3028. case WM_POINTERACTIVATE:
  3029. case WM_MOUSEACTIVATE:
  3030. if (! component.getMouseClickGrabsKeyboardFocus())
  3031. return MA_NOACTIVATE;
  3032. break;
  3033. case WM_SHOWWINDOW:
  3034. if (wParam != 0)
  3035. {
  3036. component.setVisible (true);
  3037. handleBroughtToFront();
  3038. }
  3039. break;
  3040. case WM_CLOSE:
  3041. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  3042. handleUserClosingWindow();
  3043. return 0;
  3044. #if JUCE_REMOVE_COMPONENT_FROM_DESKTOP_ON_WM_DESTROY
  3045. case WM_DESTROY:
  3046. getComponent().removeFromDesktop();
  3047. return 0;
  3048. #endif
  3049. case WM_QUERYENDSESSION:
  3050. if (auto* app = JUCEApplicationBase::getInstance())
  3051. {
  3052. app->systemRequestedQuit();
  3053. return MessageManager::getInstance()->hasStopMessageBeenSent();
  3054. }
  3055. return TRUE;
  3056. case WM_POWERBROADCAST:
  3057. handlePowerBroadcast (wParam);
  3058. break;
  3059. case WM_SYNCPAINT:
  3060. return 0;
  3061. case WM_DISPLAYCHANGE:
  3062. InvalidateRect (h, nullptr, 0);
  3063. // intentional fall-through...
  3064. JUCE_FALLTHROUGH
  3065. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  3066. doSettingChange();
  3067. break;
  3068. case WM_INITMENU:
  3069. initialiseSysMenu ((HMENU) wParam);
  3070. break;
  3071. case WM_SYSCOMMAND:
  3072. switch (wParam & 0xfff0)
  3073. {
  3074. case SC_CLOSE:
  3075. if (sendInputAttemptWhenModalMessage())
  3076. return 0;
  3077. if (hasTitleBar())
  3078. {
  3079. PostMessage (h, WM_CLOSE, 0, 0);
  3080. return 0;
  3081. }
  3082. break;
  3083. case SC_KEYMENU:
  3084. #if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
  3085. // This test prevents a press of the ALT key from triggering the ancient top-left window menu.
  3086. // By default we suppress this behaviour because it's unlikely that more than a tiny subset of
  3087. // our users will actually want it, and it causes problems if you're trying to use the ALT key
  3088. // as a modifier for mouse actions. If you really need the old behaviour, then just define
  3089. // JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
  3090. if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
  3091. return 0;
  3092. #endif
  3093. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  3094. // situations that can arise if a modal loop is started from an alt-key keypress).
  3095. if (hasTitleBar() && h == GetCapture())
  3096. ReleaseCapture();
  3097. break;
  3098. case SC_MAXIMIZE:
  3099. if (! sendInputAttemptWhenModalMessage())
  3100. setFullScreen (true);
  3101. return 0;
  3102. case SC_MINIMIZE:
  3103. if (sendInputAttemptWhenModalMessage())
  3104. return 0;
  3105. if (! hasTitleBar())
  3106. {
  3107. setMinimised (true);
  3108. return 0;
  3109. }
  3110. break;
  3111. case SC_RESTORE:
  3112. if (sendInputAttemptWhenModalMessage())
  3113. return 0;
  3114. if (hasTitleBar())
  3115. {
  3116. if (isFullScreen())
  3117. {
  3118. setFullScreen (false);
  3119. return 0;
  3120. }
  3121. }
  3122. else
  3123. {
  3124. if (isMinimised())
  3125. setMinimised (false);
  3126. else if (isFullScreen())
  3127. setFullScreen (false);
  3128. return 0;
  3129. }
  3130. break;
  3131. }
  3132. break;
  3133. case WM_NCPOINTERDOWN:
  3134. case WM_NCLBUTTONDOWN:
  3135. handleLeftClickInNCArea (wParam);
  3136. break;
  3137. case WM_NCRBUTTONDOWN:
  3138. case WM_NCMBUTTONDOWN:
  3139. sendInputAttemptWhenModalMessage();
  3140. break;
  3141. case WM_IME_SETCONTEXT:
  3142. imeHandler.handleSetContext (h, wParam == TRUE);
  3143. lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  3144. break;
  3145. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  3146. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  3147. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  3148. case WM_GETDLGCODE:
  3149. return DLGC_WANTALLKEYS;
  3150. case WM_GETOBJECT:
  3151. {
  3152. if (static_cast<long> (lParam) == WindowsAccessibility::getUiaRootObjectId())
  3153. {
  3154. if (auto* handler = component.getAccessibilityHandler())
  3155. {
  3156. LRESULT res = 0;
  3157. if (WindowsAccessibility::handleWmGetObject (handler, wParam, lParam, &res))
  3158. {
  3159. isAccessibilityActive = true;
  3160. return res;
  3161. }
  3162. }
  3163. }
  3164. break;
  3165. }
  3166. default:
  3167. break;
  3168. }
  3169. return DefWindowProcW (h, message, wParam, lParam);
  3170. }
  3171. bool sendInputAttemptWhenModalMessage()
  3172. {
  3173. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  3174. return false;
  3175. if (auto* current = Component::getCurrentlyModalComponent())
  3176. current->inputAttemptWhenModal();
  3177. return true;
  3178. }
  3179. //==============================================================================
  3180. struct IMEHandler
  3181. {
  3182. IMEHandler()
  3183. {
  3184. reset();
  3185. }
  3186. void handleSetContext (HWND hWnd, const bool windowIsActive)
  3187. {
  3188. if (compositionInProgress && ! windowIsActive)
  3189. {
  3190. compositionInProgress = false;
  3191. if (HIMC hImc = ImmGetContext (hWnd))
  3192. {
  3193. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  3194. ImmReleaseContext (hWnd, hImc);
  3195. }
  3196. }
  3197. }
  3198. void handleStartComposition (ComponentPeer& owner)
  3199. {
  3200. reset();
  3201. if (auto* target = owner.findCurrentTextInputTarget())
  3202. target->insertTextAtCaret (String());
  3203. }
  3204. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  3205. {
  3206. if (compositionInProgress)
  3207. {
  3208. // If this occurs, the user has cancelled the composition, so clear their changes..
  3209. if (auto* target = owner.findCurrentTextInputTarget())
  3210. {
  3211. target->setHighlightedRegion (compositionRange);
  3212. target->insertTextAtCaret (String());
  3213. compositionRange.setLength (0);
  3214. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  3215. target->setTemporaryUnderlining ({});
  3216. }
  3217. if (auto hImc = ImmGetContext (hWnd))
  3218. {
  3219. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  3220. ImmReleaseContext (hWnd, hImc);
  3221. }
  3222. }
  3223. reset();
  3224. }
  3225. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  3226. {
  3227. if (auto* target = owner.findCurrentTextInputTarget())
  3228. {
  3229. if (auto hImc = ImmGetContext (hWnd))
  3230. {
  3231. if (compositionRange.getStart() < 0)
  3232. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  3233. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  3234. {
  3235. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  3236. Range<int>::emptyRange (-1));
  3237. reset();
  3238. target->setTemporaryUnderlining ({});
  3239. }
  3240. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  3241. {
  3242. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  3243. getCompositionSelection (hImc, lParam));
  3244. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  3245. compositionInProgress = true;
  3246. }
  3247. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  3248. ImmReleaseContext (hWnd, hImc);
  3249. }
  3250. }
  3251. }
  3252. private:
  3253. //==============================================================================
  3254. Range<int> compositionRange; // The range being modified in the TextInputTarget
  3255. bool compositionInProgress;
  3256. //==============================================================================
  3257. void reset()
  3258. {
  3259. compositionRange = Range<int>::emptyRange (-1);
  3260. compositionInProgress = false;
  3261. }
  3262. String getCompositionString (HIMC hImc, const DWORD type) const
  3263. {
  3264. jassert (hImc != nullptr);
  3265. const auto stringSizeBytes = ImmGetCompositionString (hImc, type, nullptr, 0);
  3266. if (stringSizeBytes > 0)
  3267. {
  3268. HeapBlock<TCHAR> buffer;
  3269. buffer.calloc ((size_t) stringSizeBytes / sizeof (TCHAR) + 1);
  3270. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  3271. return String (buffer.get());
  3272. }
  3273. return {};
  3274. }
  3275. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  3276. {
  3277. jassert (hImc != nullptr);
  3278. if ((lParam & CS_NOMOVECARET) != 0)
  3279. return compositionRange.getStart();
  3280. if ((lParam & GCS_CURSORPOS) != 0)
  3281. {
  3282. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, nullptr, 0);
  3283. return compositionRange.getStart() + jmax (0, localCaretPos);
  3284. }
  3285. return compositionRange.getStart() + currentIMEString.length();
  3286. }
  3287. // Get selected/highlighted range while doing composition:
  3288. // returned range is relative to beginning of TextInputTarget, not composition string
  3289. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  3290. {
  3291. jassert (hImc != nullptr);
  3292. int selectionStart = 0;
  3293. int selectionEnd = 0;
  3294. if ((lParam & GCS_COMPATTR) != 0)
  3295. {
  3296. // Get size of attributes array:
  3297. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, nullptr, 0);
  3298. if (attributeSizeBytes > 0)
  3299. {
  3300. // Get attributes (8 bit flag per character):
  3301. HeapBlock<char> attributes (attributeSizeBytes);
  3302. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  3303. selectionStart = 0;
  3304. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  3305. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  3306. break;
  3307. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  3308. if (attributes[selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  3309. break;
  3310. }
  3311. }
  3312. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  3313. }
  3314. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  3315. {
  3316. if (compositionInProgress)
  3317. target->setHighlightedRegion (compositionRange);
  3318. target->insertTextAtCaret (newContent);
  3319. compositionRange.setLength (newContent.length());
  3320. if (newSelection.getStart() < 0)
  3321. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  3322. target->setHighlightedRegion (newSelection);
  3323. }
  3324. Array<Range<int>> getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  3325. {
  3326. Array<Range<int>> result;
  3327. if (hImc != nullptr && (lParam & GCS_COMPCLAUSE) != 0)
  3328. {
  3329. auto clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, nullptr, 0);
  3330. if (clauseDataSizeBytes > 0)
  3331. {
  3332. const auto numItems = (size_t) clauseDataSizeBytes / sizeof (uint32);
  3333. HeapBlock<uint32> clauseData (numItems);
  3334. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  3335. for (size_t i = 0; i + 1 < numItems; ++i)
  3336. result.add (Range<int> ((int) clauseData[i], (int) clauseData[i + 1]) + compositionRange.getStart());
  3337. }
  3338. }
  3339. return result;
  3340. }
  3341. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  3342. {
  3343. if (auto* targetComp = dynamic_cast<Component*> (target))
  3344. {
  3345. auto area = peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle());
  3346. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  3347. ImmSetCandidateWindow (hImc, &pos);
  3348. }
  3349. }
  3350. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  3351. };
  3352. void timerCallback() override
  3353. {
  3354. handlePositionChanged();
  3355. stopTimer();
  3356. }
  3357. static bool isAncestor (HWND outer, HWND inner)
  3358. {
  3359. if (outer == nullptr || inner == nullptr)
  3360. return false;
  3361. if (outer == inner)
  3362. return true;
  3363. return isAncestor (outer, GetAncestor (inner, GA_PARENT));
  3364. }
  3365. void windowShouldDismissModals (HWND originator)
  3366. {
  3367. if (component.isShowing() && isAncestor (originator, hwnd))
  3368. sendInputAttemptWhenModalMessage();
  3369. }
  3370. // Unfortunately SetWindowsHookEx only allows us to register a static function as a hook.
  3371. // To get around this, we keep a static list of listeners which are interested in
  3372. // top-level window events, and notify all of these listeners from the callback.
  3373. class TopLevelModalDismissBroadcaster
  3374. {
  3375. public:
  3376. TopLevelModalDismissBroadcaster()
  3377. : hook (SetWindowsHookEx (WH_CALLWNDPROC,
  3378. callWndProc,
  3379. (HINSTANCE) juce::Process::getCurrentModuleInstanceHandle(),
  3380. GetCurrentThreadId()))
  3381. {}
  3382. ~TopLevelModalDismissBroadcaster() noexcept
  3383. {
  3384. UnhookWindowsHookEx (hook);
  3385. }
  3386. private:
  3387. static void processMessage (int nCode, const CWPSTRUCT* info)
  3388. {
  3389. if (nCode < 0 || info == nullptr)
  3390. return;
  3391. constexpr UINT events[] { WM_MOVE,
  3392. WM_SIZE,
  3393. WM_WINDOWPOSCHANGING,
  3394. WM_NCPOINTERDOWN,
  3395. WM_NCLBUTTONDOWN,
  3396. WM_NCRBUTTONDOWN,
  3397. WM_NCMBUTTONDOWN };
  3398. if (std::find (std::begin (events), std::end (events), info->message) == std::end (events))
  3399. return;
  3400. if (info->message == WM_WINDOWPOSCHANGING)
  3401. {
  3402. const auto* windowPos = reinterpret_cast<const WINDOWPOS*> (info->lParam);
  3403. const auto windowPosFlags = windowPos->flags;
  3404. constexpr auto maskToCheck = SWP_NOMOVE | SWP_NOSIZE;
  3405. if ((windowPosFlags & maskToCheck) == maskToCheck)
  3406. return;
  3407. }
  3408. // windowMayDismissModals could affect the number of active ComponentPeer instances
  3409. for (auto i = ComponentPeer::getNumPeers(); --i >= 0;)
  3410. if (i < ComponentPeer::getNumPeers())
  3411. if (auto* hwndPeer = dynamic_cast<HWNDComponentPeer*> (ComponentPeer::getPeer (i)))
  3412. hwndPeer->windowShouldDismissModals (info->hwnd);
  3413. }
  3414. static LRESULT CALLBACK callWndProc (int nCode, WPARAM wParam, LPARAM lParam)
  3415. {
  3416. processMessage (nCode, reinterpret_cast<CWPSTRUCT*> (lParam));
  3417. return CallNextHookEx ({}, nCode, wParam, lParam);
  3418. }
  3419. HHOOK hook;
  3420. };
  3421. SharedResourcePointer<TopLevelModalDismissBroadcaster> modalDismissBroadcaster;
  3422. IMEHandler imeHandler;
  3423. //==============================================================================
  3424. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  3425. };
  3426. MultiTouchMapper<DWORD> HWNDComponentPeer::currentTouches;
  3427. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  3428. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  3429. {
  3430. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  3431. }
  3432. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  3433. {
  3434. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  3435. (HWND) parentHWND, true);
  3436. }
  3437. JUCE_IMPLEMENT_SINGLETON (HWNDComponentPeer::WindowClassHolder)
  3438. //==============================================================================
  3439. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  3440. {
  3441. auto k = (SHORT) keyCode;
  3442. if ((keyCode & extendedKeyModifier) == 0)
  3443. {
  3444. if (k >= (SHORT) 'a' && k <= (SHORT) 'z')
  3445. k += (SHORT) 'A' - (SHORT) 'a';
  3446. // Only translate if extendedKeyModifier flag is not set
  3447. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  3448. (SHORT) '+', VK_OEM_PLUS,
  3449. (SHORT) '-', VK_OEM_MINUS,
  3450. (SHORT) '.', VK_OEM_PERIOD,
  3451. (SHORT) ';', VK_OEM_1,
  3452. (SHORT) ':', VK_OEM_1,
  3453. (SHORT) '/', VK_OEM_2,
  3454. (SHORT) '?', VK_OEM_2,
  3455. (SHORT) '[', VK_OEM_4,
  3456. (SHORT) ']', VK_OEM_6 };
  3457. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  3458. if (k == translatedValues[i])
  3459. k = translatedValues[i + 1];
  3460. }
  3461. return HWNDComponentPeer::isKeyDown (k);
  3462. }
  3463. // (This internal function is used by the plugin client module)
  3464. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  3465. //==============================================================================
  3466. bool JUCE_CALLTYPE Process::isForegroundProcess()
  3467. {
  3468. if (auto fg = GetForegroundWindow())
  3469. {
  3470. DWORD processID = 0;
  3471. GetWindowThreadProcessId (fg, &processID);
  3472. return processID == GetCurrentProcessId();
  3473. }
  3474. return true;
  3475. }
  3476. // N/A on Windows as far as I know.
  3477. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  3478. void JUCE_CALLTYPE Process::hide() {}
  3479. //==============================================================================
  3480. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  3481. {
  3482. if (IsWindowVisible (hwnd))
  3483. {
  3484. DWORD processID = 0;
  3485. GetWindowThreadProcessId (hwnd, &processID);
  3486. if (processID == GetCurrentProcessId())
  3487. {
  3488. WINDOWINFO info;
  3489. if (GetWindowInfo (hwnd, &info)
  3490. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  3491. {
  3492. *reinterpret_cast<bool*> (lParam) = true;
  3493. return FALSE;
  3494. }
  3495. }
  3496. }
  3497. return TRUE;
  3498. }
  3499. bool juce_areThereAnyAlwaysOnTopWindows()
  3500. {
  3501. bool anyAlwaysOnTopFound = false;
  3502. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  3503. return anyAlwaysOnTopFound;
  3504. }
  3505. //==============================================================================
  3506. class WindowsMessageBox : public AsyncUpdater
  3507. {
  3508. public:
  3509. WindowsMessageBox (AlertWindow::AlertIconType iconType,
  3510. const String& boxTitle, const String& m,
  3511. Component* associatedComponent, UINT extraFlags,
  3512. ModalComponentManager::Callback* cb, const bool runAsync)
  3513. : flags (extraFlags | getMessageBoxFlags (iconType)),
  3514. owner (getWindowForMessageBox (associatedComponent)),
  3515. title (boxTitle), message (m), callback (cb)
  3516. {
  3517. if (runAsync)
  3518. triggerAsyncUpdate();
  3519. }
  3520. int getResult() const
  3521. {
  3522. const int r = MessageBox (owner, message.toWideCharPointer(), title.toWideCharPointer(), flags);
  3523. return (r == IDYES || r == IDOK) ? 1 : (r == IDNO && (flags & 1) != 0 ? 2 : 0);
  3524. }
  3525. void handleAsyncUpdate() override
  3526. {
  3527. const int result = getResult();
  3528. if (callback != nullptr)
  3529. callback->modalStateFinished (result);
  3530. delete this;
  3531. }
  3532. private:
  3533. UINT flags;
  3534. HWND owner;
  3535. String title, message;
  3536. std::unique_ptr<ModalComponentManager::Callback> callback;
  3537. static UINT getMessageBoxFlags (AlertWindow::AlertIconType iconType) noexcept
  3538. {
  3539. UINT flags = MB_TASKMODAL | MB_SETFOREGROUND;
  3540. // this window can get lost behind JUCE windows which are set to be alwaysOnTop
  3541. // so if there are any set it to be topmost
  3542. if (juce_areThereAnyAlwaysOnTopWindows())
  3543. flags |= MB_TOPMOST;
  3544. switch (iconType)
  3545. {
  3546. case AlertWindow::QuestionIcon: flags |= MB_ICONQUESTION; break;
  3547. case AlertWindow::WarningIcon: flags |= MB_ICONWARNING; break;
  3548. case AlertWindow::InfoIcon: flags |= MB_ICONINFORMATION; break;
  3549. case AlertWindow::NoIcon: JUCE_FALLTHROUGH
  3550. default: break;
  3551. }
  3552. return flags;
  3553. }
  3554. static HWND getWindowForMessageBox (Component* associatedComponent)
  3555. {
  3556. return associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : nullptr;
  3557. }
  3558. };
  3559. #if JUCE_MODAL_LOOPS_PERMITTED
  3560. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3561. const String& title, const String& message,
  3562. Component* associatedComponent)
  3563. {
  3564. WindowsMessageBox box (iconType, title, message, associatedComponent, MB_OK, nullptr, false);
  3565. (void) box.getResult();
  3566. }
  3567. #endif
  3568. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3569. const String& title, const String& message,
  3570. Component* associatedComponent,
  3571. ModalComponentManager::Callback* callback)
  3572. {
  3573. new WindowsMessageBox (iconType, title, message, associatedComponent, MB_OK, callback, true);
  3574. }
  3575. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3576. const String& title, const String& message,
  3577. Component* associatedComponent,
  3578. ModalComponentManager::Callback* callback)
  3579. {
  3580. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3581. MB_OKCANCEL, callback, callback != nullptr));
  3582. if (callback == nullptr)
  3583. return mb->getResult() != 0;
  3584. mb.release();
  3585. return false;
  3586. }
  3587. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3588. const String& title, const String& message,
  3589. Component* associatedComponent,
  3590. ModalComponentManager::Callback* callback)
  3591. {
  3592. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3593. MB_YESNOCANCEL, callback, callback != nullptr));
  3594. if (callback == nullptr)
  3595. return mb->getResult();
  3596. mb.release();
  3597. return 0;
  3598. }
  3599. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  3600. const String& title, const String& message,
  3601. Component* associatedComponent,
  3602. ModalComponentManager::Callback* callback)
  3603. {
  3604. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3605. MB_YESNO, callback, callback != nullptr));
  3606. if (callback == nullptr)
  3607. return mb->getResult();
  3608. mb.release();
  3609. return 0;
  3610. }
  3611. //==============================================================================
  3612. bool MouseInputSource::SourceList::addSource()
  3613. {
  3614. auto numSources = sources.size();
  3615. if (numSources == 0 || canUseMultiTouch())
  3616. {
  3617. addSource (numSources, numSources == 0 ? MouseInputSource::InputSourceType::mouse
  3618. : MouseInputSource::InputSourceType::touch);
  3619. return true;
  3620. }
  3621. return false;
  3622. }
  3623. bool MouseInputSource::SourceList::canUseTouch()
  3624. {
  3625. return canUseMultiTouch();
  3626. }
  3627. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3628. {
  3629. POINT mousePos;
  3630. GetCursorPos (&mousePos);
  3631. auto p = pointFromPOINT (mousePos);
  3632. if (isPerMonitorDPIAwareThread())
  3633. p = Desktop::getInstance().getDisplays().physicalToLogical (p);
  3634. return p.toFloat();
  3635. }
  3636. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3637. {
  3638. auto newPositionInt = newPosition.roundToInt();
  3639. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3640. if (isPerMonitorDPIAwareThread())
  3641. newPositionInt = Desktop::getInstance().getDisplays().logicalToPhysical (newPositionInt);
  3642. #endif
  3643. auto point = POINTFromPoint (newPositionInt);
  3644. SetCursorPos (point.x, point.y);
  3645. }
  3646. //==============================================================================
  3647. class ScreenSaverDefeater : public Timer
  3648. {
  3649. public:
  3650. ScreenSaverDefeater()
  3651. {
  3652. startTimer (10000);
  3653. timerCallback();
  3654. }
  3655. void timerCallback() override
  3656. {
  3657. if (Process::isForegroundProcess())
  3658. {
  3659. INPUT input = {};
  3660. input.type = INPUT_MOUSE;
  3661. input.mi.mouseData = MOUSEEVENTF_MOVE;
  3662. SendInput (1, &input, sizeof (INPUT));
  3663. }
  3664. }
  3665. };
  3666. static std::unique_ptr<ScreenSaverDefeater> screenSaverDefeater;
  3667. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3668. {
  3669. if (isEnabled)
  3670. screenSaverDefeater = nullptr;
  3671. else if (screenSaverDefeater == nullptr)
  3672. screenSaverDefeater.reset (new ScreenSaverDefeater());
  3673. }
  3674. bool Desktop::isScreenSaverEnabled()
  3675. {
  3676. return screenSaverDefeater == nullptr;
  3677. }
  3678. //==============================================================================
  3679. void LookAndFeel::playAlertSound()
  3680. {
  3681. MessageBeep (MB_OK);
  3682. }
  3683. //==============================================================================
  3684. void SystemClipboard::copyTextToClipboard (const String& text)
  3685. {
  3686. if (OpenClipboard (nullptr) != 0)
  3687. {
  3688. if (EmptyClipboard() != 0)
  3689. {
  3690. auto bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  3691. if (bytesNeeded > 0)
  3692. {
  3693. if (auto bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  3694. {
  3695. if (auto* data = static_cast<WCHAR*> (GlobalLock (bufH)))
  3696. {
  3697. text.copyToUTF16 (data, bytesNeeded);
  3698. GlobalUnlock (bufH);
  3699. SetClipboardData (CF_UNICODETEXT, bufH);
  3700. }
  3701. }
  3702. }
  3703. }
  3704. CloseClipboard();
  3705. }
  3706. }
  3707. String SystemClipboard::getTextFromClipboard()
  3708. {
  3709. String result;
  3710. if (OpenClipboard (nullptr) != 0)
  3711. {
  3712. if (auto bufH = GetClipboardData (CF_UNICODETEXT))
  3713. {
  3714. if (auto* data = (const WCHAR*) GlobalLock (bufH))
  3715. {
  3716. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  3717. GlobalUnlock (bufH);
  3718. }
  3719. }
  3720. CloseClipboard();
  3721. }
  3722. return result;
  3723. }
  3724. //==============================================================================
  3725. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  3726. {
  3727. if (auto* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComp))
  3728. tlw->setUsingNativeTitleBar (! enableOrDisable);
  3729. if (enableOrDisable)
  3730. kioskModeComp->setBounds (getDisplays().getDisplayForRect (kioskModeComp->getScreenBounds())->totalArea);
  3731. }
  3732. void Desktop::allowedOrientationsChanged() {}
  3733. //==============================================================================
  3734. static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd)
  3735. {
  3736. Array<const Displays::Display*> candidateDisplays;
  3737. double scaleToLookFor = -1.0;
  3738. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  3739. scaleToLookFor = peer->getPlatformScaleFactor();
  3740. else
  3741. scaleToLookFor = getScaleFactorForWindow (hwnd);
  3742. auto globalScale = Desktop::getInstance().getGlobalScaleFactor();
  3743. for (auto& d : Desktop::getInstance().getDisplays().displays)
  3744. if (approximatelyEqual (d.scale / globalScale, scaleToLookFor))
  3745. candidateDisplays.add (&d);
  3746. if (candidateDisplays.size() > 0)
  3747. {
  3748. if (candidateDisplays.size() == 1)
  3749. return candidateDisplays[0];
  3750. Rectangle<int> bounds;
  3751. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  3752. bounds = peer->getComponent().getTopLevelComponent()->getBounds();
  3753. else
  3754. bounds = Desktop::getInstance().getDisplays().physicalToLogical (rectangleFromRECT (getWindowScreenRect (hwnd)));
  3755. const Displays::Display* retVal = nullptr;
  3756. int maxArea = -1;
  3757. for (auto* d : candidateDisplays)
  3758. {
  3759. auto intersection = d->totalArea.getIntersection (bounds);
  3760. auto area = intersection.getWidth() * intersection.getHeight();
  3761. if (area > maxArea)
  3762. {
  3763. maxArea = area;
  3764. retVal = d;
  3765. }
  3766. }
  3767. if (retVal != nullptr)
  3768. return retVal;
  3769. }
  3770. return Desktop::getInstance().getDisplays().getPrimaryDisplay();
  3771. }
  3772. //==============================================================================
  3773. struct MonitorInfo
  3774. {
  3775. MonitorInfo (bool main, RECT totalArea, RECT workArea, double d) noexcept
  3776. : isMain (main),
  3777. totalAreaRect (totalArea),
  3778. workAreaRect (workArea),
  3779. dpi (d)
  3780. {
  3781. }
  3782. bool isMain;
  3783. RECT totalAreaRect, workAreaRect;
  3784. double dpi;
  3785. };
  3786. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT, LPARAM userInfo)
  3787. {
  3788. MONITORINFO info = {};
  3789. info.cbSize = sizeof (info);
  3790. GetMonitorInfo (hm, &info);
  3791. auto isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  3792. auto dpi = 0.0;
  3793. if (getDPIForMonitor != nullptr)
  3794. {
  3795. UINT dpiX = 0, dpiY = 0;
  3796. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  3797. dpi = (dpiX + dpiY) / 2.0;
  3798. }
  3799. ((Array<MonitorInfo>*) userInfo)->add ({ isMain, info.rcMonitor, info.rcWork, dpi });
  3800. return TRUE;
  3801. }
  3802. void Displays::findDisplays (float masterScale)
  3803. {
  3804. setDPIAwareness();
  3805. Array<MonitorInfo> monitors;
  3806. EnumDisplayMonitors (nullptr, nullptr, &enumMonitorsProc, (LPARAM) &monitors);
  3807. auto globalDPI = getGlobalDPI();
  3808. if (monitors.size() == 0)
  3809. {
  3810. auto windowRect = getWindowScreenRect (GetDesktopWindow());
  3811. monitors.add ({ true, windowRect, windowRect, globalDPI });
  3812. }
  3813. // make sure the first in the list is the main monitor
  3814. for (int i = 1; i < monitors.size(); ++i)
  3815. if (monitors.getReference (i).isMain)
  3816. monitors.swap (i, 0);
  3817. for (auto& monitor : monitors)
  3818. {
  3819. Display d;
  3820. d.isMain = monitor.isMain;
  3821. d.dpi = monitor.dpi;
  3822. if (d.dpi == 0)
  3823. {
  3824. d.dpi = globalDPI;
  3825. d.scale = masterScale;
  3826. }
  3827. else
  3828. {
  3829. d.scale = (d.dpi / USER_DEFAULT_SCREEN_DPI) * (masterScale / Desktop::getDefaultMasterScale());
  3830. }
  3831. d.totalArea = rectangleFromRECT (monitor.totalAreaRect);
  3832. d.userArea = rectangleFromRECT (monitor.workAreaRect);
  3833. displays.add (d);
  3834. }
  3835. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3836. if (isPerMonitorDPIAwareThread())
  3837. updateToLogical();
  3838. else
  3839. #endif
  3840. {
  3841. for (auto& d : displays)
  3842. {
  3843. d.totalArea /= masterScale;
  3844. d.userArea /= masterScale;
  3845. }
  3846. }
  3847. }
  3848. //==============================================================================
  3849. static HICON extractFileHICON (const File& file)
  3850. {
  3851. WORD iconNum = 0;
  3852. WCHAR name[MAX_PATH * 2];
  3853. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  3854. return ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  3855. name, &iconNum);
  3856. }
  3857. Image juce_createIconForFile (const File& file)
  3858. {
  3859. Image image;
  3860. if (auto icon = extractFileHICON (file))
  3861. {
  3862. image = IconConverters::createImageFromHICON (icon);
  3863. DestroyIcon (icon);
  3864. }
  3865. return image;
  3866. }
  3867. //==============================================================================
  3868. void* CustomMouseCursorInfo::create() const
  3869. {
  3870. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  3871. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  3872. Image im (image);
  3873. int hotspotX = hotspot.x;
  3874. int hotspotY = hotspot.y;
  3875. if (im.getWidth() > maxW || im.getHeight() > maxH)
  3876. {
  3877. im = im.rescaled (maxW, maxH);
  3878. hotspotX = (hotspotX * maxW) / juce::jmax (1, image.getWidth());
  3879. hotspotY = (hotspotY * maxH) / juce::jmax (1, image.getHeight());
  3880. }
  3881. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  3882. }
  3883. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool isStandard)
  3884. {
  3885. if (cursorHandle != nullptr && ! isStandard)
  3886. DestroyCursor ((HCURSOR) cursorHandle);
  3887. }
  3888. enum
  3889. {
  3890. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  3891. };
  3892. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  3893. {
  3894. LPCTSTR cursorName = IDC_ARROW;
  3895. switch (type)
  3896. {
  3897. case NormalCursor:
  3898. case ParentCursor: break;
  3899. case NoCursor: return (void*) hiddenMouseCursorHandle;
  3900. case WaitCursor: cursorName = IDC_WAIT; break;
  3901. case IBeamCursor: cursorName = IDC_IBEAM; break;
  3902. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  3903. case CrosshairCursor: cursorName = IDC_CROSS; break;
  3904. case LeftRightResizeCursor:
  3905. case LeftEdgeResizeCursor:
  3906. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  3907. case UpDownResizeCursor:
  3908. case TopEdgeResizeCursor:
  3909. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  3910. case TopLeftCornerResizeCursor:
  3911. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  3912. case TopRightCornerResizeCursor:
  3913. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  3914. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  3915. case DraggingHandCursor:
  3916. {
  3917. static void* dragHandCursor = nullptr;
  3918. if (dragHandCursor == nullptr)
  3919. {
  3920. static const unsigned char dragHandData[] =
  3921. { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  3922. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,132,117,151,116,132,146,248,60,209,138,
  3923. 98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  3924. dragHandCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), { 8, 7 }).create();
  3925. }
  3926. return dragHandCursor;
  3927. }
  3928. case CopyingCursor:
  3929. {
  3930. static void* copyCursor = nullptr;
  3931. if (copyCursor == nullptr)
  3932. {
  3933. static unsigned char copyCursorData[] = {
  3934. 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  3935. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,78,133,218,215,137,31,82,154,100,200,86,91,202,142,
  3936. 12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,252,114,147,74,83,
  3937. 5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0
  3938. };
  3939. const int copyCursorSize = 119;
  3940. copyCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), { 1, 3 }).create();
  3941. }
  3942. return copyCursor;
  3943. }
  3944. case NumStandardCursorTypes: JUCE_FALLTHROUGH
  3945. default:
  3946. jassertfalse; break;
  3947. }
  3948. if (auto cursorH = LoadCursor (nullptr, cursorName))
  3949. return cursorH;
  3950. return LoadCursor (nullptr, IDC_ARROW);
  3951. }
  3952. //==============================================================================
  3953. void MouseCursor::showInWindow (ComponentPeer*) const
  3954. {
  3955. auto c = (HCURSOR) getHandle();
  3956. if (c == nullptr)
  3957. c = LoadCursor (nullptr, IDC_ARROW);
  3958. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  3959. c = nullptr;
  3960. SetCursor (c);
  3961. }
  3962. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  3963. } // namespace juce