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.

5394 lines
191KB

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