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.

5256 lines
185KB

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