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.

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