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.

4691 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 = static_cast<ComBaseModule&&> (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. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  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 (isPerMonitorDPIAwareThread() || isPerMonitorDPIAwareWindow (hwnd))
  1192. globalPos = Desktop::getInstance().getDisplays().logicalToPhysical (globalPos);
  1193. auto w = WindowFromPoint (POINTFromPoint (globalPos));
  1194. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  1195. }
  1196. BorderSize<int> getFrameSize() const override
  1197. {
  1198. return windowBorder;
  1199. }
  1200. bool setAlwaysOnTop (bool alwaysOnTop) override
  1201. {
  1202. const bool oldDeactivate = shouldDeactivateTitleBar;
  1203. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1204. setWindowZOrder (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST);
  1205. shouldDeactivateTitleBar = oldDeactivate;
  1206. if (shadower != nullptr)
  1207. handleBroughtToFront();
  1208. return true;
  1209. }
  1210. void toFront (bool makeActive) override
  1211. {
  1212. setMinimised (false);
  1213. const bool oldDeactivate = shouldDeactivateTitleBar;
  1214. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1215. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  1216. shouldDeactivateTitleBar = oldDeactivate;
  1217. if (! makeActive)
  1218. {
  1219. // in this case a broughttofront call won't have occurred, so do it now..
  1220. handleBroughtToFront();
  1221. }
  1222. }
  1223. void toBehind (ComponentPeer* other) override
  1224. {
  1225. if (auto* otherPeer = dynamic_cast<HWNDComponentPeer*> (other))
  1226. {
  1227. setMinimised (false);
  1228. // Must be careful not to try to put a topmost window behind a normal one, or Windows
  1229. // promotes the normal one to be topmost!
  1230. if (component.isAlwaysOnTop() == otherPeer->getComponent().isAlwaysOnTop())
  1231. setWindowZOrder (hwnd, otherPeer->hwnd);
  1232. else if (otherPeer->getComponent().isAlwaysOnTop())
  1233. setWindowZOrder (hwnd, HWND_TOP);
  1234. }
  1235. else
  1236. {
  1237. jassertfalse; // wrong type of window?
  1238. }
  1239. }
  1240. bool isFocused() const override
  1241. {
  1242. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  1243. }
  1244. void grabFocus() override
  1245. {
  1246. const bool oldDeactivate = shouldDeactivateTitleBar;
  1247. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1248. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  1249. shouldDeactivateTitleBar = oldDeactivate;
  1250. }
  1251. void textInputRequired (Point<int>, TextInputTarget&) override
  1252. {
  1253. if (! hasCreatedCaret)
  1254. {
  1255. hasCreatedCaret = true;
  1256. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  1257. }
  1258. ShowCaret (hwnd);
  1259. SetCaretPos (0, 0);
  1260. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  1261. OnScreenKeyboard::getInstance()->activate();
  1262. }
  1263. void dismissPendingTextInput() override
  1264. {
  1265. imeHandler.handleSetContext (hwnd, false);
  1266. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  1267. OnScreenKeyboard::getInstance()->deactivate();
  1268. }
  1269. void repaint (const Rectangle<int>& area) override
  1270. {
  1271. auto scale = getPlatformScaleFactor();
  1272. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1273. // if the calling thread is DPI-aware but we are invalidating a non-DPI aware window RECT, we actually have to
  1274. // divide the bounds by the scale factor as it will get multiplied for the virtualised paint callback...
  1275. if (isPerMonitorDPIAwareThread() && ! isPerMonitorDPIAwareWindow (hwnd))
  1276. scale = 1.0 / Desktop::getInstance().getDisplays().getMainDisplay().scale;
  1277. #endif
  1278. const RECT r = { roundToInt (area.getX() * scale), roundToInt (area.getY() * scale),
  1279. roundToInt (area.getRight() * scale), roundToInt (area.getBottom() * scale) };
  1280. InvalidateRect (hwnd, &r, FALSE);
  1281. }
  1282. void performAnyPendingRepaintsNow() override
  1283. {
  1284. if (component.isVisible())
  1285. {
  1286. WeakReference<Component> localRef (&component);
  1287. MSG m;
  1288. if (isUsingUpdateLayeredWindow() || PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  1289. if (localRef != nullptr) // (the PeekMessage call can dispatch messages, which may delete this comp)
  1290. handlePaintMessage();
  1291. }
  1292. }
  1293. //==============================================================================
  1294. static HWNDComponentPeer* getOwnerOfWindow (HWND h) noexcept
  1295. {
  1296. if (h != 0 && JuceWindowIdentifier::isJUCEWindow (h))
  1297. return (HWNDComponentPeer*) GetWindowLongPtr (h, 8);
  1298. return nullptr;
  1299. }
  1300. //==============================================================================
  1301. bool isInside (HWND h) const noexcept
  1302. {
  1303. return GetAncestor (hwnd, GA_ROOT) == h;
  1304. }
  1305. //==============================================================================
  1306. static bool isKeyDown (const int key) noexcept { return (GetAsyncKeyState (key) & 0x8000) != 0; }
  1307. static void updateKeyModifiers() noexcept
  1308. {
  1309. int keyMods = 0;
  1310. if (isKeyDown (VK_SHIFT)) keyMods |= ModifierKeys::shiftModifier;
  1311. if (isKeyDown (VK_CONTROL)) keyMods |= ModifierKeys::ctrlModifier;
  1312. if (isKeyDown (VK_MENU)) keyMods |= ModifierKeys::altModifier;
  1313. // workaround: Windows maps AltGr to left-Ctrl + right-Alt.
  1314. if (isKeyDown (VK_RMENU) && !isKeyDown (VK_RCONTROL))
  1315. {
  1316. keyMods = (keyMods & ~ModifierKeys::ctrlModifier) | ModifierKeys::altModifier;
  1317. }
  1318. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1319. }
  1320. static void updateModifiersFromWParam (const WPARAM wParam)
  1321. {
  1322. int mouseMods = 0;
  1323. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  1324. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  1325. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  1326. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1327. updateKeyModifiers();
  1328. }
  1329. //==============================================================================
  1330. bool dontRepaint;
  1331. static ModifierKeys modifiersAtLastCallback;
  1332. //==============================================================================
  1333. struct FileDropTarget : public ComBaseClassHelper<IDropTarget>
  1334. {
  1335. FileDropTarget (HWNDComponentPeer& p) : peer (p) {}
  1336. JUCE_COMRESULT DragEnter (IDataObject* pDataObject, DWORD grfKeyState, POINTL mousePos, DWORD* pdwEffect) override
  1337. {
  1338. auto hr = updateFileList (pDataObject);
  1339. if (FAILED (hr))
  1340. return hr;
  1341. return DragOver (grfKeyState, mousePos, pdwEffect);
  1342. }
  1343. JUCE_COMRESULT DragLeave() override
  1344. {
  1345. if (peerIsDeleted)
  1346. return S_FALSE;
  1347. peer.handleDragExit (dragInfo);
  1348. return S_OK;
  1349. }
  1350. JUCE_COMRESULT DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1351. {
  1352. if (peerIsDeleted)
  1353. return S_FALSE;
  1354. dragInfo.position = getMousePos (mousePos).roundToInt();
  1355. *pdwEffect = peer.handleDragMove (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1356. : (DWORD) DROPEFFECT_NONE;
  1357. return S_OK;
  1358. }
  1359. JUCE_COMRESULT Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1360. {
  1361. auto hr = updateFileList (pDataObject);
  1362. if (FAILED (hr))
  1363. return hr;
  1364. dragInfo.position = getMousePos (mousePos).roundToInt();
  1365. *pdwEffect = peer.handleDragDrop (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1366. : (DWORD) DROPEFFECT_NONE;
  1367. return S_OK;
  1368. }
  1369. HWNDComponentPeer& peer;
  1370. ComponentPeer::DragInfo dragInfo;
  1371. bool peerIsDeleted = false;
  1372. private:
  1373. Point<float> getMousePos (POINTL mousePos) const
  1374. {
  1375. auto& comp = peer.getComponent();
  1376. return comp.getLocalPoint (nullptr, convertPhysicalScreenPointToLogical (pointFromPOINT ({ mousePos.x, mousePos.y }),
  1377. (HWND) peer.getNativeHandle()).toFloat());
  1378. }
  1379. template <typename CharType>
  1380. void parseFileList (const CharType* names, const SIZE_T totalLen)
  1381. {
  1382. for (unsigned int i = 0;;)
  1383. {
  1384. unsigned int len = 0;
  1385. while (i + len < totalLen && names[i + len] != 0)
  1386. ++len;
  1387. if (len == 0)
  1388. break;
  1389. dragInfo.files.add (String (names + i, len));
  1390. i += len + 1;
  1391. }
  1392. }
  1393. struct DroppedData
  1394. {
  1395. DroppedData (IDataObject* dataObject, CLIPFORMAT type)
  1396. {
  1397. FORMATETC format = { type, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  1398. STGMEDIUM resetMedium = { TYMED_HGLOBAL, { 0 }, 0 };
  1399. medium = resetMedium;
  1400. if (SUCCEEDED (error = dataObject->GetData (&format, &medium)))
  1401. {
  1402. dataSize = GlobalSize (medium.hGlobal);
  1403. data = GlobalLock (medium.hGlobal);
  1404. }
  1405. }
  1406. ~DroppedData()
  1407. {
  1408. if (data != nullptr)
  1409. GlobalUnlock (medium.hGlobal);
  1410. }
  1411. HRESULT error;
  1412. STGMEDIUM medium;
  1413. void* data = {};
  1414. SIZE_T dataSize;
  1415. };
  1416. HRESULT updateFileList (IDataObject* const dataObject)
  1417. {
  1418. if (peerIsDeleted)
  1419. return S_FALSE;
  1420. dragInfo.clear();
  1421. {
  1422. DroppedData fileData (dataObject, CF_HDROP);
  1423. if (SUCCEEDED (fileData.error))
  1424. {
  1425. auto dropFiles = static_cast<const LPDROPFILES> (fileData.data);
  1426. const void* const names = addBytesToPointer (dropFiles, sizeof (DROPFILES));
  1427. if (dropFiles->fWide)
  1428. parseFileList (static_cast<const WCHAR*> (names), fileData.dataSize);
  1429. else
  1430. parseFileList (static_cast<const char*> (names), fileData.dataSize);
  1431. return S_OK;
  1432. }
  1433. }
  1434. DroppedData textData (dataObject, CF_UNICODETEXT);
  1435. if (SUCCEEDED (textData.error))
  1436. {
  1437. dragInfo.text = String (CharPointer_UTF16 ((const WCHAR*) textData.data),
  1438. CharPointer_UTF16 ((const WCHAR*) addBytesToPointer (textData.data, textData.dataSize)));
  1439. return S_OK;
  1440. }
  1441. return textData.error;
  1442. }
  1443. JUCE_DECLARE_NON_COPYABLE (FileDropTarget)
  1444. };
  1445. static bool offerKeyMessageToJUCEWindow (MSG& m)
  1446. {
  1447. if (m.message == WM_KEYDOWN || m.message == WM_KEYUP)
  1448. if (Component::getCurrentlyFocusedComponent() != nullptr)
  1449. if (auto* h = getOwnerOfWindow (m.hwnd))
  1450. return m.message == WM_KEYDOWN ? h->doKeyDown (m.wParam)
  1451. : h->doKeyUp (m.wParam);
  1452. return false;
  1453. }
  1454. double getPlatformScaleFactor() const noexcept override
  1455. {
  1456. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1457. if (! isPerMonitorDPIAwareWindow (hwnd))
  1458. return 1.0;
  1459. if (auto* parentHWND = GetParent (hwnd))
  1460. {
  1461. if (auto* parentPeer = getOwnerOfWindow (parentHWND))
  1462. return parentPeer->getPlatformScaleFactor();
  1463. if (getDPIForWindow != nullptr)
  1464. return getScaleFactorForWindow (parentHWND);
  1465. }
  1466. return scaleFactor;
  1467. #else
  1468. return 1.0;
  1469. #endif
  1470. }
  1471. private:
  1472. HWND hwnd, parentToAddTo;
  1473. std::unique_ptr<DropShadower> shadower;
  1474. RenderingEngineType currentRenderingEngine;
  1475. #if JUCE_DIRECT2D
  1476. std::unique_ptr<Direct2DLowLevelGraphicsContext> direct2DContext;
  1477. #endif
  1478. uint32 lastPaintTime = 0;
  1479. ULONGLONG lastMagnifySize = 0;
  1480. bool fullScreen = false, isDragging = false, isMouseOver = false,
  1481. hasCreatedCaret = false, constrainerIsResizing = false;
  1482. BorderSize<int> windowBorder;
  1483. HICON currentWindowIcon = 0;
  1484. FileDropTarget* dropTarget = nullptr;
  1485. uint8 updateLayeredWindowAlpha = 255;
  1486. UWPUIViewSettings uwpViewSettings;
  1487. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1488. ModifierKeyProvider* modProvider = nullptr;
  1489. #endif
  1490. double scaleFactor = 1.0;
  1491. bool isInDPIChange = false;
  1492. //==============================================================================
  1493. static MultiTouchMapper<DWORD> currentTouches;
  1494. //==============================================================================
  1495. struct TemporaryImage : private Timer
  1496. {
  1497. TemporaryImage() {}
  1498. Image& getImage (bool transparent, int w, int h)
  1499. {
  1500. auto format = transparent ? Image::ARGB : Image::RGB;
  1501. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  1502. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  1503. startTimer (3000);
  1504. return image;
  1505. }
  1506. void timerCallback() override
  1507. {
  1508. stopTimer();
  1509. image = {};
  1510. }
  1511. private:
  1512. Image image;
  1513. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage)
  1514. };
  1515. TemporaryImage offscreenImageGenerator;
  1516. //==============================================================================
  1517. class WindowClassHolder : private DeletedAtShutdown
  1518. {
  1519. public:
  1520. WindowClassHolder()
  1521. {
  1522. // this name has to be different for each app/dll instance because otherwise poor old Windows can
  1523. // get a bit confused (even despite it not being a process-global window class).
  1524. String windowClassName ("JUCE_");
  1525. windowClassName << String::toHexString (Time::currentTimeMillis());
  1526. auto moduleHandle = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
  1527. TCHAR moduleFile[1024] = { 0 };
  1528. GetModuleFileName (moduleHandle, moduleFile, 1024);
  1529. WORD iconNum = 0;
  1530. WNDCLASSEX wcex = { 0 };
  1531. wcex.cbSize = sizeof (wcex);
  1532. wcex.style = CS_OWNDC;
  1533. wcex.lpfnWndProc = (WNDPROC) windowProc;
  1534. wcex.lpszClassName = windowClassName.toWideCharPointer();
  1535. wcex.cbWndExtra = 32;
  1536. wcex.hInstance = moduleHandle;
  1537. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1538. iconNum = 1;
  1539. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1540. atom = RegisterClassEx (&wcex);
  1541. jassert (atom != 0);
  1542. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  1543. }
  1544. ~WindowClassHolder()
  1545. {
  1546. if (ComponentPeer::getNumPeers() == 0)
  1547. UnregisterClass (getWindowClassName(), (HINSTANCE) Process::getCurrentModuleInstanceHandle());
  1548. clearSingletonInstance();
  1549. }
  1550. LPCTSTR getWindowClassName() const noexcept { return (LPCTSTR) (pointer_sized_uint) atom; }
  1551. JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL (WindowClassHolder)
  1552. private:
  1553. ATOM atom;
  1554. static bool isHWNDBlockedByModalComponents (HWND h)
  1555. {
  1556. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1557. if (auto* c = Desktop::getInstance().getComponent (i))
  1558. if ((! c->isCurrentlyBlockedByAnotherModalComponent())
  1559. && IsChild ((HWND) c->getWindowHandle(), h))
  1560. return false;
  1561. return true;
  1562. }
  1563. static bool checkEventBlockedByModalComps (const MSG& m)
  1564. {
  1565. if (Component::getNumCurrentlyModalComponents() == 0 || JuceWindowIdentifier::isJUCEWindow (m.hwnd))
  1566. return false;
  1567. switch (m.message)
  1568. {
  1569. case WM_MOUSEMOVE:
  1570. case WM_NCMOUSEMOVE:
  1571. case 0x020A: /* WM_MOUSEWHEEL */
  1572. case 0x020E: /* WM_MOUSEHWHEEL */
  1573. case WM_KEYUP:
  1574. case WM_SYSKEYUP:
  1575. case WM_CHAR:
  1576. case WM_APPCOMMAND:
  1577. case WM_LBUTTONUP:
  1578. case WM_MBUTTONUP:
  1579. case WM_RBUTTONUP:
  1580. case WM_MOUSEACTIVATE:
  1581. case WM_NCMOUSEHOVER:
  1582. case WM_MOUSEHOVER:
  1583. case WM_TOUCH:
  1584. case WM_POINTERUPDATE:
  1585. case WM_NCPOINTERUPDATE:
  1586. case WM_POINTERWHEEL:
  1587. case WM_POINTERHWHEEL:
  1588. case WM_POINTERUP:
  1589. case WM_POINTERACTIVATE:
  1590. return isHWNDBlockedByModalComponents(m.hwnd);
  1591. case WM_NCLBUTTONDOWN:
  1592. case WM_NCLBUTTONDBLCLK:
  1593. case WM_NCRBUTTONDOWN:
  1594. case WM_NCRBUTTONDBLCLK:
  1595. case WM_NCMBUTTONDOWN:
  1596. case WM_NCMBUTTONDBLCLK:
  1597. case WM_LBUTTONDOWN:
  1598. case WM_LBUTTONDBLCLK:
  1599. case WM_MBUTTONDOWN:
  1600. case WM_MBUTTONDBLCLK:
  1601. case WM_RBUTTONDOWN:
  1602. case WM_RBUTTONDBLCLK:
  1603. case WM_KEYDOWN:
  1604. case WM_SYSKEYDOWN:
  1605. case WM_NCPOINTERDOWN:
  1606. case WM_POINTERDOWN:
  1607. if (isHWNDBlockedByModalComponents (m.hwnd))
  1608. {
  1609. if (auto* modal = Component::getCurrentlyModalComponent (0))
  1610. modal->inputAttemptWhenModal();
  1611. return true;
  1612. }
  1613. break;
  1614. default:
  1615. break;
  1616. }
  1617. return false;
  1618. }
  1619. JUCE_DECLARE_NON_COPYABLE (WindowClassHolder)
  1620. };
  1621. //==============================================================================
  1622. static void* createWindowCallback (void* userData)
  1623. {
  1624. static_cast<HWNDComponentPeer*> (userData)->createWindow();
  1625. return nullptr;
  1626. }
  1627. void createWindow()
  1628. {
  1629. DWORD exstyle = 0;
  1630. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  1631. if (hasTitleBar())
  1632. {
  1633. type |= WS_OVERLAPPED;
  1634. if ((styleFlags & windowHasCloseButton) != 0)
  1635. {
  1636. type |= WS_SYSMENU;
  1637. }
  1638. else
  1639. {
  1640. // annoyingly, windows won't let you have a min/max button without a close button
  1641. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  1642. }
  1643. if ((styleFlags & windowIsResizable) != 0)
  1644. type |= WS_THICKFRAME;
  1645. }
  1646. else if (parentToAddTo != 0)
  1647. {
  1648. type |= WS_CHILD;
  1649. }
  1650. else
  1651. {
  1652. type |= WS_POPUP | WS_SYSMENU;
  1653. }
  1654. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1655. exstyle |= WS_EX_TOOLWINDOW;
  1656. else
  1657. exstyle |= WS_EX_APPWINDOW;
  1658. if ((styleFlags & windowHasMinimiseButton) != 0) type |= WS_MINIMIZEBOX;
  1659. if ((styleFlags & windowHasMaximiseButton) != 0) type |= WS_MAXIMIZEBOX;
  1660. if ((styleFlags & windowIgnoresMouseClicks) != 0) exstyle |= WS_EX_TRANSPARENT;
  1661. if ((styleFlags & windowIsSemiTransparent) != 0) exstyle |= WS_EX_LAYERED;
  1662. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->getWindowClassName(),
  1663. L"", type, 0, 0, 0, 0, parentToAddTo, 0,
  1664. (HINSTANCE) Process::getCurrentModuleInstanceHandle(), 0);
  1665. if (hwnd != 0)
  1666. {
  1667. SetWindowLongPtr (hwnd, 0, 0);
  1668. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  1669. JuceWindowIdentifier::setAsJUCEWindow (hwnd, true);
  1670. if (dropTarget == nullptr)
  1671. {
  1672. HWNDComponentPeer* peer = nullptr;
  1673. if (dontRepaint)
  1674. peer = getOwnerOfWindow (parentToAddTo);
  1675. if (peer == nullptr)
  1676. peer = this;
  1677. dropTarget = new FileDropTarget (*peer);
  1678. }
  1679. RegisterDragDrop (hwnd, dropTarget);
  1680. if (canUseMultiTouch())
  1681. registerTouchWindow (hwnd, 0);
  1682. setDPIAwareness();
  1683. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1684. if (isPerMonitorDPIAwareThread())
  1685. {
  1686. auto bounds = component.getBounds();
  1687. if (bounds.isEmpty())
  1688. scaleFactor = Desktop::getInstance().getDisplays().getMainDisplay().scale;
  1689. else
  1690. scaleFactor = Desktop::getInstance().getDisplays().findDisplayForRect (bounds).scale;
  1691. scaleFactor /= Desktop::getInstance().getGlobalScaleFactor();
  1692. }
  1693. #endif
  1694. setMessageFilter();
  1695. updateBorderSize();
  1696. checkForPointerAPI();
  1697. // This is needed so that our plugin window gets notified of WM_SETTINGCHANGE messages
  1698. // and can respond to display scale changes
  1699. if (! JUCEApplication::isStandaloneApp())
  1700. settingChangeCallback = forceDisplayUpdate;
  1701. // Calling this function here is (for some reason) necessary to make Windows
  1702. // correctly enable the menu items that we specify in the wm_initmenu message.
  1703. GetSystemMenu (hwnd, false);
  1704. auto alpha = component.getAlpha();
  1705. if (alpha < 1.0f)
  1706. setAlpha (alpha);
  1707. }
  1708. else
  1709. {
  1710. jassertfalse;
  1711. }
  1712. }
  1713. static BOOL CALLBACK revokeChildDragDropCallback (HWND hwnd, LPARAM) { RevokeDragDrop (hwnd); return TRUE; }
  1714. static void* destroyWindowCallback (void* handle)
  1715. {
  1716. auto hwnd = reinterpret_cast<HWND> (handle);
  1717. if (IsWindow (hwnd))
  1718. {
  1719. RevokeDragDrop (hwnd);
  1720. // NB: we need to do this before DestroyWindow() as child HWNDs will be invalid after
  1721. EnumChildWindows (hwnd, revokeChildDragDropCallback, 0);
  1722. DestroyWindow (hwnd);
  1723. }
  1724. return nullptr;
  1725. }
  1726. static void* toFrontCallback1 (void* h)
  1727. {
  1728. SetForegroundWindow ((HWND) h);
  1729. return nullptr;
  1730. }
  1731. static void* toFrontCallback2 (void* h)
  1732. {
  1733. setWindowZOrder ((HWND) h, HWND_TOP);
  1734. return nullptr;
  1735. }
  1736. static void* setFocusCallback (void* h)
  1737. {
  1738. SetFocus ((HWND) h);
  1739. return nullptr;
  1740. }
  1741. static void* getFocusCallback (void*)
  1742. {
  1743. return GetFocus();
  1744. }
  1745. bool isUsingUpdateLayeredWindow() const
  1746. {
  1747. return ! component.isOpaque();
  1748. }
  1749. bool hasTitleBar() const noexcept { return (styleFlags & windowHasTitleBar) != 0; }
  1750. void updateShadower()
  1751. {
  1752. if (! component.isCurrentlyModal() && (styleFlags & windowHasDropShadow) != 0
  1753. && ((! hasTitleBar()) || SystemStats::getOperatingSystemType() < SystemStats::WinVista))
  1754. {
  1755. shadower.reset (component.getLookAndFeel().createDropShadowerForComponent (&component));
  1756. if (shadower != nullptr)
  1757. shadower->setOwner (&component);
  1758. }
  1759. }
  1760. void setIcon (const Image& newIcon)
  1761. {
  1762. if (auto hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0))
  1763. {
  1764. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  1765. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  1766. if (currentWindowIcon != 0)
  1767. DestroyIcon (currentWindowIcon);
  1768. currentWindowIcon = hicon;
  1769. }
  1770. }
  1771. void setMessageFilter()
  1772. {
  1773. typedef BOOL (WINAPI* ChangeWindowMessageFilterExFunc) (HWND, UINT, DWORD, PVOID);
  1774. if (auto changeMessageFilter = (ChangeWindowMessageFilterExFunc) getUser32Function ("ChangeWindowMessageFilterEx"))
  1775. {
  1776. changeMessageFilter (hwnd, WM_DROPFILES, 1 /*MSGFLT_ALLOW*/, nullptr);
  1777. changeMessageFilter (hwnd, WM_COPYDATA, 1 /*MSGFLT_ALLOW*/, nullptr);
  1778. changeMessageFilter (hwnd, 0x49, 1 /*MSGFLT_ALLOW*/, nullptr);
  1779. }
  1780. }
  1781. struct ChildWindowClippingInfo
  1782. {
  1783. HDC dc;
  1784. HWNDComponentPeer* peer;
  1785. RectangleList<int>* clip;
  1786. Point<int> origin;
  1787. int savedDC;
  1788. };
  1789. static BOOL CALLBACK clipChildWindowCallback (HWND hwnd, LPARAM context)
  1790. {
  1791. if (IsWindowVisible (hwnd))
  1792. {
  1793. auto& info = *(ChildWindowClippingInfo*) context;
  1794. auto parent = GetParent (hwnd);
  1795. if (parent == info.peer->hwnd)
  1796. {
  1797. auto r = getWindowRect (hwnd);
  1798. POINT pos = { r.left, r.top };
  1799. ScreenToClient (GetParent (hwnd), &pos);
  1800. Rectangle<int> clip (pos.x, pos.y,
  1801. r.right - r.left,
  1802. r.bottom - r.top);
  1803. info.clip->subtract (clip - info.origin);
  1804. if (info.savedDC == 0)
  1805. info.savedDC = SaveDC (info.dc);
  1806. ExcludeClipRect (info.dc, clip.getX(), clip.getY(), clip.getRight(), clip.getBottom());
  1807. }
  1808. }
  1809. return TRUE;
  1810. }
  1811. //==============================================================================
  1812. void handlePaintMessage()
  1813. {
  1814. #if JUCE_DIRECT2D
  1815. if (direct2DContext != nullptr)
  1816. {
  1817. RECT r;
  1818. if (GetUpdateRect (hwnd, &r, false))
  1819. {
  1820. direct2DContext->start();
  1821. direct2DContext->clipToRectangle (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r), hwnd));
  1822. handlePaint (*direct2DContext);
  1823. direct2DContext->end();
  1824. ValidateRect (hwnd, &r);
  1825. }
  1826. }
  1827. else
  1828. #endif
  1829. {
  1830. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  1831. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  1832. PAINTSTRUCT paintStruct;
  1833. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  1834. // message and become re-entrant, but that's OK
  1835. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  1836. // corrupt the image it's using to paint into, so do a check here.
  1837. static bool reentrant = false;
  1838. if (! reentrant)
  1839. {
  1840. const ScopedValueSetter<bool> setter (reentrant, true, false);
  1841. if (dontRepaint)
  1842. component.handleCommandMessage (0); // (this triggers a repaint in the openGL context)
  1843. else
  1844. performPaint (dc, rgn, regionType, paintStruct);
  1845. }
  1846. DeleteObject (rgn);
  1847. EndPaint (hwnd, &paintStruct);
  1848. #if JUCE_MSVC
  1849. _fpreset(); // because some graphics cards can unmask FP exceptions
  1850. #endif
  1851. }
  1852. lastPaintTime = Time::getMillisecondCounter();
  1853. }
  1854. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  1855. {
  1856. int x = paintStruct.rcPaint.left;
  1857. int y = paintStruct.rcPaint.top;
  1858. int w = paintStruct.rcPaint.right - x;
  1859. int h = paintStruct.rcPaint.bottom - y;
  1860. const bool transparent = isUsingUpdateLayeredWindow();
  1861. if (transparent)
  1862. {
  1863. // it's not possible to have a transparent window with a title bar at the moment!
  1864. jassert (! hasTitleBar());
  1865. auto r = getWindowRect (hwnd);
  1866. x = y = 0;
  1867. w = r.right - r.left;
  1868. h = r.bottom - r.top;
  1869. }
  1870. if (w > 0 && h > 0)
  1871. {
  1872. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  1873. RectangleList<int> contextClip;
  1874. const Rectangle<int> clipBounds (w, h);
  1875. bool needToPaintAll = true;
  1876. if (regionType == COMPLEXREGION && ! transparent)
  1877. {
  1878. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  1879. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  1880. DeleteObject (clipRgn);
  1881. char rgnData[8192];
  1882. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  1883. if (res > 0 && res <= sizeof (rgnData))
  1884. {
  1885. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  1886. if (hdr->iType == RDH_RECTANGLES
  1887. && hdr->rcBound.right - hdr->rcBound.left >= w
  1888. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  1889. {
  1890. needToPaintAll = false;
  1891. auto rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  1892. for (int i = (int) ((RGNDATA*) rgnData)->rdh.nCount; --i >= 0;)
  1893. {
  1894. if (rects->right <= x + w && rects->bottom <= y + h)
  1895. {
  1896. const int cx = jmax (x, (int) rects->left);
  1897. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  1898. rects->right - cx, rects->bottom - rects->top)
  1899. .getIntersection (clipBounds));
  1900. }
  1901. else
  1902. {
  1903. needToPaintAll = true;
  1904. break;
  1905. }
  1906. ++rects;
  1907. }
  1908. }
  1909. }
  1910. }
  1911. if (needToPaintAll)
  1912. {
  1913. contextClip.clear();
  1914. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  1915. }
  1916. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  1917. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  1918. if (! contextClip.isEmpty())
  1919. {
  1920. if (transparent)
  1921. for (auto& i : contextClip)
  1922. offscreenImage.clear (i);
  1923. {
  1924. std::unique_ptr<LowLevelGraphicsContext> context (component.getLookAndFeel()
  1925. .createGraphicsContext (offscreenImage, Point<int> (-x, -y), contextClip));
  1926. context->addTransform (AffineTransform::scale ((float) getPlatformScaleFactor()));
  1927. handlePaint (*context);
  1928. }
  1929. static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData())
  1930. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  1931. }
  1932. if (childClipInfo.savedDC != 0)
  1933. RestoreDC (dc, childClipInfo.savedDC);
  1934. }
  1935. }
  1936. //==============================================================================
  1937. void doMouseEvent (Point<float> position, float pressure, float orientation = 0.0f, ModifierKeys mods = ModifierKeys::currentModifiers)
  1938. {
  1939. handleMouseEvent (MouseInputSource::InputSourceType::mouse, position, mods, pressure, orientation, getMouseEventTime());
  1940. }
  1941. StringArray getAvailableRenderingEngines() override
  1942. {
  1943. StringArray s ("Software Renderer");
  1944. #if JUCE_DIRECT2D
  1945. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  1946. s.add ("Direct2D");
  1947. #endif
  1948. return s;
  1949. }
  1950. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  1951. #if JUCE_DIRECT2D
  1952. void updateDirect2DContext()
  1953. {
  1954. if (currentRenderingEngine != direct2DRenderingEngine)
  1955. direct2DContext = nullptr;
  1956. else if (direct2DContext == nullptr)
  1957. direct2DContext.reset (new Direct2DLowLevelGraphicsContext (hwnd));
  1958. }
  1959. #endif
  1960. void setCurrentRenderingEngine (int index) override
  1961. {
  1962. ignoreUnused (index);
  1963. #if JUCE_DIRECT2D
  1964. if (getAvailableRenderingEngines().size() > 1)
  1965. {
  1966. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  1967. updateDirect2DContext();
  1968. repaint (component.getLocalBounds());
  1969. }
  1970. #endif
  1971. }
  1972. static int getMinTimeBetweenMouseMoves()
  1973. {
  1974. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  1975. return 0;
  1976. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  1977. }
  1978. bool isTouchEvent() noexcept
  1979. {
  1980. if (registerTouchWindow == nullptr)
  1981. return false;
  1982. // Relevant info about touch/pen detection flags:
  1983. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
  1984. // http://www.petertissen.de/?p=4
  1985. return (GetMessageExtraInfo() & 0xFFFFFF80 /*SIGNATURE_MASK*/) == 0xFF515780 /*MI_WP_SIGNATURE*/;
  1986. }
  1987. static bool areOtherTouchSourcesActive()
  1988. {
  1989. for (auto& ms : Desktop::getInstance().getMouseSources())
  1990. if (ms.isDragging() && (ms.getType() == MouseInputSource::InputSourceType::touch
  1991. || ms.getType() == MouseInputSource::InputSourceType::pen))
  1992. return true;
  1993. return false;
  1994. }
  1995. void doMouseMove (Point<float> position, bool isMouseDownEvent)
  1996. {
  1997. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  1998. // this will be handled by WM_TOUCH
  1999. if (isTouchEvent() || areOtherTouchSourcesActive())
  2000. return;
  2001. if (! isMouseOver)
  2002. {
  2003. isMouseOver = true;
  2004. // This avoids a rare stuck-button problem when focus is lost unexpectedly, but must
  2005. // not be called as part of a move, in case it's actually a mouse-drag from another
  2006. // app which ends up here when we get focus before the mouse is released..
  2007. if (isMouseDownEvent && getNativeRealtimeModifiers != nullptr)
  2008. getNativeRealtimeModifiers();
  2009. updateKeyModifiers();
  2010. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2011. if (modProvider != nullptr)
  2012. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2013. #endif
  2014. TRACKMOUSEEVENT tme;
  2015. tme.cbSize = sizeof (tme);
  2016. tme.dwFlags = TME_LEAVE;
  2017. tme.hwndTrack = hwnd;
  2018. tme.dwHoverTime = 0;
  2019. if (! TrackMouseEvent (&tme))
  2020. jassertfalse;
  2021. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  2022. }
  2023. else if (! isDragging)
  2024. {
  2025. if (! contains (position.roundToInt(), false))
  2026. return;
  2027. }
  2028. static uint32 lastMouseTime = 0;
  2029. static auto minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  2030. auto now = Time::getMillisecondCounter();
  2031. if (! Desktop::getInstance().getMainMouseSource().isDragging())
  2032. modsToSend = modsToSend.withoutMouseButtons();
  2033. if (now >= lastMouseTime + minTimeBetweenMouses)
  2034. {
  2035. lastMouseTime = now;
  2036. doMouseEvent (position, MouseInputSource::invalidPressure,
  2037. MouseInputSource::invalidOrientation, modsToSend);
  2038. }
  2039. }
  2040. void doMouseDown (Point<float> position, const WPARAM wParam)
  2041. {
  2042. // this will be handled by WM_TOUCH
  2043. if (isTouchEvent() || areOtherTouchSourcesActive())
  2044. return;
  2045. if (GetCapture() != hwnd)
  2046. SetCapture (hwnd);
  2047. doMouseMove (position, true);
  2048. if (isValidPeer (this))
  2049. {
  2050. updateModifiersFromWParam (wParam);
  2051. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2052. if (modProvider != nullptr)
  2053. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2054. #endif
  2055. isDragging = true;
  2056. doMouseEvent (position, MouseInputSource::invalidPressure);
  2057. }
  2058. }
  2059. void doMouseUp (Point<float> position, const WPARAM wParam)
  2060. {
  2061. // this will be handled by WM_TOUCH
  2062. if (isTouchEvent() || areOtherTouchSourcesActive())
  2063. return;
  2064. updateModifiersFromWParam (wParam);
  2065. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2066. if (modProvider != nullptr)
  2067. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2068. #endif
  2069. const bool wasDragging = isDragging;
  2070. isDragging = false;
  2071. // release the mouse capture if the user has released all buttons
  2072. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  2073. ReleaseCapture();
  2074. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  2075. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  2076. if (wasDragging)
  2077. doMouseEvent (position, MouseInputSource::invalidPressure);
  2078. }
  2079. void doCaptureChanged()
  2080. {
  2081. if (constrainerIsResizing)
  2082. {
  2083. if (constrainer != nullptr)
  2084. constrainer->resizeEnd();
  2085. constrainerIsResizing = false;
  2086. }
  2087. if (isDragging)
  2088. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  2089. }
  2090. void doMouseExit()
  2091. {
  2092. isMouseOver = false;
  2093. if (! areOtherTouchSourcesActive())
  2094. doMouseEvent (getCurrentMousePos(), MouseInputSource::invalidPressure);
  2095. }
  2096. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  2097. {
  2098. auto currentMousePos = getPOINTFromLParam (GetMessagePos());
  2099. // Because Windows stupidly sends all wheel events to the window with the keyboard
  2100. // focus, we have to redirect them here according to the mouse pos..
  2101. auto* peer = getOwnerOfWindow (WindowFromPoint (currentMousePos));
  2102. if (peer == nullptr)
  2103. peer = this;
  2104. localPos = peer->globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (currentMousePos), hwnd).toFloat());
  2105. return peer;
  2106. }
  2107. static MouseInputSource::InputSourceType getPointerType (WPARAM wParam)
  2108. {
  2109. if (getPointerTypeFunction != nullptr)
  2110. {
  2111. POINTER_INPUT_TYPE pointerType;
  2112. if (getPointerTypeFunction (GET_POINTERID_WPARAM (wParam), &pointerType))
  2113. {
  2114. if (pointerType == 2)
  2115. return MouseInputSource::InputSourceType::touch;
  2116. if (pointerType == 3)
  2117. return MouseInputSource::InputSourceType::pen;
  2118. }
  2119. }
  2120. return MouseInputSource::InputSourceType::mouse;
  2121. }
  2122. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  2123. {
  2124. updateKeyModifiers();
  2125. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  2126. MouseWheelDetails wheel;
  2127. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  2128. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  2129. wheel.isReversed = false;
  2130. wheel.isSmooth = false;
  2131. wheel.isInertial = false;
  2132. Point<float> localPos;
  2133. if (auto* peer = findPeerUnderMouse (localPos))
  2134. peer->handleMouseWheel (getPointerType (wParam), localPos, getMouseEventTime(), wheel);
  2135. }
  2136. bool doGestureEvent (LPARAM lParam)
  2137. {
  2138. GESTUREINFO gi;
  2139. zerostruct (gi);
  2140. gi.cbSize = sizeof (gi);
  2141. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  2142. {
  2143. updateKeyModifiers();
  2144. Point<float> localPos;
  2145. if (auto* peer = findPeerUnderMouse (localPos))
  2146. {
  2147. switch (gi.dwID)
  2148. {
  2149. case 3: /*GID_ZOOM*/
  2150. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  2151. peer->handleMagnifyGesture (MouseInputSource::InputSourceType::touch, localPos, getMouseEventTime(),
  2152. (float) (gi.ullArguments / (double) lastMagnifySize));
  2153. lastMagnifySize = gi.ullArguments;
  2154. return true;
  2155. case 4: /*GID_PAN*/
  2156. case 5: /*GID_ROTATE*/
  2157. case 6: /*GID_TWOFINGERTAP*/
  2158. case 7: /*GID_PRESSANDTAP*/
  2159. default:
  2160. break;
  2161. }
  2162. }
  2163. }
  2164. return false;
  2165. }
  2166. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  2167. {
  2168. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2169. if (auto* parent = getOwnerOfWindow (GetParent (hwnd)))
  2170. if (parent != this)
  2171. return parent->doTouchEvent (numInputs, eventHandle);
  2172. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  2173. if (getTouchInputInfo (eventHandle, numInputs, inputInfo, sizeof (TOUCHINPUT)))
  2174. {
  2175. for (int i = 0; i < numInputs; ++i)
  2176. {
  2177. auto flags = inputInfo[i].dwFlags;
  2178. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  2179. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  2180. return 0; // abandon method if this window was deleted by the callback
  2181. }
  2182. }
  2183. closeTouchInputHandle (eventHandle);
  2184. return 0;
  2185. }
  2186. bool handleTouchInput (const TOUCHINPUT& touch, const bool isDown, const bool isUp,
  2187. const float touchPressure = MouseInputSource::invalidPressure,
  2188. const float orientation = 0.0f)
  2189. {
  2190. auto isCancel = false;
  2191. const auto touchIndex = currentTouches.getIndexOfTouch (this, touch.dwID);
  2192. const auto time = getMouseEventTime();
  2193. const auto pos = globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT ({ roundToInt (touch.x / 100.0f),
  2194. roundToInt (touch.y / 100.0f) }), hwnd).toFloat());
  2195. const auto pressure = touchPressure;
  2196. auto modsToSend = ModifierKeys::currentModifiers;
  2197. if (isDown)
  2198. {
  2199. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2200. modsToSend = ModifierKeys::currentModifiers;
  2201. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2202. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  2203. pressure, orientation, time, {}, touchIndex);
  2204. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2205. return false;
  2206. }
  2207. else if (isUp)
  2208. {
  2209. modsToSend = modsToSend.withoutMouseButtons();
  2210. ModifierKeys::currentModifiers = modsToSend;
  2211. currentTouches.clearTouch (touchIndex);
  2212. if (! currentTouches.areAnyTouchesActive())
  2213. isCancel = true;
  2214. }
  2215. else
  2216. {
  2217. modsToSend = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2218. }
  2219. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend,
  2220. pressure, orientation, time, {}, touchIndex);
  2221. if (! isValidPeer (this))
  2222. return false;
  2223. if (isUp)
  2224. {
  2225. handleMouseEvent (MouseInputSource::InputSourceType::touch, { -10.0f, -10.0f }, ModifierKeys::currentModifiers.withoutMouseButtons(),
  2226. pressure, orientation, time, {}, touchIndex);
  2227. if (! isValidPeer (this))
  2228. return false;
  2229. if (isCancel)
  2230. {
  2231. currentTouches.clear();
  2232. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2233. }
  2234. }
  2235. return true;
  2236. }
  2237. bool handlePointerInput (WPARAM wParam, LPARAM lParam, const bool isDown, const bool isUp)
  2238. {
  2239. if (! canUsePointerAPI)
  2240. return false;
  2241. auto pointerType = getPointerType (wParam);
  2242. if (pointerType == MouseInputSource::InputSourceType::touch)
  2243. {
  2244. POINTER_TOUCH_INFO touchInfo;
  2245. if (! getPointerTouchInfo (GET_POINTERID_WPARAM (wParam), &touchInfo))
  2246. return false;
  2247. const auto pressure = touchInfo.touchMask & TOUCH_MASK_PRESSURE ? touchInfo.pressure
  2248. : MouseInputSource::invalidPressure;
  2249. const auto orientation = touchInfo.touchMask & TOUCH_MASK_ORIENTATION ? degreesToRadians (static_cast<float> (touchInfo.orientation))
  2250. : MouseInputSource::invalidOrientation;
  2251. if (! handleTouchInput (emulateTouchEventFromPointer (lParam, wParam),
  2252. isDown, isUp, pressure, orientation))
  2253. return false;
  2254. }
  2255. else if (pointerType == MouseInputSource::InputSourceType::pen)
  2256. {
  2257. POINTER_PEN_INFO penInfo;
  2258. if (! getPointerPenInfo (GET_POINTERID_WPARAM (wParam), &penInfo))
  2259. return false;
  2260. const auto pressure = (penInfo.penMask & PEN_MASK_PRESSURE) ? penInfo.pressure / 1024.0f : MouseInputSource::invalidPressure;
  2261. if (! handlePenInput (penInfo, globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (lParam)), hwnd).toFloat()),
  2262. pressure, isDown, isUp))
  2263. return false;
  2264. }
  2265. else
  2266. {
  2267. return false;
  2268. }
  2269. return true;
  2270. }
  2271. TOUCHINPUT emulateTouchEventFromPointer (LPARAM lParam, WPARAM wParam)
  2272. {
  2273. Point<int> p (GET_X_LPARAM (lParam),
  2274. GET_Y_LPARAM (lParam));
  2275. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  2276. if (! isPerMonitorDPIAwareThread())
  2277. p = Desktop::getInstance().getDisplays().physicalToLogical (p);
  2278. #endif
  2279. TOUCHINPUT touchInput;
  2280. touchInput.dwID = GET_POINTERID_WPARAM (wParam);
  2281. touchInput.x = p.x * 100;
  2282. touchInput.y = p.y * 100;
  2283. return touchInput;
  2284. }
  2285. bool handlePenInput (POINTER_PEN_INFO penInfo, Point<float> pos, const float pressure, bool isDown, bool isUp)
  2286. {
  2287. const auto time = getMouseEventTime();
  2288. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2289. PenDetails penDetails;
  2290. penDetails.rotation = (penInfo.penMask & PEN_MASK_ROTATION) ? degreesToRadians (static_cast<float> (penInfo.rotation)) : MouseInputSource::invalidRotation;
  2291. penDetails.tiltX = (penInfo.penMask & PEN_MASK_TILT_X) ? penInfo.tiltX / 90.0f : MouseInputSource::invalidTiltX;
  2292. penDetails.tiltY = (penInfo.penMask & PEN_MASK_TILT_Y) ? penInfo.tiltY / 90.0f : MouseInputSource::invalidTiltY;
  2293. auto pInfoFlags = penInfo.pointerInfo.pointerFlags;
  2294. if ((pInfoFlags & POINTER_FLAG_FIRSTBUTTON) != 0)
  2295. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2296. else if ((pInfoFlags & POINTER_FLAG_SECONDBUTTON) != 0)
  2297. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::rightButtonModifier);
  2298. if (isDown)
  2299. {
  2300. modsToSend = ModifierKeys::currentModifiers;
  2301. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2302. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend.withoutMouseButtons(),
  2303. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2304. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2305. return false;
  2306. }
  2307. else if (isUp || ! (pInfoFlags & POINTER_FLAG_INCONTACT))
  2308. {
  2309. modsToSend = modsToSend.withoutMouseButtons();
  2310. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2311. }
  2312. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend, pressure,
  2313. MouseInputSource::invalidOrientation, time, penDetails);
  2314. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2315. return false;
  2316. if (isUp)
  2317. {
  2318. handleMouseEvent (MouseInputSource::InputSourceType::pen, { -10.0f, -10.0f }, ModifierKeys::currentModifiers,
  2319. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2320. if (! isValidPeer (this))
  2321. return false;
  2322. }
  2323. return true;
  2324. }
  2325. //==============================================================================
  2326. void sendModifierKeyChangeIfNeeded()
  2327. {
  2328. if (modifiersAtLastCallback != ModifierKeys::currentModifiers)
  2329. {
  2330. modifiersAtLastCallback = ModifierKeys::currentModifiers;
  2331. handleModifierKeysChange();
  2332. }
  2333. }
  2334. bool doKeyUp (const WPARAM key)
  2335. {
  2336. updateKeyModifiers();
  2337. switch (key)
  2338. {
  2339. case VK_SHIFT:
  2340. case VK_CONTROL:
  2341. case VK_MENU:
  2342. case VK_CAPITAL:
  2343. case VK_LWIN:
  2344. case VK_RWIN:
  2345. case VK_APPS:
  2346. case VK_NUMLOCK:
  2347. case VK_SCROLL:
  2348. case VK_LSHIFT:
  2349. case VK_RSHIFT:
  2350. case VK_LCONTROL:
  2351. case VK_LMENU:
  2352. case VK_RCONTROL:
  2353. case VK_RMENU:
  2354. sendModifierKeyChangeIfNeeded();
  2355. }
  2356. return handleKeyUpOrDown (false)
  2357. || Component::getCurrentlyModalComponent() != nullptr;
  2358. }
  2359. bool doKeyDown (const WPARAM key)
  2360. {
  2361. updateKeyModifiers();
  2362. bool used = false;
  2363. switch (key)
  2364. {
  2365. case VK_SHIFT:
  2366. case VK_LSHIFT:
  2367. case VK_RSHIFT:
  2368. case VK_CONTROL:
  2369. case VK_LCONTROL:
  2370. case VK_RCONTROL:
  2371. case VK_MENU:
  2372. case VK_LMENU:
  2373. case VK_RMENU:
  2374. case VK_LWIN:
  2375. case VK_RWIN:
  2376. case VK_CAPITAL:
  2377. case VK_NUMLOCK:
  2378. case VK_SCROLL:
  2379. case VK_APPS:
  2380. sendModifierKeyChangeIfNeeded();
  2381. break;
  2382. case VK_LEFT:
  2383. case VK_RIGHT:
  2384. case VK_UP:
  2385. case VK_DOWN:
  2386. case VK_PRIOR:
  2387. case VK_NEXT:
  2388. case VK_HOME:
  2389. case VK_END:
  2390. case VK_DELETE:
  2391. case VK_INSERT:
  2392. case VK_F1:
  2393. case VK_F2:
  2394. case VK_F3:
  2395. case VK_F4:
  2396. case VK_F5:
  2397. case VK_F6:
  2398. case VK_F7:
  2399. case VK_F8:
  2400. case VK_F9:
  2401. case VK_F10:
  2402. case VK_F11:
  2403. case VK_F12:
  2404. case VK_F13:
  2405. case VK_F14:
  2406. case VK_F15:
  2407. case VK_F16:
  2408. case VK_F17:
  2409. case VK_F18:
  2410. case VK_F19:
  2411. case VK_F20:
  2412. case VK_F21:
  2413. case VK_F22:
  2414. case VK_F23:
  2415. case VK_F24:
  2416. used = handleKeyUpOrDown (true);
  2417. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  2418. break;
  2419. default:
  2420. used = handleKeyUpOrDown (true);
  2421. {
  2422. MSG msg;
  2423. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  2424. {
  2425. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  2426. // manually generate the key-press event that matches this key-down.
  2427. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  2428. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  2429. BYTE keyState[256];
  2430. GetKeyboardState (keyState);
  2431. WCHAR text[16] = { 0 };
  2432. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  2433. text[0] = 0;
  2434. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  2435. }
  2436. }
  2437. break;
  2438. }
  2439. return used || (Component::getCurrentlyModalComponent() != nullptr);
  2440. }
  2441. bool doKeyChar (int key, const LPARAM flags)
  2442. {
  2443. updateKeyModifiers();
  2444. auto textChar = (juce_wchar) key;
  2445. const int virtualScanCode = (flags >> 16) & 0xff;
  2446. if (key >= '0' && key <= '9')
  2447. {
  2448. switch (virtualScanCode) // check for a numeric keypad scan-code
  2449. {
  2450. case 0x52:
  2451. case 0x4f:
  2452. case 0x50:
  2453. case 0x51:
  2454. case 0x4b:
  2455. case 0x4c:
  2456. case 0x4d:
  2457. case 0x47:
  2458. case 0x48:
  2459. case 0x49:
  2460. key = (key - '0') + KeyPress::numberPad0;
  2461. break;
  2462. default:
  2463. break;
  2464. }
  2465. }
  2466. else
  2467. {
  2468. // convert the scan code to an unmodified character code..
  2469. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  2470. UINT keyChar = MapVirtualKey (virtualKey, 2);
  2471. keyChar = LOWORD (keyChar);
  2472. if (keyChar != 0)
  2473. key = (int) keyChar;
  2474. // avoid sending junk text characters for some control-key combinations
  2475. if (textChar < ' ' && ModifierKeys::currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  2476. textChar = 0;
  2477. }
  2478. return handleKeyPress (key, textChar);
  2479. }
  2480. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  2481. {
  2482. if (HWND parentH = GetParent (hwnd))
  2483. PostMessage (parentH, message, wParam, lParam);
  2484. }
  2485. bool doAppCommand (const LPARAM lParam)
  2486. {
  2487. int key = 0;
  2488. switch (GET_APPCOMMAND_LPARAM (lParam))
  2489. {
  2490. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  2491. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  2492. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  2493. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  2494. default: break;
  2495. }
  2496. if (key != 0)
  2497. {
  2498. updateKeyModifiers();
  2499. if (hwnd == GetActiveWindow())
  2500. {
  2501. handleKeyPress (key, 0);
  2502. return true;
  2503. }
  2504. }
  2505. return false;
  2506. }
  2507. bool isConstrainedNativeWindow() const
  2508. {
  2509. return constrainer != nullptr
  2510. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  2511. && ! isKioskMode();
  2512. }
  2513. Rectangle<int> getCurrentScaledBounds() const
  2514. {
  2515. return ScalingHelpers::unscaledScreenPosToScaled (component, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (component, component.getBounds())));
  2516. }
  2517. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  2518. {
  2519. if (isConstrainedNativeWindow())
  2520. {
  2521. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r), hwnd));
  2522. auto current = getCurrentScaledBounds();
  2523. constrainer->checkBounds (pos, current,
  2524. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2525. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  2526. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  2527. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  2528. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  2529. r = RECTFromRectangle (convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos), hwnd));
  2530. }
  2531. return TRUE;
  2532. }
  2533. LRESULT handlePositionChanging (WINDOWPOS& wp)
  2534. {
  2535. if (isConstrainedNativeWindow())
  2536. {
  2537. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  2538. && (wp.x > -32000 && wp.y > -32000)
  2539. && ! Component::isMouseButtonDownAnywhere())
  2540. {
  2541. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, convertPhysicalScreenRectangleToLogical (rectangleFromRECT ({ wp.x, wp.y, wp.x + wp.cx, wp.y + wp.cy }), hwnd));
  2542. auto current = getCurrentScaledBounds();
  2543. constrainer->checkBounds (pos, current,
  2544. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2545. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  2546. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  2547. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  2548. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  2549. pos = convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos), hwnd);
  2550. wp.x = pos.getX();
  2551. wp.y = pos.getY();
  2552. wp.cx = pos.getWidth();
  2553. wp.cy = pos.getHeight();
  2554. }
  2555. }
  2556. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  2557. component.setVisible (true);
  2558. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  2559. component.setVisible (false);
  2560. return 0;
  2561. }
  2562. bool handlePositionChanged()
  2563. {
  2564. auto pos = getCurrentMousePos();
  2565. if (contains (pos.roundToInt(), false))
  2566. {
  2567. if (! areOtherTouchSourcesActive())
  2568. doMouseEvent (pos, MouseInputSource::invalidPressure);
  2569. if (! isValidPeer (this))
  2570. return true;
  2571. }
  2572. handleMovedOrResized();
  2573. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly..
  2574. }
  2575. LRESULT handleDPIChanging (int newDPI, RECT newRect)
  2576. {
  2577. auto newScale = (double) newDPI / USER_DEFAULT_SCREEN_DPI;
  2578. if (! approximatelyEqual (scaleFactor, newScale))
  2579. {
  2580. const ScopedValueSetter<bool> setter (isInDPIChange, true);
  2581. auto oldScale = scaleFactor;
  2582. scaleFactor = newScale;
  2583. auto scaleRatio = scaleFactor / oldScale;
  2584. EnumChildWindows (hwnd, scaleChildHWNDCallback, (LPARAM) &scaleRatio);
  2585. setBounds (windowBorder.subtractedFrom (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (newRect), hwnd)), false);
  2586. updateShadower();
  2587. InvalidateRect (hwnd, nullptr, FALSE);
  2588. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  2589. }
  2590. return 0;
  2591. }
  2592. static BOOL CALLBACK scaleChildHWNDCallback (HWND hwnd, LPARAM context)
  2593. {
  2594. auto r = getWindowRect (hwnd);
  2595. POINT p { r.left, r.top };
  2596. ScreenToClient (GetParent (hwnd), &p);
  2597. auto ratio = *(double*) context;
  2598. SetWindowPos (hwnd, 0, roundToInt (p.x * ratio), roundToInt (p.y * ratio),
  2599. roundToInt ((r.right - r.left) * ratio), roundToInt ((r.bottom - r.top) * ratio),
  2600. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  2601. if (auto* peer = getOwnerOfWindow (hwnd))
  2602. peer->handleChildDPIChanging();
  2603. return TRUE;
  2604. }
  2605. void handleChildDPIChanging()
  2606. {
  2607. const ScopedValueSetter<bool> setter (isInDPIChange, true);
  2608. scaleFactor = getScaleFactorForWindow (parentToAddTo);
  2609. updateShadower();
  2610. InvalidateRect (hwnd, nullptr, FALSE);
  2611. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  2612. }
  2613. void handleAppActivation (const WPARAM wParam)
  2614. {
  2615. modifiersAtLastCallback = -1;
  2616. updateKeyModifiers();
  2617. if (isMinimised())
  2618. {
  2619. component.repaint();
  2620. handleMovedOrResized();
  2621. if (! isValidPeer (this))
  2622. return;
  2623. }
  2624. auto* underMouse = component.getComponentAt (component.getMouseXYRelative());
  2625. if (underMouse == nullptr)
  2626. underMouse = &component;
  2627. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  2628. {
  2629. if (LOWORD (wParam) == WA_CLICKACTIVE)
  2630. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  2631. else
  2632. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  2633. }
  2634. else
  2635. {
  2636. handleBroughtToFront();
  2637. }
  2638. }
  2639. void handlePowerBroadcast (WPARAM wParam)
  2640. {
  2641. if (auto* app = JUCEApplicationBase::getInstance())
  2642. {
  2643. switch (wParam)
  2644. {
  2645. case PBT_APMSUSPEND: app->suspended(); break;
  2646. case PBT_APMQUERYSUSPENDFAILED:
  2647. case PBT_APMRESUMECRITICAL:
  2648. case PBT_APMRESUMESUSPEND:
  2649. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  2650. default: break;
  2651. }
  2652. }
  2653. }
  2654. void handleLeftClickInNCArea (WPARAM wParam)
  2655. {
  2656. if (! sendInputAttemptWhenModalMessage())
  2657. {
  2658. switch (wParam)
  2659. {
  2660. case HTBOTTOM:
  2661. case HTBOTTOMLEFT:
  2662. case HTBOTTOMRIGHT:
  2663. case HTGROWBOX:
  2664. case HTLEFT:
  2665. case HTRIGHT:
  2666. case HTTOP:
  2667. case HTTOPLEFT:
  2668. case HTTOPRIGHT:
  2669. if (isConstrainedNativeWindow())
  2670. {
  2671. constrainerIsResizing = true;
  2672. constrainer->resizeStart();
  2673. }
  2674. break;
  2675. default:
  2676. break;
  2677. }
  2678. }
  2679. }
  2680. void initialiseSysMenu (HMENU menu) const
  2681. {
  2682. if (! hasTitleBar())
  2683. {
  2684. if (isFullScreen())
  2685. {
  2686. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  2687. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  2688. }
  2689. else if (! isMinimised())
  2690. {
  2691. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  2692. }
  2693. }
  2694. }
  2695. void doSettingChange()
  2696. {
  2697. forceDisplayUpdate();
  2698. if (fullScreen && ! isMinimised())
  2699. setWindowPos (hwnd, Desktop::getInstance().getDisplays().findDisplayForRect (component.getScreenBounds()).userArea,
  2700. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  2701. }
  2702. static void forceDisplayUpdate()
  2703. {
  2704. const_cast<Displays&> (Desktop::getInstance().getDisplays()).refresh();
  2705. }
  2706. //==============================================================================
  2707. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2708. void setModifierKeyProvider (ModifierKeyProvider* provider) override
  2709. {
  2710. modProvider = provider;
  2711. }
  2712. void removeModifierKeyProvider() override
  2713. {
  2714. modProvider = nullptr;
  2715. }
  2716. #endif
  2717. //==============================================================================
  2718. public:
  2719. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2720. {
  2721. // Ensure that non-client areas are scaled for per-monitor DPI awareness v1 - can't
  2722. // do this in peerWindowProc as we have no window at this point
  2723. if (message == WM_NCCREATE && enableNonClientDPIScaling != nullptr)
  2724. enableNonClientDPIScaling (h);
  2725. if (auto* peer = getOwnerOfWindow (h))
  2726. {
  2727. jassert (isValidPeer (peer));
  2728. return peer->peerWindowProc (h, message, wParam, lParam);
  2729. }
  2730. return DefWindowProcW (h, message, wParam, lParam);
  2731. }
  2732. private:
  2733. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  2734. {
  2735. auto& mm = *MessageManager::getInstance();
  2736. if (mm.currentThreadHasLockedMessageManager())
  2737. return callback (userData);
  2738. return mm.callFunctionOnMessageThread (callback, userData);
  2739. }
  2740. static POINT getPOINTFromLParam (LPARAM lParam) noexcept
  2741. {
  2742. return { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
  2743. }
  2744. Point<float> getPointFromLocalLParam (LPARAM lParam) noexcept
  2745. {
  2746. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  2747. if (isPerMonitorDPIAwareWindow (hwnd))
  2748. {
  2749. // LPARAM is relative to this window's top-left but may be on a different monitor so we need to calculate the
  2750. // physical screen position and then convert this to local logical coordinates
  2751. auto localPos = getPOINTFromLParam (lParam);
  2752. auto r = getWindowRect (hwnd);
  2753. return globalToLocal (Desktop::getInstance().getDisplays().physicalToLogical (pointFromPOINT ({ r.left + localPos.x + roundToInt (windowBorder.getLeft() * scaleFactor),
  2754. r.top + localPos.y + roundToInt (windowBorder.getTop() * scaleFactor) })).toFloat());
  2755. }
  2756. #endif
  2757. return { static_cast<float> (GET_X_LPARAM (lParam)), static_cast<float> (GET_Y_LPARAM (lParam)) };
  2758. }
  2759. Point<float> getCurrentMousePos() noexcept
  2760. {
  2761. return globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (GetMessagePos())), hwnd).toFloat());
  2762. }
  2763. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2764. {
  2765. switch (message)
  2766. {
  2767. //==============================================================================
  2768. case WM_NCHITTEST:
  2769. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2770. return HTTRANSPARENT;
  2771. if (! hasTitleBar())
  2772. return HTCLIENT;
  2773. break;
  2774. //==============================================================================
  2775. case WM_PAINT:
  2776. handlePaintMessage();
  2777. return 0;
  2778. case WM_NCPAINT:
  2779. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  2780. if (hasTitleBar())
  2781. break; // let the DefWindowProc handle drawing the frame.
  2782. return 0;
  2783. case WM_ERASEBKGND:
  2784. case WM_NCCALCSIZE:
  2785. if (hasTitleBar())
  2786. break;
  2787. return 1;
  2788. //==============================================================================
  2789. case WM_POINTERUPDATE:
  2790. if (handlePointerInput (wParam, lParam, false, false))
  2791. return 0;
  2792. break;
  2793. case WM_POINTERDOWN:
  2794. if (handlePointerInput (wParam, lParam, true, false))
  2795. return 0;
  2796. break;
  2797. case WM_POINTERUP:
  2798. if (handlePointerInput (wParam, lParam, false, true))
  2799. return 0;
  2800. break;
  2801. //==============================================================================
  2802. case WM_MOUSEMOVE: doMouseMove (getPointFromLocalLParam (lParam), false); return 0;
  2803. case WM_POINTERLEAVE:
  2804. case WM_MOUSELEAVE: doMouseExit(); return 0;
  2805. case WM_LBUTTONDOWN:
  2806. case WM_MBUTTONDOWN:
  2807. case WM_RBUTTONDOWN: doMouseDown (getPointFromLocalLParam (lParam), wParam); return 0;
  2808. case WM_LBUTTONUP:
  2809. case WM_MBUTTONUP:
  2810. case WM_RBUTTONUP: doMouseUp (getPointFromLocalLParam (lParam), wParam); return 0;
  2811. case WM_POINTERWHEEL:
  2812. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  2813. case WM_POINTERHWHEEL:
  2814. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  2815. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  2816. case WM_NCPOINTERUPDATE:
  2817. case WM_NCMOUSEMOVE:
  2818. if (hasTitleBar())
  2819. break;
  2820. return 0;
  2821. case WM_TOUCH:
  2822. if (getTouchInputInfo != nullptr)
  2823. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  2824. break;
  2825. case 0x119: /* WM_GESTURE */
  2826. if (doGestureEvent (lParam))
  2827. return 0;
  2828. break;
  2829. //==============================================================================
  2830. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  2831. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  2832. case 0x2e0: /* WM_DPICHANGED */ return handleDPIChanging ((int) HIWORD (wParam), *(RECT*) lParam);
  2833. case WM_WINDOWPOSCHANGED:
  2834. {
  2835. const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
  2836. if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
  2837. startTimer (100);
  2838. else
  2839. if (handlePositionChanged())
  2840. return 0;
  2841. }
  2842. break;
  2843. //==============================================================================
  2844. case WM_KEYDOWN:
  2845. case WM_SYSKEYDOWN:
  2846. if (doKeyDown (wParam))
  2847. return 0;
  2848. forwardMessageToParent (message, wParam, lParam);
  2849. break;
  2850. case WM_KEYUP:
  2851. case WM_SYSKEYUP:
  2852. if (doKeyUp (wParam))
  2853. return 0;
  2854. forwardMessageToParent (message, wParam, lParam);
  2855. break;
  2856. case WM_CHAR:
  2857. if (doKeyChar ((int) wParam, lParam))
  2858. return 0;
  2859. forwardMessageToParent (message, wParam, lParam);
  2860. break;
  2861. case WM_APPCOMMAND:
  2862. if (doAppCommand (lParam))
  2863. return TRUE;
  2864. break;
  2865. case WM_MENUCHAR: // triggered when alt+something is pressed
  2866. return MNC_CLOSE << 16; // (avoids making the default system beep)
  2867. //==============================================================================
  2868. case WM_SETFOCUS:
  2869. updateKeyModifiers();
  2870. handleFocusGain();
  2871. break;
  2872. case WM_KILLFOCUS:
  2873. if (hasCreatedCaret)
  2874. {
  2875. hasCreatedCaret = false;
  2876. DestroyCaret();
  2877. }
  2878. handleFocusLoss();
  2879. break;
  2880. case WM_ACTIVATEAPP:
  2881. // Windows does weird things to process priority when you swap apps,
  2882. // so this forces an update when the app is brought to the front
  2883. if (wParam != FALSE)
  2884. juce_repeatLastProcessPriority();
  2885. else
  2886. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  2887. juce_checkCurrentlyFocusedTopLevelWindow();
  2888. modifiersAtLastCallback = -1;
  2889. return 0;
  2890. case WM_ACTIVATE:
  2891. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  2892. {
  2893. handleAppActivation (wParam);
  2894. return 0;
  2895. }
  2896. break;
  2897. case WM_NCACTIVATE:
  2898. // while a temporary window is being shown, prevent Windows from deactivating the
  2899. // title bars of our main windows.
  2900. if (wParam == 0 && ! shouldDeactivateTitleBar)
  2901. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  2902. break;
  2903. case WM_POINTERACTIVATE:
  2904. case WM_MOUSEACTIVATE:
  2905. if (! component.getMouseClickGrabsKeyboardFocus())
  2906. return MA_NOACTIVATE;
  2907. break;
  2908. case WM_SHOWWINDOW:
  2909. if (wParam != 0)
  2910. {
  2911. component.setVisible (true);
  2912. handleBroughtToFront();
  2913. }
  2914. break;
  2915. case WM_CLOSE:
  2916. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  2917. handleUserClosingWindow();
  2918. return 0;
  2919. #if JUCE_REMOVE_COMPONENT_FROM_DESKTOP_ON_WM_DESTROY
  2920. case WM_DESTROY:
  2921. getComponent().removeFromDesktop();
  2922. return 0;
  2923. #endif
  2924. case WM_QUERYENDSESSION:
  2925. if (auto* app = JUCEApplicationBase::getInstance())
  2926. {
  2927. app->systemRequestedQuit();
  2928. return MessageManager::getInstance()->hasStopMessageBeenSent();
  2929. }
  2930. return TRUE;
  2931. case WM_POWERBROADCAST:
  2932. handlePowerBroadcast (wParam);
  2933. break;
  2934. case WM_SYNCPAINT:
  2935. return 0;
  2936. case WM_DISPLAYCHANGE:
  2937. InvalidateRect (h, 0, 0);
  2938. // intentional fall-through...
  2939. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  2940. doSettingChange();
  2941. break;
  2942. case WM_INITMENU:
  2943. initialiseSysMenu ((HMENU) wParam);
  2944. break;
  2945. case WM_SYSCOMMAND:
  2946. switch (wParam & 0xfff0)
  2947. {
  2948. case SC_CLOSE:
  2949. if (sendInputAttemptWhenModalMessage())
  2950. return 0;
  2951. if (hasTitleBar())
  2952. {
  2953. PostMessage (h, WM_CLOSE, 0, 0);
  2954. return 0;
  2955. }
  2956. break;
  2957. case SC_KEYMENU:
  2958. #if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
  2959. // This test prevents a press of the ALT key from triggering the ancient top-left window menu.
  2960. // By default we suppress this behaviour because it's unlikely that more than a tiny subset of
  2961. // our users will actually want it, and it causes problems if you're trying to use the ALT key
  2962. // as a modifier for mouse actions. If you really need the old behaviour, then just define
  2963. // JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
  2964. if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
  2965. return 0;
  2966. #endif
  2967. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  2968. // situations that can arise if a modal loop is started from an alt-key keypress).
  2969. if (hasTitleBar() && h == GetCapture())
  2970. ReleaseCapture();
  2971. break;
  2972. case SC_MAXIMIZE:
  2973. if (! sendInputAttemptWhenModalMessage())
  2974. setFullScreen (true);
  2975. return 0;
  2976. case SC_MINIMIZE:
  2977. if (sendInputAttemptWhenModalMessage())
  2978. return 0;
  2979. if (! hasTitleBar())
  2980. {
  2981. setMinimised (true);
  2982. return 0;
  2983. }
  2984. break;
  2985. case SC_RESTORE:
  2986. if (sendInputAttemptWhenModalMessage())
  2987. return 0;
  2988. if (hasTitleBar())
  2989. {
  2990. if (isFullScreen())
  2991. {
  2992. setFullScreen (false);
  2993. return 0;
  2994. }
  2995. }
  2996. else
  2997. {
  2998. if (isMinimised())
  2999. setMinimised (false);
  3000. else if (isFullScreen())
  3001. setFullScreen (false);
  3002. return 0;
  3003. }
  3004. break;
  3005. }
  3006. break;
  3007. case WM_NCPOINTERDOWN:
  3008. case WM_NCLBUTTONDOWN:
  3009. handleLeftClickInNCArea (wParam);
  3010. break;
  3011. case WM_NCRBUTTONDOWN:
  3012. case WM_NCMBUTTONDOWN:
  3013. sendInputAttemptWhenModalMessage();
  3014. break;
  3015. case WM_IME_SETCONTEXT:
  3016. imeHandler.handleSetContext (h, wParam == TRUE);
  3017. lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  3018. break;
  3019. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  3020. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  3021. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  3022. case WM_GETDLGCODE:
  3023. return DLGC_WANTALLKEYS;
  3024. default:
  3025. break;
  3026. }
  3027. return DefWindowProcW (h, message, wParam, lParam);
  3028. }
  3029. bool sendInputAttemptWhenModalMessage()
  3030. {
  3031. if (component.isCurrentlyBlockedByAnotherModalComponent())
  3032. {
  3033. if (Component* const current = Component::getCurrentlyModalComponent())
  3034. current->inputAttemptWhenModal();
  3035. return true;
  3036. }
  3037. return false;
  3038. }
  3039. //==============================================================================
  3040. struct IMEHandler
  3041. {
  3042. IMEHandler()
  3043. {
  3044. reset();
  3045. }
  3046. void handleSetContext (HWND hWnd, const bool windowIsActive)
  3047. {
  3048. if (compositionInProgress && ! windowIsActive)
  3049. {
  3050. compositionInProgress = false;
  3051. if (HIMC hImc = ImmGetContext (hWnd))
  3052. {
  3053. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  3054. ImmReleaseContext (hWnd, hImc);
  3055. }
  3056. }
  3057. }
  3058. void handleStartComposition (ComponentPeer& owner)
  3059. {
  3060. reset();
  3061. if (auto* target = owner.findCurrentTextInputTarget())
  3062. target->insertTextAtCaret (String());
  3063. }
  3064. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  3065. {
  3066. if (compositionInProgress)
  3067. {
  3068. // If this occurs, the user has cancelled the composition, so clear their changes..
  3069. if (auto* target = owner.findCurrentTextInputTarget())
  3070. {
  3071. target->setHighlightedRegion (compositionRange);
  3072. target->insertTextAtCaret (String());
  3073. compositionRange.setLength (0);
  3074. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  3075. target->setTemporaryUnderlining ({});
  3076. }
  3077. if (auto hImc = ImmGetContext (hWnd))
  3078. {
  3079. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  3080. ImmReleaseContext (hWnd, hImc);
  3081. }
  3082. }
  3083. reset();
  3084. }
  3085. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  3086. {
  3087. if (auto* target = owner.findCurrentTextInputTarget())
  3088. {
  3089. if (auto hImc = ImmGetContext (hWnd))
  3090. {
  3091. if (compositionRange.getStart() < 0)
  3092. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  3093. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  3094. {
  3095. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  3096. Range<int>::emptyRange (-1));
  3097. reset();
  3098. target->setTemporaryUnderlining ({});
  3099. }
  3100. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  3101. {
  3102. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  3103. getCompositionSelection (hImc, lParam));
  3104. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  3105. compositionInProgress = true;
  3106. }
  3107. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  3108. ImmReleaseContext (hWnd, hImc);
  3109. }
  3110. }
  3111. }
  3112. private:
  3113. //==============================================================================
  3114. Range<int> compositionRange; // The range being modified in the TextInputTarget
  3115. bool compositionInProgress;
  3116. //==============================================================================
  3117. void reset()
  3118. {
  3119. compositionRange = Range<int>::emptyRange (-1);
  3120. compositionInProgress = false;
  3121. }
  3122. String getCompositionString (HIMC hImc, const DWORD type) const
  3123. {
  3124. jassert (hImc != 0);
  3125. const int stringSizeBytes = ImmGetCompositionString (hImc, type, 0, 0);
  3126. if (stringSizeBytes > 0)
  3127. {
  3128. HeapBlock<TCHAR> buffer;
  3129. buffer.calloc (stringSizeBytes / sizeof (TCHAR) + 1);
  3130. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  3131. return String (buffer.get());
  3132. }
  3133. return {};
  3134. }
  3135. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  3136. {
  3137. jassert (hImc != 0);
  3138. if ((lParam & CS_NOMOVECARET) != 0)
  3139. return compositionRange.getStart();
  3140. if ((lParam & GCS_CURSORPOS) != 0)
  3141. {
  3142. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, 0, 0);
  3143. return compositionRange.getStart() + jmax (0, localCaretPos);
  3144. }
  3145. return compositionRange.getStart() + currentIMEString.length();
  3146. }
  3147. // Get selected/highlighted range while doing composition:
  3148. // returned range is relative to beginning of TextInputTarget, not composition string
  3149. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  3150. {
  3151. jassert (hImc != 0);
  3152. int selectionStart = 0;
  3153. int selectionEnd = 0;
  3154. if ((lParam & GCS_COMPATTR) != 0)
  3155. {
  3156. // Get size of attributes array:
  3157. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, 0, 0);
  3158. if (attributeSizeBytes > 0)
  3159. {
  3160. // Get attributes (8 bit flag per character):
  3161. HeapBlock<char> attributes (attributeSizeBytes);
  3162. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  3163. selectionStart = 0;
  3164. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  3165. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  3166. break;
  3167. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  3168. if (attributes[selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  3169. break;
  3170. }
  3171. }
  3172. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  3173. }
  3174. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  3175. {
  3176. if (compositionInProgress)
  3177. target->setHighlightedRegion (compositionRange);
  3178. target->insertTextAtCaret (newContent);
  3179. compositionRange.setLength (newContent.length());
  3180. if (newSelection.getStart() < 0)
  3181. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  3182. target->setHighlightedRegion (newSelection);
  3183. }
  3184. Array<Range<int>> getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  3185. {
  3186. Array<Range<int>> result;
  3187. if (hImc != 0 && (lParam & GCS_COMPCLAUSE) != 0)
  3188. {
  3189. auto clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, 0, 0);
  3190. if (clauseDataSizeBytes > 0)
  3191. {
  3192. const size_t numItems = clauseDataSizeBytes / sizeof (uint32);
  3193. HeapBlock<uint32> clauseData (numItems);
  3194. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  3195. for (size_t i = 0; i + 1 < numItems; ++i)
  3196. result.add (Range<int> ((int) clauseData[i], (int) clauseData[i + 1]) + compositionRange.getStart());
  3197. }
  3198. }
  3199. return result;
  3200. }
  3201. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  3202. {
  3203. if (auto* targetComp = dynamic_cast<Component*> (target))
  3204. {
  3205. auto area = peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle());
  3206. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  3207. ImmSetCandidateWindow (hImc, &pos);
  3208. }
  3209. }
  3210. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  3211. };
  3212. void timerCallback() override
  3213. {
  3214. handlePositionChanged();
  3215. stopTimer();
  3216. }
  3217. IMEHandler imeHandler;
  3218. //==============================================================================
  3219. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  3220. };
  3221. MultiTouchMapper<DWORD> HWNDComponentPeer::currentTouches;
  3222. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  3223. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  3224. {
  3225. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  3226. }
  3227. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  3228. {
  3229. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  3230. (HWND) parentHWND, true);
  3231. }
  3232. JUCE_API bool shouldScaleGLWindow (void* hwnd)
  3233. {
  3234. return isPerMonitorDPIAwareWindow ((HWND) hwnd);
  3235. }
  3236. JUCE_IMPLEMENT_SINGLETON (HWNDComponentPeer::WindowClassHolder)
  3237. //==============================================================================
  3238. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  3239. {
  3240. auto k = (SHORT) keyCode;
  3241. if ((keyCode & extendedKeyModifier) == 0)
  3242. {
  3243. if (k >= (SHORT) 'a' && k <= (SHORT) 'z')
  3244. k += (SHORT) 'A' - (SHORT) 'a';
  3245. // Only translate if extendedKeyModifier flag is not set
  3246. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  3247. (SHORT) '+', VK_OEM_PLUS,
  3248. (SHORT) '-', VK_OEM_MINUS,
  3249. (SHORT) '.', VK_OEM_PERIOD,
  3250. (SHORT) ';', VK_OEM_1,
  3251. (SHORT) ':', VK_OEM_1,
  3252. (SHORT) '/', VK_OEM_2,
  3253. (SHORT) '?', VK_OEM_2,
  3254. (SHORT) '[', VK_OEM_4,
  3255. (SHORT) ']', VK_OEM_6 };
  3256. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  3257. if (k == translatedValues[i])
  3258. k = translatedValues[i + 1];
  3259. }
  3260. return HWNDComponentPeer::isKeyDown (k);
  3261. }
  3262. // (This internal function is used by the plugin client module)
  3263. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  3264. //==============================================================================
  3265. bool JUCE_CALLTYPE Process::isForegroundProcess()
  3266. {
  3267. if (auto fg = GetForegroundWindow())
  3268. {
  3269. DWORD processID = 0;
  3270. GetWindowThreadProcessId (fg, &processID);
  3271. return processID == GetCurrentProcessId();
  3272. }
  3273. return true;
  3274. }
  3275. // N/A on Windows as far as I know.
  3276. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  3277. void JUCE_CALLTYPE Process::hide() {}
  3278. //==============================================================================
  3279. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  3280. {
  3281. if (IsWindowVisible (hwnd))
  3282. {
  3283. DWORD processID = 0;
  3284. GetWindowThreadProcessId (hwnd, &processID);
  3285. if (processID == GetCurrentProcessId())
  3286. {
  3287. WINDOWINFO info;
  3288. if (GetWindowInfo (hwnd, &info)
  3289. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  3290. {
  3291. *reinterpret_cast<bool*> (lParam) = true;
  3292. return FALSE;
  3293. }
  3294. }
  3295. }
  3296. return TRUE;
  3297. }
  3298. bool juce_areThereAnyAlwaysOnTopWindows()
  3299. {
  3300. bool anyAlwaysOnTopFound = false;
  3301. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  3302. return anyAlwaysOnTopFound;
  3303. }
  3304. //==============================================================================
  3305. class WindowsMessageBox : public AsyncUpdater
  3306. {
  3307. public:
  3308. WindowsMessageBox (AlertWindow::AlertIconType iconType,
  3309. const String& boxTitle, const String& m,
  3310. Component* associatedComponent, UINT extraFlags,
  3311. ModalComponentManager::Callback* cb, const bool runAsync)
  3312. : flags (extraFlags | getMessageBoxFlags (iconType)),
  3313. owner (getWindowForMessageBox (associatedComponent)),
  3314. title (boxTitle), message (m), callback (cb)
  3315. {
  3316. if (runAsync)
  3317. triggerAsyncUpdate();
  3318. }
  3319. int getResult() const
  3320. {
  3321. const int r = MessageBox (owner, message.toWideCharPointer(), title.toWideCharPointer(), flags);
  3322. return (r == IDYES || r == IDOK) ? 1 : (r == IDNO && (flags & 1) != 0 ? 2 : 0);
  3323. }
  3324. void handleAsyncUpdate() override
  3325. {
  3326. const int result = getResult();
  3327. if (callback != nullptr)
  3328. callback->modalStateFinished (result);
  3329. delete this;
  3330. }
  3331. private:
  3332. UINT flags;
  3333. HWND owner;
  3334. String title, message;
  3335. std::unique_ptr<ModalComponentManager::Callback> callback;
  3336. static UINT getMessageBoxFlags (AlertWindow::AlertIconType iconType) noexcept
  3337. {
  3338. UINT flags = MB_TASKMODAL | MB_SETFOREGROUND;
  3339. // this window can get lost behind JUCE windows which are set to be alwaysOnTop
  3340. // so if there are any set it to be topmost
  3341. if (juce_areThereAnyAlwaysOnTopWindows())
  3342. flags |= MB_TOPMOST;
  3343. switch (iconType)
  3344. {
  3345. case AlertWindow::QuestionIcon: flags |= MB_ICONQUESTION; break;
  3346. case AlertWindow::WarningIcon: flags |= MB_ICONWARNING; break;
  3347. case AlertWindow::InfoIcon: flags |= MB_ICONINFORMATION; break;
  3348. default: break;
  3349. }
  3350. return flags;
  3351. }
  3352. static HWND getWindowForMessageBox (Component* associatedComponent)
  3353. {
  3354. return associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : 0;
  3355. }
  3356. };
  3357. #if JUCE_MODAL_LOOPS_PERMITTED
  3358. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3359. const String& title, const String& message,
  3360. Component* associatedComponent)
  3361. {
  3362. WindowsMessageBox box (iconType, title, message, associatedComponent, MB_OK, 0, false);
  3363. (void) box.getResult();
  3364. }
  3365. #endif
  3366. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3367. const String& title, const String& message,
  3368. Component* associatedComponent,
  3369. ModalComponentManager::Callback* callback)
  3370. {
  3371. new WindowsMessageBox (iconType, title, message, associatedComponent, MB_OK, callback, true);
  3372. }
  3373. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3374. const String& title, const String& message,
  3375. Component* associatedComponent,
  3376. ModalComponentManager::Callback* callback)
  3377. {
  3378. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3379. MB_OKCANCEL, callback, callback != nullptr));
  3380. if (callback == nullptr)
  3381. return mb->getResult() != 0;
  3382. mb.release();
  3383. return false;
  3384. }
  3385. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3386. const String& title, const String& message,
  3387. Component* associatedComponent,
  3388. ModalComponentManager::Callback* callback)
  3389. {
  3390. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3391. MB_YESNOCANCEL, callback, callback != nullptr));
  3392. if (callback == nullptr)
  3393. return mb->getResult();
  3394. mb.release();
  3395. return 0;
  3396. }
  3397. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  3398. const String& title, const String& message,
  3399. Component* associatedComponent,
  3400. ModalComponentManager::Callback* callback)
  3401. {
  3402. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3403. MB_YESNO, callback, callback != nullptr));
  3404. if (callback == nullptr)
  3405. return mb->getResult();
  3406. mb.release();
  3407. return 0;
  3408. }
  3409. //==============================================================================
  3410. bool MouseInputSource::SourceList::addSource()
  3411. {
  3412. auto numSources = sources.size();
  3413. if (numSources == 0 || canUseMultiTouch())
  3414. {
  3415. addSource (numSources, numSources == 0 ? MouseInputSource::InputSourceType::mouse
  3416. : MouseInputSource::InputSourceType::touch);
  3417. return true;
  3418. }
  3419. return false;
  3420. }
  3421. bool MouseInputSource::SourceList::canUseTouch()
  3422. {
  3423. return canUseMultiTouch();
  3424. }
  3425. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3426. {
  3427. POINT mousePos;
  3428. GetCursorPos (&mousePos);
  3429. auto p = pointFromPOINT (mousePos);
  3430. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3431. if (isPerMonitorDPIAwareThread())
  3432. p = Desktop::getInstance().getDisplays().physicalToLogical (p);
  3433. #endif
  3434. return p.toFloat();
  3435. }
  3436. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3437. {
  3438. auto newPositionInt = newPosition.roundToInt();
  3439. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3440. if (isPerMonitorDPIAwareThread())
  3441. newPositionInt = Desktop::getInstance().getDisplays().logicalToPhysical (newPositionInt);
  3442. #endif
  3443. auto point = POINTFromPoint (newPositionInt);
  3444. SetCursorPos (point.x, point.y);
  3445. }
  3446. //==============================================================================
  3447. class ScreenSaverDefeater : public Timer
  3448. {
  3449. public:
  3450. ScreenSaverDefeater()
  3451. {
  3452. startTimer (10000);
  3453. timerCallback();
  3454. }
  3455. void timerCallback() override
  3456. {
  3457. if (Process::isForegroundProcess())
  3458. {
  3459. INPUT input = { 0 };
  3460. input.type = INPUT_MOUSE;
  3461. input.mi.mouseData = MOUSEEVENTF_MOVE;
  3462. SendInput (1, &input, sizeof (INPUT));
  3463. }
  3464. }
  3465. };
  3466. static std::unique_ptr<ScreenSaverDefeater> screenSaverDefeater;
  3467. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3468. {
  3469. if (isEnabled)
  3470. screenSaverDefeater = nullptr;
  3471. else if (screenSaverDefeater == nullptr)
  3472. screenSaverDefeater.reset (new ScreenSaverDefeater());
  3473. }
  3474. bool Desktop::isScreenSaverEnabled()
  3475. {
  3476. return screenSaverDefeater == nullptr;
  3477. }
  3478. //==============================================================================
  3479. void LookAndFeel::playAlertSound()
  3480. {
  3481. MessageBeep (MB_OK);
  3482. }
  3483. //==============================================================================
  3484. void SystemClipboard::copyTextToClipboard (const String& text)
  3485. {
  3486. if (OpenClipboard (0) != 0)
  3487. {
  3488. if (EmptyClipboard() != 0)
  3489. {
  3490. auto bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  3491. if (bytesNeeded > 0)
  3492. {
  3493. if (auto bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  3494. {
  3495. if (auto* data = static_cast<WCHAR*> (GlobalLock (bufH)))
  3496. {
  3497. text.copyToUTF16 (data, bytesNeeded);
  3498. GlobalUnlock (bufH);
  3499. SetClipboardData (CF_UNICODETEXT, bufH);
  3500. }
  3501. }
  3502. }
  3503. }
  3504. CloseClipboard();
  3505. }
  3506. }
  3507. String SystemClipboard::getTextFromClipboard()
  3508. {
  3509. String result;
  3510. if (OpenClipboard (0) != 0)
  3511. {
  3512. if (auto bufH = GetClipboardData (CF_UNICODETEXT))
  3513. {
  3514. if (auto* data = (const WCHAR*) GlobalLock (bufH))
  3515. {
  3516. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  3517. GlobalUnlock (bufH);
  3518. }
  3519. }
  3520. CloseClipboard();
  3521. }
  3522. return result;
  3523. }
  3524. //==============================================================================
  3525. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  3526. {
  3527. if (auto* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComp))
  3528. tlw->setUsingNativeTitleBar (! enableOrDisable);
  3529. if (enableOrDisable)
  3530. kioskModeComp->setBounds (getDisplays().getMainDisplay().totalArea);
  3531. }
  3532. void Desktop::allowedOrientationsChanged() {}
  3533. //==============================================================================
  3534. static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd)
  3535. {
  3536. Array<Displays::Display*> candidateDisplays;
  3537. double scaleToLookFor = -1.0;
  3538. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  3539. scaleToLookFor = peer->getPlatformScaleFactor();
  3540. else
  3541. scaleToLookFor = getScaleFactorForWindow (hwnd);
  3542. auto globalScale = Desktop::getInstance().getGlobalScaleFactor();
  3543. for (auto& d : Desktop::getInstance().getDisplays().displays)
  3544. if (approximatelyEqual (d.scale / globalScale, scaleToLookFor))
  3545. candidateDisplays.add (&d);
  3546. if (candidateDisplays.size() > 0)
  3547. {
  3548. if (candidateDisplays.size() == 1)
  3549. return candidateDisplays[0];
  3550. Rectangle<int> bounds;
  3551. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  3552. bounds = peer->getComponent().getTopLevelComponent()->getBounds();
  3553. else
  3554. bounds = Desktop::getInstance().getDisplays().physicalToLogical (rectangleFromRECT (getWindowRect (hwnd)));
  3555. Displays::Display* retVal = nullptr;
  3556. int maxArea = -1;
  3557. for (auto* d : candidateDisplays)
  3558. {
  3559. auto intersection = d->totalArea.getIntersection (bounds);
  3560. auto area = intersection.getWidth() * intersection.getHeight();
  3561. if (area > maxArea)
  3562. {
  3563. maxArea = area;
  3564. retVal = d;
  3565. }
  3566. }
  3567. if (retVal != nullptr)
  3568. return retVal;
  3569. }
  3570. return &Desktop::getInstance().getDisplays().getMainDisplay();
  3571. }
  3572. //==============================================================================
  3573. struct MonitorInfo
  3574. {
  3575. MonitorInfo (bool main, RECT rect, double d) noexcept
  3576. : isMain (main), bounds (rect), dpi (d) {}
  3577. bool isMain;
  3578. RECT bounds;
  3579. double dpi;
  3580. };
  3581. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT r, LPARAM userInfo)
  3582. {
  3583. MONITORINFO info = { 0 };
  3584. info.cbSize = sizeof (info);
  3585. GetMonitorInfo (hm, &info);
  3586. auto isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  3587. auto dpi = 0.0;
  3588. if (getDPIForMonitor != nullptr)
  3589. {
  3590. UINT dpiX = 0, dpiY = 0;
  3591. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  3592. dpi = (dpiX + dpiY) / 2.0;
  3593. }
  3594. ((Array<MonitorInfo>*) userInfo)->add ({ isMain, *r, dpi });
  3595. return TRUE;
  3596. }
  3597. void Displays::findDisplays (float masterScale)
  3598. {
  3599. setDPIAwareness();
  3600. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3601. DPI_AWARENESS_CONTEXT prevContext = nullptr;
  3602. if (setThreadDPIAwarenessContext != nullptr && getAwarenessFromDPIAwarenessContext != nullptr && getThreadDPIAwarenessContext != nullptr
  3603. && getAwarenessFromDPIAwarenessContext (getThreadDPIAwarenessContext()) != DPI_Awareness::DPI_Awareness_Per_Monitor_Aware)
  3604. {
  3605. prevContext = setThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
  3606. }
  3607. #endif
  3608. Array<MonitorInfo> monitors;
  3609. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitors);
  3610. auto globalDPI = getGlobalDPI();
  3611. if (monitors.size() == 0)
  3612. monitors.add ({ true, getWindowRect (GetDesktopWindow()), globalDPI });
  3613. // make sure the first in the list is the main monitor
  3614. for (int i = 1; i < monitors.size(); ++i)
  3615. if (monitors.getReference (i).isMain)
  3616. monitors.swap (i, 0);
  3617. for (auto& monitor : monitors)
  3618. {
  3619. Display d;
  3620. d.isMain = monitor.isMain;
  3621. d.dpi = monitor.dpi;
  3622. if (d.dpi == 0)
  3623. {
  3624. d.dpi = globalDPI;
  3625. d.scale = masterScale;
  3626. }
  3627. else
  3628. {
  3629. d.scale = (d.dpi / USER_DEFAULT_SCREEN_DPI) * (masterScale / Desktop::getDefaultMasterScale());
  3630. }
  3631. d.userArea = d.totalArea = Rectangle<int>::leftTopRightBottom (monitor.bounds.left, monitor.bounds.top,
  3632. monitor.bounds.right, monitor.bounds.bottom);
  3633. if (d.isMain)
  3634. {
  3635. RECT workArea;
  3636. SystemParametersInfo (SPI_GETWORKAREA, 0, &workArea, 0);
  3637. d.userArea = d.userArea.getIntersection (Rectangle<int>::leftTopRightBottom (workArea.left, workArea.top,
  3638. workArea.right, workArea.bottom));
  3639. }
  3640. displays.add (d);
  3641. }
  3642. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3643. updateToLogical();
  3644. // Reset the DPI awareness context if it was overridden earlier
  3645. if (prevContext != nullptr)
  3646. setThreadDPIAwarenessContext (prevContext);
  3647. #else
  3648. for (auto& d : displays)
  3649. {
  3650. d.totalArea /= masterScale;
  3651. d.userArea /= masterScale;
  3652. }
  3653. #endif
  3654. }
  3655. //==============================================================================
  3656. static HICON extractFileHICON (const File& file)
  3657. {
  3658. WORD iconNum = 0;
  3659. WCHAR name[MAX_PATH * 2];
  3660. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  3661. return ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  3662. name, &iconNum);
  3663. }
  3664. Image juce_createIconForFile (const File& file)
  3665. {
  3666. Image image;
  3667. if (auto icon = extractFileHICON (file))
  3668. {
  3669. image = IconConverters::createImageFromHICON (icon);
  3670. DestroyIcon (icon);
  3671. }
  3672. return image;
  3673. }
  3674. //==============================================================================
  3675. void* CustomMouseCursorInfo::create() const
  3676. {
  3677. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  3678. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  3679. Image im (image);
  3680. int hotspotX = hotspot.x;
  3681. int hotspotY = hotspot.y;
  3682. if (im.getWidth() > maxW || im.getHeight() > maxH)
  3683. {
  3684. im = im.rescaled (maxW, maxH);
  3685. hotspotX = (hotspotX * maxW) / image.getWidth();
  3686. hotspotY = (hotspotY * maxH) / image.getHeight();
  3687. }
  3688. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  3689. }
  3690. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool isStandard)
  3691. {
  3692. if (cursorHandle != nullptr && ! isStandard)
  3693. DestroyCursor ((HCURSOR) cursorHandle);
  3694. }
  3695. enum
  3696. {
  3697. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  3698. };
  3699. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  3700. {
  3701. LPCTSTR cursorName = IDC_ARROW;
  3702. switch (type)
  3703. {
  3704. case NormalCursor:
  3705. case ParentCursor: break;
  3706. case NoCursor: return (void*) hiddenMouseCursorHandle;
  3707. case WaitCursor: cursorName = IDC_WAIT; break;
  3708. case IBeamCursor: cursorName = IDC_IBEAM; break;
  3709. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  3710. case CrosshairCursor: cursorName = IDC_CROSS; break;
  3711. case LeftRightResizeCursor:
  3712. case LeftEdgeResizeCursor:
  3713. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  3714. case UpDownResizeCursor:
  3715. case TopEdgeResizeCursor:
  3716. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  3717. case TopLeftCornerResizeCursor:
  3718. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  3719. case TopRightCornerResizeCursor:
  3720. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  3721. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  3722. case DraggingHandCursor:
  3723. {
  3724. static void* dragHandCursor = nullptr;
  3725. if (dragHandCursor == nullptr)
  3726. {
  3727. static const unsigned char dragHandData[] =
  3728. { 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,
  3729. 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,
  3730. 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 };
  3731. dragHandCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), { 8, 7 }).create();
  3732. }
  3733. return dragHandCursor;
  3734. }
  3735. case CopyingCursor:
  3736. {
  3737. static void* copyCursor = nullptr;
  3738. if (copyCursor == nullptr)
  3739. {
  3740. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3741. 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,
  3742. 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,
  3743. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3744. const int copyCursorSize = 119;
  3745. copyCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), { 1, 3 }).create();
  3746. }
  3747. return copyCursor;
  3748. }
  3749. default:
  3750. jassertfalse; break;
  3751. }
  3752. if (auto cursorH = LoadCursor (0, cursorName))
  3753. return cursorH;
  3754. return LoadCursor (0, IDC_ARROW);
  3755. }
  3756. //==============================================================================
  3757. void MouseCursor::showInWindow (ComponentPeer*) const
  3758. {
  3759. auto c = (HCURSOR) getHandle();
  3760. if (c == 0)
  3761. c = LoadCursor (0, IDC_ARROW);
  3762. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  3763. c = 0;
  3764. SetCursor (c);
  3765. }
  3766. } // namespace juce