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.

4759 lines
169KB

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