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.

4685 lines
166KB

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