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.

4727 lines
168KB

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