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.

5361 lines
190KB

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