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.

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