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.

4181 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, (int) (r.right - r.left))
  971. && isPositiveAndBelow (localPos.y, (int) (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. currentTouches.clearTouch (touchIndex);
  1933. if (! currentTouches.areAnyTouchesActive())
  1934. isCancel = true;
  1935. }
  1936. else
  1937. {
  1938. modsToSend = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1939. }
  1940. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend,
  1941. pressure, orientation, time, {}, touchIndex);
  1942. if (! isValidPeer (this))
  1943. return false;
  1944. if (isUp)
  1945. {
  1946. handleMouseEvent (MouseInputSource::InputSourceType::touch, { -10.0f, -10.0f }, currentModifiers.withoutMouseButtons(),
  1947. pressure, orientation, time, {}, touchIndex);
  1948. if (! isValidPeer (this))
  1949. return false;
  1950. if (isCancel)
  1951. {
  1952. currentTouches.clear();
  1953. currentModifiers = currentModifiers.withoutMouseButtons();
  1954. }
  1955. }
  1956. return true;
  1957. }
  1958. bool handlePointerInput (WPARAM wParam, LPARAM lParam, const bool isDown, const bool isUp)
  1959. {
  1960. if (! canUsePointerAPI)
  1961. return false;
  1962. auto pointerType = getPointerType (wParam);
  1963. if (pointerType == MouseInputSource::InputSourceType::touch)
  1964. {
  1965. POINTER_TOUCH_INFO touchInfo;
  1966. if (! getPointerTouchInfo (GET_POINTERID_WPARAM (wParam), &touchInfo))
  1967. return false;
  1968. const auto pressure = touchInfo.touchMask & TOUCH_MASK_PRESSURE ? touchInfo.pressure
  1969. : MouseInputSource::invalidPressure;
  1970. const auto orientation = touchInfo.touchMask & TOUCH_MASK_ORIENTATION ? degreesToRadians (static_cast<float> (touchInfo.orientation))
  1971. : MouseInputSource::invalidOrientation;
  1972. if (! handleTouchInput (emulateTouchEventFromPointer (lParam, wParam),
  1973. isDown, isUp, pressure, orientation))
  1974. return false;
  1975. }
  1976. else if (pointerType == MouseInputSource::InputSourceType::pen)
  1977. {
  1978. POINTER_PEN_INFO penInfo;
  1979. if (! getPointerPenInfo (GET_POINTERID_WPARAM (wParam), &penInfo))
  1980. return false;
  1981. const auto pressure = (penInfo.penMask & PEN_MASK_PRESSURE) ? penInfo.pressure / 1024.0f : MouseInputSource::invalidPressure;
  1982. if (! handlePenInput (penInfo, globalToLocal (Point<float> (static_cast<float> (GET_X_LPARAM(lParam)),
  1983. static_cast<float> (GET_Y_LPARAM(lParam)))),
  1984. pressure, isDown, isUp))
  1985. return false;
  1986. }
  1987. else
  1988. {
  1989. return false;
  1990. }
  1991. return true;
  1992. }
  1993. TOUCHINPUT emulateTouchEventFromPointer (LPARAM lParam, WPARAM wParam)
  1994. {
  1995. TOUCHINPUT touchInput;
  1996. touchInput.dwID = GET_POINTERID_WPARAM (wParam);
  1997. touchInput.x = GET_X_LPARAM (lParam) * 100;
  1998. touchInput.y = GET_Y_LPARAM (lParam) * 100;
  1999. return touchInput;
  2000. }
  2001. bool handlePenInput (POINTER_PEN_INFO penInfo, Point<float> pos, const float pressure, bool isDown, bool isUp)
  2002. {
  2003. const auto time = getMouseEventTime();
  2004. ModifierKeys modsToSend (currentModifiers);
  2005. PenDetails penDetails;
  2006. penDetails.rotation = (penInfo.penMask & PEN_MASK_ROTATION) ? degreesToRadians (static_cast<float> (penInfo.rotation)) : MouseInputSource::invalidRotation;
  2007. penDetails.tiltX = (penInfo.penMask & PEN_MASK_TILT_X) ? penInfo.tiltX / 90.0f : MouseInputSource::invalidTiltX;
  2008. penDetails.tiltY = (penInfo.penMask & PEN_MASK_TILT_Y) ? penInfo.tiltY / 90.0f : MouseInputSource::invalidTiltY;
  2009. auto pInfoFlags = penInfo.pointerInfo.pointerFlags;
  2010. if ((pInfoFlags & POINTER_FLAG_FIRSTBUTTON) != 0)
  2011. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  2012. else if ((pInfoFlags & POINTER_FLAG_SECONDBUTTON) != 0)
  2013. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::rightButtonModifier);
  2014. if (isDown)
  2015. {
  2016. modsToSend = currentModifiers;
  2017. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  2018. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend.withoutMouseButtons(),
  2019. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2020. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2021. return false;
  2022. }
  2023. else if (isUp || ! (pInfoFlags & POINTER_FLAG_INCONTACT))
  2024. {
  2025. modsToSend = modsToSend.withoutMouseButtons();
  2026. }
  2027. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend, pressure,
  2028. MouseInputSource::invalidOrientation, time, penDetails);
  2029. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  2030. return false;
  2031. if (isUp)
  2032. {
  2033. handleMouseEvent (MouseInputSource::InputSourceType::pen, { -10.0f, -10.0f }, currentModifiers,
  2034. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  2035. if (! isValidPeer (this))
  2036. return false;
  2037. }
  2038. return true;
  2039. }
  2040. //==============================================================================
  2041. void sendModifierKeyChangeIfNeeded()
  2042. {
  2043. if (modifiersAtLastCallback != currentModifiers)
  2044. {
  2045. modifiersAtLastCallback = currentModifiers;
  2046. handleModifierKeysChange();
  2047. }
  2048. }
  2049. bool doKeyUp (const WPARAM key)
  2050. {
  2051. updateKeyModifiers();
  2052. switch (key)
  2053. {
  2054. case VK_SHIFT:
  2055. case VK_CONTROL:
  2056. case VK_MENU:
  2057. case VK_CAPITAL:
  2058. case VK_LWIN:
  2059. case VK_RWIN:
  2060. case VK_APPS:
  2061. case VK_NUMLOCK:
  2062. case VK_SCROLL:
  2063. case VK_LSHIFT:
  2064. case VK_RSHIFT:
  2065. case VK_LCONTROL:
  2066. case VK_LMENU:
  2067. case VK_RCONTROL:
  2068. case VK_RMENU:
  2069. sendModifierKeyChangeIfNeeded();
  2070. }
  2071. return handleKeyUpOrDown (false)
  2072. || Component::getCurrentlyModalComponent() != nullptr;
  2073. }
  2074. bool doKeyDown (const WPARAM key)
  2075. {
  2076. updateKeyModifiers();
  2077. bool used = false;
  2078. switch (key)
  2079. {
  2080. case VK_SHIFT:
  2081. case VK_LSHIFT:
  2082. case VK_RSHIFT:
  2083. case VK_CONTROL:
  2084. case VK_LCONTROL:
  2085. case VK_RCONTROL:
  2086. case VK_MENU:
  2087. case VK_LMENU:
  2088. case VK_RMENU:
  2089. case VK_LWIN:
  2090. case VK_RWIN:
  2091. case VK_CAPITAL:
  2092. case VK_NUMLOCK:
  2093. case VK_SCROLL:
  2094. case VK_APPS:
  2095. sendModifierKeyChangeIfNeeded();
  2096. break;
  2097. case VK_LEFT:
  2098. case VK_RIGHT:
  2099. case VK_UP:
  2100. case VK_DOWN:
  2101. case VK_PRIOR:
  2102. case VK_NEXT:
  2103. case VK_HOME:
  2104. case VK_END:
  2105. case VK_DELETE:
  2106. case VK_INSERT:
  2107. case VK_F1:
  2108. case VK_F2:
  2109. case VK_F3:
  2110. case VK_F4:
  2111. case VK_F5:
  2112. case VK_F6:
  2113. case VK_F7:
  2114. case VK_F8:
  2115. case VK_F9:
  2116. case VK_F10:
  2117. case VK_F11:
  2118. case VK_F12:
  2119. case VK_F13:
  2120. case VK_F14:
  2121. case VK_F15:
  2122. case VK_F16:
  2123. case VK_F17:
  2124. case VK_F18:
  2125. case VK_F19:
  2126. case VK_F20:
  2127. case VK_F21:
  2128. case VK_F22:
  2129. case VK_F23:
  2130. case VK_F24:
  2131. used = handleKeyUpOrDown (true);
  2132. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  2133. break;
  2134. default:
  2135. used = handleKeyUpOrDown (true);
  2136. {
  2137. MSG msg;
  2138. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  2139. {
  2140. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  2141. // manually generate the key-press event that matches this key-down.
  2142. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  2143. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  2144. BYTE keyState[256];
  2145. GetKeyboardState (keyState);
  2146. WCHAR text[16] = { 0 };
  2147. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  2148. text[0] = 0;
  2149. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  2150. }
  2151. }
  2152. break;
  2153. }
  2154. return used || (Component::getCurrentlyModalComponent() != nullptr);
  2155. }
  2156. bool doKeyChar (int key, const LPARAM flags)
  2157. {
  2158. updateKeyModifiers();
  2159. juce_wchar textChar = (juce_wchar) key;
  2160. const int virtualScanCode = (flags >> 16) & 0xff;
  2161. if (key >= '0' && key <= '9')
  2162. {
  2163. switch (virtualScanCode) // check for a numeric keypad scan-code
  2164. {
  2165. case 0x52:
  2166. case 0x4f:
  2167. case 0x50:
  2168. case 0x51:
  2169. case 0x4b:
  2170. case 0x4c:
  2171. case 0x4d:
  2172. case 0x47:
  2173. case 0x48:
  2174. case 0x49:
  2175. key = (key - '0') + KeyPress::numberPad0;
  2176. break;
  2177. default:
  2178. break;
  2179. }
  2180. }
  2181. else
  2182. {
  2183. // convert the scan code to an unmodified character code..
  2184. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  2185. UINT keyChar = MapVirtualKey (virtualKey, 2);
  2186. keyChar = LOWORD (keyChar);
  2187. if (keyChar != 0)
  2188. key = (int) keyChar;
  2189. // avoid sending junk text characters for some control-key combinations
  2190. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  2191. textChar = 0;
  2192. }
  2193. return handleKeyPress (key, textChar);
  2194. }
  2195. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  2196. {
  2197. if (HWND parentH = GetParent (hwnd))
  2198. PostMessage (parentH, message, wParam, lParam);
  2199. }
  2200. bool doAppCommand (const LPARAM lParam)
  2201. {
  2202. int key = 0;
  2203. switch (GET_APPCOMMAND_LPARAM (lParam))
  2204. {
  2205. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  2206. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  2207. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  2208. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  2209. default: break;
  2210. }
  2211. if (key != 0)
  2212. {
  2213. updateKeyModifiers();
  2214. if (hwnd == GetActiveWindow())
  2215. {
  2216. handleKeyPress (key, 0);
  2217. return true;
  2218. }
  2219. }
  2220. return false;
  2221. }
  2222. bool isConstrainedNativeWindow() const
  2223. {
  2224. return constrainer != nullptr
  2225. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  2226. && ! isKioskMode();
  2227. }
  2228. Rectangle<int> getCurrentScaledBounds (float scale) const
  2229. {
  2230. return ScalingHelpers::unscaledScreenPosToScaled (scale, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (scale, component.getBounds())));
  2231. }
  2232. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  2233. {
  2234. if (isConstrainedNativeWindow())
  2235. {
  2236. auto scale = getComponent().getDesktopScaleFactor();
  2237. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, rectangleFromRECT (r));
  2238. auto current = getCurrentScaledBounds (scale);
  2239. constrainer->checkBounds (pos, current,
  2240. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2241. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  2242. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  2243. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  2244. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  2245. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  2246. r.left = pos.getX();
  2247. r.top = pos.getY();
  2248. r.right = pos.getRight();
  2249. r.bottom = pos.getBottom();
  2250. }
  2251. return TRUE;
  2252. }
  2253. LRESULT handlePositionChanging (WINDOWPOS& wp)
  2254. {
  2255. if (isConstrainedNativeWindow())
  2256. {
  2257. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  2258. && ! Component::isMouseButtonDownAnywhere())
  2259. {
  2260. auto scale = getComponent().getDesktopScaleFactor();
  2261. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, Rectangle<int> (wp.x, wp.y, wp.cx, wp.cy));
  2262. auto current = getCurrentScaledBounds (scale);
  2263. constrainer->checkBounds (pos, current,
  2264. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2265. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  2266. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  2267. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  2268. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  2269. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  2270. wp.x = pos.getX();
  2271. wp.y = pos.getY();
  2272. wp.cx = pos.getWidth();
  2273. wp.cy = pos.getHeight();
  2274. }
  2275. }
  2276. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  2277. component.setVisible (true);
  2278. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  2279. component.setVisible (false);
  2280. return 0;
  2281. }
  2282. bool handlePositionChanged()
  2283. {
  2284. auto pos = getCurrentMousePos();
  2285. if (contains (pos.roundToInt(), false))
  2286. {
  2287. if (! areOtherTouchSourcesActive())
  2288. doMouseEvent (pos, MouseInputSource::invalidPressure);
  2289. if (! isValidPeer (this))
  2290. return true;
  2291. }
  2292. handleMovedOrResized();
  2293. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly..
  2294. }
  2295. void handleAppActivation (const WPARAM wParam)
  2296. {
  2297. modifiersAtLastCallback = -1;
  2298. updateKeyModifiers();
  2299. if (isMinimised())
  2300. {
  2301. component.repaint();
  2302. handleMovedOrResized();
  2303. if (! isValidPeer (this))
  2304. return;
  2305. }
  2306. auto* underMouse = component.getComponentAt (component.getMouseXYRelative());
  2307. if (underMouse == nullptr)
  2308. underMouse = &component;
  2309. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  2310. {
  2311. if (LOWORD (wParam) == WA_CLICKACTIVE)
  2312. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  2313. else
  2314. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  2315. }
  2316. else
  2317. {
  2318. handleBroughtToFront();
  2319. }
  2320. }
  2321. void handlePowerBroadcast (WPARAM wParam)
  2322. {
  2323. if (auto* app = JUCEApplicationBase::getInstance())
  2324. {
  2325. switch (wParam)
  2326. {
  2327. case PBT_APMSUSPEND: app->suspended(); break;
  2328. case PBT_APMQUERYSUSPENDFAILED:
  2329. case PBT_APMRESUMECRITICAL:
  2330. case PBT_APMRESUMESUSPEND:
  2331. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  2332. default: break;
  2333. }
  2334. }
  2335. }
  2336. void handleLeftClickInNCArea (WPARAM wParam)
  2337. {
  2338. if (! sendInputAttemptWhenModalMessage())
  2339. {
  2340. switch (wParam)
  2341. {
  2342. case HTBOTTOM:
  2343. case HTBOTTOMLEFT:
  2344. case HTBOTTOMRIGHT:
  2345. case HTGROWBOX:
  2346. case HTLEFT:
  2347. case HTRIGHT:
  2348. case HTTOP:
  2349. case HTTOPLEFT:
  2350. case HTTOPRIGHT:
  2351. if (isConstrainedNativeWindow())
  2352. {
  2353. constrainerIsResizing = true;
  2354. constrainer->resizeStart();
  2355. }
  2356. break;
  2357. default:
  2358. break;
  2359. }
  2360. }
  2361. }
  2362. void initialiseSysMenu (HMENU menu) const
  2363. {
  2364. if (! hasTitleBar())
  2365. {
  2366. if (isFullScreen())
  2367. {
  2368. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  2369. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  2370. }
  2371. else if (! isMinimised())
  2372. {
  2373. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  2374. }
  2375. }
  2376. }
  2377. void doSettingChange()
  2378. {
  2379. auto& desktop = Desktop::getInstance();
  2380. const_cast<Desktop::Displays&> (desktop.getDisplays()).refresh();
  2381. if (fullScreen && ! isMinimised())
  2382. {
  2383. auto& display = desktop.getDisplays().getDisplayContaining (component.getScreenBounds().getCentre());
  2384. setWindowPos (hwnd, display.userArea * display.scale,
  2385. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  2386. }
  2387. }
  2388. void handleDPIChange() // happens when a window moves to a screen with a different DPI.
  2389. {
  2390. }
  2391. //==============================================================================
  2392. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2393. void setModifierKeyProvider (ModifierKeyProvider* provider) override
  2394. {
  2395. modProvider = provider;
  2396. }
  2397. void removeModifierKeyProvider() override
  2398. {
  2399. modProvider = nullptr;
  2400. }
  2401. #endif
  2402. //==============================================================================
  2403. public:
  2404. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2405. {
  2406. if (auto* peer = getOwnerOfWindow (h))
  2407. {
  2408. jassert (isValidPeer (peer));
  2409. return peer->peerWindowProc (h, message, wParam, lParam);
  2410. }
  2411. return DefWindowProcW (h, message, wParam, lParam);
  2412. }
  2413. private:
  2414. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  2415. {
  2416. auto& mm = *MessageManager::getInstance();
  2417. if (mm.currentThreadHasLockedMessageManager())
  2418. return callback (userData);
  2419. return mm.callFunctionOnMessageThread (callback, userData);
  2420. }
  2421. static Point<float> getPointFromLParam (LPARAM lParam) noexcept
  2422. {
  2423. return { static_cast<float> (GET_X_LPARAM (lParam)),
  2424. static_cast<float> (GET_Y_LPARAM (lParam)) };
  2425. }
  2426. static Point<float> getCurrentMousePosGlobal() noexcept
  2427. {
  2428. return getPointFromLParam (GetMessagePos());
  2429. }
  2430. Point<float> getCurrentMousePos() noexcept
  2431. {
  2432. return globalToLocal (getCurrentMousePosGlobal());
  2433. }
  2434. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2435. {
  2436. switch (message)
  2437. {
  2438. //==============================================================================
  2439. case WM_NCHITTEST:
  2440. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2441. return HTTRANSPARENT;
  2442. if (! hasTitleBar())
  2443. return HTCLIENT;
  2444. break;
  2445. //==============================================================================
  2446. case WM_PAINT:
  2447. handlePaintMessage();
  2448. return 0;
  2449. case WM_NCPAINT:
  2450. if (wParam != 1) // (1 = a repaint of the entire NC region)
  2451. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  2452. if (hasTitleBar())
  2453. break; // let the DefWindowProc handle drawing the frame.
  2454. return 0;
  2455. case WM_ERASEBKGND:
  2456. case WM_NCCALCSIZE:
  2457. if (hasTitleBar())
  2458. break;
  2459. return 1;
  2460. //==============================================================================
  2461. case WM_POINTERUPDATE:
  2462. if (handlePointerInput (wParam, lParam, false, false))
  2463. return 0;
  2464. break;
  2465. case WM_POINTERDOWN:
  2466. if (handlePointerInput (wParam, lParam, true, false))
  2467. return 0;
  2468. break;
  2469. case WM_POINTERUP:
  2470. if (handlePointerInput (wParam, lParam, false, true))
  2471. return 0;
  2472. break;
  2473. //==============================================================================
  2474. case WM_MOUSEMOVE: doMouseMove (getPointFromLParam (lParam), false); return 0;
  2475. case WM_POINTERLEAVE:
  2476. case WM_MOUSELEAVE: doMouseExit(); return 0;
  2477. case WM_LBUTTONDOWN:
  2478. case WM_MBUTTONDOWN:
  2479. case WM_RBUTTONDOWN: doMouseDown (getPointFromLParam (lParam), wParam); return 0;
  2480. case WM_LBUTTONUP:
  2481. case WM_MBUTTONUP:
  2482. case WM_RBUTTONUP: doMouseUp (getPointFromLParam (lParam), wParam); return 0;
  2483. case WM_POINTERWHEEL:
  2484. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  2485. case WM_POINTERHWHEEL:
  2486. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  2487. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  2488. case WM_NCPOINTERUPDATE:
  2489. case WM_NCMOUSEMOVE:
  2490. if (hasTitleBar())
  2491. break;
  2492. return 0;
  2493. case WM_TOUCH:
  2494. if (getTouchInputInfo != nullptr)
  2495. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  2496. break;
  2497. case 0x119: /* WM_GESTURE */
  2498. if (doGestureEvent (lParam))
  2499. return 0;
  2500. break;
  2501. //==============================================================================
  2502. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  2503. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  2504. case WM_WINDOWPOSCHANGED:
  2505. {
  2506. const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
  2507. if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
  2508. startTimer(100);
  2509. else
  2510. if (handlePositionChanged())
  2511. return 0;
  2512. }
  2513. break;
  2514. //==============================================================================
  2515. case WM_KEYDOWN:
  2516. case WM_SYSKEYDOWN:
  2517. if (doKeyDown (wParam))
  2518. return 0;
  2519. forwardMessageToParent (message, wParam, lParam);
  2520. break;
  2521. case WM_KEYUP:
  2522. case WM_SYSKEYUP:
  2523. if (doKeyUp (wParam))
  2524. return 0;
  2525. forwardMessageToParent (message, wParam, lParam);
  2526. break;
  2527. case WM_CHAR:
  2528. if (doKeyChar ((int) wParam, lParam))
  2529. return 0;
  2530. forwardMessageToParent (message, wParam, lParam);
  2531. break;
  2532. case WM_APPCOMMAND:
  2533. if (doAppCommand (lParam))
  2534. return TRUE;
  2535. break;
  2536. case WM_MENUCHAR: // triggered when alt+something is pressed
  2537. return MNC_CLOSE << 16; // (avoids making the default system beep)
  2538. //==============================================================================
  2539. case WM_SETFOCUS:
  2540. updateKeyModifiers();
  2541. handleFocusGain();
  2542. break;
  2543. case WM_KILLFOCUS:
  2544. if (hasCreatedCaret)
  2545. {
  2546. hasCreatedCaret = false;
  2547. DestroyCaret();
  2548. }
  2549. handleFocusLoss();
  2550. break;
  2551. case WM_ACTIVATEAPP:
  2552. // Windows does weird things to process priority when you swap apps,
  2553. // so this forces an update when the app is brought to the front
  2554. if (wParam != FALSE)
  2555. juce_repeatLastProcessPriority();
  2556. else
  2557. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  2558. juce_checkCurrentlyFocusedTopLevelWindow();
  2559. modifiersAtLastCallback = -1;
  2560. return 0;
  2561. case WM_ACTIVATE:
  2562. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  2563. {
  2564. handleAppActivation (wParam);
  2565. return 0;
  2566. }
  2567. break;
  2568. case WM_NCACTIVATE:
  2569. // while a temporary window is being shown, prevent Windows from deactivating the
  2570. // title bars of our main windows.
  2571. if (wParam == 0 && ! shouldDeactivateTitleBar)
  2572. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  2573. break;
  2574. case WM_POINTERACTIVATE:
  2575. case WM_MOUSEACTIVATE:
  2576. if (! component.getMouseClickGrabsKeyboardFocus())
  2577. return MA_NOACTIVATE;
  2578. break;
  2579. case WM_SHOWWINDOW:
  2580. if (wParam != 0)
  2581. {
  2582. component.setVisible (true);
  2583. handleBroughtToFront();
  2584. }
  2585. break;
  2586. case WM_CLOSE:
  2587. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  2588. handleUserClosingWindow();
  2589. return 0;
  2590. #if JUCE_REMOVE_COMPONENT_FROM_DESKTOP_ON_WM_DESTROY
  2591. case WM_DESTROY:
  2592. getComponent().removeFromDesktop();
  2593. return 0;
  2594. #endif
  2595. case WM_QUERYENDSESSION:
  2596. if (auto* app = JUCEApplicationBase::getInstance())
  2597. {
  2598. app->systemRequestedQuit();
  2599. return MessageManager::getInstance()->hasStopMessageBeenSent();
  2600. }
  2601. return TRUE;
  2602. case WM_POWERBROADCAST:
  2603. handlePowerBroadcast (wParam);
  2604. break;
  2605. case WM_SYNCPAINT:
  2606. return 0;
  2607. case WM_DISPLAYCHANGE:
  2608. InvalidateRect (h, 0, 0);
  2609. // intentional fall-through...
  2610. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  2611. doSettingChange();
  2612. break;
  2613. case 0x2e0: // WM_DPICHANGED
  2614. handleDPIChange();
  2615. break;
  2616. case WM_INITMENU:
  2617. initialiseSysMenu ((HMENU) wParam);
  2618. break;
  2619. case WM_SYSCOMMAND:
  2620. switch (wParam & 0xfff0)
  2621. {
  2622. case SC_CLOSE:
  2623. if (sendInputAttemptWhenModalMessage())
  2624. return 0;
  2625. if (hasTitleBar())
  2626. {
  2627. PostMessage (h, WM_CLOSE, 0, 0);
  2628. return 0;
  2629. }
  2630. break;
  2631. case SC_KEYMENU:
  2632. #if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
  2633. // This test prevents a press of the ALT key from triggering the ancient top-left window menu.
  2634. // By default we suppress this behaviour because it's unlikely that more than a tiny subset of
  2635. // our users will actually want it, and it causes problems if you're trying to use the ALT key
  2636. // as a modifier for mouse actions. If you really need the old behaviour, then just define
  2637. // JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
  2638. if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
  2639. return 0;
  2640. #endif
  2641. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  2642. // situations that can arise if a modal loop is started from an alt-key keypress).
  2643. if (hasTitleBar() && h == GetCapture())
  2644. ReleaseCapture();
  2645. break;
  2646. case SC_MAXIMIZE:
  2647. if (! sendInputAttemptWhenModalMessage())
  2648. setFullScreen (true);
  2649. return 0;
  2650. case SC_MINIMIZE:
  2651. if (sendInputAttemptWhenModalMessage())
  2652. return 0;
  2653. if (! hasTitleBar())
  2654. {
  2655. setMinimised (true);
  2656. return 0;
  2657. }
  2658. break;
  2659. case SC_RESTORE:
  2660. if (sendInputAttemptWhenModalMessage())
  2661. return 0;
  2662. if (hasTitleBar())
  2663. {
  2664. if (isFullScreen())
  2665. {
  2666. setFullScreen (false);
  2667. return 0;
  2668. }
  2669. }
  2670. else
  2671. {
  2672. if (isMinimised())
  2673. setMinimised (false);
  2674. else if (isFullScreen())
  2675. setFullScreen (false);
  2676. return 0;
  2677. }
  2678. break;
  2679. }
  2680. break;
  2681. case WM_NCPOINTERDOWN:
  2682. case WM_NCLBUTTONDOWN:
  2683. handleLeftClickInNCArea (wParam);
  2684. break;
  2685. case WM_NCRBUTTONDOWN:
  2686. case WM_NCMBUTTONDOWN:
  2687. sendInputAttemptWhenModalMessage();
  2688. break;
  2689. case WM_IME_SETCONTEXT:
  2690. imeHandler.handleSetContext (h, wParam == TRUE);
  2691. lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  2692. break;
  2693. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  2694. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  2695. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  2696. case WM_GETDLGCODE:
  2697. return DLGC_WANTALLKEYS;
  2698. default:
  2699. break;
  2700. }
  2701. return DefWindowProcW (h, message, wParam, lParam);
  2702. }
  2703. bool sendInputAttemptWhenModalMessage()
  2704. {
  2705. if (component.isCurrentlyBlockedByAnotherModalComponent())
  2706. {
  2707. if (Component* const current = Component::getCurrentlyModalComponent())
  2708. current->inputAttemptWhenModal();
  2709. return true;
  2710. }
  2711. return false;
  2712. }
  2713. //==============================================================================
  2714. struct IMEHandler
  2715. {
  2716. IMEHandler()
  2717. {
  2718. reset();
  2719. }
  2720. void handleSetContext (HWND hWnd, const bool windowIsActive)
  2721. {
  2722. if (compositionInProgress && ! windowIsActive)
  2723. {
  2724. compositionInProgress = false;
  2725. if (HIMC hImc = ImmGetContext (hWnd))
  2726. {
  2727. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  2728. ImmReleaseContext (hWnd, hImc);
  2729. }
  2730. }
  2731. }
  2732. void handleStartComposition (ComponentPeer& owner)
  2733. {
  2734. reset();
  2735. if (auto* target = owner.findCurrentTextInputTarget())
  2736. target->insertTextAtCaret (String());
  2737. }
  2738. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  2739. {
  2740. if (compositionInProgress)
  2741. {
  2742. // If this occurs, the user has cancelled the composition, so clear their changes..
  2743. if (auto* target = owner.findCurrentTextInputTarget())
  2744. {
  2745. target->setHighlightedRegion (compositionRange);
  2746. target->insertTextAtCaret (String());
  2747. compositionRange.setLength (0);
  2748. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  2749. target->setTemporaryUnderlining (Array<Range<int> >());
  2750. }
  2751. if (auto hImc = ImmGetContext (hWnd))
  2752. {
  2753. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  2754. ImmReleaseContext (hWnd, hImc);
  2755. }
  2756. }
  2757. reset();
  2758. }
  2759. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  2760. {
  2761. if (auto* target = owner.findCurrentTextInputTarget())
  2762. {
  2763. if (auto hImc = ImmGetContext (hWnd))
  2764. {
  2765. if (compositionRange.getStart() < 0)
  2766. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  2767. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  2768. {
  2769. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  2770. Range<int>::emptyRange (-1));
  2771. reset();
  2772. target->setTemporaryUnderlining (Array<Range<int> >());
  2773. }
  2774. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  2775. {
  2776. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  2777. getCompositionSelection (hImc, lParam));
  2778. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  2779. compositionInProgress = true;
  2780. }
  2781. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  2782. ImmReleaseContext (hWnd, hImc);
  2783. }
  2784. }
  2785. }
  2786. private:
  2787. //==============================================================================
  2788. Range<int> compositionRange; // The range being modified in the TextInputTarget
  2789. bool compositionInProgress;
  2790. //==============================================================================
  2791. void reset()
  2792. {
  2793. compositionRange = Range<int>::emptyRange (-1);
  2794. compositionInProgress = false;
  2795. }
  2796. String getCompositionString (HIMC hImc, const DWORD type) const
  2797. {
  2798. jassert (hImc != 0);
  2799. const int stringSizeBytes = ImmGetCompositionString (hImc, type, 0, 0);
  2800. if (stringSizeBytes > 0)
  2801. {
  2802. HeapBlock<TCHAR> buffer;
  2803. buffer.calloc (stringSizeBytes / sizeof (TCHAR) + 1);
  2804. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  2805. return String (buffer.get());
  2806. }
  2807. return {};
  2808. }
  2809. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  2810. {
  2811. jassert (hImc != 0);
  2812. if ((lParam & CS_NOMOVECARET) != 0)
  2813. return compositionRange.getStart();
  2814. if ((lParam & GCS_CURSORPOS) != 0)
  2815. {
  2816. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, 0, 0);
  2817. return compositionRange.getStart() + jmax (0, localCaretPos);
  2818. }
  2819. return compositionRange.getStart() + currentIMEString.length();
  2820. }
  2821. // Get selected/highlighted range while doing composition:
  2822. // returned range is relative to beginning of TextInputTarget, not composition string
  2823. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  2824. {
  2825. jassert (hImc != 0);
  2826. int selectionStart = 0;
  2827. int selectionEnd = 0;
  2828. if ((lParam & GCS_COMPATTR) != 0)
  2829. {
  2830. // Get size of attributes array:
  2831. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, 0, 0);
  2832. if (attributeSizeBytes > 0)
  2833. {
  2834. // Get attributes (8 bit flag per character):
  2835. HeapBlock<char> attributes ((size_t) attributeSizeBytes);
  2836. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  2837. selectionStart = 0;
  2838. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  2839. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  2840. break;
  2841. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  2842. if (attributes [selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  2843. break;
  2844. }
  2845. }
  2846. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  2847. }
  2848. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  2849. {
  2850. if (compositionInProgress)
  2851. target->setHighlightedRegion (compositionRange);
  2852. target->insertTextAtCaret (newContent);
  2853. compositionRange.setLength (newContent.length());
  2854. if (newSelection.getStart() < 0)
  2855. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  2856. target->setHighlightedRegion (newSelection);
  2857. }
  2858. Array<Range<int>> getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  2859. {
  2860. Array<Range<int>> result;
  2861. if (hImc != 0 && (lParam & GCS_COMPCLAUSE) != 0)
  2862. {
  2863. auto clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, 0, 0);
  2864. if (clauseDataSizeBytes > 0)
  2865. {
  2866. const size_t numItems = clauseDataSizeBytes / sizeof (uint32);
  2867. HeapBlock<uint32> clauseData (numItems);
  2868. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  2869. for (size_t i = 0; i + 1 < numItems; ++i)
  2870. result.add (Range<int> ((int) clauseData [i], (int) clauseData [i + 1]) + compositionRange.getStart());
  2871. }
  2872. }
  2873. return result;
  2874. }
  2875. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  2876. {
  2877. if (auto* targetComp = dynamic_cast<Component*> (target))
  2878. {
  2879. auto area = peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle());
  2880. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  2881. ImmSetCandidateWindow (hImc, &pos);
  2882. }
  2883. }
  2884. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  2885. };
  2886. void timerCallback() override
  2887. {
  2888. handlePositionChanged();
  2889. stopTimer();
  2890. }
  2891. IMEHandler imeHandler;
  2892. //==============================================================================
  2893. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  2894. };
  2895. ModifierKeys HWNDComponentPeer::currentModifiers;
  2896. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  2897. MultiTouchMapper<DWORD> HWNDComponentPeer::currentTouches;
  2898. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  2899. {
  2900. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  2901. }
  2902. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  2903. {
  2904. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  2905. (HWND) parentHWND, true);
  2906. }
  2907. juce_ImplementSingleton_SingleThreaded (HWNDComponentPeer::WindowClassHolder)
  2908. //==============================================================================
  2909. void ModifierKeys::updateCurrentModifiers() noexcept
  2910. {
  2911. currentModifiers = HWNDComponentPeer::currentModifiers;
  2912. }
  2913. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2914. {
  2915. HWNDComponentPeer::updateKeyModifiers();
  2916. int mouseMods = 0;
  2917. if (HWNDComponentPeer::isKeyDown (VK_LBUTTON)) mouseMods |= ModifierKeys::leftButtonModifier;
  2918. if (HWNDComponentPeer::isKeyDown (VK_RBUTTON)) mouseMods |= ModifierKeys::rightButtonModifier;
  2919. if (HWNDComponentPeer::isKeyDown (VK_MBUTTON)) mouseMods |= ModifierKeys::middleButtonModifier;
  2920. HWNDComponentPeer::currentModifiers
  2921. = HWNDComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2922. return HWNDComponentPeer::currentModifiers;
  2923. }
  2924. //==============================================================================
  2925. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  2926. {
  2927. auto k = (SHORT) keyCode;
  2928. if ((keyCode & extendedKeyModifier) == 0)
  2929. {
  2930. if (k >= (SHORT) 'a' && k <= (SHORT) 'z')
  2931. k += (SHORT) 'A' - (SHORT) 'a';
  2932. // Only translate if extendedKeyModifier flag is not set
  2933. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  2934. (SHORT) '+', VK_OEM_PLUS,
  2935. (SHORT) '-', VK_OEM_MINUS,
  2936. (SHORT) '.', VK_OEM_PERIOD,
  2937. (SHORT) ';', VK_OEM_1,
  2938. (SHORT) ':', VK_OEM_1,
  2939. (SHORT) '/', VK_OEM_2,
  2940. (SHORT) '?', VK_OEM_2,
  2941. (SHORT) '[', VK_OEM_4,
  2942. (SHORT) ']', VK_OEM_6 };
  2943. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  2944. if (k == translatedValues [i])
  2945. k = translatedValues [i + 1];
  2946. }
  2947. return HWNDComponentPeer::isKeyDown (k);
  2948. }
  2949. // (This internal function is used by the plugin client module)
  2950. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  2951. //==============================================================================
  2952. bool JUCE_CALLTYPE Process::isForegroundProcess()
  2953. {
  2954. if (auto fg = GetForegroundWindow())
  2955. {
  2956. DWORD processID = 0;
  2957. GetWindowThreadProcessId (fg, &processID);
  2958. return processID == GetCurrentProcessId();
  2959. }
  2960. return true;
  2961. }
  2962. // N/A on Windows as far as I know.
  2963. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2964. void JUCE_CALLTYPE Process::hide() {}
  2965. //==============================================================================
  2966. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  2967. {
  2968. if (IsWindowVisible (hwnd))
  2969. {
  2970. DWORD processID = 0;
  2971. GetWindowThreadProcessId (hwnd, &processID);
  2972. if (processID == GetCurrentProcessId())
  2973. {
  2974. WINDOWINFO info;
  2975. if (GetWindowInfo (hwnd, &info)
  2976. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  2977. {
  2978. *reinterpret_cast<bool*> (lParam) = true;
  2979. return FALSE;
  2980. }
  2981. }
  2982. }
  2983. return TRUE;
  2984. }
  2985. bool juce_areThereAnyAlwaysOnTopWindows()
  2986. {
  2987. bool anyAlwaysOnTopFound = false;
  2988. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  2989. return anyAlwaysOnTopFound;
  2990. }
  2991. //==============================================================================
  2992. class WindowsMessageBox : public AsyncUpdater
  2993. {
  2994. public:
  2995. WindowsMessageBox (AlertWindow::AlertIconType iconType,
  2996. const String& boxTitle, const String& m,
  2997. Component* associatedComponent, UINT extraFlags,
  2998. ModalComponentManager::Callback* cb, const bool runAsync)
  2999. : flags (extraFlags | getMessageBoxFlags (iconType)),
  3000. owner (getWindowForMessageBox (associatedComponent)),
  3001. title (boxTitle), message (m), callback (cb)
  3002. {
  3003. if (runAsync)
  3004. triggerAsyncUpdate();
  3005. }
  3006. int getResult() const
  3007. {
  3008. const int r = MessageBox (owner, message.toWideCharPointer(), title.toWideCharPointer(), flags);
  3009. return (r == IDYES || r == IDOK) ? 1 : (r == IDNO && (flags & 1) != 0 ? 2 : 0);
  3010. }
  3011. void handleAsyncUpdate() override
  3012. {
  3013. const int result = getResult();
  3014. if (callback != nullptr)
  3015. callback->modalStateFinished (result);
  3016. delete this;
  3017. }
  3018. private:
  3019. UINT flags;
  3020. HWND owner;
  3021. String title, message;
  3022. ScopedPointer<ModalComponentManager::Callback> callback;
  3023. static UINT getMessageBoxFlags (AlertWindow::AlertIconType iconType) noexcept
  3024. {
  3025. UINT flags = MB_TASKMODAL | MB_SETFOREGROUND;
  3026. switch (iconType)
  3027. {
  3028. case AlertWindow::QuestionIcon: flags |= MB_ICONQUESTION; break;
  3029. case AlertWindow::WarningIcon: flags |= MB_ICONWARNING; break;
  3030. case AlertWindow::InfoIcon: flags |= MB_ICONINFORMATION; break;
  3031. default: break;
  3032. }
  3033. return flags;
  3034. }
  3035. static HWND getWindowForMessageBox (Component* associatedComponent)
  3036. {
  3037. return associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : 0;
  3038. }
  3039. };
  3040. #if JUCE_MODAL_LOOPS_PERMITTED
  3041. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  3042. const String& title, const String& message,
  3043. Component* associatedComponent)
  3044. {
  3045. WindowsMessageBox box (iconType, title, message, associatedComponent, MB_OK, 0, false);
  3046. (void) box.getResult();
  3047. }
  3048. #endif
  3049. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  3050. const String& title, const String& message,
  3051. Component* associatedComponent,
  3052. ModalComponentManager::Callback* callback)
  3053. {
  3054. new WindowsMessageBox (iconType, title, message, associatedComponent, MB_OK, callback, true);
  3055. }
  3056. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  3057. const String& title, const String& message,
  3058. Component* associatedComponent,
  3059. ModalComponentManager::Callback* callback)
  3060. {
  3061. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3062. MB_OKCANCEL, callback, callback != nullptr));
  3063. if (callback == nullptr)
  3064. return mb->getResult() != 0;
  3065. mb.release();
  3066. return false;
  3067. }
  3068. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  3069. const String& title, const String& message,
  3070. Component* associatedComponent,
  3071. ModalComponentManager::Callback* callback)
  3072. {
  3073. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3074. MB_YESNOCANCEL, callback, callback != nullptr));
  3075. if (callback == nullptr)
  3076. return mb->getResult();
  3077. mb.release();
  3078. return 0;
  3079. }
  3080. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  3081. const String& title, const String& message,
  3082. Component* associatedComponent,
  3083. ModalComponentManager::Callback* callback)
  3084. {
  3085. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3086. MB_YESNO, callback, callback != nullptr));
  3087. if (callback == nullptr)
  3088. return mb->getResult();
  3089. mb.release();
  3090. return 0;
  3091. }
  3092. //==============================================================================
  3093. bool MouseInputSource::SourceList::addSource()
  3094. {
  3095. auto numSources = sources.size();
  3096. if (numSources == 0 || canUseMultiTouch())
  3097. {
  3098. addSource (numSources, numSources == 0 ? MouseInputSource::InputSourceType::mouse
  3099. : MouseInputSource::InputSourceType::touch);
  3100. return true;
  3101. }
  3102. return false;
  3103. }
  3104. bool MouseInputSource::SourceList::canUseTouch()
  3105. {
  3106. return canUseMultiTouch();
  3107. }
  3108. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3109. {
  3110. POINT mousePos;
  3111. GetCursorPos (&mousePos);
  3112. return { (float) mousePos.x, (float) mousePos.y };
  3113. }
  3114. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3115. {
  3116. SetCursorPos (roundToInt (newPosition.x),
  3117. roundToInt (newPosition.y));
  3118. }
  3119. //==============================================================================
  3120. class ScreenSaverDefeater : public Timer
  3121. {
  3122. public:
  3123. ScreenSaverDefeater()
  3124. {
  3125. startTimer (10000);
  3126. timerCallback();
  3127. }
  3128. void timerCallback() override
  3129. {
  3130. if (Process::isForegroundProcess())
  3131. {
  3132. INPUT input = { 0 };
  3133. input.type = INPUT_MOUSE;
  3134. input.mi.mouseData = MOUSEEVENTF_MOVE;
  3135. SendInput (1, &input, sizeof (INPUT));
  3136. }
  3137. }
  3138. };
  3139. static ScopedPointer<ScreenSaverDefeater> screenSaverDefeater;
  3140. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3141. {
  3142. if (isEnabled)
  3143. screenSaverDefeater = nullptr;
  3144. else if (screenSaverDefeater == nullptr)
  3145. screenSaverDefeater = new ScreenSaverDefeater();
  3146. }
  3147. bool Desktop::isScreenSaverEnabled()
  3148. {
  3149. return screenSaverDefeater == nullptr;
  3150. }
  3151. //==============================================================================
  3152. void LookAndFeel::playAlertSound()
  3153. {
  3154. MessageBeep (MB_OK);
  3155. }
  3156. //==============================================================================
  3157. void SystemClipboard::copyTextToClipboard (const String& text)
  3158. {
  3159. if (OpenClipboard (0) != 0)
  3160. {
  3161. if (EmptyClipboard() != 0)
  3162. {
  3163. auto bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  3164. if (bytesNeeded > 0)
  3165. {
  3166. if (auto bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  3167. {
  3168. if (auto* data = static_cast<WCHAR*> (GlobalLock (bufH)))
  3169. {
  3170. text.copyToUTF16 (data, bytesNeeded);
  3171. GlobalUnlock (bufH);
  3172. SetClipboardData (CF_UNICODETEXT, bufH);
  3173. }
  3174. }
  3175. }
  3176. }
  3177. CloseClipboard();
  3178. }
  3179. }
  3180. String SystemClipboard::getTextFromClipboard()
  3181. {
  3182. String result;
  3183. if (OpenClipboard (0) != 0)
  3184. {
  3185. if (auto bufH = GetClipboardData (CF_UNICODETEXT))
  3186. {
  3187. if (auto* data = (const WCHAR*) GlobalLock (bufH))
  3188. {
  3189. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  3190. GlobalUnlock (bufH);
  3191. }
  3192. }
  3193. CloseClipboard();
  3194. }
  3195. return result;
  3196. }
  3197. //==============================================================================
  3198. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  3199. {
  3200. if (auto* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComp))
  3201. tlw->setUsingNativeTitleBar (! enableOrDisable);
  3202. if (enableOrDisable)
  3203. kioskModeComp->setBounds (getDisplays().getMainDisplay().totalArea);
  3204. }
  3205. void Desktop::allowedOrientationsChanged() {}
  3206. //==============================================================================
  3207. struct MonitorInfo
  3208. {
  3209. MonitorInfo (Rectangle<int> rect, bool main, double d) noexcept
  3210. : bounds (rect), dpi (d), isMain (main) {}
  3211. Rectangle<int> bounds;
  3212. double dpi;
  3213. bool isMain;
  3214. };
  3215. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT r, LPARAM userInfo)
  3216. {
  3217. MONITORINFO info = { 0 };
  3218. info.cbSize = sizeof (info);
  3219. GetMonitorInfo (hm, &info);
  3220. const bool isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  3221. double dpi = 0;
  3222. if (getDPIForMonitor != nullptr)
  3223. {
  3224. UINT dpiX = 0, dpiY = 0;
  3225. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  3226. dpi = (dpiX + dpiY) / 2.0;
  3227. }
  3228. ((Array<MonitorInfo>*) userInfo)->add (MonitorInfo (rectangleFromRECT (*r), isMain, dpi));
  3229. return TRUE;
  3230. }
  3231. void Desktop::Displays::findDisplays (float masterScale)
  3232. {
  3233. setDPIAwareness();
  3234. Array<MonitorInfo> monitors;
  3235. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitors);
  3236. const double globalDPI = getGlobalDPI();
  3237. if (monitors.size() == 0)
  3238. monitors.add (MonitorInfo (rectangleFromRECT (getWindowRect (GetDesktopWindow())), true, globalDPI));
  3239. // make sure the first in the list is the main monitor
  3240. for (int i = 1; i < monitors.size(); ++i)
  3241. if (monitors.getReference(i).isMain)
  3242. monitors.swap (i, 0);
  3243. RECT workArea;
  3244. SystemParametersInfo (SPI_GETWORKAREA, 0, &workArea, 0);
  3245. for (int i = 0; i < monitors.size(); ++i)
  3246. {
  3247. Display d;
  3248. d.userArea = d.totalArea = monitors.getReference(i).bounds / masterScale;
  3249. d.isMain = monitors.getReference(i).isMain;
  3250. d.dpi = monitors.getReference(i).dpi;
  3251. if (d.dpi == 0)
  3252. {
  3253. d.scale = masterScale;
  3254. d.dpi = globalDPI;
  3255. }
  3256. else
  3257. {
  3258. d.scale = d.dpi / 96.0;
  3259. }
  3260. if (d.isMain)
  3261. d.userArea = d.userArea.getIntersection (rectangleFromRECT (workArea) / masterScale);
  3262. displays.add (d);
  3263. }
  3264. }
  3265. //==============================================================================
  3266. static HICON extractFileHICON (const File& file)
  3267. {
  3268. WORD iconNum = 0;
  3269. WCHAR name [MAX_PATH * 2];
  3270. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  3271. return ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  3272. name, &iconNum);
  3273. }
  3274. Image juce_createIconForFile (const File& file)
  3275. {
  3276. Image image;
  3277. if (auto icon = extractFileHICON (file))
  3278. {
  3279. image = IconConverters::createImageFromHICON (icon);
  3280. DestroyIcon (icon);
  3281. }
  3282. return image;
  3283. }
  3284. //==============================================================================
  3285. void* CustomMouseCursorInfo::create() const
  3286. {
  3287. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  3288. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  3289. Image im (image);
  3290. int hotspotX = hotspot.x;
  3291. int hotspotY = hotspot.y;
  3292. if (im.getWidth() > maxW || im.getHeight() > maxH)
  3293. {
  3294. im = im.rescaled (maxW, maxH);
  3295. hotspotX = (hotspotX * maxW) / image.getWidth();
  3296. hotspotY = (hotspotY * maxH) / image.getHeight();
  3297. }
  3298. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  3299. }
  3300. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool isStandard)
  3301. {
  3302. if (cursorHandle != nullptr && ! isStandard)
  3303. DestroyCursor ((HCURSOR) cursorHandle);
  3304. }
  3305. enum
  3306. {
  3307. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  3308. };
  3309. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  3310. {
  3311. LPCTSTR cursorName = IDC_ARROW;
  3312. switch (type)
  3313. {
  3314. case NormalCursor:
  3315. case ParentCursor: break;
  3316. case NoCursor: return (void*) hiddenMouseCursorHandle;
  3317. case WaitCursor: cursorName = IDC_WAIT; break;
  3318. case IBeamCursor: cursorName = IDC_IBEAM; break;
  3319. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  3320. case CrosshairCursor: cursorName = IDC_CROSS; break;
  3321. case LeftRightResizeCursor:
  3322. case LeftEdgeResizeCursor:
  3323. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  3324. case UpDownResizeCursor:
  3325. case TopEdgeResizeCursor:
  3326. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  3327. case TopLeftCornerResizeCursor:
  3328. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  3329. case TopRightCornerResizeCursor:
  3330. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  3331. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  3332. case DraggingHandCursor:
  3333. {
  3334. static void* dragHandCursor = nullptr;
  3335. if (dragHandCursor == nullptr)
  3336. {
  3337. static const unsigned char dragHandData[] =
  3338. { 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,
  3339. 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,
  3340. 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 };
  3341. dragHandCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7).create();
  3342. }
  3343. return dragHandCursor;
  3344. }
  3345. case CopyingCursor:
  3346. {
  3347. static void* copyCursor = nullptr;
  3348. if (copyCursor == nullptr)
  3349. {
  3350. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3351. 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,
  3352. 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,
  3353. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3354. const int copyCursorSize = 119;
  3355. copyCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
  3356. }
  3357. return copyCursor;
  3358. }
  3359. default:
  3360. jassertfalse; break;
  3361. }
  3362. HCURSOR cursorH = LoadCursor (0, cursorName);
  3363. if (cursorH == 0)
  3364. cursorH = LoadCursor (0, IDC_ARROW);
  3365. return cursorH;
  3366. }
  3367. //==============================================================================
  3368. void MouseCursor::showInWindow (ComponentPeer*) const
  3369. {
  3370. auto c = (HCURSOR) getHandle();
  3371. if (c == 0)
  3372. c = LoadCursor (0, IDC_ARROW);
  3373. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  3374. c = 0;
  3375. SetCursor (c);
  3376. }
  3377. void MouseCursor::showInAllWindows() const
  3378. {
  3379. showInWindow (nullptr);
  3380. }
  3381. } // namespace juce