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.

4101 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. MultiTouchMapper<DWORD> currentTouches;
  1190. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1191. ModifierKeyProvider* modProvider = nullptr;
  1192. #endif
  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. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  1496. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  1497. PAINTSTRUCT paintStruct;
  1498. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  1499. // message and become re-entrant, but that's OK
  1500. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  1501. // corrupt the image it's using to paint into, so do a check here.
  1502. static bool reentrant = false;
  1503. if (! reentrant)
  1504. {
  1505. const ScopedValueSetter<bool> setter (reentrant, true, false);
  1506. if (dontRepaint)
  1507. component.handleCommandMessage (0); // (this triggers a repaint in the openGL context)
  1508. else
  1509. performPaint (dc, rgn, regionType, paintStruct);
  1510. }
  1511. DeleteObject (rgn);
  1512. EndPaint (hwnd, &paintStruct);
  1513. #if JUCE_MSVC
  1514. _fpreset(); // because some graphics cards can unmask FP exceptions
  1515. #endif
  1516. lastPaintTime = Time::getMillisecondCounter();
  1517. }
  1518. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  1519. {
  1520. int x = paintStruct.rcPaint.left;
  1521. int y = paintStruct.rcPaint.top;
  1522. int w = paintStruct.rcPaint.right - x;
  1523. int h = paintStruct.rcPaint.bottom - y;
  1524. const bool transparent = isUsingUpdateLayeredWindow();
  1525. if (transparent)
  1526. {
  1527. // it's not possible to have a transparent window with a title bar at the moment!
  1528. jassert (! hasTitleBar());
  1529. auto r = getWindowRect (hwnd);
  1530. x = y = 0;
  1531. w = r.right - r.left;
  1532. h = r.bottom - r.top;
  1533. }
  1534. if (w > 0 && h > 0)
  1535. {
  1536. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  1537. RectangleList<int> contextClip;
  1538. const Rectangle<int> clipBounds (w, h);
  1539. bool needToPaintAll = true;
  1540. if (regionType == COMPLEXREGION && ! transparent)
  1541. {
  1542. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  1543. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  1544. DeleteObject (clipRgn);
  1545. char rgnData[8192];
  1546. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  1547. if (res > 0 && res <= sizeof (rgnData))
  1548. {
  1549. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  1550. if (hdr->iType == RDH_RECTANGLES
  1551. && hdr->rcBound.right - hdr->rcBound.left >= w
  1552. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  1553. {
  1554. needToPaintAll = false;
  1555. auto rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  1556. for (int i = (int) ((RGNDATA*) rgnData)->rdh.nCount; --i >= 0;)
  1557. {
  1558. if (rects->right <= x + w && rects->bottom <= y + h)
  1559. {
  1560. const int cx = jmax (x, (int) rects->left);
  1561. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  1562. rects->right - cx, rects->bottom - rects->top)
  1563. .getIntersection (clipBounds));
  1564. }
  1565. else
  1566. {
  1567. needToPaintAll = true;
  1568. break;
  1569. }
  1570. ++rects;
  1571. }
  1572. }
  1573. }
  1574. }
  1575. if (needToPaintAll)
  1576. {
  1577. contextClip.clear();
  1578. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  1579. }
  1580. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  1581. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  1582. if (! contextClip.isEmpty())
  1583. {
  1584. if (transparent)
  1585. for (auto& i : contextClip)
  1586. offscreenImage.clear (i);
  1587. {
  1588. ScopedPointer<LowLevelGraphicsContext> context (component.getLookAndFeel()
  1589. .createGraphicsContext (offscreenImage, Point<int> (-x, -y), contextClip));
  1590. handlePaint (*context);
  1591. }
  1592. static_cast<WindowsBitmapImage*> (offscreenImage.getPixelData())
  1593. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  1594. }
  1595. if (childClipInfo.savedDC != 0)
  1596. RestoreDC (dc, childClipInfo.savedDC);
  1597. }
  1598. }
  1599. //==============================================================================
  1600. void doMouseEvent (Point<float> position, float pressure, float orientation = 0.0f, ModifierKeys mods = currentModifiers)
  1601. {
  1602. handleMouseEvent (MouseInputSource::InputSourceType::mouse, position, mods, pressure, orientation, getMouseEventTime());
  1603. }
  1604. StringArray getAvailableRenderingEngines() override
  1605. {
  1606. StringArray s ("Software Renderer");
  1607. #if JUCE_DIRECT2D
  1608. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  1609. s.add ("Direct2D");
  1610. #endif
  1611. return s;
  1612. }
  1613. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  1614. #if JUCE_DIRECT2D
  1615. void updateDirect2DContext()
  1616. {
  1617. if (currentRenderingEngine != direct2DRenderingEngine)
  1618. direct2DContext = 0;
  1619. else if (direct2DContext == 0)
  1620. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  1621. }
  1622. #endif
  1623. void setCurrentRenderingEngine (int index) override
  1624. {
  1625. ignoreUnused (index);
  1626. #if JUCE_DIRECT2D
  1627. if (getAvailableRenderingEngines().size() > 1)
  1628. {
  1629. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  1630. updateDirect2DContext();
  1631. repaint (component.getLocalBounds());
  1632. }
  1633. #endif
  1634. }
  1635. static int getMinTimeBetweenMouseMoves()
  1636. {
  1637. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  1638. return 0;
  1639. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  1640. }
  1641. bool isTouchEvent() noexcept
  1642. {
  1643. if (registerTouchWindow == nullptr)
  1644. return false;
  1645. // Relevant info about touch/pen detection flags:
  1646. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx
  1647. // http://www.petertissen.de/?p=4
  1648. return (GetMessageExtraInfo() & 0xFFFFFF80 /*SIGNATURE_MASK*/) == 0xFF515780 /*MI_WP_SIGNATURE*/;
  1649. }
  1650. static bool areOtherTouchSourcesActive()
  1651. {
  1652. for (auto& ms : Desktop::getInstance().getMouseSources())
  1653. if (ms.isDragging() && (ms.getType() == MouseInputSource::InputSourceType::touch
  1654. || ms.getType() == MouseInputSource::InputSourceType::pen))
  1655. return true;
  1656. return false;
  1657. }
  1658. void doMouseMove (Point<float> position, bool isMouseDownEvent)
  1659. {
  1660. ModifierKeys modsToSend (currentModifiers);
  1661. // this will be handled by WM_TOUCH
  1662. if (isTouchEvent() || areOtherTouchSourcesActive())
  1663. return;
  1664. if (! isMouseOver)
  1665. {
  1666. isMouseOver = true;
  1667. // This avoids a rare stuck-button problem when focus is lost unexpectedly, but must
  1668. // not be called as part of a move, in case it's actually a mouse-drag from another
  1669. // app which ends up here when we get focus before the mouse is released..
  1670. if (isMouseDownEvent)
  1671. ModifierKeys::getCurrentModifiersRealtime();
  1672. updateKeyModifiers();
  1673. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1674. if (modProvider != nullptr)
  1675. currentModifiers = currentModifiers.withFlags (modProvider->getWin32Modifiers());
  1676. #endif
  1677. TRACKMOUSEEVENT tme;
  1678. tme.cbSize = sizeof (tme);
  1679. tme.dwFlags = TME_LEAVE;
  1680. tme.hwndTrack = hwnd;
  1681. tme.dwHoverTime = 0;
  1682. if (! TrackMouseEvent (&tme))
  1683. jassertfalse;
  1684. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1685. }
  1686. else if (! isDragging)
  1687. {
  1688. if (! contains (position.roundToInt(), false))
  1689. return;
  1690. }
  1691. static uint32 lastMouseTime = 0;
  1692. static int minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  1693. const uint32 now = Time::getMillisecondCounter();
  1694. if (! Desktop::getInstance().getMainMouseSource().isDragging())
  1695. modsToSend = modsToSend.withoutMouseButtons();
  1696. if (now >= lastMouseTime + minTimeBetweenMouses)
  1697. {
  1698. lastMouseTime = now;
  1699. doMouseEvent (position, MouseInputSource::invalidPressure,
  1700. MouseInputSource::invalidOrientation, modsToSend);
  1701. }
  1702. }
  1703. void doMouseDown (Point<float> position, const WPARAM wParam)
  1704. {
  1705. // this will be handled by WM_TOUCH
  1706. if (isTouchEvent() || areOtherTouchSourcesActive())
  1707. return;
  1708. if (GetCapture() != hwnd)
  1709. SetCapture (hwnd);
  1710. doMouseMove (position, true);
  1711. if (isValidPeer (this))
  1712. {
  1713. updateModifiersFromWParam (wParam);
  1714. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1715. if (modProvider != nullptr)
  1716. currentModifiers = currentModifiers.withFlags (modProvider->getWin32Modifiers());
  1717. #endif
  1718. isDragging = true;
  1719. doMouseEvent (position, MouseInputSource::invalidPressure);
  1720. }
  1721. }
  1722. void doMouseUp (Point<float> position, const WPARAM wParam)
  1723. {
  1724. // this will be handled by WM_TOUCH
  1725. if (isTouchEvent() || areOtherTouchSourcesActive())
  1726. return;
  1727. updateModifiersFromWParam (wParam);
  1728. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  1729. if (modProvider != nullptr)
  1730. currentModifiers = currentModifiers.withFlags (modProvider->getWin32Modifiers());
  1731. #endif
  1732. const bool wasDragging = isDragging;
  1733. isDragging = false;
  1734. // release the mouse capture if the user has released all buttons
  1735. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  1736. ReleaseCapture();
  1737. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  1738. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  1739. if (wasDragging)
  1740. doMouseEvent (position, MouseInputSource::invalidPressure);
  1741. }
  1742. void doCaptureChanged()
  1743. {
  1744. if (constrainerIsResizing)
  1745. {
  1746. if (constrainer != nullptr)
  1747. constrainer->resizeEnd();
  1748. constrainerIsResizing = false;
  1749. }
  1750. if (isDragging)
  1751. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  1752. }
  1753. void doMouseExit()
  1754. {
  1755. isMouseOver = false;
  1756. if (! areOtherTouchSourcesActive())
  1757. doMouseEvent (getCurrentMousePos(), MouseInputSource::invalidPressure);
  1758. }
  1759. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  1760. {
  1761. auto globalPos = getCurrentMousePosGlobal().roundToInt();
  1762. // Because Windows stupidly sends all wheel events to the window with the keyboard
  1763. // focus, we have to redirect them here according to the mouse pos..
  1764. POINT p = { globalPos.x, globalPos.y };
  1765. auto* peer = getOwnerOfWindow (WindowFromPoint (p));
  1766. if (peer == nullptr)
  1767. peer = this;
  1768. localPos = peer->globalToLocal (globalPos.toFloat());
  1769. return peer;
  1770. }
  1771. static MouseInputSource::InputSourceType getPointerType (WPARAM wParam)
  1772. {
  1773. if (getPointerTypeFunction != nullptr)
  1774. {
  1775. POINTER_INPUT_TYPE pointerType;
  1776. if (getPointerTypeFunction (GET_POINTERID_WPARAM (wParam), &pointerType))
  1777. {
  1778. if (pointerType == 2)
  1779. return MouseInputSource::InputSourceType::touch;
  1780. if (pointerType == 3)
  1781. return MouseInputSource::InputSourceType::pen;
  1782. }
  1783. }
  1784. return MouseInputSource::InputSourceType::mouse;
  1785. }
  1786. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  1787. {
  1788. updateKeyModifiers();
  1789. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  1790. MouseWheelDetails wheel;
  1791. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  1792. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  1793. wheel.isReversed = false;
  1794. wheel.isSmooth = false;
  1795. wheel.isInertial = false;
  1796. Point<float> localPos;
  1797. if (auto* peer = findPeerUnderMouse (localPos))
  1798. peer->handleMouseWheel (getPointerType (wParam), localPos, getMouseEventTime(), wheel);
  1799. }
  1800. bool doGestureEvent (LPARAM lParam)
  1801. {
  1802. GESTUREINFO gi;
  1803. zerostruct (gi);
  1804. gi.cbSize = sizeof (gi);
  1805. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  1806. {
  1807. updateKeyModifiers();
  1808. Point<float> localPos;
  1809. if (auto* peer = findPeerUnderMouse (localPos))
  1810. {
  1811. switch (gi.dwID)
  1812. {
  1813. case 3: /*GID_ZOOM*/
  1814. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  1815. peer->handleMagnifyGesture (MouseInputSource::InputSourceType::touch, localPos, getMouseEventTime(),
  1816. (float) (gi.ullArguments / (double) lastMagnifySize));
  1817. lastMagnifySize = gi.ullArguments;
  1818. return true;
  1819. case 4: /*GID_PAN*/
  1820. case 5: /*GID_ROTATE*/
  1821. case 6: /*GID_TWOFINGERTAP*/
  1822. case 7: /*GID_PRESSANDTAP*/
  1823. default:
  1824. break;
  1825. }
  1826. }
  1827. }
  1828. return false;
  1829. }
  1830. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  1831. {
  1832. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  1833. if (auto* parent = getOwnerOfWindow (GetParent (hwnd)))
  1834. if (parent != this)
  1835. return parent->doTouchEvent (numInputs, eventHandle);
  1836. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  1837. if (getTouchInputInfo (eventHandle, numInputs, inputInfo, sizeof (TOUCHINPUT)))
  1838. {
  1839. for (int i = 0; i < numInputs; ++i)
  1840. {
  1841. auto flags = inputInfo[i].dwFlags;
  1842. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  1843. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  1844. return 0; // abandon method if this window was deleted by the callback
  1845. }
  1846. }
  1847. closeTouchInputHandle (eventHandle);
  1848. return 0;
  1849. }
  1850. bool handleTouchInput (const TOUCHINPUT& touch, const bool isDown, const bool isUp,
  1851. const float touchPressure = MouseInputSource::invalidPressure,
  1852. const float orientation = 0.0f)
  1853. {
  1854. bool isCancel = false;
  1855. const int touchIndex = currentTouches.getIndexOfTouch (touch.dwID);
  1856. auto time = getMouseEventTime();
  1857. auto pos = globalToLocal (Point<float> (touch.x / 100.0f,
  1858. touch.y / 100.0f));
  1859. const float pressure = touchPressure;
  1860. ModifierKeys modsToSend (currentModifiers);
  1861. if (isDown)
  1862. {
  1863. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1864. modsToSend = currentModifiers;
  1865. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  1866. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend.withoutMouseButtons(), pressure, orientation, time, PenDetails(), touchIndex);
  1867. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1868. return false;
  1869. }
  1870. else if (isUp)
  1871. {
  1872. modsToSend = modsToSend.withoutMouseButtons();
  1873. currentTouches.clearTouch (touchIndex);
  1874. if (! currentTouches.areAnyTouchesActive())
  1875. isCancel = true;
  1876. }
  1877. else
  1878. {
  1879. modsToSend = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1880. }
  1881. if (isCancel)
  1882. {
  1883. currentTouches.clear();
  1884. currentModifiers = currentModifiers.withoutMouseButtons();
  1885. }
  1886. handleMouseEvent (MouseInputSource::InputSourceType::touch, pos, modsToSend, pressure, orientation, time, PenDetails(), touchIndex);
  1887. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1888. return false;
  1889. if (isUp || isCancel)
  1890. {
  1891. handleMouseEvent (MouseInputSource::InputSourceType::touch, Point<float> (-10.0f, -10.0f), currentModifiers, pressure, orientation, time, PenDetails(), touchIndex);
  1892. if (! isValidPeer (this))
  1893. return false;
  1894. }
  1895. return true;
  1896. }
  1897. bool handlePointerInput (WPARAM wParam, LPARAM lParam, const bool isDown, const bool isUp)
  1898. {
  1899. if (! canUsePointerAPI)
  1900. return false;
  1901. auto pointerType = getPointerType (wParam);
  1902. if (pointerType == MouseInputSource::InputSourceType::touch)
  1903. {
  1904. POINTER_TOUCH_INFO touchInfo;
  1905. if (! getPointerTouchInfo (GET_POINTERID_WPARAM (wParam), &touchInfo))
  1906. return false;
  1907. const auto pressure = touchInfo.touchMask & TOUCH_MASK_PRESSURE ? touchInfo.pressure
  1908. : MouseInputSource::invalidPressure;
  1909. const auto orientation = touchInfo.touchMask & TOUCH_MASK_ORIENTATION ? degreesToRadians (static_cast<float> (touchInfo.orientation))
  1910. : MouseInputSource::invalidOrientation;
  1911. if (! handleTouchInput (emulateTouchEventFromPointer (lParam, wParam),
  1912. isDown, isUp, pressure, orientation))
  1913. return false;
  1914. }
  1915. else if (pointerType == MouseInputSource::InputSourceType::pen)
  1916. {
  1917. POINTER_PEN_INFO penInfo;
  1918. if (! getPointerPenInfo (GET_POINTERID_WPARAM (wParam), &penInfo))
  1919. return false;
  1920. const auto pressure = (penInfo.penMask & PEN_MASK_PRESSURE) ? penInfo.pressure / 1024.0f : MouseInputSource::invalidPressure;
  1921. if (! handlePenInput (penInfo, globalToLocal (Point<float> (static_cast<float> (GET_X_LPARAM(lParam)),
  1922. static_cast<float> (GET_Y_LPARAM(lParam)))),
  1923. pressure, isDown, isUp))
  1924. return false;
  1925. }
  1926. else
  1927. {
  1928. return false;
  1929. }
  1930. return true;
  1931. }
  1932. TOUCHINPUT emulateTouchEventFromPointer (LPARAM lParam, WPARAM wParam)
  1933. {
  1934. TOUCHINPUT touchInput;
  1935. touchInput.dwID = GET_POINTERID_WPARAM (wParam);
  1936. touchInput.x = GET_X_LPARAM (lParam) * 100;
  1937. touchInput.y = GET_Y_LPARAM (lParam) * 100;
  1938. return touchInput;
  1939. }
  1940. bool handlePenInput (POINTER_PEN_INFO penInfo, Point<float> pos, const float pressure, bool isDown, bool isUp)
  1941. {
  1942. const auto time = getMouseEventTime();
  1943. ModifierKeys modsToSend (currentModifiers);
  1944. PenDetails penDetails;
  1945. penDetails.rotation = (penInfo.penMask & PEN_MASK_ROTATION) ? degreesToRadians (static_cast<float> (penInfo.rotation)) : MouseInputSource::invalidRotation;
  1946. penDetails.tiltX = (penInfo.penMask & PEN_MASK_TILT_X) ? penInfo.tiltX / 90.0f : MouseInputSource::invalidTiltX;
  1947. penDetails.tiltY = (penInfo.penMask & PEN_MASK_TILT_Y) ? penInfo.tiltY / 90.0f : MouseInputSource::invalidTiltY;
  1948. auto pInfoFlags = penInfo.pointerInfo.pointerFlags;
  1949. if ((pInfoFlags & POINTER_FLAG_FIRSTBUTTON) != 0)
  1950. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1951. else if ((pInfoFlags & POINTER_FLAG_SECONDBUTTON) != 0)
  1952. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::rightButtonModifier);
  1953. if (isDown)
  1954. {
  1955. modsToSend = currentModifiers;
  1956. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  1957. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend.withoutMouseButtons(),
  1958. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  1959. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1960. return false;
  1961. }
  1962. else if (isUp || ! (pInfoFlags & POINTER_FLAG_INCONTACT))
  1963. {
  1964. modsToSend = modsToSend.withoutMouseButtons();
  1965. }
  1966. handleMouseEvent (MouseInputSource::InputSourceType::pen, pos, modsToSend, pressure,
  1967. MouseInputSource::invalidOrientation, time, penDetails);
  1968. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1969. return false;
  1970. if (isUp)
  1971. {
  1972. handleMouseEvent (MouseInputSource::InputSourceType::pen, { -10.0f, -10.0f }, currentModifiers,
  1973. pressure, MouseInputSource::invalidOrientation, time, penDetails);
  1974. if (! isValidPeer (this))
  1975. return false;
  1976. }
  1977. return true;
  1978. }
  1979. //==============================================================================
  1980. void sendModifierKeyChangeIfNeeded()
  1981. {
  1982. if (modifiersAtLastCallback != currentModifiers)
  1983. {
  1984. modifiersAtLastCallback = currentModifiers;
  1985. handleModifierKeysChange();
  1986. }
  1987. }
  1988. bool doKeyUp (const WPARAM key)
  1989. {
  1990. updateKeyModifiers();
  1991. switch (key)
  1992. {
  1993. case VK_SHIFT:
  1994. case VK_CONTROL:
  1995. case VK_MENU:
  1996. case VK_CAPITAL:
  1997. case VK_LWIN:
  1998. case VK_RWIN:
  1999. case VK_APPS:
  2000. case VK_NUMLOCK:
  2001. case VK_SCROLL:
  2002. case VK_LSHIFT:
  2003. case VK_RSHIFT:
  2004. case VK_LCONTROL:
  2005. case VK_LMENU:
  2006. case VK_RCONTROL:
  2007. case VK_RMENU:
  2008. sendModifierKeyChangeIfNeeded();
  2009. }
  2010. return handleKeyUpOrDown (false)
  2011. || Component::getCurrentlyModalComponent() != nullptr;
  2012. }
  2013. bool doKeyDown (const WPARAM key)
  2014. {
  2015. updateKeyModifiers();
  2016. bool used = false;
  2017. switch (key)
  2018. {
  2019. case VK_SHIFT:
  2020. case VK_LSHIFT:
  2021. case VK_RSHIFT:
  2022. case VK_CONTROL:
  2023. case VK_LCONTROL:
  2024. case VK_RCONTROL:
  2025. case VK_MENU:
  2026. case VK_LMENU:
  2027. case VK_RMENU:
  2028. case VK_LWIN:
  2029. case VK_RWIN:
  2030. case VK_CAPITAL:
  2031. case VK_NUMLOCK:
  2032. case VK_SCROLL:
  2033. case VK_APPS:
  2034. sendModifierKeyChangeIfNeeded();
  2035. break;
  2036. case VK_LEFT:
  2037. case VK_RIGHT:
  2038. case VK_UP:
  2039. case VK_DOWN:
  2040. case VK_PRIOR:
  2041. case VK_NEXT:
  2042. case VK_HOME:
  2043. case VK_END:
  2044. case VK_DELETE:
  2045. case VK_INSERT:
  2046. case VK_F1:
  2047. case VK_F2:
  2048. case VK_F3:
  2049. case VK_F4:
  2050. case VK_F5:
  2051. case VK_F6:
  2052. case VK_F7:
  2053. case VK_F8:
  2054. case VK_F9:
  2055. case VK_F10:
  2056. case VK_F11:
  2057. case VK_F12:
  2058. case VK_F13:
  2059. case VK_F14:
  2060. case VK_F15:
  2061. case VK_F16:
  2062. used = handleKeyUpOrDown (true);
  2063. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  2064. break;
  2065. default:
  2066. used = handleKeyUpOrDown (true);
  2067. {
  2068. MSG msg;
  2069. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  2070. {
  2071. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  2072. // manually generate the key-press event that matches this key-down.
  2073. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  2074. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  2075. BYTE keyState[256];
  2076. GetKeyboardState (keyState);
  2077. WCHAR text[16] = { 0 };
  2078. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  2079. text[0] = 0;
  2080. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  2081. }
  2082. }
  2083. break;
  2084. }
  2085. return used || (Component::getCurrentlyModalComponent() != nullptr);
  2086. }
  2087. bool doKeyChar (int key, const LPARAM flags)
  2088. {
  2089. updateKeyModifiers();
  2090. juce_wchar textChar = (juce_wchar) key;
  2091. const int virtualScanCode = (flags >> 16) & 0xff;
  2092. if (key >= '0' && key <= '9')
  2093. {
  2094. switch (virtualScanCode) // check for a numeric keypad scan-code
  2095. {
  2096. case 0x52:
  2097. case 0x4f:
  2098. case 0x50:
  2099. case 0x51:
  2100. case 0x4b:
  2101. case 0x4c:
  2102. case 0x4d:
  2103. case 0x47:
  2104. case 0x48:
  2105. case 0x49:
  2106. key = (key - '0') + KeyPress::numberPad0;
  2107. break;
  2108. default:
  2109. break;
  2110. }
  2111. }
  2112. else
  2113. {
  2114. // convert the scan code to an unmodified character code..
  2115. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  2116. UINT keyChar = MapVirtualKey (virtualKey, 2);
  2117. keyChar = LOWORD (keyChar);
  2118. if (keyChar != 0)
  2119. key = (int) keyChar;
  2120. // avoid sending junk text characters for some control-key combinations
  2121. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  2122. textChar = 0;
  2123. }
  2124. return handleKeyPress (key, textChar);
  2125. }
  2126. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  2127. {
  2128. if (HWND parentH = GetParent (hwnd))
  2129. PostMessage (parentH, message, wParam, lParam);
  2130. }
  2131. bool doAppCommand (const LPARAM lParam)
  2132. {
  2133. int key = 0;
  2134. switch (GET_APPCOMMAND_LPARAM (lParam))
  2135. {
  2136. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  2137. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  2138. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  2139. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  2140. default: break;
  2141. }
  2142. if (key != 0)
  2143. {
  2144. updateKeyModifiers();
  2145. if (hwnd == GetActiveWindow())
  2146. {
  2147. handleKeyPress (key, 0);
  2148. return true;
  2149. }
  2150. }
  2151. return false;
  2152. }
  2153. bool isConstrainedNativeWindow() const
  2154. {
  2155. return constrainer != nullptr
  2156. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  2157. && ! isKioskMode();
  2158. }
  2159. Rectangle<int> getCurrentScaledBounds (float scale) const
  2160. {
  2161. return ScalingHelpers::unscaledScreenPosToScaled (scale, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (scale, component.getBounds())));
  2162. }
  2163. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  2164. {
  2165. if (isConstrainedNativeWindow())
  2166. {
  2167. auto scale = getComponent().getDesktopScaleFactor();
  2168. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, rectangleFromRECT (r));
  2169. auto current = getCurrentScaledBounds (scale);
  2170. constrainer->checkBounds (pos, current,
  2171. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2172. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  2173. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  2174. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  2175. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  2176. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  2177. r.left = pos.getX();
  2178. r.top = pos.getY();
  2179. r.right = pos.getRight();
  2180. r.bottom = pos.getBottom();
  2181. }
  2182. return TRUE;
  2183. }
  2184. LRESULT handlePositionChanging (WINDOWPOS& wp)
  2185. {
  2186. if (isConstrainedNativeWindow())
  2187. {
  2188. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  2189. && ! Component::isMouseButtonDownAnywhere())
  2190. {
  2191. auto scale = getComponent().getDesktopScaleFactor();
  2192. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, Rectangle<int> (wp.x, wp.y, wp.cx, wp.cy));
  2193. auto current = getCurrentScaledBounds (scale);
  2194. constrainer->checkBounds (pos, current,
  2195. Desktop::getInstance().getDisplays().getTotalBounds (true),
  2196. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  2197. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  2198. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  2199. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  2200. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  2201. wp.x = pos.getX();
  2202. wp.y = pos.getY();
  2203. wp.cx = pos.getWidth();
  2204. wp.cy = pos.getHeight();
  2205. }
  2206. }
  2207. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  2208. component.setVisible (true);
  2209. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  2210. component.setVisible (false);
  2211. return 0;
  2212. }
  2213. bool handlePositionChanged()
  2214. {
  2215. auto pos = getCurrentMousePos();
  2216. if (contains (pos.roundToInt(), false))
  2217. {
  2218. if (! areOtherTouchSourcesActive())
  2219. doMouseEvent (pos, MouseInputSource::invalidPressure);
  2220. if (! isValidPeer (this))
  2221. return true;
  2222. }
  2223. handleMovedOrResized();
  2224. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly..
  2225. }
  2226. void handleAppActivation (const WPARAM wParam)
  2227. {
  2228. modifiersAtLastCallback = -1;
  2229. updateKeyModifiers();
  2230. if (isMinimised())
  2231. {
  2232. component.repaint();
  2233. handleMovedOrResized();
  2234. if (! isValidPeer (this))
  2235. return;
  2236. }
  2237. auto* underMouse = component.getComponentAt (component.getMouseXYRelative());
  2238. if (underMouse == nullptr)
  2239. underMouse = &component;
  2240. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  2241. {
  2242. if (LOWORD (wParam) == WA_CLICKACTIVE)
  2243. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  2244. else
  2245. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  2246. }
  2247. else
  2248. {
  2249. handleBroughtToFront();
  2250. }
  2251. }
  2252. void handlePowerBroadcast (WPARAM wParam)
  2253. {
  2254. if (auto* app = JUCEApplicationBase::getInstance())
  2255. {
  2256. switch (wParam)
  2257. {
  2258. case PBT_APMSUSPEND: app->suspended(); break;
  2259. case PBT_APMQUERYSUSPENDFAILED:
  2260. case PBT_APMRESUMECRITICAL:
  2261. case PBT_APMRESUMESUSPEND:
  2262. case PBT_APMRESUMEAUTOMATIC: app->resumed(); break;
  2263. default: break;
  2264. }
  2265. }
  2266. }
  2267. void handleLeftClickInNCArea (WPARAM wParam)
  2268. {
  2269. if (! sendInputAttemptWhenModalMessage())
  2270. {
  2271. switch (wParam)
  2272. {
  2273. case HTBOTTOM:
  2274. case HTBOTTOMLEFT:
  2275. case HTBOTTOMRIGHT:
  2276. case HTGROWBOX:
  2277. case HTLEFT:
  2278. case HTRIGHT:
  2279. case HTTOP:
  2280. case HTTOPLEFT:
  2281. case HTTOPRIGHT:
  2282. if (isConstrainedNativeWindow())
  2283. {
  2284. constrainerIsResizing = true;
  2285. constrainer->resizeStart();
  2286. }
  2287. break;
  2288. default:
  2289. break;
  2290. }
  2291. }
  2292. }
  2293. void initialiseSysMenu (HMENU menu) const
  2294. {
  2295. if (! hasTitleBar())
  2296. {
  2297. if (isFullScreen())
  2298. {
  2299. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  2300. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  2301. }
  2302. else if (! isMinimised())
  2303. {
  2304. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  2305. }
  2306. }
  2307. }
  2308. void doSettingChange()
  2309. {
  2310. auto& desktop = Desktop::getInstance();
  2311. const_cast<Desktop::Displays&> (desktop.getDisplays()).refresh();
  2312. if (fullScreen && ! isMinimised())
  2313. {
  2314. auto& display = desktop.getDisplays().getDisplayContaining (component.getScreenBounds().getCentre());
  2315. setWindowPos (hwnd, display.userArea * display.scale,
  2316. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  2317. }
  2318. }
  2319. void handleDPIChange() // happens when a window moves to a screen with a different DPI.
  2320. {
  2321. }
  2322. //==============================================================================
  2323. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2324. void setModifierKeyProvider (ModifierKeyProvider* provider) override
  2325. {
  2326. modProvider = provider;
  2327. }
  2328. void removeModifierKeyProvider() override
  2329. {
  2330. modProvider = nullptr;
  2331. }
  2332. #endif
  2333. //==============================================================================
  2334. public:
  2335. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2336. {
  2337. if (auto* peer = getOwnerOfWindow (h))
  2338. {
  2339. jassert (isValidPeer (peer));
  2340. return peer->peerWindowProc (h, message, wParam, lParam);
  2341. }
  2342. return DefWindowProcW (h, message, wParam, lParam);
  2343. }
  2344. private:
  2345. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  2346. {
  2347. auto& mm = *MessageManager::getInstance();
  2348. if (mm.currentThreadHasLockedMessageManager())
  2349. return callback (userData);
  2350. return mm.callFunctionOnMessageThread (callback, userData);
  2351. }
  2352. static Point<float> getPointFromLParam (LPARAM lParam) noexcept
  2353. {
  2354. return { static_cast<float> (GET_X_LPARAM (lParam)),
  2355. static_cast<float> (GET_Y_LPARAM (lParam)) };
  2356. }
  2357. static Point<float> getCurrentMousePosGlobal() noexcept
  2358. {
  2359. return getPointFromLParam (GetMessagePos());
  2360. }
  2361. Point<float> getCurrentMousePos() noexcept
  2362. {
  2363. return globalToLocal (getCurrentMousePosGlobal());
  2364. }
  2365. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  2366. {
  2367. switch (message)
  2368. {
  2369. //==============================================================================
  2370. case WM_NCHITTEST:
  2371. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  2372. return HTTRANSPARENT;
  2373. if (! hasTitleBar())
  2374. return HTCLIENT;
  2375. break;
  2376. //==============================================================================
  2377. case WM_PAINT:
  2378. handlePaintMessage();
  2379. return 0;
  2380. case WM_NCPAINT:
  2381. if (wParam != 1) // (1 = a repaint of the entire NC region)
  2382. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  2383. if (hasTitleBar())
  2384. break; // let the DefWindowProc handle drawing the frame.
  2385. return 0;
  2386. case WM_ERASEBKGND:
  2387. case WM_NCCALCSIZE:
  2388. if (hasTitleBar())
  2389. break;
  2390. return 1;
  2391. //==============================================================================
  2392. case WM_POINTERUPDATE:
  2393. if (handlePointerInput (wParam, lParam, false, false))
  2394. return 0;
  2395. break;
  2396. case WM_POINTERDOWN:
  2397. if (handlePointerInput (wParam, lParam, true, false))
  2398. return 0;
  2399. break;
  2400. case WM_POINTERUP:
  2401. if (handlePointerInput (wParam, lParam, false, true))
  2402. return 0;
  2403. break;
  2404. //==============================================================================
  2405. case WM_MOUSEMOVE: doMouseMove (getPointFromLParam (lParam), false); return 0;
  2406. case WM_POINTERLEAVE:
  2407. case WM_MOUSELEAVE: doMouseExit(); return 0;
  2408. case WM_LBUTTONDOWN:
  2409. case WM_MBUTTONDOWN:
  2410. case WM_RBUTTONDOWN: doMouseDown (getPointFromLParam (lParam), wParam); return 0;
  2411. case WM_LBUTTONUP:
  2412. case WM_MBUTTONUP:
  2413. case WM_RBUTTONUP: doMouseUp (getPointFromLParam (lParam), wParam); return 0;
  2414. case WM_POINTERWHEEL:
  2415. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  2416. case WM_POINTERHWHEEL:
  2417. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  2418. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  2419. case WM_NCPOINTERUPDATE:
  2420. case WM_NCMOUSEMOVE:
  2421. if (hasTitleBar())
  2422. break;
  2423. return 0;
  2424. case WM_TOUCH:
  2425. if (getTouchInputInfo != nullptr)
  2426. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  2427. break;
  2428. case 0x119: /* WM_GESTURE */
  2429. if (doGestureEvent (lParam))
  2430. return 0;
  2431. break;
  2432. //==============================================================================
  2433. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  2434. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  2435. case WM_WINDOWPOSCHANGED:
  2436. {
  2437. const WINDOWPOS& wPos = *reinterpret_cast<WINDOWPOS*> (lParam);
  2438. if ((wPos.flags & SWP_NOMOVE) != 0 && (wPos.flags & SWP_NOSIZE) != 0)
  2439. startTimer(100);
  2440. else
  2441. if (handlePositionChanged())
  2442. return 0;
  2443. }
  2444. break;
  2445. //==============================================================================
  2446. case WM_KEYDOWN:
  2447. case WM_SYSKEYDOWN:
  2448. if (doKeyDown (wParam))
  2449. return 0;
  2450. forwardMessageToParent (message, wParam, lParam);
  2451. break;
  2452. case WM_KEYUP:
  2453. case WM_SYSKEYUP:
  2454. if (doKeyUp (wParam))
  2455. return 0;
  2456. forwardMessageToParent (message, wParam, lParam);
  2457. break;
  2458. case WM_CHAR:
  2459. if (doKeyChar ((int) wParam, lParam))
  2460. return 0;
  2461. forwardMessageToParent (message, wParam, lParam);
  2462. break;
  2463. case WM_APPCOMMAND:
  2464. if (doAppCommand (lParam))
  2465. return TRUE;
  2466. break;
  2467. case WM_MENUCHAR: // triggered when alt+something is pressed
  2468. return MNC_CLOSE << 16; // (avoids making the default system beep)
  2469. //==============================================================================
  2470. case WM_SETFOCUS:
  2471. updateKeyModifiers();
  2472. handleFocusGain();
  2473. break;
  2474. case WM_KILLFOCUS:
  2475. if (hasCreatedCaret)
  2476. {
  2477. hasCreatedCaret = false;
  2478. DestroyCaret();
  2479. }
  2480. handleFocusLoss();
  2481. break;
  2482. case WM_ACTIVATEAPP:
  2483. // Windows does weird things to process priority when you swap apps,
  2484. // so this forces an update when the app is brought to the front
  2485. if (wParam != FALSE)
  2486. juce_repeatLastProcessPriority();
  2487. else
  2488. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  2489. juce_checkCurrentlyFocusedTopLevelWindow();
  2490. modifiersAtLastCallback = -1;
  2491. return 0;
  2492. case WM_ACTIVATE:
  2493. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  2494. {
  2495. handleAppActivation (wParam);
  2496. return 0;
  2497. }
  2498. break;
  2499. case WM_NCACTIVATE:
  2500. // while a temporary window is being shown, prevent Windows from deactivating the
  2501. // title bars of our main windows.
  2502. if (wParam == 0 && ! shouldDeactivateTitleBar)
  2503. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  2504. break;
  2505. case WM_POINTERACTIVATE:
  2506. case WM_MOUSEACTIVATE:
  2507. if (! component.getMouseClickGrabsKeyboardFocus())
  2508. return MA_NOACTIVATE;
  2509. break;
  2510. case WM_SHOWWINDOW:
  2511. if (wParam != 0)
  2512. {
  2513. component.setVisible (true);
  2514. handleBroughtToFront();
  2515. }
  2516. break;
  2517. case WM_CLOSE:
  2518. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  2519. handleUserClosingWindow();
  2520. return 0;
  2521. #if JUCE_REMOVE_COMPONENT_FROM_DESKTOP_ON_WM_DESTROY
  2522. case WM_DESTROY:
  2523. getComponent().removeFromDesktop();
  2524. return 0;
  2525. #endif
  2526. case WM_QUERYENDSESSION:
  2527. if (auto* app = JUCEApplicationBase::getInstance())
  2528. {
  2529. app->systemRequestedQuit();
  2530. return MessageManager::getInstance()->hasStopMessageBeenSent();
  2531. }
  2532. return TRUE;
  2533. case WM_POWERBROADCAST:
  2534. handlePowerBroadcast (wParam);
  2535. break;
  2536. case WM_SYNCPAINT:
  2537. return 0;
  2538. case WM_DISPLAYCHANGE:
  2539. InvalidateRect (h, 0, 0);
  2540. // intentional fall-through...
  2541. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  2542. doSettingChange();
  2543. break;
  2544. case 0x2e0: // WM_DPICHANGED
  2545. handleDPIChange();
  2546. break;
  2547. case WM_INITMENU:
  2548. initialiseSysMenu ((HMENU) wParam);
  2549. break;
  2550. case WM_SYSCOMMAND:
  2551. switch (wParam & 0xfff0)
  2552. {
  2553. case SC_CLOSE:
  2554. if (sendInputAttemptWhenModalMessage())
  2555. return 0;
  2556. if (hasTitleBar())
  2557. {
  2558. PostMessage (h, WM_CLOSE, 0, 0);
  2559. return 0;
  2560. }
  2561. break;
  2562. case SC_KEYMENU:
  2563. #if ! JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU
  2564. // This test prevents a press of the ALT key from triggering the ancient top-left window menu.
  2565. // By default we suppress this behaviour because it's unlikely that more than a tiny subset of
  2566. // our users will actually want it, and it causes problems if you're trying to use the ALT key
  2567. // as a modifier for mouse actions. If you really need the old behaviour, then just define
  2568. // JUCE_WINDOWS_ALT_KEY_TRIGGERS_MENU=1 in your app.
  2569. if ((lParam >> 16) <= 0) // Values above zero indicate that a mouse-click triggered the menu
  2570. return 0;
  2571. #endif
  2572. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  2573. // situations that can arise if a modal loop is started from an alt-key keypress).
  2574. if (hasTitleBar() && h == GetCapture())
  2575. ReleaseCapture();
  2576. break;
  2577. case SC_MAXIMIZE:
  2578. if (! sendInputAttemptWhenModalMessage())
  2579. setFullScreen (true);
  2580. return 0;
  2581. case SC_MINIMIZE:
  2582. if (sendInputAttemptWhenModalMessage())
  2583. return 0;
  2584. if (! hasTitleBar())
  2585. {
  2586. setMinimised (true);
  2587. return 0;
  2588. }
  2589. break;
  2590. case SC_RESTORE:
  2591. if (sendInputAttemptWhenModalMessage())
  2592. return 0;
  2593. if (hasTitleBar())
  2594. {
  2595. if (isFullScreen())
  2596. {
  2597. setFullScreen (false);
  2598. return 0;
  2599. }
  2600. }
  2601. else
  2602. {
  2603. if (isMinimised())
  2604. setMinimised (false);
  2605. else if (isFullScreen())
  2606. setFullScreen (false);
  2607. return 0;
  2608. }
  2609. break;
  2610. }
  2611. break;
  2612. case WM_NCPOINTERDOWN:
  2613. case WM_NCLBUTTONDOWN:
  2614. handleLeftClickInNCArea (wParam);
  2615. break;
  2616. case WM_NCRBUTTONDOWN:
  2617. case WM_NCMBUTTONDOWN:
  2618. sendInputAttemptWhenModalMessage();
  2619. break;
  2620. case WM_IME_SETCONTEXT:
  2621. imeHandler.handleSetContext (h, wParam == TRUE);
  2622. lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  2623. break;
  2624. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  2625. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  2626. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  2627. case WM_GETDLGCODE:
  2628. return DLGC_WANTALLKEYS;
  2629. default:
  2630. break;
  2631. }
  2632. return DefWindowProcW (h, message, wParam, lParam);
  2633. }
  2634. bool sendInputAttemptWhenModalMessage()
  2635. {
  2636. if (component.isCurrentlyBlockedByAnotherModalComponent())
  2637. {
  2638. if (Component* const current = Component::getCurrentlyModalComponent())
  2639. current->inputAttemptWhenModal();
  2640. return true;
  2641. }
  2642. return false;
  2643. }
  2644. //==============================================================================
  2645. struct IMEHandler
  2646. {
  2647. IMEHandler()
  2648. {
  2649. reset();
  2650. }
  2651. void handleSetContext (HWND hWnd, const bool windowIsActive)
  2652. {
  2653. if (compositionInProgress && ! windowIsActive)
  2654. {
  2655. compositionInProgress = false;
  2656. if (HIMC hImc = ImmGetContext (hWnd))
  2657. {
  2658. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  2659. ImmReleaseContext (hWnd, hImc);
  2660. }
  2661. }
  2662. }
  2663. void handleStartComposition (ComponentPeer& owner)
  2664. {
  2665. reset();
  2666. if (auto* target = owner.findCurrentTextInputTarget())
  2667. target->insertTextAtCaret (String());
  2668. }
  2669. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  2670. {
  2671. if (compositionInProgress)
  2672. {
  2673. // If this occurs, the user has cancelled the composition, so clear their changes..
  2674. if (auto* target = owner.findCurrentTextInputTarget())
  2675. {
  2676. target->setHighlightedRegion (compositionRange);
  2677. target->insertTextAtCaret (String());
  2678. compositionRange.setLength (0);
  2679. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  2680. target->setTemporaryUnderlining (Array<Range<int> >());
  2681. }
  2682. if (auto hImc = ImmGetContext (hWnd))
  2683. {
  2684. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  2685. ImmReleaseContext (hWnd, hImc);
  2686. }
  2687. }
  2688. reset();
  2689. }
  2690. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  2691. {
  2692. if (auto* target = owner.findCurrentTextInputTarget())
  2693. {
  2694. if (auto hImc = ImmGetContext (hWnd))
  2695. {
  2696. if (compositionRange.getStart() < 0)
  2697. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  2698. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  2699. {
  2700. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  2701. Range<int>::emptyRange (-1));
  2702. reset();
  2703. target->setTemporaryUnderlining (Array<Range<int> >());
  2704. }
  2705. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  2706. {
  2707. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  2708. getCompositionSelection (hImc, lParam));
  2709. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  2710. compositionInProgress = true;
  2711. }
  2712. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  2713. ImmReleaseContext (hWnd, hImc);
  2714. }
  2715. }
  2716. }
  2717. private:
  2718. //==============================================================================
  2719. Range<int> compositionRange; // The range being modified in the TextInputTarget
  2720. bool compositionInProgress;
  2721. //==============================================================================
  2722. void reset()
  2723. {
  2724. compositionRange = Range<int>::emptyRange (-1);
  2725. compositionInProgress = false;
  2726. }
  2727. String getCompositionString (HIMC hImc, const DWORD type) const
  2728. {
  2729. jassert (hImc != 0);
  2730. const int stringSizeBytes = ImmGetCompositionString (hImc, type, 0, 0);
  2731. if (stringSizeBytes > 0)
  2732. {
  2733. HeapBlock<TCHAR> buffer;
  2734. buffer.calloc (stringSizeBytes / sizeof (TCHAR) + 1);
  2735. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  2736. return String (buffer);
  2737. }
  2738. return {};
  2739. }
  2740. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  2741. {
  2742. jassert (hImc != 0);
  2743. if ((lParam & CS_NOMOVECARET) != 0)
  2744. return compositionRange.getStart();
  2745. if ((lParam & GCS_CURSORPOS) != 0)
  2746. {
  2747. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, 0, 0);
  2748. return compositionRange.getStart() + jmax (0, localCaretPos);
  2749. }
  2750. return compositionRange.getStart() + currentIMEString.length();
  2751. }
  2752. // Get selected/highlighted range while doing composition:
  2753. // returned range is relative to beginning of TextInputTarget, not composition string
  2754. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  2755. {
  2756. jassert (hImc != 0);
  2757. int selectionStart = 0;
  2758. int selectionEnd = 0;
  2759. if ((lParam & GCS_COMPATTR) != 0)
  2760. {
  2761. // Get size of attributes array:
  2762. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, 0, 0);
  2763. if (attributeSizeBytes > 0)
  2764. {
  2765. // Get attributes (8 bit flag per character):
  2766. HeapBlock<char> attributes ((size_t) attributeSizeBytes);
  2767. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  2768. selectionStart = 0;
  2769. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  2770. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  2771. break;
  2772. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  2773. if (attributes [selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  2774. break;
  2775. }
  2776. }
  2777. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  2778. }
  2779. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  2780. {
  2781. if (compositionInProgress)
  2782. target->setHighlightedRegion (compositionRange);
  2783. target->insertTextAtCaret (newContent);
  2784. compositionRange.setLength (newContent.length());
  2785. if (newSelection.getStart() < 0)
  2786. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  2787. target->setHighlightedRegion (newSelection);
  2788. }
  2789. Array<Range<int>> getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  2790. {
  2791. Array<Range<int>> result;
  2792. if (hImc != 0 && (lParam & GCS_COMPCLAUSE) != 0)
  2793. {
  2794. auto clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, 0, 0);
  2795. if (clauseDataSizeBytes > 0)
  2796. {
  2797. const size_t numItems = clauseDataSizeBytes / sizeof (uint32);
  2798. HeapBlock<uint32> clauseData (numItems);
  2799. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  2800. for (size_t i = 0; i + 1 < numItems; ++i)
  2801. result.add (Range<int> ((int) clauseData [i], (int) clauseData [i + 1]) + compositionRange.getStart());
  2802. }
  2803. }
  2804. return result;
  2805. }
  2806. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  2807. {
  2808. if (auto* targetComp = dynamic_cast<Component*> (target))
  2809. {
  2810. auto area = peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle());
  2811. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  2812. ImmSetCandidateWindow (hImc, &pos);
  2813. }
  2814. }
  2815. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  2816. };
  2817. void timerCallback() override
  2818. {
  2819. handlePositionChanged();
  2820. stopTimer();
  2821. }
  2822. IMEHandler imeHandler;
  2823. //==============================================================================
  2824. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  2825. };
  2826. ModifierKeys HWNDComponentPeer::currentModifiers;
  2827. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  2828. ComponentPeer* Component::createNewPeer (int styleFlags, void* parentHWND)
  2829. {
  2830. return new HWNDComponentPeer (*this, styleFlags, (HWND) parentHWND, false);
  2831. }
  2832. JUCE_API ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component& component, void* parentHWND)
  2833. {
  2834. return new HWNDComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  2835. (HWND) parentHWND, true);
  2836. }
  2837. juce_ImplementSingleton_SingleThreaded (HWNDComponentPeer::WindowClassHolder)
  2838. //==============================================================================
  2839. void ModifierKeys::updateCurrentModifiers() noexcept
  2840. {
  2841. currentModifiers = HWNDComponentPeer::currentModifiers;
  2842. }
  2843. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2844. {
  2845. HWNDComponentPeer::updateKeyModifiers();
  2846. int mouseMods = 0;
  2847. if (HWNDComponentPeer::isKeyDown (VK_LBUTTON)) mouseMods |= ModifierKeys::leftButtonModifier;
  2848. if (HWNDComponentPeer::isKeyDown (VK_RBUTTON)) mouseMods |= ModifierKeys::rightButtonModifier;
  2849. if (HWNDComponentPeer::isKeyDown (VK_MBUTTON)) mouseMods |= ModifierKeys::middleButtonModifier;
  2850. HWNDComponentPeer::currentModifiers
  2851. = HWNDComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2852. return HWNDComponentPeer::currentModifiers;
  2853. }
  2854. //==============================================================================
  2855. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  2856. {
  2857. auto k = (SHORT) keyCode;
  2858. if ((keyCode & extendedKeyModifier) == 0)
  2859. {
  2860. if (k >= (SHORT) 'a' && k <= (SHORT) 'z')
  2861. k += (SHORT) 'A' - (SHORT) 'a';
  2862. // Only translate if extendedKeyModifier flag is not set
  2863. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  2864. (SHORT) '+', VK_OEM_PLUS,
  2865. (SHORT) '-', VK_OEM_MINUS,
  2866. (SHORT) '.', VK_OEM_PERIOD,
  2867. (SHORT) ';', VK_OEM_1,
  2868. (SHORT) ':', VK_OEM_1,
  2869. (SHORT) '/', VK_OEM_2,
  2870. (SHORT) '?', VK_OEM_2,
  2871. (SHORT) '[', VK_OEM_4,
  2872. (SHORT) ']', VK_OEM_6 };
  2873. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  2874. if (k == translatedValues [i])
  2875. k = translatedValues [i + 1];
  2876. }
  2877. return HWNDComponentPeer::isKeyDown (k);
  2878. }
  2879. // (This internal function is used by the plugin client module)
  2880. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  2881. //==============================================================================
  2882. bool JUCE_CALLTYPE Process::isForegroundProcess()
  2883. {
  2884. if (auto fg = GetForegroundWindow())
  2885. {
  2886. DWORD processID = 0;
  2887. GetWindowThreadProcessId (fg, &processID);
  2888. return processID == GetCurrentProcessId();
  2889. }
  2890. return true;
  2891. }
  2892. // N/A on Windows as far as I know.
  2893. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2894. void JUCE_CALLTYPE Process::hide() {}
  2895. //==============================================================================
  2896. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  2897. {
  2898. if (IsWindowVisible (hwnd))
  2899. {
  2900. DWORD processID = 0;
  2901. GetWindowThreadProcessId (hwnd, &processID);
  2902. if (processID == GetCurrentProcessId())
  2903. {
  2904. WINDOWINFO info;
  2905. if (GetWindowInfo (hwnd, &info)
  2906. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  2907. {
  2908. *reinterpret_cast<bool*> (lParam) = true;
  2909. return FALSE;
  2910. }
  2911. }
  2912. }
  2913. return TRUE;
  2914. }
  2915. bool juce_areThereAnyAlwaysOnTopWindows()
  2916. {
  2917. bool anyAlwaysOnTopFound = false;
  2918. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  2919. return anyAlwaysOnTopFound;
  2920. }
  2921. //==============================================================================
  2922. class WindowsMessageBox : public AsyncUpdater
  2923. {
  2924. public:
  2925. WindowsMessageBox (AlertWindow::AlertIconType iconType,
  2926. const String& boxTitle, const String& m,
  2927. Component* associatedComponent, UINT extraFlags,
  2928. ModalComponentManager::Callback* cb, const bool runAsync)
  2929. : flags (extraFlags | getMessageBoxFlags (iconType)),
  2930. owner (getWindowForMessageBox (associatedComponent)),
  2931. title (boxTitle), message (m), callback (cb)
  2932. {
  2933. if (runAsync)
  2934. triggerAsyncUpdate();
  2935. }
  2936. int getResult() const
  2937. {
  2938. const int r = MessageBox (owner, message.toWideCharPointer(), title.toWideCharPointer(), flags);
  2939. return (r == IDYES || r == IDOK) ? 1 : (r == IDNO && (flags & 1) != 0 ? 2 : 0);
  2940. }
  2941. void handleAsyncUpdate() override
  2942. {
  2943. const int result = getResult();
  2944. if (callback != nullptr)
  2945. callback->modalStateFinished (result);
  2946. delete this;
  2947. }
  2948. private:
  2949. UINT flags;
  2950. HWND owner;
  2951. String title, message;
  2952. ScopedPointer<ModalComponentManager::Callback> callback;
  2953. static UINT getMessageBoxFlags (AlertWindow::AlertIconType iconType) noexcept
  2954. {
  2955. UINT flags = MB_TASKMODAL | MB_SETFOREGROUND;
  2956. switch (iconType)
  2957. {
  2958. case AlertWindow::QuestionIcon: flags |= MB_ICONQUESTION; break;
  2959. case AlertWindow::WarningIcon: flags |= MB_ICONWARNING; break;
  2960. case AlertWindow::InfoIcon: flags |= MB_ICONINFORMATION; break;
  2961. default: break;
  2962. }
  2963. return flags;
  2964. }
  2965. static HWND getWindowForMessageBox (Component* associatedComponent)
  2966. {
  2967. return associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : 0;
  2968. }
  2969. };
  2970. #if JUCE_MODAL_LOOPS_PERMITTED
  2971. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  2972. const String& title, const String& message,
  2973. Component* associatedComponent)
  2974. {
  2975. WindowsMessageBox box (iconType, title, message, associatedComponent, MB_OK, 0, false);
  2976. (void) box.getResult();
  2977. }
  2978. #endif
  2979. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  2980. const String& title, const String& message,
  2981. Component* associatedComponent,
  2982. ModalComponentManager::Callback* callback)
  2983. {
  2984. new WindowsMessageBox (iconType, title, message, associatedComponent, MB_OK, callback, true);
  2985. }
  2986. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  2987. const String& title, const String& message,
  2988. Component* associatedComponent,
  2989. ModalComponentManager::Callback* callback)
  2990. {
  2991. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  2992. MB_OKCANCEL, callback, callback != nullptr));
  2993. if (callback == nullptr)
  2994. return mb->getResult() != 0;
  2995. mb.release();
  2996. return false;
  2997. }
  2998. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  2999. const String& title, const String& message,
  3000. Component* associatedComponent,
  3001. ModalComponentManager::Callback* callback)
  3002. {
  3003. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3004. MB_YESNOCANCEL, callback, callback != nullptr));
  3005. if (callback == nullptr)
  3006. return mb->getResult();
  3007. mb.release();
  3008. return 0;
  3009. }
  3010. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (AlertWindow::AlertIconType iconType,
  3011. const String& title, const String& message,
  3012. Component* associatedComponent,
  3013. ModalComponentManager::Callback* callback)
  3014. {
  3015. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  3016. MB_YESNO, callback, callback != nullptr));
  3017. if (callback == nullptr)
  3018. return mb->getResult();
  3019. mb.release();
  3020. return 0;
  3021. }
  3022. //==============================================================================
  3023. bool MouseInputSource::SourceList::addSource()
  3024. {
  3025. auto numSources = sources.size();
  3026. if (numSources == 0 || canUseMultiTouch())
  3027. {
  3028. addSource (numSources, numSources == 0 ? MouseInputSource::InputSourceType::mouse
  3029. : MouseInputSource::InputSourceType::touch);
  3030. return true;
  3031. }
  3032. return false;
  3033. }
  3034. bool MouseInputSource::SourceList::canUseTouch()
  3035. {
  3036. return canUseMultiTouch();
  3037. }
  3038. Point<float> MouseInputSource::getCurrentRawMousePosition()
  3039. {
  3040. POINT mousePos;
  3041. GetCursorPos (&mousePos);
  3042. return { (float) mousePos.x, (float) mousePos.y };
  3043. }
  3044. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  3045. {
  3046. SetCursorPos (roundToInt (newPosition.x),
  3047. roundToInt (newPosition.y));
  3048. }
  3049. //==============================================================================
  3050. class ScreenSaverDefeater : public Timer
  3051. {
  3052. public:
  3053. ScreenSaverDefeater()
  3054. {
  3055. startTimer (10000);
  3056. timerCallback();
  3057. }
  3058. void timerCallback() override
  3059. {
  3060. if (Process::isForegroundProcess())
  3061. {
  3062. INPUT input = { 0 };
  3063. input.type = INPUT_MOUSE;
  3064. input.mi.mouseData = MOUSEEVENTF_MOVE;
  3065. SendInput (1, &input, sizeof (INPUT));
  3066. }
  3067. }
  3068. };
  3069. static ScopedPointer<ScreenSaverDefeater> screenSaverDefeater;
  3070. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  3071. {
  3072. if (isEnabled)
  3073. screenSaverDefeater = nullptr;
  3074. else if (screenSaverDefeater == nullptr)
  3075. screenSaverDefeater = new ScreenSaverDefeater();
  3076. }
  3077. bool Desktop::isScreenSaverEnabled()
  3078. {
  3079. return screenSaverDefeater == nullptr;
  3080. }
  3081. //==============================================================================
  3082. void LookAndFeel::playAlertSound()
  3083. {
  3084. MessageBeep (MB_OK);
  3085. }
  3086. //==============================================================================
  3087. void SystemClipboard::copyTextToClipboard (const String& text)
  3088. {
  3089. if (OpenClipboard (0) != 0)
  3090. {
  3091. if (EmptyClipboard() != 0)
  3092. {
  3093. auto bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  3094. if (bytesNeeded > 0)
  3095. {
  3096. if (auto bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  3097. {
  3098. if (auto* data = static_cast<WCHAR*> (GlobalLock (bufH)))
  3099. {
  3100. text.copyToUTF16 (data, bytesNeeded);
  3101. GlobalUnlock (bufH);
  3102. SetClipboardData (CF_UNICODETEXT, bufH);
  3103. }
  3104. }
  3105. }
  3106. }
  3107. CloseClipboard();
  3108. }
  3109. }
  3110. String SystemClipboard::getTextFromClipboard()
  3111. {
  3112. String result;
  3113. if (OpenClipboard (0) != 0)
  3114. {
  3115. if (auto bufH = GetClipboardData (CF_UNICODETEXT))
  3116. {
  3117. if (auto* data = (const WCHAR*) GlobalLock (bufH))
  3118. {
  3119. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  3120. GlobalUnlock (bufH);
  3121. }
  3122. }
  3123. CloseClipboard();
  3124. }
  3125. return result;
  3126. }
  3127. //==============================================================================
  3128. void Desktop::setKioskComponent (Component* kioskModeComp, bool enableOrDisable, bool /*allowMenusAndBars*/)
  3129. {
  3130. if (auto* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComp))
  3131. tlw->setUsingNativeTitleBar (! enableOrDisable);
  3132. if (enableOrDisable)
  3133. kioskModeComp->setBounds (getDisplays().getMainDisplay().totalArea);
  3134. }
  3135. void Desktop::allowedOrientationsChanged() {}
  3136. //==============================================================================
  3137. struct MonitorInfo
  3138. {
  3139. MonitorInfo (Rectangle<int> rect, bool main, double d) noexcept
  3140. : bounds (rect), dpi (d), isMain (main) {}
  3141. Rectangle<int> bounds;
  3142. double dpi;
  3143. bool isMain;
  3144. };
  3145. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT r, LPARAM userInfo)
  3146. {
  3147. MONITORINFO info = { 0 };
  3148. info.cbSize = sizeof (info);
  3149. GetMonitorInfo (hm, &info);
  3150. const bool isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  3151. double dpi = 0;
  3152. if (getDPIForMonitor != nullptr)
  3153. {
  3154. UINT dpiX = 0, dpiY = 0;
  3155. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  3156. dpi = (dpiX + dpiY) / 2.0;
  3157. }
  3158. ((Array<MonitorInfo>*) userInfo)->add (MonitorInfo (rectangleFromRECT (*r), isMain, dpi));
  3159. return TRUE;
  3160. }
  3161. void Desktop::Displays::findDisplays (float masterScale)
  3162. {
  3163. setDPIAwareness();
  3164. Array<MonitorInfo> monitors;
  3165. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitors);
  3166. const double globalDPI = getGlobalDPI();
  3167. if (monitors.size() == 0)
  3168. monitors.add (MonitorInfo (rectangleFromRECT (getWindowRect (GetDesktopWindow())), true, globalDPI));
  3169. // make sure the first in the list is the main monitor
  3170. for (int i = 1; i < monitors.size(); ++i)
  3171. if (monitors.getReference(i).isMain)
  3172. monitors.swap (i, 0);
  3173. RECT workArea;
  3174. SystemParametersInfo (SPI_GETWORKAREA, 0, &workArea, 0);
  3175. for (int i = 0; i < monitors.size(); ++i)
  3176. {
  3177. Display d;
  3178. d.userArea = d.totalArea = monitors.getReference(i).bounds / masterScale;
  3179. d.isMain = monitors.getReference(i).isMain;
  3180. d.dpi = monitors.getReference(i).dpi;
  3181. if (d.dpi == 0)
  3182. {
  3183. d.scale = masterScale;
  3184. d.dpi = globalDPI;
  3185. }
  3186. else
  3187. {
  3188. d.scale = d.dpi / 96.0;
  3189. }
  3190. if (d.isMain)
  3191. d.userArea = d.userArea.getIntersection (rectangleFromRECT (workArea) / masterScale);
  3192. displays.add (d);
  3193. }
  3194. }
  3195. //==============================================================================
  3196. static HICON extractFileHICON (const File& file)
  3197. {
  3198. WORD iconNum = 0;
  3199. WCHAR name [MAX_PATH * 2];
  3200. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  3201. return ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  3202. name, &iconNum);
  3203. }
  3204. Image juce_createIconForFile (const File& file)
  3205. {
  3206. Image image;
  3207. if (auto icon = extractFileHICON (file))
  3208. {
  3209. image = IconConverters::createImageFromHICON (icon);
  3210. DestroyIcon (icon);
  3211. }
  3212. return image;
  3213. }
  3214. //==============================================================================
  3215. void* CustomMouseCursorInfo::create() const
  3216. {
  3217. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  3218. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  3219. Image im (image);
  3220. int hotspotX = hotspot.x;
  3221. int hotspotY = hotspot.y;
  3222. if (im.getWidth() > maxW || im.getHeight() > maxH)
  3223. {
  3224. im = im.rescaled (maxW, maxH);
  3225. hotspotX = (hotspotX * maxW) / image.getWidth();
  3226. hotspotY = (hotspotY * maxH) / image.getHeight();
  3227. }
  3228. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  3229. }
  3230. void MouseCursor::deleteMouseCursor (void* cursorHandle, bool isStandard)
  3231. {
  3232. if (cursorHandle != nullptr && ! isStandard)
  3233. DestroyCursor ((HCURSOR) cursorHandle);
  3234. }
  3235. enum
  3236. {
  3237. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  3238. };
  3239. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  3240. {
  3241. LPCTSTR cursorName = IDC_ARROW;
  3242. switch (type)
  3243. {
  3244. case NormalCursor:
  3245. case ParentCursor: break;
  3246. case NoCursor: return (void*) hiddenMouseCursorHandle;
  3247. case WaitCursor: cursorName = IDC_WAIT; break;
  3248. case IBeamCursor: cursorName = IDC_IBEAM; break;
  3249. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  3250. case CrosshairCursor: cursorName = IDC_CROSS; break;
  3251. case LeftRightResizeCursor:
  3252. case LeftEdgeResizeCursor:
  3253. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  3254. case UpDownResizeCursor:
  3255. case TopEdgeResizeCursor:
  3256. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  3257. case TopLeftCornerResizeCursor:
  3258. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  3259. case TopRightCornerResizeCursor:
  3260. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  3261. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  3262. case DraggingHandCursor:
  3263. {
  3264. static void* dragHandCursor = nullptr;
  3265. if (dragHandCursor == nullptr)
  3266. {
  3267. static const unsigned char dragHandData[] =
  3268. { 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,
  3269. 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,
  3270. 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 };
  3271. dragHandCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7).create();
  3272. }
  3273. return dragHandCursor;
  3274. }
  3275. case CopyingCursor:
  3276. {
  3277. static void* copyCursor = nullptr;
  3278. if (copyCursor == nullptr)
  3279. {
  3280. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  3281. 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,
  3282. 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,
  3283. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  3284. const int copyCursorSize = 119;
  3285. copyCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
  3286. }
  3287. return copyCursor;
  3288. }
  3289. default:
  3290. jassertfalse; break;
  3291. }
  3292. HCURSOR cursorH = LoadCursor (0, cursorName);
  3293. if (cursorH == 0)
  3294. cursorH = LoadCursor (0, IDC_ARROW);
  3295. return cursorH;
  3296. }
  3297. //==============================================================================
  3298. void MouseCursor::showInWindow (ComponentPeer*) const
  3299. {
  3300. auto c = (HCURSOR) getHandle();
  3301. if (c == 0)
  3302. c = LoadCursor (0, IDC_ARROW);
  3303. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  3304. c = 0;
  3305. SetCursor (c);
  3306. }
  3307. void MouseCursor::showInAllWindows() const
  3308. {
  3309. showInWindow (nullptr);
  3310. }