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.

4669 lines
166KB

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