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.

4734 lines
168KB

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