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.

5398 lines
191KB

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