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.

5379 lines
190KB

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