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.

5212 lines
185KB

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