Audio plugin host https://kx.studio/carla
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.

5405 lines
192KB

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