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.

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