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.

4704 lines
167KB

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