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.

4782 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. using ComponentPeer::localToGlobal;
  1150. using ComponentPeer::globalToLocal;
  1151. void setAlpha (float newAlpha) override
  1152. {
  1153. auto intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  1154. if (component.isOpaque())
  1155. {
  1156. if (newAlpha < 1.0f)
  1157. {
  1158. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  1159. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  1160. }
  1161. else
  1162. {
  1163. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  1164. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  1165. }
  1166. }
  1167. else
  1168. {
  1169. updateLayeredWindowAlpha = intAlpha;
  1170. component.repaint();
  1171. }
  1172. }
  1173. void setMinimised (bool shouldBeMinimised) override
  1174. {
  1175. if (shouldBeMinimised != isMinimised())
  1176. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  1177. }
  1178. bool isMinimised() const override
  1179. {
  1180. WINDOWPLACEMENT wp;
  1181. wp.length = sizeof (WINDOWPLACEMENT);
  1182. GetWindowPlacement (hwnd, &wp);
  1183. return wp.showCmd == SW_SHOWMINIMIZED;
  1184. }
  1185. void setFullScreen (bool shouldBeFullScreen) override
  1186. {
  1187. setMinimised (false);
  1188. if (isFullScreen() != shouldBeFullScreen)
  1189. {
  1190. if (constrainer != nullptr)
  1191. constrainer->resizeStart();
  1192. fullScreen = shouldBeFullScreen;
  1193. const WeakReference<Component> deletionChecker (&component);
  1194. if (! fullScreen)
  1195. {
  1196. auto boundsCopy = lastNonFullscreenBounds;
  1197. if (hasTitleBar())
  1198. ShowWindow (hwnd, SW_SHOWNORMAL);
  1199. if (! boundsCopy.isEmpty())
  1200. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, boundsCopy), false);
  1201. }
  1202. else
  1203. {
  1204. if (hasTitleBar())
  1205. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  1206. else
  1207. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  1208. }
  1209. if (deletionChecker != nullptr)
  1210. handleMovedOrResized();
  1211. if (constrainer != nullptr)
  1212. constrainer->resizeEnd();
  1213. }
  1214. }
  1215. bool isFullScreen() const override
  1216. {
  1217. if (! hasTitleBar())
  1218. return fullScreen;
  1219. WINDOWPLACEMENT wp;
  1220. wp.length = sizeof (wp);
  1221. GetWindowPlacement (hwnd, &wp);
  1222. return wp.showCmd == SW_SHOWMAXIMIZED;
  1223. }
  1224. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  1225. {
  1226. auto r = convertPhysicalScreenRectangleToLogical (rectangleFromRECT (getWindowRect (hwnd)), hwnd);
  1227. if (! r.withZeroOrigin().contains (localPos))
  1228. return false;
  1229. auto globalPos = localPos + getScreenPosition();
  1230. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1231. if (isPerMonitorDPIAwareThread() || isPerMonitorDPIAwareWindow (hwnd))
  1232. globalPos = Desktop::getInstance().getDisplays().logicalToPhysical (globalPos);
  1233. #endif
  1234. auto w = WindowFromPoint (POINTFromPoint (globalPos));
  1235. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  1236. }
  1237. BorderSize<int> getFrameSize() const override
  1238. {
  1239. return windowBorder;
  1240. }
  1241. bool setAlwaysOnTop (bool alwaysOnTop) override
  1242. {
  1243. const bool oldDeactivate = shouldDeactivateTitleBar;
  1244. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1245. setWindowZOrder (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST);
  1246. shouldDeactivateTitleBar = oldDeactivate;
  1247. if (shadower != nullptr)
  1248. handleBroughtToFront();
  1249. return true;
  1250. }
  1251. void toFront (bool makeActive) override
  1252. {
  1253. setMinimised (false);
  1254. const bool oldDeactivate = shouldDeactivateTitleBar;
  1255. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1256. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  1257. shouldDeactivateTitleBar = oldDeactivate;
  1258. if (! makeActive)
  1259. {
  1260. // in this case a broughttofront call won't have occurred, so do it now..
  1261. handleBroughtToFront();
  1262. }
  1263. }
  1264. void toBehind (ComponentPeer* other) override
  1265. {
  1266. if (auto* otherPeer = dynamic_cast<HWNDComponentPeer*> (other))
  1267. {
  1268. setMinimised (false);
  1269. // Must be careful not to try to put a topmost window behind a normal one, or Windows
  1270. // promotes the normal one to be topmost!
  1271. if (component.isAlwaysOnTop() == otherPeer->getComponent().isAlwaysOnTop())
  1272. setWindowZOrder (hwnd, otherPeer->hwnd);
  1273. else if (otherPeer->getComponent().isAlwaysOnTop())
  1274. setWindowZOrder (hwnd, HWND_TOP);
  1275. }
  1276. else
  1277. {
  1278. jassertfalse; // wrong type of window?
  1279. }
  1280. }
  1281. bool isFocused() const override
  1282. {
  1283. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  1284. }
  1285. void grabFocus() override
  1286. {
  1287. const bool oldDeactivate = shouldDeactivateTitleBar;
  1288. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  1289. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  1290. shouldDeactivateTitleBar = oldDeactivate;
  1291. }
  1292. void textInputRequired (Point<int>, TextInputTarget&) override
  1293. {
  1294. if (! hasCreatedCaret)
  1295. {
  1296. hasCreatedCaret = true;
  1297. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  1298. }
  1299. ShowCaret (hwnd);
  1300. SetCaretPos (0, 0);
  1301. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  1302. OnScreenKeyboard::getInstance()->activate();
  1303. }
  1304. void dismissPendingTextInput() override
  1305. {
  1306. imeHandler.handleSetContext (hwnd, false);
  1307. if (uwpViewSettings.isTabletModeActivatedForWindow (hwnd))
  1308. OnScreenKeyboard::getInstance()->deactivate();
  1309. }
  1310. void repaint (const Rectangle<int>& area) override
  1311. {
  1312. auto scale = getPlatformScaleFactor();
  1313. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1314. // if the calling thread is DPI-aware but we are invalidating a non-DPI aware window RECT, we actually have to
  1315. // divide the bounds by the scale factor as it will get multiplied for the virtualised paint callback...
  1316. if (isPerMonitorDPIAwareThread() && ! isPerMonitorDPIAwareWindow (hwnd))
  1317. scale = 1.0 / Desktop::getInstance().getDisplays().getMainDisplay().scale;
  1318. #endif
  1319. const RECT r = { roundToInt (area.getX() * scale), roundToInt (area.getY() * scale),
  1320. roundToInt (area.getRight() * scale), roundToInt (area.getBottom() * scale) };
  1321. InvalidateRect (hwnd, &r, FALSE);
  1322. }
  1323. void performAnyPendingRepaintsNow() override
  1324. {
  1325. if (component.isVisible())
  1326. {
  1327. WeakReference<Component> localRef (&component);
  1328. MSG m;
  1329. if (isUsingUpdateLayeredWindow() || PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  1330. if (localRef != nullptr) // (the PeekMessage call can dispatch messages, which may delete this comp)
  1331. handlePaintMessage();
  1332. }
  1333. }
  1334. //==============================================================================
  1335. static HWNDComponentPeer* getOwnerOfWindow (HWND h) noexcept
  1336. {
  1337. if (h != 0 && JuceWindowIdentifier::isJUCEWindow (h))
  1338. return (HWNDComponentPeer*) GetWindowLongPtr (h, 8);
  1339. return nullptr;
  1340. }
  1341. //==============================================================================
  1342. bool isInside (HWND h) const noexcept
  1343. {
  1344. return GetAncestor (hwnd, GA_ROOT) == h;
  1345. }
  1346. //==============================================================================
  1347. static bool isKeyDown (const int key) noexcept { return (GetAsyncKeyState (key) & 0x8000) != 0; }
  1348. static void updateKeyModifiers() noexcept
  1349. {
  1350. int keyMods = 0;
  1351. if (isKeyDown (VK_SHIFT)) keyMods |= ModifierKeys::shiftModifier;
  1352. if (isKeyDown (VK_CONTROL)) keyMods |= ModifierKeys::ctrlModifier;
  1353. if (isKeyDown (VK_MENU)) keyMods |= ModifierKeys::altModifier;
  1354. // workaround: Windows maps AltGr to left-Ctrl + right-Alt.
  1355. if (isKeyDown (VK_RMENU) && !isKeyDown (VK_RCONTROL))
  1356. {
  1357. keyMods = (keyMods & ~ModifierKeys::ctrlModifier) | ModifierKeys::altModifier;
  1358. }
  1359. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1360. }
  1361. static void updateModifiersFromWParam (const WPARAM wParam)
  1362. {
  1363. int mouseMods = 0;
  1364. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  1365. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  1366. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  1367. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  1368. updateKeyModifiers();
  1369. }
  1370. //==============================================================================
  1371. bool dontRepaint;
  1372. static ModifierKeys modifiersAtLastCallback;
  1373. //==============================================================================
  1374. struct FileDropTarget : public ComBaseClassHelper<IDropTarget>
  1375. {
  1376. FileDropTarget (HWNDComponentPeer& p) : peer (p) {}
  1377. JUCE_COMRESULT DragEnter (IDataObject* pDataObject, DWORD grfKeyState, POINTL mousePos, DWORD* pdwEffect) override
  1378. {
  1379. auto hr = updateFileList (pDataObject);
  1380. if (FAILED (hr))
  1381. return hr;
  1382. return DragOver (grfKeyState, mousePos, pdwEffect);
  1383. }
  1384. JUCE_COMRESULT DragLeave() override
  1385. {
  1386. if (peerIsDeleted)
  1387. return S_FALSE;
  1388. peer.handleDragExit (dragInfo);
  1389. return S_OK;
  1390. }
  1391. JUCE_COMRESULT DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1392. {
  1393. if (peerIsDeleted)
  1394. return S_FALSE;
  1395. dragInfo.position = getMousePos (mousePos).roundToInt();
  1396. *pdwEffect = peer.handleDragMove (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1397. : (DWORD) DROPEFFECT_NONE;
  1398. return S_OK;
  1399. }
  1400. JUCE_COMRESULT Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect) override
  1401. {
  1402. auto hr = updateFileList (pDataObject);
  1403. if (FAILED (hr))
  1404. return hr;
  1405. dragInfo.position = getMousePos (mousePos).roundToInt();
  1406. *pdwEffect = peer.handleDragDrop (dragInfo) ? (DWORD) DROPEFFECT_COPY
  1407. : (DWORD) DROPEFFECT_NONE;
  1408. return S_OK;
  1409. }
  1410. HWNDComponentPeer& peer;
  1411. ComponentPeer::DragInfo dragInfo;
  1412. bool peerIsDeleted = false;
  1413. private:
  1414. Point<float> getMousePos (POINTL mousePos) const
  1415. {
  1416. Point<float> screenPos;
  1417. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1418. auto h = (HWND) peer.getNativeHandle();
  1419. if (isPerMonitorDPIAwareWindow (h))
  1420. screenPos = convertPhysicalScreenPointToLogical (pointFromPOINT ({ mousePos.x, mousePos.y }), h).toFloat();
  1421. else
  1422. #endif
  1423. screenPos = pointFromPOINT ({ mousePos.x, mousePos.y }).toFloat() / static_cast<float> (getGlobalDPI() / USER_DEFAULT_SCREEN_DPI);
  1424. return peer.getComponent().getLocalPoint (nullptr, screenPos);
  1425. }
  1426. template <typename CharType>
  1427. void parseFileList (const CharType* names, const SIZE_T totalLen)
  1428. {
  1429. for (unsigned int i = 0;;)
  1430. {
  1431. unsigned int len = 0;
  1432. while (i + len < totalLen && names[i + len] != 0)
  1433. ++len;
  1434. if (len == 0)
  1435. break;
  1436. dragInfo.files.add (String (names + i, len));
  1437. i += len + 1;
  1438. }
  1439. }
  1440. struct DroppedData
  1441. {
  1442. DroppedData (IDataObject* dataObject, CLIPFORMAT type)
  1443. {
  1444. FORMATETC format = { type, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  1445. STGMEDIUM resetMedium = { TYMED_HGLOBAL, { 0 }, 0 };
  1446. medium = resetMedium;
  1447. if (SUCCEEDED (error = dataObject->GetData (&format, &medium)))
  1448. {
  1449. dataSize = GlobalSize (medium.hGlobal);
  1450. data = GlobalLock (medium.hGlobal);
  1451. }
  1452. }
  1453. ~DroppedData()
  1454. {
  1455. if (data != nullptr)
  1456. GlobalUnlock (medium.hGlobal);
  1457. }
  1458. HRESULT error;
  1459. STGMEDIUM medium;
  1460. void* data = {};
  1461. SIZE_T dataSize;
  1462. };
  1463. HRESULT updateFileList (IDataObject* const dataObject)
  1464. {
  1465. if (peerIsDeleted)
  1466. return S_FALSE;
  1467. dragInfo.clear();
  1468. {
  1469. DroppedData fileData (dataObject, CF_HDROP);
  1470. if (SUCCEEDED (fileData.error))
  1471. {
  1472. auto dropFiles = static_cast<const LPDROPFILES> (fileData.data);
  1473. const void* const names = addBytesToPointer (dropFiles, sizeof (DROPFILES));
  1474. if (dropFiles->fWide)
  1475. parseFileList (static_cast<const WCHAR*> (names), fileData.dataSize);
  1476. else
  1477. parseFileList (static_cast<const char*> (names), fileData.dataSize);
  1478. return S_OK;
  1479. }
  1480. }
  1481. DroppedData textData (dataObject, CF_UNICODETEXT);
  1482. if (SUCCEEDED (textData.error))
  1483. {
  1484. dragInfo.text = String (CharPointer_UTF16 ((const WCHAR*) textData.data),
  1485. CharPointer_UTF16 ((const WCHAR*) addBytesToPointer (textData.data, textData.dataSize)));
  1486. return S_OK;
  1487. }
  1488. return textData.error;
  1489. }
  1490. JUCE_DECLARE_NON_COPYABLE (FileDropTarget)
  1491. };
  1492. static bool offerKeyMessageToJUCEWindow (MSG& m)
  1493. {
  1494. if (m.message == WM_KEYDOWN || m.message == WM_KEYUP)
  1495. if (Component::getCurrentlyFocusedComponent() != nullptr)
  1496. if (auto* h = getOwnerOfWindow (m.hwnd))
  1497. return m.message == WM_KEYDOWN ? h->doKeyDown (m.wParam)
  1498. : h->doKeyUp (m.wParam);
  1499. return false;
  1500. }
  1501. double getPlatformScaleFactor() const noexcept override
  1502. {
  1503. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1504. if (! isPerMonitorDPIAwareWindow (hwnd))
  1505. return 1.0;
  1506. if (auto* parentHWND = GetParent (hwnd))
  1507. {
  1508. if (auto* parentPeer = getOwnerOfWindow (parentHWND))
  1509. return parentPeer->getPlatformScaleFactor();
  1510. if (getDPIForWindow != nullptr)
  1511. return getScaleFactorForWindow (parentHWND);
  1512. }
  1513. return scaleFactor;
  1514. #else
  1515. return 1.0;
  1516. #endif
  1517. }
  1518. private:
  1519. HWND hwnd, parentToAddTo;
  1520. std::unique_ptr<DropShadower> shadower;
  1521. RenderingEngineType currentRenderingEngine;
  1522. #if JUCE_DIRECT2D
  1523. std::unique_ptr<Direct2DLowLevelGraphicsContext> direct2DContext;
  1524. #endif
  1525. uint32 lastPaintTime = 0;
  1526. ULONGLONG lastMagnifySize = 0;
  1527. bool fullScreen = false, isDragging = false, isMouseOver = false,
  1528. hasCreatedCaret = false, constrainerIsResizing = false;
  1529. BorderSize<int> windowBorder;
  1530. HICON currentWindowIcon = 0;
  1531. FileDropTarget* dropTarget = nullptr;
  1532. uint8 updateLayeredWindowAlpha = 255;
  1533. UWPUIViewSettings uwpViewSettings;
  1534. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1535. ModifierKeyProvider* modProvider = nullptr;
  1536. #endif
  1537. double scaleFactor = 1.0;
  1538. bool isInDPIChange = false;
  1539. //==============================================================================
  1540. static MultiTouchMapper<DWORD> currentTouches;
  1541. //==============================================================================
  1542. struct TemporaryImage : private Timer
  1543. {
  1544. TemporaryImage() {}
  1545. Image& getImage (bool transparent, int w, int h)
  1546. {
  1547. auto format = transparent ? Image::ARGB : Image::RGB;
  1548. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  1549. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  1550. startTimer (3000);
  1551. return image;
  1552. }
  1553. void timerCallback() override
  1554. {
  1555. stopTimer();
  1556. image = {};
  1557. }
  1558. private:
  1559. Image image;
  1560. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage)
  1561. };
  1562. TemporaryImage offscreenImageGenerator;
  1563. //==============================================================================
  1564. class WindowClassHolder : private DeletedAtShutdown
  1565. {
  1566. public:
  1567. WindowClassHolder()
  1568. {
  1569. // this name has to be different for each app/dll instance because otherwise poor old Windows can
  1570. // get a bit confused (even despite it not being a process-global window class).
  1571. String windowClassName ("JUCE_");
  1572. windowClassName << String::toHexString (Time::currentTimeMillis());
  1573. auto moduleHandle = (HINSTANCE) Process::getCurrentModuleInstanceHandle();
  1574. TCHAR moduleFile[1024] = { 0 };
  1575. GetModuleFileName (moduleHandle, moduleFile, 1024);
  1576. WORD iconNum = 0;
  1577. WNDCLASSEX wcex = { 0 };
  1578. wcex.cbSize = sizeof (wcex);
  1579. wcex.style = CS_OWNDC;
  1580. wcex.lpfnWndProc = (WNDPROC) windowProc;
  1581. wcex.lpszClassName = windowClassName.toWideCharPointer();
  1582. wcex.cbWndExtra = 32;
  1583. wcex.hInstance = moduleHandle;
  1584. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1585. iconNum = 1;
  1586. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  1587. atom = RegisterClassEx (&wcex);
  1588. jassert (atom != 0);
  1589. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  1590. }
  1591. ~WindowClassHolder()
  1592. {
  1593. if (ComponentPeer::getNumPeers() == 0)
  1594. UnregisterClass (getWindowClassName(), (HINSTANCE) Process::getCurrentModuleInstanceHandle());
  1595. clearSingletonInstance();
  1596. }
  1597. LPCTSTR getWindowClassName() const noexcept { return (LPCTSTR) (pointer_sized_uint) atom; }
  1598. JUCE_DECLARE_SINGLETON_SINGLETHREADED_MINIMAL (WindowClassHolder)
  1599. private:
  1600. ATOM atom;
  1601. static bool isHWNDBlockedByModalComponents (HWND h)
  1602. {
  1603. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  1604. if (auto* c = Desktop::getInstance().getComponent (i))
  1605. if ((! c->isCurrentlyBlockedByAnotherModalComponent())
  1606. && IsChild ((HWND) c->getWindowHandle(), h))
  1607. return false;
  1608. return true;
  1609. }
  1610. static bool checkEventBlockedByModalComps (const MSG& m)
  1611. {
  1612. if (Component::getNumCurrentlyModalComponents() == 0 || JuceWindowIdentifier::isJUCEWindow (m.hwnd))
  1613. return false;
  1614. switch (m.message)
  1615. {
  1616. case WM_MOUSEMOVE:
  1617. case WM_NCMOUSEMOVE:
  1618. case 0x020A: /* WM_MOUSEWHEEL */
  1619. case 0x020E: /* WM_MOUSEHWHEEL */
  1620. case WM_KEYUP:
  1621. case WM_SYSKEYUP:
  1622. case WM_CHAR:
  1623. case WM_APPCOMMAND:
  1624. case WM_LBUTTONUP:
  1625. case WM_MBUTTONUP:
  1626. case WM_RBUTTONUP:
  1627. case WM_MOUSEACTIVATE:
  1628. case WM_NCMOUSEHOVER:
  1629. case WM_MOUSEHOVER:
  1630. case WM_TOUCH:
  1631. case WM_POINTERUPDATE:
  1632. case WM_NCPOINTERUPDATE:
  1633. case WM_POINTERWHEEL:
  1634. case WM_POINTERHWHEEL:
  1635. case WM_POINTERUP:
  1636. case WM_POINTERACTIVATE:
  1637. return isHWNDBlockedByModalComponents(m.hwnd);
  1638. case WM_NCLBUTTONDOWN:
  1639. case WM_NCLBUTTONDBLCLK:
  1640. case WM_NCRBUTTONDOWN:
  1641. case WM_NCRBUTTONDBLCLK:
  1642. case WM_NCMBUTTONDOWN:
  1643. case WM_NCMBUTTONDBLCLK:
  1644. case WM_LBUTTONDOWN:
  1645. case WM_LBUTTONDBLCLK:
  1646. case WM_MBUTTONDOWN:
  1647. case WM_MBUTTONDBLCLK:
  1648. case WM_RBUTTONDOWN:
  1649. case WM_RBUTTONDBLCLK:
  1650. case WM_KEYDOWN:
  1651. case WM_SYSKEYDOWN:
  1652. case WM_NCPOINTERDOWN:
  1653. case WM_POINTERDOWN:
  1654. if (isHWNDBlockedByModalComponents (m.hwnd))
  1655. {
  1656. if (auto* modal = Component::getCurrentlyModalComponent (0))
  1657. modal->inputAttemptWhenModal();
  1658. return true;
  1659. }
  1660. break;
  1661. default:
  1662. break;
  1663. }
  1664. return false;
  1665. }
  1666. JUCE_DECLARE_NON_COPYABLE (WindowClassHolder)
  1667. };
  1668. //==============================================================================
  1669. static void* createWindowCallback (void* userData)
  1670. {
  1671. static_cast<HWNDComponentPeer*> (userData)->createWindow();
  1672. return nullptr;
  1673. }
  1674. void createWindow()
  1675. {
  1676. DWORD exstyle = 0;
  1677. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  1678. if (hasTitleBar())
  1679. {
  1680. type |= WS_OVERLAPPED;
  1681. if ((styleFlags & windowHasCloseButton) != 0)
  1682. {
  1683. type |= WS_SYSMENU;
  1684. }
  1685. else
  1686. {
  1687. // annoyingly, windows won't let you have a min/max button without a close button
  1688. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  1689. }
  1690. if ((styleFlags & windowIsResizable) != 0)
  1691. type |= WS_THICKFRAME;
  1692. }
  1693. else if (parentToAddTo != 0)
  1694. {
  1695. type |= WS_CHILD;
  1696. }
  1697. else
  1698. {
  1699. type |= WS_POPUP | WS_SYSMENU;
  1700. }
  1701. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1702. exstyle |= WS_EX_TOOLWINDOW;
  1703. else
  1704. exstyle |= WS_EX_APPWINDOW;
  1705. if ((styleFlags & windowHasMinimiseButton) != 0) type |= WS_MINIMIZEBOX;
  1706. if ((styleFlags & windowHasMaximiseButton) != 0) type |= WS_MAXIMIZEBOX;
  1707. if ((styleFlags & windowIgnoresMouseClicks) != 0) exstyle |= WS_EX_TRANSPARENT;
  1708. if ((styleFlags & windowIsSemiTransparent) != 0) exstyle |= WS_EX_LAYERED;
  1709. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->getWindowClassName(),
  1710. L"", type, 0, 0, 0, 0, parentToAddTo, 0,
  1711. (HINSTANCE) Process::getCurrentModuleInstanceHandle(), 0);
  1712. if (hwnd != 0)
  1713. {
  1714. SetWindowLongPtr (hwnd, 0, 0);
  1715. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  1716. JuceWindowIdentifier::setAsJUCEWindow (hwnd, true);
  1717. if (dropTarget == nullptr)
  1718. {
  1719. HWNDComponentPeer* peer = nullptr;
  1720. if (dontRepaint)
  1721. peer = getOwnerOfWindow (parentToAddTo);
  1722. if (peer == nullptr)
  1723. peer = this;
  1724. dropTarget = new FileDropTarget (*peer);
  1725. }
  1726. RegisterDragDrop (hwnd, dropTarget);
  1727. if (canUseMultiTouch())
  1728. registerTouchWindow (hwnd, 0);
  1729. setDPIAwareness();
  1730. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  1731. if (isPerMonitorDPIAwareThread())
  1732. {
  1733. auto bounds = component.getBounds();
  1734. if (bounds.isEmpty())
  1735. scaleFactor = Desktop::getInstance().getDisplays().getMainDisplay().scale;
  1736. else
  1737. scaleFactor = Desktop::getInstance().getDisplays().findDisplayForRect (bounds).scale;
  1738. scaleFactor /= Desktop::getInstance().getGlobalScaleFactor();
  1739. }
  1740. #endif
  1741. setMessageFilter();
  1742. updateBorderSize();
  1743. checkForPointerAPI();
  1744. // This is needed so that our plugin window gets notified of WM_SETTINGCHANGE messages
  1745. // and can respond to display scale changes
  1746. if (! JUCEApplication::isStandaloneApp())
  1747. settingChangeCallback = forceDisplayUpdate;
  1748. // Calling this function here is (for some reason) necessary to make Windows
  1749. // correctly enable the menu items that we specify in the wm_initmenu message.
  1750. GetSystemMenu (hwnd, false);
  1751. auto alpha = component.getAlpha();
  1752. if (alpha < 1.0f)
  1753. setAlpha (alpha);
  1754. }
  1755. else
  1756. {
  1757. jassertfalse;
  1758. }
  1759. }
  1760. static BOOL CALLBACK revokeChildDragDropCallback (HWND hwnd, LPARAM) { RevokeDragDrop (hwnd); return TRUE; }
  1761. static void* destroyWindowCallback (void* handle)
  1762. {
  1763. auto hwnd = reinterpret_cast<HWND> (handle);
  1764. if (IsWindow (hwnd))
  1765. {
  1766. RevokeDragDrop (hwnd);
  1767. // NB: we need to do this before DestroyWindow() as child HWNDs will be invalid after
  1768. EnumChildWindows (hwnd, revokeChildDragDropCallback, 0);
  1769. DestroyWindow (hwnd);
  1770. }
  1771. return nullptr;
  1772. }
  1773. static void* toFrontCallback1 (void* h)
  1774. {
  1775. SetForegroundWindow ((HWND) h);
  1776. return nullptr;
  1777. }
  1778. static void* toFrontCallback2 (void* h)
  1779. {
  1780. setWindowZOrder ((HWND) h, HWND_TOP);
  1781. return nullptr;
  1782. }
  1783. static void* setFocusCallback (void* h)
  1784. {
  1785. SetFocus ((HWND) h);
  1786. return nullptr;
  1787. }
  1788. static void* getFocusCallback (void*)
  1789. {
  1790. return GetFocus();
  1791. }
  1792. bool isUsingUpdateLayeredWindow() const
  1793. {
  1794. return ! component.isOpaque();
  1795. }
  1796. bool hasTitleBar() const noexcept { return (styleFlags & windowHasTitleBar) != 0; }
  1797. void updateShadower()
  1798. {
  1799. if (! component.isCurrentlyModal() && (styleFlags & windowHasDropShadow) != 0
  1800. && ((! hasTitleBar()) || SystemStats::getOperatingSystemType() < SystemStats::WinVista))
  1801. {
  1802. shadower.reset (component.getLookAndFeel().createDropShadowerForComponent (&component));
  1803. if (shadower != nullptr)
  1804. shadower->setOwner (&component);
  1805. }
  1806. }
  1807. void setIcon (const Image& newIcon)
  1808. {
  1809. if (auto hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0))
  1810. {
  1811. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  1812. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  1813. if (currentWindowIcon != 0)
  1814. DestroyIcon (currentWindowIcon);
  1815. currentWindowIcon = hicon;
  1816. }
  1817. }
  1818. void setMessageFilter()
  1819. {
  1820. typedef BOOL (WINAPI* ChangeWindowMessageFilterExFunc) (HWND, UINT, DWORD, PVOID);
  1821. if (auto changeMessageFilter = (ChangeWindowMessageFilterExFunc) getUser32Function ("ChangeWindowMessageFilterEx"))
  1822. {
  1823. changeMessageFilter (hwnd, WM_DROPFILES, 1 /*MSGFLT_ALLOW*/, nullptr);
  1824. changeMessageFilter (hwnd, WM_COPYDATA, 1 /*MSGFLT_ALLOW*/, nullptr);
  1825. changeMessageFilter (hwnd, 0x49, 1 /*MSGFLT_ALLOW*/, nullptr);
  1826. }
  1827. }
  1828. struct ChildWindowClippingInfo
  1829. {
  1830. HDC dc;
  1831. HWNDComponentPeer* peer;
  1832. RectangleList<int>* clip;
  1833. Point<int> origin;
  1834. int savedDC;
  1835. };
  1836. static BOOL CALLBACK clipChildWindowCallback (HWND hwnd, LPARAM context)
  1837. {
  1838. if (IsWindowVisible (hwnd))
  1839. {
  1840. auto& info = *(ChildWindowClippingInfo*) context;
  1841. auto parent = GetParent (hwnd);
  1842. if (parent == info.peer->hwnd)
  1843. {
  1844. auto r = getWindowRect (hwnd);
  1845. POINT pos = { r.left, r.top };
  1846. ScreenToClient (GetParent (hwnd), &pos);
  1847. Rectangle<int> clip (pos.x, pos.y,
  1848. r.right - r.left,
  1849. r.bottom - r.top);
  1850. info.clip->subtract (clip - info.origin);
  1851. if (info.savedDC == 0)
  1852. info.savedDC = SaveDC (info.dc);
  1853. ExcludeClipRect (info.dc, clip.getX(), clip.getY(), clip.getRight(), clip.getBottom());
  1854. }
  1855. }
  1856. return TRUE;
  1857. }
  1858. //==============================================================================
  1859. void handlePaintMessage()
  1860. {
  1861. #if JUCE_DIRECT2D
  1862. if (direct2DContext != nullptr)
  1863. {
  1864. RECT r;
  1865. if (GetUpdateRect (hwnd, &r, false))
  1866. {
  1867. direct2DContext->start();
  1868. direct2DContext->clipToRectangle (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r), hwnd));
  1869. handlePaint (*direct2DContext);
  1870. direct2DContext->end();
  1871. ValidateRect (hwnd, &r);
  1872. }
  1873. }
  1874. else
  1875. #endif
  1876. {
  1877. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  1878. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  1879. PAINTSTRUCT paintStruct;
  1880. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  1881. // message and become re-entrant, but that's OK
  1882. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  1883. // corrupt the image it's using to paint into, so do a check here.
  1884. static bool reentrant = false;
  1885. if (! reentrant)
  1886. {
  1887. const ScopedValueSetter<bool> setter (reentrant, true, false);
  1888. if (dontRepaint)
  1889. component.handleCommandMessage (0); // (this triggers a repaint in the openGL context)
  1890. else
  1891. performPaint (dc, rgn, regionType, paintStruct);
  1892. }
  1893. DeleteObject (rgn);
  1894. EndPaint (hwnd, &paintStruct);
  1895. #if JUCE_MSVC
  1896. _fpreset(); // because some graphics cards can unmask FP exceptions
  1897. #endif
  1898. }
  1899. lastPaintTime = Time::getMillisecondCounter();
  1900. }
  1901. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  1902. {
  1903. int x = paintStruct.rcPaint.left;
  1904. int y = paintStruct.rcPaint.top;
  1905. int w = paintStruct.rcPaint.right - x;
  1906. int h = paintStruct.rcPaint.bottom - y;
  1907. const bool transparent = isUsingUpdateLayeredWindow();
  1908. if (transparent)
  1909. {
  1910. // it's not possible to have a transparent window with a title bar at the moment!
  1911. jassert (! hasTitleBar());
  1912. auto r = getWindowRect (hwnd);
  1913. x = y = 0;
  1914. w = r.right - r.left;
  1915. h = r.bottom - r.top;
  1916. }
  1917. if (w > 0 && h > 0)
  1918. {
  1919. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  1920. RectangleList<int> contextClip;
  1921. const Rectangle<int> clipBounds (w, h);
  1922. bool needToPaintAll = true;
  1923. if (regionType == COMPLEXREGION && ! transparent)
  1924. {
  1925. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  1926. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  1927. DeleteObject (clipRgn);
  1928. char rgnData[8192];
  1929. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  1930. if (res > 0 && res <= sizeof (rgnData))
  1931. {
  1932. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  1933. if (hdr->iType == RDH_RECTANGLES
  1934. && hdr->rcBound.right - hdr->rcBound.left >= w
  1935. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  1936. {
  1937. needToPaintAll = false;
  1938. auto rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  1939. for (int i = (int) ((RGNDATA*) rgnData)->rdh.nCount; --i >= 0;)
  1940. {
  1941. if (rects->right <= x + w && rects->bottom <= y + h)
  1942. {
  1943. const int cx = jmax (x, (int) rects->left);
  1944. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  1945. rects->right - cx, rects->bottom - rects->top)
  1946. .getIntersection (clipBounds));
  1947. }
  1948. else
  1949. {
  1950. needToPaintAll = true;
  1951. break;
  1952. }
  1953. ++rects;
  1954. }
  1955. }
  1956. }
  1957. }
  1958. if (needToPaintAll)
  1959. {
  1960. contextClip.clear();
  1961. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  1962. }
  1963. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  1964. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  1965. if (! contextClip.isEmpty())
  1966. {
  1967. if (transparent)
  1968. for (auto& i : contextClip)
  1969. offscreenImage.clear (i);
  1970. {
  1971. auto context = component.getLookAndFeel()
  1972. .createGraphicsContext (offscreenImage, { -x, -y }, contextClip);
  1973. context->addTransform (AffineTransform::scale ((float) getPlatformScaleFactor()));
  1974. handlePaint (*context);
  1975. }
  1976. static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData())
  1977. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  1978. }
  1979. if (childClipInfo.savedDC != 0)
  1980. RestoreDC (dc, childClipInfo.savedDC);
  1981. }
  1982. }
  1983. //==============================================================================
  1984. void doMouseEvent (Point<float> position, float pressure, float orientation = 0.0f, ModifierKeys mods = ModifierKeys::currentModifiers)
  1985. {
  1986. handleMouseEvent (MouseInputSource::InputSourceType::mouse, position, mods, pressure, orientation, getMouseEventTime());
  1987. }
  1988. StringArray getAvailableRenderingEngines() override
  1989. {
  1990. StringArray s ("Software Renderer");
  1991. #if JUCE_DIRECT2D
  1992. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  1993. s.add ("Direct2D");
  1994. #endif
  1995. return s;
  1996. }
  1997. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  1998. #if JUCE_DIRECT2D
  1999. void updateDirect2DContext()
  2000. {
  2001. if (currentRenderingEngine != direct2DRenderingEngine)
  2002. direct2DContext = nullptr;
  2003. else if (direct2DContext == nullptr)
  2004. direct2DContext.reset (new Direct2DLowLevelGraphicsContext (hwnd));
  2005. }
  2006. #endif
  2007. void setCurrentRenderingEngine (int index) override
  2008. {
  2009. ignoreUnused (index);
  2010. #if JUCE_DIRECT2D
  2011. if (getAvailableRenderingEngines().size() > 1)
  2012. {
  2013. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  2014. updateDirect2DContext();
  2015. repaint (component.getLocalBounds());
  2016. }
  2017. #endif
  2018. }
  2019. static int getMinTimeBetweenMouseMoves()
  2020. {
  2021. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  2022. return 0;
  2023. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  2024. }
  2025. bool isTouchEvent() noexcept
  2026. {
  2027. if (registerTouchWindow == nullptr)
  2028. return false;
  2029. // Relevant info about touch/pen detection flags:
  2030. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
  2031. // http://www.petertissen.de/?p=4
  2032. return (GetMessageExtraInfo() & 0xFFFFFF80 /*SIGNATURE_MASK*/) == 0xFF515780 /*MI_WP_SIGNATURE*/;
  2033. }
  2034. static bool areOtherTouchSourcesActive()
  2035. {
  2036. for (auto& ms : Desktop::getInstance().getMouseSources())
  2037. if (ms.isDragging() && (ms.getType() == MouseInputSource::InputSourceType::touch
  2038. || ms.getType() == MouseInputSource::InputSourceType::pen))
  2039. return true;
  2040. return false;
  2041. }
  2042. void doMouseMove (Point<float> position, bool isMouseDownEvent)
  2043. {
  2044. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2045. // this will be handled by WM_TOUCH
  2046. if (isTouchEvent() || areOtherTouchSourcesActive())
  2047. return;
  2048. if (! isMouseOver)
  2049. {
  2050. isMouseOver = true;
  2051. // This avoids a rare stuck-button problem when focus is lost unexpectedly, but must
  2052. // not be called as part of a move, in case it's actually a mouse-drag from another
  2053. // app which ends up here when we get focus before the mouse is released..
  2054. if (isMouseDownEvent && getNativeRealtimeModifiers != nullptr)
  2055. getNativeRealtimeModifiers();
  2056. updateKeyModifiers();
  2057. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2058. if (modProvider != nullptr)
  2059. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2060. #endif
  2061. TRACKMOUSEEVENT tme;
  2062. tme.cbSize = sizeof (tme);
  2063. tme.dwFlags = TME_LEAVE;
  2064. tme.hwndTrack = hwnd;
  2065. tme.dwHoverTime = 0;
  2066. if (! TrackMouseEvent (&tme))
  2067. jassertfalse;
  2068. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  2069. }
  2070. else if (! isDragging)
  2071. {
  2072. if (! contains (position.roundToInt(), false))
  2073. return;
  2074. }
  2075. static uint32 lastMouseTime = 0;
  2076. static auto minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  2077. auto now = Time::getMillisecondCounter();
  2078. if (! Desktop::getInstance().getMainMouseSource().isDragging())
  2079. modsToSend = modsToSend.withoutMouseButtons();
  2080. if (now >= lastMouseTime + minTimeBetweenMouses)
  2081. {
  2082. lastMouseTime = now;
  2083. doMouseEvent (position, MouseInputSource::invalidPressure,
  2084. MouseInputSource::invalidOrientation, modsToSend);
  2085. }
  2086. }
  2087. void doMouseDown (Point<float> position, const WPARAM wParam)
  2088. {
  2089. // this will be handled by WM_TOUCH
  2090. if (isTouchEvent() || areOtherTouchSourcesActive())
  2091. return;
  2092. if (GetCapture() != hwnd)
  2093. SetCapture (hwnd);
  2094. doMouseMove (position, true);
  2095. if (isValidPeer (this))
  2096. {
  2097. updateModifiersFromWParam (wParam);
  2098. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2099. if (modProvider != nullptr)
  2100. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2101. #endif
  2102. isDragging = true;
  2103. doMouseEvent (position, MouseInputSource::invalidPressure);
  2104. }
  2105. }
  2106. void doMouseUp (Point<float> position, const WPARAM wParam)
  2107. {
  2108. // this will be handled by WM_TOUCH
  2109. if (isTouchEvent() || areOtherTouchSourcesActive())
  2110. return;
  2111. updateModifiersFromWParam (wParam);
  2112. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2113. if (modProvider != nullptr)
  2114. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (modProvider->getWin32Modifiers());
  2115. #endif
  2116. const bool wasDragging = isDragging;
  2117. isDragging = false;
  2118. // release the mouse capture if the user has released all buttons
  2119. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  2120. ReleaseCapture();
  2121. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  2122. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  2123. if (wasDragging)
  2124. doMouseEvent (position, MouseInputSource::invalidPressure);
  2125. }
  2126. void doCaptureChanged()
  2127. {
  2128. if (constrainerIsResizing)
  2129. {
  2130. if (constrainer != nullptr)
  2131. constrainer->resizeEnd();
  2132. constrainerIsResizing = false;
  2133. }
  2134. if (isDragging)
  2135. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  2136. }
  2137. void doMouseExit()
  2138. {
  2139. isMouseOver = false;
  2140. if (! areOtherTouchSourcesActive())
  2141. doMouseEvent (getCurrentMousePos(), MouseInputSource::invalidPressure);
  2142. }
  2143. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  2144. {
  2145. auto currentMousePos = getPOINTFromLParam (GetMessagePos());
  2146. // Because Windows stupidly sends all wheel events to the window with the keyboard
  2147. // focus, we have to redirect them here according to the mouse pos..
  2148. auto* peer = getOwnerOfWindow (WindowFromPoint (currentMousePos));
  2149. if (peer == nullptr)
  2150. peer = this;
  2151. localPos = peer->globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (currentMousePos), hwnd).toFloat());
  2152. return peer;
  2153. }
  2154. static MouseInputSource::InputSourceType getPointerType (WPARAM wParam)
  2155. {
  2156. if (getPointerTypeFunction != nullptr)
  2157. {
  2158. POINTER_INPUT_TYPE pointerType;
  2159. if (getPointerTypeFunction (GET_POINTERID_WPARAM (wParam), &pointerType))
  2160. {
  2161. if (pointerType == 2)
  2162. return MouseInputSource::InputSourceType::touch;
  2163. if (pointerType == 3)
  2164. return MouseInputSource::InputSourceType::pen;
  2165. }
  2166. }
  2167. return MouseInputSource::InputSourceType::mouse;
  2168. }
  2169. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  2170. {
  2171. updateKeyModifiers();
  2172. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  2173. MouseWheelDetails wheel;
  2174. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  2175. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  2176. wheel.isReversed = false;
  2177. wheel.isSmooth = false;
  2178. wheel.isInertial = false;
  2179. Point<float> localPos;
  2180. if (auto* peer = findPeerUnderMouse (localPos))
  2181. peer->handleMouseWheel (getPointerType (wParam), localPos, getMouseEventTime(), wheel);
  2182. }
  2183. bool doGestureEvent (LPARAM lParam)
  2184. {
  2185. GESTUREINFO gi;
  2186. zerostruct (gi);
  2187. gi.cbSize = sizeof (gi);
  2188. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  2189. {
  2190. updateKeyModifiers();
  2191. Point<float> localPos;
  2192. if (auto* peer = findPeerUnderMouse (localPos))
  2193. {
  2194. switch (gi.dwID)
  2195. {
  2196. case 3: /*GID_ZOOM*/
  2197. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  2198. peer->handleMagnifyGesture (MouseInputSource::InputSourceType::touch, localPos, getMouseEventTime(),
  2199. (float) (gi.ullArguments / (double) lastMagnifySize));
  2200. lastMagnifySize = gi.ullArguments;
  2201. return true;
  2202. case 4: /*GID_PAN*/
  2203. case 5: /*GID_ROTATE*/
  2204. case 6: /*GID_TWOFINGERTAP*/
  2205. case 7: /*GID_PRESSANDTAP*/
  2206. default:
  2207. break;
  2208. }
  2209. }
  2210. }
  2211. return false;
  2212. }
  2213. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  2214. {
  2215. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2216. if (auto* parent = getOwnerOfWindow (GetParent (hwnd)))
  2217. if (parent != this)
  2218. return parent->doTouchEvent (numInputs, eventHandle);
  2219. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  2220. if (getTouchInputInfo (eventHandle, numInputs, inputInfo, sizeof (TOUCHINPUT)))
  2221. {
  2222. for (int i = 0; i < numInputs; ++i)
  2223. {
  2224. auto flags = inputInfo[i].dwFlags;
  2225. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  2226. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  2227. return 0; // abandon method if this window was deleted by the callback
  2228. }
  2229. }
  2230. closeTouchInputHandle (eventHandle);
  2231. return 0;
  2232. }
  2233. bool handleTouchInput (const TOUCHINPUT& touch, const bool isDown, const bool isUp,
  2234. const float touchPressure = MouseInputSource::invalidPressure,
  2235. const float orientation = 0.0f)
  2236. {
  2237. auto isCancel = false;
  2238. const auto touchIndex = currentTouches.getIndexOfTouch (this, touch.dwID);
  2239. const auto time = getMouseEventTime();
  2240. const auto pos = globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT ({ roundToInt (touch.x / 100.0f),
  2241. roundToInt (touch.y / 100.0f) }), hwnd).toFloat());
  2242. const auto pressure = touchPressure;
  2243. auto modsToSend = ModifierKeys::currentModifiers;
  2244. if (isDown)
  2245. {
  2246. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2247. modsToSend = ModifierKeys::currentModifiers;
  2248. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2249. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(),
  2250. pressure, orientation, time, {}, touchIndex);
  2251. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2252. return false;
  2253. }
  2254. else if (isUp)
  2255. {
  2256. modsToSend = modsToSend.withoutMouseButtons();
  2257. ModifierKeys::currentModifiers = modsToSend;
  2258. currentTouches.clearTouch (touchIndex);
  2259. if (! currentTouches.areAnyTouchesActive())
  2260. isCancel = true;
  2261. }
  2262. else
  2263. {
  2264. modsToSend = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2265. }
  2266. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend,
  2267. pressure, orientation, time, {}, touchIndex);
  2268. if (! isValidPeer (this))
  2269. return false;
  2270. if (isUp)
  2271. {
  2272. handleMouseEvent (MouseInputSource::InputSourceType::touch, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers.withoutMouseButtons(),
  2273. pressure, orientation, time, {}, touchIndex);
  2274. if (! isValidPeer (this))
  2275. return false;
  2276. if (isCancel)
  2277. {
  2278. currentTouches.clear();
  2279. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2280. }
  2281. }
  2282. return true;
  2283. }
  2284. bool handlePointerInput (WPARAM wParam, LPARAM lParam, const bool isDown, const bool isUp)
  2285. {
  2286. if (! canUsePointerAPI)
  2287. return false;
  2288. auto pointerType = getPointerType (wParam);
  2289. if (pointerType == MouseInputSource::InputSourceType::touch)
  2290. {
  2291. POINTER_TOUCH_INFO touchInfo;
  2292. if (! getPointerTouchInfo (GET_POINTERID_WPARAM (wParam), &touchInfo))
  2293. return false;
  2294. const auto pressure = touchInfo.touchMask & TOUCH_MASK_PRESSURE ? touchInfo.pressure
  2295. : MouseInputSource::invalidPressure;
  2296. const auto orientation = touchInfo.touchMask & TOUCH_MASK_ORIENTATION ? degreesToRadians (static_cast<float> (touchInfo.orientation))
  2297. : MouseInputSource::invalidOrientation;
  2298. if (! handleTouchInput (emulateTouchEventFromPointer (touchInfo.pointerInfo.ptPixelLocationRaw, wParam),
  2299. isDown, isUp, pressure, orientation))
  2300. return false;
  2301. }
  2302. else if (pointerType == MouseInputSource::InputSourceType::pen)
  2303. {
  2304. POINTER_PEN_INFO penInfo;
  2305. if (! getPointerPenInfo (GET_POINTERID_WPARAM (wParam), &penInfo))
  2306. return false;
  2307. const auto pressure = (penInfo.penMask & PEN_MASK_PRESSURE) ? penInfo.pressure / 1024.0f : MouseInputSource::invalidPressure;
  2308. if (! handlePenInput (penInfo, globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (lParam)), hwnd).toFloat()),
  2309. pressure, isDown, isUp))
  2310. return false;
  2311. }
  2312. else
  2313. {
  2314. return false;
  2315. }
  2316. return true;
  2317. }
  2318. TOUCHINPUT emulateTouchEventFromPointer (POINT p, WPARAM wParam)
  2319. {
  2320. TOUCHINPUT touchInput;
  2321. touchInput.dwID = GET_POINTERID_WPARAM (wParam);
  2322. touchInput.x = p.x * 100;
  2323. touchInput.y = p.y * 100;
  2324. return touchInput;
  2325. }
  2326. bool handlePenInput (POINTER_PEN_INFO penInfo, Point<float> pos, const float pressure, bool isDown, bool isUp)
  2327. {
  2328. const auto time = getMouseEventTime();
  2329. ModifierKeys modsToSend (ModifierKeys::currentModifiers);
  2330. PenDetails penDetails;
  2331. penDetails.rotation = (penInfo.penMask & PEN_MASK_ROTATION) ? degreesToRadians (static_cast<float> (penInfo.rotation)) : MouseInputSource::invalidRotation;
  2332. penDetails.tiltX = (penInfo.penMask & PEN_MASK_TILT_X) ? penInfo.tiltX / 90.0f : MouseInputSource::invalidTiltX;
  2333. penDetails.tiltY = (penInfo.penMask & PEN_MASK_TILT_Y) ? penInfo.tiltY / 90.0f : MouseInputSource::invalidTiltY;
  2334. auto pInfoFlags = penInfo.pointerInfo.pointerFlags;
  2335. if ((pInfoFlags & POINTER_FLAG_FIRSTBUTTON) != 0)
  2336. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2337. else if ((pInfoFlags & POINTER_FLAG_SECONDBUTTON) != 0)
  2338. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::rightButtonModifier);
  2339. if (isDown)
  2340. {
  2341. modsToSend = ModifierKeys::currentModifiers;
  2342. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2343. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend.withoutMouseButtons(),
  2344. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2345. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2346. return false;
  2347. }
  2348. else if (isUp || ! (pInfoFlags & POINTER_FLAG_INCONTACT))
  2349. {
  2350. modsToSend = modsToSend.withoutMouseButtons();
  2351. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  2352. }
  2353. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend, pressure,
  2354. MouseInputSource::invalidOrientation, time, penDetails);
  2355. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2356. return false;
  2357. if (isUp)
  2358. {
  2359. handleMouseEvent (MouseInputSource::InputSourceType::pen, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  2360. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2361. if (! isValidPeer (this))
  2362. return false;
  2363. }
  2364. return true;
  2365. }
  2366. //==============================================================================
  2367. void sendModifierKeyChangeIfNeeded()
  2368. {
  2369. if (modifiersAtLastCallback != ModifierKeys::currentModifiers)
  2370. {
  2371. modifiersAtLastCallback = ModifierKeys::currentModifiers;
  2372. handleModifierKeysChange();
  2373. }
  2374. }
  2375. bool doKeyUp (const WPARAM key)
  2376. {
  2377. updateKeyModifiers();
  2378. switch (key)
  2379. {
  2380. case VK_SHIFT:
  2381. case VK_CONTROL:
  2382. case VK_MENU:
  2383. case VK_CAPITAL:
  2384. case VK_LWIN:
  2385. case VK_RWIN:
  2386. case VK_APPS:
  2387. case VK_NUMLOCK:
  2388. case VK_SCROLL:
  2389. case VK_LSHIFT:
  2390. case VK_RSHIFT:
  2391. case VK_LCONTROL:
  2392. case VK_LMENU:
  2393. case VK_RCONTROL:
  2394. case VK_RMENU:
  2395. sendModifierKeyChangeIfNeeded();
  2396. }
  2397. return handleKeyUpOrDown (false)
  2398. || Component::getCurrentlyModalComponent() != nullptr;
  2399. }
  2400. bool doKeyDown (const WPARAM key)
  2401. {
  2402. updateKeyModifiers();
  2403. bool used = false;
  2404. switch (key)
  2405. {
  2406. case VK_SHIFT:
  2407. case VK_LSHIFT:
  2408. case VK_RSHIFT:
  2409. case VK_CONTROL:
  2410. case VK_LCONTROL:
  2411. case VK_RCONTROL:
  2412. case VK_MENU:
  2413. case VK_LMENU:
  2414. case VK_RMENU:
  2415. case VK_LWIN:
  2416. case VK_RWIN:
  2417. case VK_CAPITAL:
  2418. case VK_NUMLOCK:
  2419. case VK_SCROLL:
  2420. case VK_APPS:
  2421. used = handleKeyUpOrDown (true);
  2422. sendModifierKeyChangeIfNeeded();
  2423. break;
  2424. case VK_LEFT:
  2425. case VK_RIGHT:
  2426. case VK_UP:
  2427. case VK_DOWN:
  2428. case VK_PRIOR:
  2429. case VK_NEXT:
  2430. case VK_HOME:
  2431. case VK_END:
  2432. case VK_DELETE:
  2433. case VK_INSERT:
  2434. case VK_F1:
  2435. case VK_F2:
  2436. case VK_F3:
  2437. case VK_F4:
  2438. case VK_F5:
  2439. case VK_F6:
  2440. case VK_F7:
  2441. case VK_F8:
  2442. case VK_F9:
  2443. case VK_F10:
  2444. case VK_F11:
  2445. case VK_F12:
  2446. case VK_F13:
  2447. case VK_F14:
  2448. case VK_F15:
  2449. case VK_F16:
  2450. case VK_F17:
  2451. case VK_F18:
  2452. case VK_F19:
  2453. case VK_F20:
  2454. case VK_F21:
  2455. case VK_F22:
  2456. case VK_F23:
  2457. case VK_F24:
  2458. used = handleKeyUpOrDown (true);
  2459. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  2460. break;
  2461. default:
  2462. used = handleKeyUpOrDown (true);
  2463. {
  2464. MSG msg;
  2465. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  2466. {
  2467. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  2468. // manually generate the key-press event that matches this key-down.
  2469. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  2470. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  2471. BYTE keyState[256];
  2472. GetKeyboardState (keyState);
  2473. WCHAR text[16] = { 0 };
  2474. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  2475. text[0] = 0;
  2476. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  2477. }
  2478. }
  2479. break;
  2480. }
  2481. return used || (Component::getCurrentlyModalComponent() != nullptr);
  2482. }
  2483. bool doKeyChar (int key, const LPARAM flags)
  2484. {
  2485. updateKeyModifiers();
  2486. auto textChar = (juce_wchar) key;
  2487. const int virtualScanCode = (flags >> 16) & 0xff;
  2488. if (key >= '0' && key <= '9')
  2489. {
  2490. switch (virtualScanCode) // check for a numeric keypad scan-code
  2491. {
  2492. case 0x52:
  2493. case 0x4f:
  2494. case 0x50:
  2495. case 0x51:
  2496. case 0x4b:
  2497. case 0x4c:
  2498. case 0x4d:
  2499. case 0x47:
  2500. case 0x48:
  2501. case 0x49:
  2502. key = (key - '0') + KeyPress::numberPad0;
  2503. break;
  2504. default:
  2505. break;
  2506. }
  2507. }
  2508. else
  2509. {
  2510. // convert the scan code to an unmodified character code..
  2511. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  2512. UINT keyChar = MapVirtualKey (virtualKey, 2);
  2513. keyChar = LOWORD (keyChar);
  2514. if (keyChar != 0)
  2515. key = (int) keyChar;
  2516. // avoid sending junk text characters for some control-key combinations
  2517. if (textChar < ' ' && ModifierKeys::currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  2518. textChar = 0;
  2519. }
  2520. return handleKeyPress (key, textChar);
  2521. }
  2522. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  2523. {
  2524. if (HWND parentH = GetParent (hwnd))
  2525. PostMessage (parentH, message, wParam, lParam);
  2526. }
  2527. bool doAppCommand (const LPARAM lParam)
  2528. {
  2529. int key = 0;
  2530. switch (GET_APPCOMMAND_LPARAM (lParam))
  2531. {
  2532. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  2533. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  2534. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  2535. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  2536. default: break;
  2537. }
  2538. if (key != 0)
  2539. {
  2540. updateKeyModifiers();
  2541. if (hwnd == GetActiveWindow())
  2542. {
  2543. handleKeyPress (key, 0);
  2544. return true;
  2545. }
  2546. }
  2547. return false;
  2548. }
  2549. bool isConstrainedNativeWindow() const
  2550. {
  2551. return constrainer != nullptr
  2552. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  2553. && ! isKioskMode();
  2554. }
  2555. Rectangle<int> getCurrentScaledBounds() const
  2556. {
  2557. return ScalingHelpers::unscaledScreenPosToScaled (component, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (component, component.getBounds())));
  2558. }
  2559. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  2560. {
  2561. if (isConstrainedNativeWindow())
  2562. {
  2563. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, convertPhysicalScreenRectangleToLogical (rectangleFromRECT (r), hwnd));
  2564. auto current = getCurrentScaledBounds();
  2565. constrainer->checkBounds (pos, current,
  2566. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2567. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  2568. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  2569. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  2570. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  2571. r = RECTFromRectangle (convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos), hwnd));
  2572. }
  2573. return TRUE;
  2574. }
  2575. LRESULT handlePositionChanging (WINDOWPOS& wp)
  2576. {
  2577. if (isConstrainedNativeWindow())
  2578. {
  2579. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  2580. && (wp.x > -32000 && wp.y > -32000)
  2581. && ! Component::isMouseButtonDownAnywhere())
  2582. {
  2583. auto pos = ScalingHelpers::unscaledScreenPosToScaled (component, convertPhysicalScreenRectangleToLogical (rectangleFromRECT ({ wp.x, wp.y, wp.x + wp.cx, wp.y + wp.cy }), hwnd));
  2584. auto current = getCurrentScaledBounds();
  2585. constrainer->checkBounds (pos, current,
  2586. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2587. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  2588. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  2589. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  2590. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  2591. pos = convertLogicalScreenRectangleToPhysical (ScalingHelpers::scaledScreenPosToUnscaled (component, pos), hwnd);
  2592. wp.x = pos.getX();
  2593. wp.y = pos.getY();
  2594. wp.cx = pos.getWidth();
  2595. wp.cy = pos.getHeight();
  2596. }
  2597. }
  2598. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  2599. component.setVisible (true);
  2600. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  2601. component.setVisible (false);
  2602. return 0;
  2603. }
  2604. bool handlePositionChanged()
  2605. {
  2606. auto pos = getCurrentMousePos();
  2607. if (contains (pos.roundToInt(), false))
  2608. {
  2609. if (! areOtherTouchSourcesActive())
  2610. doMouseEvent (pos, MouseInputSource::invalidPressure);
  2611. if (! isValidPeer (this))
  2612. return true;
  2613. }
  2614. handleMovedOrResized();
  2615. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly..
  2616. }
  2617. LRESULT handleDPIChanging (int newDPI, RECT newRect)
  2618. {
  2619. auto newScale = (double) newDPI / USER_DEFAULT_SCREEN_DPI;
  2620. if (! approximatelyEqual (scaleFactor, newScale))
  2621. {
  2622. const ScopedValueSetter<bool> setter (isInDPIChange, true);
  2623. auto oldScale = scaleFactor;
  2624. scaleFactor = newScale;
  2625. auto scaleRatio = scaleFactor / oldScale;
  2626. EnumChildWindows (hwnd, scaleChildHWNDCallback, (LPARAM) &scaleRatio);
  2627. setBounds (windowBorder.subtractedFrom (convertPhysicalScreenRectangleToLogical (rectangleFromRECT (newRect), hwnd)), false);
  2628. updateShadower();
  2629. InvalidateRect (hwnd, nullptr, FALSE);
  2630. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  2631. }
  2632. return 0;
  2633. }
  2634. static BOOL CALLBACK scaleChildHWNDCallback (HWND hwnd, LPARAM context)
  2635. {
  2636. auto r = getWindowRect (hwnd);
  2637. POINT p { r.left, r.top };
  2638. ScreenToClient (GetParent (hwnd), &p);
  2639. auto ratio = *(double*) context;
  2640. SetWindowPos (hwnd, 0, roundToInt (p.x * ratio), roundToInt (p.y * ratio),
  2641. roundToInt ((r.right - r.left) * ratio), roundToInt ((r.bottom - r.top) * ratio),
  2642. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  2643. if (auto* peer = getOwnerOfWindow (hwnd))
  2644. peer->handleChildDPIChanging();
  2645. return TRUE;
  2646. }
  2647. void handleChildDPIChanging()
  2648. {
  2649. const ScopedValueSetter<bool> setter (isInDPIChange, true);
  2650. scaleFactor = getScaleFactorForWindow (parentToAddTo);
  2651. updateShadower();
  2652. InvalidateRect (hwnd, nullptr, FALSE);
  2653. scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (scaleFactor); });
  2654. }
  2655. void handleAppActivation (const WPARAM wParam)
  2656. {
  2657. modifiersAtLastCallback = -1;
  2658. updateKeyModifiers();
  2659. if (isMinimised())
  2660. {
  2661. component.repaint();
  2662. handleMovedOrResized();
  2663. if (! isValidPeer (this))
  2664. return;
  2665. }
  2666. auto* underMouse = component.getComponentAt (component.getMouseXYRelative());
  2667. if (underMouse == nullptr)
  2668. underMouse = &component;
  2669. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  2670. {
  2671. if (LOWORD (wParam) == WA_CLICKACTIVE)
  2672. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  2673. else
  2674. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  2675. }
  2676. else
  2677. {
  2678. handleBroughtToFront();
  2679. }
  2680. }
  2681. void handlePowerBroadcast (WPARAM wParam)
  2682. {
  2683. if (auto* app = JUCEApplicationBase::getInstance())
  2684. {
  2685. switch (wParam)
  2686. {
  2687. case PBT_APMSUSPEND: app->suspended(); break;
  2688. case PBT_APMQUERYSUSPENDFAILED:
  2689. case PBT_APMRESUMECRITICAL:
  2690. case PBT_APMRESUMESUSPEND:
  2691. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  2692. default: break;
  2693. }
  2694. }
  2695. }
  2696. void handleLeftClickInNCArea (WPARAM wParam)
  2697. {
  2698. if (! sendInputAttemptWhenModalMessage())
  2699. {
  2700. switch (wParam)
  2701. {
  2702. case HTBOTTOM:
  2703. case HTBOTTOMLEFT:
  2704. case HTBOTTOMRIGHT:
  2705. case HTGROWBOX:
  2706. case HTLEFT:
  2707. case HTRIGHT:
  2708. case HTTOP:
  2709. case HTTOPLEFT:
  2710. case HTTOPRIGHT:
  2711. if (isConstrainedNativeWindow())
  2712. {
  2713. constrainerIsResizing = true;
  2714. constrainer->resizeStart();
  2715. }
  2716. break;
  2717. default:
  2718. break;
  2719. }
  2720. }
  2721. }
  2722. void initialiseSysMenu (HMENU menu) const
  2723. {
  2724. if (! hasTitleBar())
  2725. {
  2726. if (isFullScreen())
  2727. {
  2728. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  2729. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  2730. }
  2731. else if (! isMinimised())
  2732. {
  2733. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  2734. }
  2735. }
  2736. }
  2737. void doSettingChange()
  2738. {
  2739. forceDisplayUpdate();
  2740. if (fullScreen && ! isMinimised())
  2741. setWindowPos (hwnd, ScalingHelpers::scaledScreenPosToUnscaled (component, Desktop::getInstance().getDisplays().findDisplayForRect (component.getScreenBounds()).userArea),
  2742. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  2743. }
  2744. static void forceDisplayUpdate()
  2745. {
  2746. const_cast<Displays&> (Desktop::getInstance().getDisplays()).refresh();
  2747. }
  2748. //==============================================================================
  2749. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2750. void setModifierKeyProvider (ModifierKeyProvider* provider) override
  2751. {
  2752. modProvider = provider;
  2753. }
  2754. void removeModifierKeyProvider() override
  2755. {
  2756. modProvider = nullptr;
  2757. }
  2758. #endif
  2759. //==============================================================================
  2760. public:
  2761. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2762. {
  2763. // Ensure that non-client areas are scaled for per-monitor DPI awareness v1 - can't
  2764. // do this in peerWindowProc as we have no window at this point
  2765. if (message == WM_NCCREATE && enableNonClientDPIScaling != nullptr)
  2766. enableNonClientDPIScaling (h);
  2767. if (auto* peer = getOwnerOfWindow (h))
  2768. {
  2769. jassert (isValidPeer (peer));
  2770. return peer->peerWindowProc (h, message, wParam, lParam);
  2771. }
  2772. return DefWindowProcW (h, message, wParam, lParam);
  2773. }
  2774. private:
  2775. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  2776. {
  2777. auto& mm = *MessageManager::getInstance();
  2778. if (mm.currentThreadHasLockedMessageManager())
  2779. return callback (userData);
  2780. return mm.callFunctionOnMessageThread (callback, userData);
  2781. }
  2782. static POINT getPOINTFromLParam (LPARAM lParam) noexcept
  2783. {
  2784. return { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
  2785. }
  2786. Point<float> getPointFromLocalLParam (LPARAM lParam) noexcept
  2787. {
  2788. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  2789. if (isPerMonitorDPIAwareWindow (hwnd))
  2790. {
  2791. // LPARAM is relative to this window's top-left but may be on a different monitor so we need to calculate the
  2792. // physical screen position and then convert this to local logical coordinates
  2793. auto localPos = getPOINTFromLParam (lParam);
  2794. auto r = getWindowRect (hwnd);
  2795. return globalToLocal (Desktop::getInstance().getDisplays().physicalToLogical (pointFromPOINT ({ r.left + localPos.x + roundToInt (windowBorder.getLeft() * scaleFactor),
  2796. r.top + localPos.y + roundToInt (windowBorder.getTop() * scaleFactor) })).toFloat());
  2797. }
  2798. #endif
  2799. return { static_cast<float> (GET_X_LPARAM (lParam)), static_cast<float> (GET_Y_LPARAM (lParam)) };
  2800. }
  2801. Point<float> getCurrentMousePos() noexcept
  2802. {
  2803. return globalToLocal (convertPhysicalScreenPointToLogical (pointFromPOINT (getPOINTFromLParam (GetMessagePos())), hwnd).toFloat());
  2804. }
  2805. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2806. {
  2807. switch (message)
  2808. {
  2809. //==============================================================================
  2810. case WM_NCHITTEST:
  2811. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2812. return HTTRANSPARENT;
  2813. if (! hasTitleBar())
  2814. return HTCLIENT;
  2815. break;
  2816. //==============================================================================
  2817. case WM_PAINT:
  2818. handlePaintMessage();
  2819. return 0;
  2820. case WM_NCPAINT:
  2821. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  2822. if (hasTitleBar())
  2823. break; // let the DefWindowProc handle drawing the frame.
  2824. return 0;
  2825. case WM_ERASEBKGND:
  2826. case WM_NCCALCSIZE:
  2827. if (hasTitleBar())
  2828. break;
  2829. return 1;
  2830. //==============================================================================
  2831. case WM_POINTERUPDATE:
  2832. if (handlePointerInput (wParam, lParam, false, false))
  2833. return 0;
  2834. break;
  2835. case WM_POINTERDOWN:
  2836. if (handlePointerInput (wParam, lParam, true, false))
  2837. return 0;
  2838. break;
  2839. case WM_POINTERUP:
  2840. if (handlePointerInput (wParam, lParam, false, true))
  2841. return 0;
  2842. break;
  2843. //==============================================================================
  2844. case WM_MOUSEMOVE: doMouseMove (getPointFromLocalLParam (lParam), false); return 0;
  2845. case WM_POINTERLEAVE:
  2846. case WM_MOUSELEAVE: doMouseExit(); return 0;
  2847. case WM_LBUTTONDOWN:
  2848. case WM_MBUTTONDOWN:
  2849. case WM_RBUTTONDOWN: doMouseDown (getPointFromLocalLParam (lParam), wParam); return 0;
  2850. case WM_LBUTTONUP:
  2851. case WM_MBUTTONUP:
  2852. case WM_RBUTTONUP: doMouseUp (getPointFromLocalLParam (lParam), wParam); return 0;
  2853. case WM_POINTERWHEEL:
  2854. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  2855. case WM_POINTERHWHEEL:
  2856. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  2857. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  2858. case WM_NCPOINTERUPDATE:
  2859. case WM_NCMOUSEMOVE:
  2860. if (hasTitleBar())
  2861. break;
  2862. return 0;
  2863. case WM_TOUCH:
  2864. if (getTouchInputInfo != nullptr)
  2865. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  2866. break;
  2867. case 0x119: /* WM_GESTURE */
  2868. if (doGestureEvent (lParam))
  2869. return 0;
  2870. break;
  2871. //==============================================================================
  2872. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  2873. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  2874. case 0x2e0: /* WM_DPICHANGED */ return handleDPIChanging ((int) HIWORD (wParam), *(RECT*) lParam);
  2875. case WM_WINDOWPOSCHANGED:
  2876. {
  2877. const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
  2878. if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
  2879. startTimer (100);
  2880. else
  2881. if (handlePositionChanged())
  2882. return 0;
  2883. }
  2884. break;
  2885. //==============================================================================
  2886. case WM_KEYDOWN:
  2887. case WM_SYSKEYDOWN:
  2888. if (doKeyDown (wParam))
  2889. return 0;
  2890. forwardMessageToParent (message, wParam, lParam);
  2891. break;
  2892. case WM_KEYUP:
  2893. case WM_SYSKEYUP:
  2894. if (doKeyUp (wParam))
  2895. return 0;
  2896. forwardMessageToParent (message, wParam, lParam);
  2897. break;
  2898. case WM_CHAR:
  2899. if (doKeyChar ((int) wParam, lParam))
  2900. return 0;
  2901. forwardMessageToParent (message, wParam, lParam);
  2902. break;
  2903. case WM_APPCOMMAND:
  2904. if (doAppCommand (lParam))
  2905. return TRUE;
  2906. break;
  2907. case WM_MENUCHAR: // triggered when alt+something is pressed
  2908. return MNC_CLOSE << 16; // (avoids making the default system beep)
  2909. //==============================================================================
  2910. case WM_SETFOCUS:
  2911. updateKeyModifiers();
  2912. handleFocusGain();
  2913. break;
  2914. case WM_KILLFOCUS:
  2915. if (hasCreatedCaret)
  2916. {
  2917. hasCreatedCaret = false;
  2918. DestroyCaret();
  2919. }
  2920. handleFocusLoss();
  2921. break;
  2922. case WM_ACTIVATEAPP:
  2923. // Windows does weird things to process priority when you swap apps,
  2924. // so this forces an update when the app is brought to the front
  2925. if (wParam != FALSE)
  2926. juce_repeatLastProcessPriority();
  2927. else
  2928. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  2929. juce_checkCurrentlyFocusedTopLevelWindow();
  2930. modifiersAtLastCallback = -1;
  2931. return 0;
  2932. case WM_ACTIVATE:
  2933. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  2934. {
  2935. handleAppActivation (wParam);
  2936. return 0;
  2937. }
  2938. break;
  2939. case WM_NCACTIVATE:
  2940. // while a temporary window is being shown, prevent Windows from deactivating the
  2941. // title bars of our main windows.
  2942. if (wParam == 0 && ! shouldDeactivateTitleBar)
  2943. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  2944. break;
  2945. case WM_POINTERACTIVATE:
  2946. case WM_MOUSEACTIVATE:
  2947. if (! component.getMouseClickGrabsKeyboardFocus())
  2948. return MA_NOACTIVATE;
  2949. break;
  2950. case WM_SHOWWINDOW:
  2951. if (wParam != 0)
  2952. {
  2953. component.setVisible (true);
  2954. handleBroughtToFront();
  2955. }
  2956. break;
  2957. case WM_CLOSE:
  2958. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  2959. handleUserClosingWindow();
  2960. return 0;
  2961. #if JUCE_REMOVE_COMPONENT_FROM_DESKTOP_ON_WM_DESTROY
  2962. case WM_DESTROY:
  2963. getComponent().removeFromDesktop();
  2964. return 0;
  2965. #endif
  2966. case WM_QUERYENDSESSION:
  2967. if (auto* app = JUCEApplicationBase::getInstance())
  2968. {
  2969. app->systemRequestedQuit();
  2970. return MessageManager::getInstance()->hasStopMessageBeenSent();
  2971. }
  2972. return TRUE;
  2973. case WM_POWERBROADCAST:
  2974. handlePowerBroadcast (wParam);
  2975. break;
  2976. case WM_SYNCPAINT:
  2977. return 0;
  2978. case WM_DISPLAYCHANGE:
  2979. InvalidateRect (h, 0, 0);
  2980. // intentional fall-through...
  2981. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  2982. doSettingChange();
  2983. break;
  2984. case WM_INITMENU:
  2985. initialiseSysMenu ((HMENU) wParam);
  2986. break;
  2987. case WM_SYSCOMMAND:
  2988. switch (wParam & 0xfff0)
  2989. {
  2990. case SC_CLOSE:
  2991. if (sendInputAttemptWhenModalMessage())
  2992. return 0;
  2993. if (hasTitleBar())
  2994. {
  2995. PostMessage (h, WM_CLOSE, 0, 0);
  2996. return 0;
  2997. }
  2998. break;
  2999. case SC_KEYMENU:
  3000. #if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
  3001. // This test prevents a press of the ALT key from triggering the ancient top-left window menu.
  3002. // By default we suppress this behaviour because it's unlikely that more than a tiny subset of
  3003. // our users will actually want it, and it causes problems if you're trying to use the ALT key
  3004. // as a modifier for mouse actions. If you really need the old behaviour, then just define
  3005. // JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
  3006. if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
  3007. return 0;
  3008. #endif
  3009. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  3010. // situations that can arise if a modal loop is started from an alt-key keypress).
  3011. if (hasTitleBar() && h == GetCapture())
  3012. ReleaseCapture();
  3013. break;
  3014. case SC_MAXIMIZE:
  3015. if (! sendInputAttemptWhenModalMessage())
  3016. setFullScreen (true);
  3017. return 0;
  3018. case SC_MINIMIZE:
  3019. if (sendInputAttemptWhenModalMessage())
  3020. return 0;
  3021. if (! hasTitleBar())
  3022. {
  3023. setMinimised (true);
  3024. return 0;
  3025. }
  3026. break;
  3027. case SC_RESTORE:
  3028. if (sendInputAttemptWhenModalMessage())
  3029. return 0;
  3030. if (hasTitleBar())
  3031. {
  3032. if (isFullScreen())
  3033. {
  3034. setFullScreen (false);
  3035. return 0;
  3036. }
  3037. }
  3038. else
  3039. {
  3040. if (isMinimised())
  3041. setMinimised (false);
  3042. else if (isFullScreen())
  3043. setFullScreen (false);
  3044. return 0;
  3045. }
  3046. break;
  3047. }
  3048. break;
  3049. case WM_NCPOINTERDOWN:
  3050. case WM_NCLBUTTONDOWN:
  3051. handleLeftClickInNCArea (wParam);
  3052. break;
  3053. case WM_NCRBUTTONDOWN:
  3054. case WM_NCMBUTTONDOWN:
  3055. sendInputAttemptWhenModalMessage();
  3056. break;
  3057. case WM_IME_SETCONTEXT:
  3058. imeHandler.handleSetContext (h, wParam == TRUE);
  3059. lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  3060. break;
  3061. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  3062. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  3063. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  3064. case WM_GETDLGCODE:
  3065. return DLGC_WANTALLKEYS;
  3066. default:
  3067. break;
  3068. }
  3069. return DefWindowProcW (h, message, wParam, lParam);
  3070. }
  3071. bool sendInputAttemptWhenModalMessage()
  3072. {
  3073. if (component.isCurrentlyBlockedByAnotherModalComponent())
  3074. {
  3075. if (Component* const current = Component::getCurrentlyModalComponent())
  3076. current->inputAttemptWhenModal();
  3077. return true;
  3078. }
  3079. return false;
  3080. }
  3081. //==============================================================================
  3082. struct IMEHandler
  3083. {
  3084. IMEHandler()
  3085. {
  3086. reset();
  3087. }
  3088. void handleSetContext (HWND hWnd, const bool windowIsActive)
  3089. {
  3090. if (compositionInProgress && ! windowIsActive)
  3091. {
  3092. compositionInProgress = false;
  3093. if (HIMC hImc = ImmGetContext (hWnd))
  3094. {
  3095. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  3096. ImmReleaseContext (hWnd, hImc);
  3097. }
  3098. }
  3099. }
  3100. void handleStartComposition (ComponentPeer& owner)
  3101. {
  3102. reset();
  3103. if (auto* target = owner.findCurrentTextInputTarget())
  3104. target->insertTextAtCaret (String());
  3105. }
  3106. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  3107. {
  3108. if (compositionInProgress)
  3109. {
  3110. // If this occurs, the user has cancelled the composition, so clear their changes..
  3111. if (auto* target = owner.findCurrentTextInputTarget())
  3112. {
  3113. target->setHighlightedRegion (compositionRange);
  3114. target->insertTextAtCaret (String());
  3115. compositionRange.setLength (0);
  3116. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  3117. target->setTemporaryUnderlining ({});
  3118. }
  3119. if (auto hImc = ImmGetContext (hWnd))
  3120. {
  3121. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  3122. ImmReleaseContext (hWnd, hImc);
  3123. }
  3124. }
  3125. reset();
  3126. }
  3127. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  3128. {
  3129. if (auto* target = owner.findCurrentTextInputTarget())
  3130. {
  3131. if (auto hImc = ImmGetContext (hWnd))
  3132. {
  3133. if (compositionRange.getStart() < 0)
  3134. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  3135. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  3136. {
  3137. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  3138. Range<int>::emptyRange (-1));
  3139. reset();
  3140. target->setTemporaryUnderlining ({});
  3141. }
  3142. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  3143. {
  3144. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  3145. getCompositionSelection (hImc, lParam));
  3146. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  3147. compositionInProgress = true;
  3148. }
  3149. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  3150. ImmReleaseContext (hWnd, hImc);
  3151. }
  3152. }
  3153. }
  3154. private:
  3155. //==============================================================================
  3156. Range<int> compositionRange; // The range being modified in the TextInputTarget
  3157. bool compositionInProgress;
  3158. //==============================================================================
  3159. void reset()
  3160. {
  3161. compositionRange = Range<int>::emptyRange (-1);
  3162. compositionInProgress = false;
  3163. }
  3164. String getCompositionString (HIMC hImc, const DWORD type) const
  3165. {
  3166. jassert (hImc != 0);
  3167. const int stringSizeBytes = ImmGetCompositionString (hImc, type, 0, 0);
  3168. if (stringSizeBytes > 0)
  3169. {
  3170. HeapBlock<TCHAR> buffer;
  3171. buffer.calloc (stringSizeBytes / sizeof (TCHAR) + 1);
  3172. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  3173. return String (buffer.get());
  3174. }
  3175. return {};
  3176. }
  3177. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  3178. {
  3179. jassert (hImc != 0);
  3180. if ((lParam & CS_NOMOVECARET) != 0)
  3181. return compositionRange.getStart();
  3182. if ((lParam & GCS_CURSORPOS) != 0)
  3183. {
  3184. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, 0, 0);
  3185. return compositionRange.getStart() + jmax (0, localCaretPos);
  3186. }
  3187. return compositionRange.getStart() + currentIMEString.length();
  3188. }
  3189. // Get selected/highlighted range while doing composition:
  3190. // returned range is relative to beginning of TextInputTarget, not composition string
  3191. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  3192. {
  3193. jassert (hImc != 0);
  3194. int selectionStart = 0;
  3195. int selectionEnd = 0;
  3196. if ((lParam & GCS_COMPATTR) != 0)
  3197. {
  3198. // Get size of attributes array:
  3199. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, 0, 0);
  3200. if (attributeSizeBytes > 0)
  3201. {
  3202. // Get attributes (8 bit flag per character):
  3203. HeapBlock<char> attributes (attributeSizeBytes);
  3204. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  3205. selectionStart = 0;
  3206. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  3207. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  3208. break;
  3209. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  3210. if (attributes[selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  3211. break;
  3212. }
  3213. }
  3214. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  3215. }
  3216. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  3217. {
  3218. if (compositionInProgress)
  3219. target->setHighlightedRegion (compositionRange);
  3220. target->insertTextAtCaret (newContent);
  3221. compositionRange.setLength (newContent.length());
  3222. if (newSelection.getStart() < 0)
  3223. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  3224. target->setHighlightedRegion (newSelection);
  3225. }
  3226. Array<Range<int>> getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  3227. {
  3228. Array<Range<int>> result;
  3229. if (hImc != 0 && (lParam & GCS_COMPCLAUSE) != 0)
  3230. {
  3231. auto clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, 0, 0);
  3232. if (clauseDataSizeBytes > 0)
  3233. {
  3234. const size_t numItems = clauseDataSizeBytes / sizeof (uint32);
  3235. HeapBlock<uint32> clauseData (numItems);
  3236. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  3237. for (size_t i = 0; i + 1 < numItems; ++i)
  3238. result.add (Range<int> ((int) clauseData[i], (int) clauseData[i + 1]) + compositionRange.getStart());
  3239. }
  3240. }
  3241. return result;
  3242. }
  3243. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  3244. {
  3245. if (auto* targetComp = dynamic_cast<Component*> (target))
  3246. {
  3247. auto area = peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle());
  3248. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  3249. ImmSetCandidateWindow (hImc, &pos);
  3250. }
  3251. }
  3252. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  3253. };
  3254. void timerCallback() override
  3255. {
  3256. handlePositionChanged();
  3257. stopTimer();
  3258. }
  3259. IMEHandler imeHandler;
  3260. //==============================================================================
  3261. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  3262. };
  3263. MultiTouchMapper<DWORD> HWNDComponentPeer::currentTouches;
  3264. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  3265. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  3266. {
  3267. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  3268. }
  3269. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  3270. {
  3271. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  3272. (HWND) parentHWND, true);
  3273. }
  3274. JUCE_API bool shouldScaleGLWindow (void* hwnd)
  3275. {
  3276. return isPerMonitorDPIAwareWindow ((HWND) hwnd);
  3277. }
  3278. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3279. JUCE_API void setProcessDPIAwarenessIfNecessary (void* hwnd)
  3280. {
  3281. if (getProcessDPIAwareness == nullptr)
  3282. return;
  3283. DPI_Awareness context;
  3284. getProcessDPIAwareness (0, &context);
  3285. if (isPerMonitorDPIAwareWindow ((HWND) hwnd) && context != DPI_Awareness::DPI_Awareness_Per_Monitor_Aware
  3286. && setProcessDPIAwareness != nullptr)
  3287. {
  3288. setProcessDPIAwareness (DPI_Awareness::DPI_Awareness_Per_Monitor_Aware);
  3289. }
  3290. }
  3291. #endif
  3292. JUCE_API void setThreadDPIAwareness (void* hwnd)
  3293. {
  3294. if (setThreadDPIAwarenessContext != nullptr)
  3295. {
  3296. if (! JUCEApplicationBase::isStandaloneApp())
  3297. {
  3298. if (hwnd != nullptr)
  3299. setThreadDPIAwarenessContext (isPerMonitorDPIAwareWindow ((HWND) hwnd) ? DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE
  3300. : DPI_AWARENESS_CONTEXT_UNAWARE);
  3301. }
  3302. else
  3303. {
  3304. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3305. setThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
  3306. #else
  3307. setThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_UNAWARE);
  3308. #endif
  3309. }
  3310. }
  3311. }
  3312. JUCE_IMPLEMENT_SINGLETON (HWNDComponentPeer::WindowClassHolder)
  3313. //==============================================================================
  3314. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  3315. {
  3316. auto k = (SHORT) keyCode;
  3317. if ((keyCode & extendedKeyModifier) == 0)
  3318. {
  3319. if (k >= (SHORT) 'a' && k <= (SHORT) 'z')
  3320. k += (SHORT) 'A' - (SHORT) 'a';
  3321. // Only translate if extendedKeyModifier flag is not set
  3322. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  3323. (SHORT) '+', VK_OEM_PLUS,
  3324. (SHORT) '-', VK_OEM_MINUS,
  3325. (SHORT) '.', VK_OEM_PERIOD,
  3326. (SHORT) ';', VK_OEM_1,
  3327. (SHORT) ':', VK_OEM_1,
  3328. (SHORT) '/', VK_OEM_2,
  3329. (SHORT) '?', VK_OEM_2,
  3330. (SHORT) '[', VK_OEM_4,
  3331. (SHORT) ']', VK_OEM_6 };
  3332. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  3333. if (k == translatedValues[i])
  3334. k = translatedValues[i + 1];
  3335. }
  3336. return HWNDComponentPeer::isKeyDown (k);
  3337. }
  3338. // (This internal function is used by the plugin client module)
  3339. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  3340. //==============================================================================
  3341. bool JUCE_CALLTYPE Process::isForegroundProcess()
  3342. {
  3343. if (auto fg = GetForegroundWindow())
  3344. {
  3345. DWORD processID = 0;
  3346. GetWindowThreadProcessId (fg, &processID);
  3347. return processID == GetCurrentProcessId();
  3348. }
  3349. return true;
  3350. }
  3351. // N/A on Windows as far as I know.
  3352. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  3353. void JUCE_CALLTYPE Process::hide() {}
  3354. //==============================================================================
  3355. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  3356. {
  3357. if (IsWindowVisible (hwnd))
  3358. {
  3359. DWORD processID = 0;
  3360. GetWindowThreadProcessId (hwnd, &processID);
  3361. if (processID == GetCurrentProcessId())
  3362. {
  3363. WINDOWINFO info;
  3364. if (GetWindowInfo (hwnd, &info)
  3365. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  3366. {
  3367. *reinterpret_cast<bool*> (lParam) = true;
  3368. return FALSE;
  3369. }
  3370. }
  3371. }
  3372. return TRUE;
  3373. }
  3374. bool juce_areThereAnyAlwaysOnTopWindows()
  3375. {
  3376. bool anyAlwaysOnTopFound = false;
  3377. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  3378. return anyAlwaysOnTopFound;
  3379. }
  3380. //==============================================================================
  3381. class WindowsMessageBox : public AsyncUpdater
  3382. {
  3383. public:
  3384. WindowsMessageBox (AlertWindow::AlertIconType iconType,
  3385. const String& boxTitle, const String& m,
  3386. Component* associatedComponent, UINT extraFlags,
  3387. ModalComponentManager::Callback* cb, const bool runAsync)
  3388. : flags (extraFlags | getMessageBoxFlags (iconType)),
  3389. owner (getWindowForMessageBox (associatedComponent)),
  3390. title (boxTitle), message (m), callback (cb)
  3391. {
  3392. if (runAsync)
  3393. triggerAsyncUpdate();
  3394. }
  3395. int getResult() const
  3396. {
  3397. const int r = MessageBox (owner, message.toWideCharPointer(), title.toWideCharPointer(), flags);
  3398. return (r == IDYES || r == IDOK) ? 1 : (r == IDNO && (flags & 1) != 0 ? 2 : 0);
  3399. }
  3400. void handleAsyncUpdate() override
  3401. {
  3402. const int result = getResult();
  3403. if (callback != nullptr)
  3404. callback->modalStateFinished (result);
  3405. delete this;
  3406. }
  3407. private:
  3408. UINT flags;
  3409. HWND owner;
  3410. String title, message;
  3411. std::unique_ptr<ModalComponentManager::Callback> callback;
  3412. static UINT getMessageBoxFlags (AlertWindow::AlertIconType iconType) noexcept
  3413. {
  3414. UINT flags = MB_TASKMODAL | MB_SETFOREGROUND;
  3415. // this window can get lost behind JUCE windows which are set to be alwaysOnTop
  3416. // so if there are any set it to be topmost
  3417. if (juce_areThereAnyAlwaysOnTopWindows())
  3418. flags |= MB_TOPMOST;
  3419. switch (iconType)
  3420. {
  3421. case AlertWindow::QuestionIcon: flags |= MB_ICONQUESTION; break;
  3422. case AlertWindow::WarningIcon: flags |= MB_ICONWARNING; break;
  3423. case AlertWindow::InfoIcon: flags |= MB_ICONINFORMATION; break;
  3424. default: break;
  3425. }
  3426. return flags;
  3427. }
  3428. static HWND getWindowForMessageBox (Component* associatedComponent)
  3429. {
  3430. return associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : 0;
  3431. }
  3432. };
  3433. #if JUCE_MODAL_LOOPS_PERMITTED
  3434. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3435. const String& title, const String& message,
  3436. Component* associatedComponent)
  3437. {
  3438. WindowsMessageBox box (iconType, title, message, associatedComponent, MB_OK, 0, false);
  3439. (void) box.getResult();
  3440. }
  3441. #endif
  3442. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3443. const String& title, const String& message,
  3444. Component* associatedComponent,
  3445. ModalComponentManager::Callback* callback)
  3446. {
  3447. new WindowsMessageBox (iconType, title, message, associatedComponent, MB_OK, callback, true);
  3448. }
  3449. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3450. const String& title, const String& message,
  3451. Component* associatedComponent,
  3452. ModalComponentManager::Callback* callback)
  3453. {
  3454. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3455. MB_OKCANCEL, callback, callback != nullptr));
  3456. if (callback == nullptr)
  3457. return mb->getResult() != 0;
  3458. mb.release();
  3459. return false;
  3460. }
  3461. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3462. const String& title, const String& message,
  3463. Component* associatedComponent,
  3464. ModalComponentManager::Callback* callback)
  3465. {
  3466. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3467. MB_YESNOCANCEL, callback, callback != nullptr));
  3468. if (callback == nullptr)
  3469. return mb->getResult();
  3470. mb.release();
  3471. return 0;
  3472. }
  3473. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  3474. const String& title, const String& message,
  3475. Component* associatedComponent,
  3476. ModalComponentManager::Callback* callback)
  3477. {
  3478. std::unique_ptr<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3479. MB_YESNO, callback, callback != nullptr));
  3480. if (callback == nullptr)
  3481. return mb->getResult();
  3482. mb.release();
  3483. return 0;
  3484. }
  3485. //==============================================================================
  3486. bool MouseInputSource::SourceList::addSource()
  3487. {
  3488. auto numSources = sources.size();
  3489. if (numSources == 0 || canUseMultiTouch())
  3490. {
  3491. addSource (numSources, numSources == 0 ? MouseInputSource::InputSourceType::mouse
  3492. : MouseInputSource::InputSourceType::touch);
  3493. return true;
  3494. }
  3495. return false;
  3496. }
  3497. bool MouseInputSource::SourceList::canUseTouch()
  3498. {
  3499. return canUseMultiTouch();
  3500. }
  3501. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3502. {
  3503. POINT mousePos;
  3504. GetCursorPos (&mousePos);
  3505. auto p = pointFromPOINT (mousePos);
  3506. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3507. if (isPerMonitorDPIAwareThread())
  3508. p = Desktop::getInstance().getDisplays().physicalToLogical (p);
  3509. #endif
  3510. return p.toFloat();
  3511. }
  3512. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3513. {
  3514. auto newPositionInt = newPosition.roundToInt();
  3515. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3516. if (isPerMonitorDPIAwareThread())
  3517. newPositionInt = Desktop::getInstance().getDisplays().logicalToPhysical (newPositionInt);
  3518. #endif
  3519. auto point = POINTFromPoint (newPositionInt);
  3520. SetCursorPos (point.x, point.y);
  3521. }
  3522. //==============================================================================
  3523. class ScreenSaverDefeater : public Timer
  3524. {
  3525. public:
  3526. ScreenSaverDefeater()
  3527. {
  3528. startTimer (10000);
  3529. timerCallback();
  3530. }
  3531. void timerCallback() override
  3532. {
  3533. if (Process::isForegroundProcess())
  3534. {
  3535. INPUT input = { 0 };
  3536. input.type = INPUT_MOUSE;
  3537. input.mi.mouseData = MOUSEEVENTF_MOVE;
  3538. SendInput (1, &input, sizeof (INPUT));
  3539. }
  3540. }
  3541. };
  3542. static std::unique_ptr<ScreenSaverDefeater> screenSaverDefeater;
  3543. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3544. {
  3545. if (isEnabled)
  3546. screenSaverDefeater = nullptr;
  3547. else if (screenSaverDefeater == nullptr)
  3548. screenSaverDefeater.reset (new ScreenSaverDefeater());
  3549. }
  3550. bool Desktop::isScreenSaverEnabled()
  3551. {
  3552. return screenSaverDefeater == nullptr;
  3553. }
  3554. //==============================================================================
  3555. void LookAndFeel::playAlertSound()
  3556. {
  3557. MessageBeep (MB_OK);
  3558. }
  3559. //==============================================================================
  3560. void SystemClipboard::copyTextToClipboard (const String& text)
  3561. {
  3562. if (OpenClipboard (0) != 0)
  3563. {
  3564. if (EmptyClipboard() != 0)
  3565. {
  3566. auto bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  3567. if (bytesNeeded > 0)
  3568. {
  3569. if (auto bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  3570. {
  3571. if (auto* data = static_cast<WCHAR*> (GlobalLock (bufH)))
  3572. {
  3573. text.copyToUTF16 (data, bytesNeeded);
  3574. GlobalUnlock (bufH);
  3575. SetClipboardData (CF_UNICODETEXT, bufH);
  3576. }
  3577. }
  3578. }
  3579. }
  3580. CloseClipboard();
  3581. }
  3582. }
  3583. String SystemClipboard::getTextFromClipboard()
  3584. {
  3585. String result;
  3586. if (OpenClipboard (0) != 0)
  3587. {
  3588. if (auto bufH = GetClipboardData (CF_UNICODETEXT))
  3589. {
  3590. if (auto* data = (const WCHAR*) GlobalLock (bufH))
  3591. {
  3592. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  3593. GlobalUnlock (bufH);
  3594. }
  3595. }
  3596. CloseClipboard();
  3597. }
  3598. return result;
  3599. }
  3600. //==============================================================================
  3601. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  3602. {
  3603. if (auto* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComp))
  3604. tlw->setUsingNativeTitleBar (! enableOrDisable);
  3605. if (enableOrDisable)
  3606. kioskModeComp->setBounds (getDisplays().getMainDisplay().totalArea);
  3607. }
  3608. void Desktop::allowedOrientationsChanged() {}
  3609. //==============================================================================
  3610. static const Displays::Display* getCurrentDisplayFromScaleFactor (HWND hwnd)
  3611. {
  3612. Array<const Displays::Display*> candidateDisplays;
  3613. double scaleToLookFor = -1.0;
  3614. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  3615. scaleToLookFor = peer->getPlatformScaleFactor();
  3616. else
  3617. scaleToLookFor = getScaleFactorForWindow (hwnd);
  3618. auto globalScale = Desktop::getInstance().getGlobalScaleFactor();
  3619. for (auto& d : Desktop::getInstance().getDisplays().displays)
  3620. if (approximatelyEqual (d.scale / globalScale, scaleToLookFor))
  3621. candidateDisplays.add (&d);
  3622. if (candidateDisplays.size() > 0)
  3623. {
  3624. if (candidateDisplays.size() == 1)
  3625. return candidateDisplays[0];
  3626. Rectangle<int> bounds;
  3627. if (auto* peer = HWNDComponentPeer::getOwnerOfWindow (hwnd))
  3628. bounds = peer->getComponent().getTopLevelComponent()->getBounds();
  3629. else
  3630. bounds = Desktop::getInstance().getDisplays().physicalToLogical (rectangleFromRECT (getWindowRect (hwnd)));
  3631. const Displays::Display* retVal = nullptr;
  3632. int maxArea = -1;
  3633. for (auto* d : candidateDisplays)
  3634. {
  3635. auto intersection = d->totalArea.getIntersection (bounds);
  3636. auto area = intersection.getWidth() * intersection.getHeight();
  3637. if (area > maxArea)
  3638. {
  3639. maxArea = area;
  3640. retVal = d;
  3641. }
  3642. }
  3643. if (retVal != nullptr)
  3644. return retVal;
  3645. }
  3646. return &Desktop::getInstance().getDisplays().getMainDisplay();
  3647. }
  3648. //==============================================================================
  3649. struct MonitorInfo
  3650. {
  3651. MonitorInfo (bool main, RECT rect, double d) noexcept
  3652. : isMain (main), bounds (rect), dpi (d) {}
  3653. bool isMain;
  3654. RECT bounds;
  3655. double dpi;
  3656. };
  3657. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT r, LPARAM userInfo)
  3658. {
  3659. MONITORINFO info = { 0 };
  3660. info.cbSize = sizeof (info);
  3661. GetMonitorInfo (hm, &info);
  3662. auto isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  3663. auto dpi = 0.0;
  3664. if (getDPIForMonitor != nullptr)
  3665. {
  3666. UINT dpiX = 0, dpiY = 0;
  3667. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  3668. dpi = (dpiX + dpiY) / 2.0;
  3669. }
  3670. ((Array<MonitorInfo>*) userInfo)->add ({ isMain, *r, dpi });
  3671. return TRUE;
  3672. }
  3673. void Displays::findDisplays (float masterScale)
  3674. {
  3675. setDPIAwareness();
  3676. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3677. DPI_AWARENESS_CONTEXT prevContext = nullptr;
  3678. if (setThreadDPIAwarenessContext != nullptr && getAwarenessFromDPIAwarenessContext != nullptr && getThreadDPIAwarenessContext != nullptr
  3679. && getAwarenessFromDPIAwarenessContext (getThreadDPIAwarenessContext()) != DPI_Awareness::DPI_Awareness_Per_Monitor_Aware)
  3680. {
  3681. prevContext = setThreadDPIAwarenessContext (DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
  3682. }
  3683. #endif
  3684. Array<MonitorInfo> monitors;
  3685. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitors);
  3686. auto globalDPI = getGlobalDPI();
  3687. if (monitors.size() == 0)
  3688. monitors.add ({ true, getWindowRect (GetDesktopWindow()), globalDPI });
  3689. // make sure the first in the list is the main monitor
  3690. for (int i = 1; i < monitors.size(); ++i)
  3691. if (monitors.getReference (i).isMain)
  3692. monitors.swap (i, 0);
  3693. for (auto& monitor : monitors)
  3694. {
  3695. Display d;
  3696. d.isMain = monitor.isMain;
  3697. d.dpi = monitor.dpi;
  3698. if (d.dpi == 0)
  3699. {
  3700. d.dpi = globalDPI;
  3701. d.scale = masterScale;
  3702. }
  3703. else
  3704. {
  3705. d.scale = (d.dpi / USER_DEFAULT_SCREEN_DPI) * (masterScale / Desktop::getDefaultMasterScale());
  3706. }
  3707. d.userArea = d.totalArea = Rectangle<int>::leftTopRightBottom (monitor.bounds.left, monitor.bounds.top,
  3708. monitor.bounds.right, monitor.bounds.bottom);
  3709. if (d.isMain)
  3710. {
  3711. RECT workArea;
  3712. SystemParametersInfo (SPI_GETWORKAREA, 0, &workArea, 0);
  3713. d.userArea = d.userArea.getIntersection (Rectangle<int>::leftTopRightBottom (workArea.left, workArea.top,
  3714. workArea.right, workArea.bottom));
  3715. }
  3716. displays.add (d);
  3717. }
  3718. #if JUCE_WIN_PER_MONITOR_DPI_AWARE
  3719. updateToLogical();
  3720. // Reset the DPI awareness context if it was overridden earlier
  3721. if (prevContext != nullptr)
  3722. setThreadDPIAwarenessContext (prevContext);
  3723. #else
  3724. for (auto& d : displays)
  3725. {
  3726. d.totalArea /= masterScale;
  3727. d.userArea /= masterScale;
  3728. }
  3729. #endif
  3730. }
  3731. //==============================================================================
  3732. static HICON extractFileHICON (const File& file)
  3733. {
  3734. WORD iconNum = 0;
  3735. WCHAR name[MAX_PATH * 2];
  3736. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  3737. return ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  3738. name, &iconNum);
  3739. }
  3740. Image juce_createIconForFile (const File& file)
  3741. {
  3742. Image image;
  3743. if (auto icon = extractFileHICON (file))
  3744. {
  3745. image = IconConverters::createImageFromHICON (icon);
  3746. DestroyIcon (icon);
  3747. }
  3748. return image;
  3749. }
  3750. //==============================================================================
  3751. void* CustomMouseCursorInfo::create() const
  3752. {
  3753. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  3754. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  3755. Image im (image);
  3756. int hotspotX = hotspot.x;
  3757. int hotspotY = hotspot.y;
  3758. if (im.getWidth() > maxW || im.getHeight() > maxH)
  3759. {
  3760. im = im.rescaled (maxW, maxH);
  3761. hotspotX = (hotspotX * maxW) / image.getWidth();
  3762. hotspotY = (hotspotY * maxH) / image.getHeight();
  3763. }
  3764. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  3765. }
  3766. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool isStandard)
  3767. {
  3768. if (cursorHandle != nullptr && ! isStandard)
  3769. DestroyCursor ((HCURSOR) cursorHandle);
  3770. }
  3771. enum
  3772. {
  3773. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  3774. };
  3775. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  3776. {
  3777. LPCTSTR cursorName = IDC_ARROW;
  3778. switch (type)
  3779. {
  3780. case NormalCursor:
  3781. case ParentCursor: break;
  3782. case NoCursor: return (void*) hiddenMouseCursorHandle;
  3783. case WaitCursor: cursorName = IDC_WAIT; break;
  3784. case IBeamCursor: cursorName = IDC_IBEAM; break;
  3785. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  3786. case CrosshairCursor: cursorName = IDC_CROSS; break;
  3787. case LeftRightResizeCursor:
  3788. case LeftEdgeResizeCursor:
  3789. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  3790. case UpDownResizeCursor:
  3791. case TopEdgeResizeCursor:
  3792. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  3793. case TopLeftCornerResizeCursor:
  3794. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  3795. case TopRightCornerResizeCursor:
  3796. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  3797. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  3798. case DraggingHandCursor:
  3799. {
  3800. static void* dragHandCursor = nullptr;
  3801. if (dragHandCursor == nullptr)
  3802. {
  3803. static const unsigned char dragHandData[] =
  3804. { 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,
  3805. 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,
  3806. 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 };
  3807. dragHandCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), { 8, 7 }).create();
  3808. }
  3809. return dragHandCursor;
  3810. }
  3811. case CopyingCursor:
  3812. {
  3813. static void* copyCursor = nullptr;
  3814. if (copyCursor == nullptr)
  3815. {
  3816. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3817. 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,
  3818. 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,
  3819. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3820. const int copyCursorSize = 119;
  3821. copyCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), { 1, 3 }).create();
  3822. }
  3823. return copyCursor;
  3824. }
  3825. default:
  3826. jassertfalse; break;
  3827. }
  3828. if (auto cursorH = LoadCursor (0, cursorName))
  3829. return cursorH;
  3830. return LoadCursor (0, IDC_ARROW);
  3831. }
  3832. //==============================================================================
  3833. void MouseCursor::showInWindow (ComponentPeer*) const
  3834. {
  3835. auto c = (HCURSOR) getHandle();
  3836. if (c == 0)
  3837. c = LoadCursor (0, IDC_ARROW);
  3838. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  3839. c = 0;
  3840. SetCursor (c);
  3841. }
  3842. } // namespace juce