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.

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