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.

4232 lines
147KB

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