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.

4735 lines
168KB

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