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.

4820 lines
172KB

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