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.

4176 lines
144KB

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