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.

4129 lines
142KB

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