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.

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