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.

4062 lines
141KB

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