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.

5302 lines
187KB

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