The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4893 lines
173KB

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