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.

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