Audio plugin host https://kx.studio/carla
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.

3469 lines
119KB

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