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.

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