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.

4817 lines
171KB

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