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.

4946 lines
175KB

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