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.

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