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.

4855 lines
173KB

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