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.

5343 lines
189KB

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