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.

4984 lines
177KB

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