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.

4751 lines
169KB

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