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.

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