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.

3468 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 (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 || dontRepaint))
  1243. {
  1244. const ScopedValueSetter<bool> setter (reentrant, true, false);
  1245. performPaint (dc, rgn, regionType, paintStruct);
  1246. }
  1247. DeleteObject (rgn);
  1248. EndPaint (hwnd, &paintStruct);
  1249. #ifndef JUCE_GCC
  1250. _fpreset(); // because some graphics cards can unmask FP exceptions
  1251. #endif
  1252. lastPaintTime = Time::getMillisecondCounter();
  1253. }
  1254. void performPaint (HDC dc, HRGN rgn, int regionType, PAINTSTRUCT& paintStruct)
  1255. {
  1256. int x = paintStruct.rcPaint.left;
  1257. int y = paintStruct.rcPaint.top;
  1258. int w = paintStruct.rcPaint.right - x;
  1259. int h = paintStruct.rcPaint.bottom - y;
  1260. const bool transparent = isUsingUpdateLayeredWindow();
  1261. if (transparent)
  1262. {
  1263. // it's not possible to have a transparent window with a title bar at the moment!
  1264. jassert (! hasTitleBar());
  1265. RECT r = getWindowRect (hwnd);
  1266. x = y = 0;
  1267. w = r.right - r.left;
  1268. h = r.bottom - r.top;
  1269. }
  1270. if (w > 0 && h > 0)
  1271. {
  1272. Image& offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  1273. RectangleList<int> contextClip;
  1274. const Rectangle<int> clipBounds (w, h);
  1275. bool needToPaintAll = true;
  1276. if (regionType == COMPLEXREGION && ! transparent)
  1277. {
  1278. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  1279. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  1280. DeleteObject (clipRgn);
  1281. char rgnData [8192];
  1282. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  1283. if (res > 0 && res <= sizeof (rgnData))
  1284. {
  1285. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  1286. if (hdr->iType == RDH_RECTANGLES
  1287. && hdr->rcBound.right - hdr->rcBound.left >= w
  1288. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  1289. {
  1290. needToPaintAll = false;
  1291. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  1292. for (int i = (int) ((RGNDATA*) rgnData)->rdh.nCount; --i >= 0;)
  1293. {
  1294. if (rects->right <= x + w && rects->bottom <= y + h)
  1295. {
  1296. const int cx = jmax (x, (int) rects->left);
  1297. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y,
  1298. rects->right - cx, rects->bottom - rects->top)
  1299. .getIntersection (clipBounds));
  1300. }
  1301. else
  1302. {
  1303. needToPaintAll = true;
  1304. break;
  1305. }
  1306. ++rects;
  1307. }
  1308. }
  1309. }
  1310. }
  1311. if (needToPaintAll)
  1312. {
  1313. contextClip.clear();
  1314. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  1315. }
  1316. ChildWindowClippingInfo childClipInfo = { dc, this, &contextClip, Point<int> (x, y), 0 };
  1317. EnumChildWindows (hwnd, clipChildWindowCallback, (LPARAM) &childClipInfo);
  1318. if (! contextClip.isEmpty())
  1319. {
  1320. if (transparent)
  1321. for (const Rectangle<int>* i = contextClip.begin(), * const e = contextClip.end(); i != e; ++i)
  1322. offscreenImage.clear (*i);
  1323. // if the component's not opaque, this won't draw properly unless the platform can support this
  1324. jassert (Desktop::canUseSemiTransparentWindows() || component.isOpaque());
  1325. {
  1326. ScopedPointer<LowLevelGraphicsContext> context (component.getLookAndFeel()
  1327. .createGraphicsContext (offscreenImage, Point<int> (-x, -y), contextClip));
  1328. handlePaint (*context);
  1329. }
  1330. static_cast <WindowsBitmapImage*> (offscreenImage.getPixelData())
  1331. ->blitToWindow (hwnd, dc, transparent, x, y, updateLayeredWindowAlpha);
  1332. }
  1333. if (childClipInfo.savedDC != 0)
  1334. RestoreDC (dc, childClipInfo.savedDC);
  1335. }
  1336. }
  1337. //==============================================================================
  1338. void doMouseEvent (Point<float> position)
  1339. {
  1340. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  1341. }
  1342. StringArray getAvailableRenderingEngines() override
  1343. {
  1344. StringArray s ("Software Renderer");
  1345. #if JUCE_DIRECT2D
  1346. if (SystemStats::getOperatingSystemType() >= SystemStats::Windows7)
  1347. s.add ("Direct2D");
  1348. #endif
  1349. return s;
  1350. }
  1351. int getCurrentRenderingEngine() const override { return currentRenderingEngine; }
  1352. #if JUCE_DIRECT2D
  1353. void updateDirect2DContext()
  1354. {
  1355. if (currentRenderingEngine != direct2DRenderingEngine)
  1356. direct2DContext = 0;
  1357. else if (direct2DContext == 0)
  1358. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  1359. }
  1360. #endif
  1361. void setCurrentRenderingEngine (int index) override
  1362. {
  1363. (void) index;
  1364. #if JUCE_DIRECT2D
  1365. if (getAvailableRenderingEngines().size() > 1)
  1366. {
  1367. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  1368. updateDirect2DContext();
  1369. repaint (component.getLocalBounds());
  1370. }
  1371. #endif
  1372. }
  1373. static int getMinTimeBetweenMouseMoves()
  1374. {
  1375. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  1376. return 0;
  1377. return 1000 / 60; // Throttling the incoming mouse-events seems to still be needed in XP..
  1378. }
  1379. void doMouseMove (Point<float> position)
  1380. {
  1381. if (! isMouseOver)
  1382. {
  1383. isMouseOver = true;
  1384. ModifierKeys::getCurrentModifiersRealtime(); // (This avoids a rare stuck-button problem when focus is lost unexpectedly)
  1385. updateKeyModifiers();
  1386. TRACKMOUSEEVENT tme;
  1387. tme.cbSize = sizeof (tme);
  1388. tme.dwFlags = TME_LEAVE;
  1389. tme.hwndTrack = hwnd;
  1390. tme.dwHoverTime = 0;
  1391. if (! TrackMouseEvent (&tme))
  1392. jassertfalse;
  1393. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1394. }
  1395. else if (! isDragging)
  1396. {
  1397. if (! contains (position.roundToInt(), false))
  1398. return;
  1399. }
  1400. static uint32 lastMouseTime = 0;
  1401. static int minTimeBetweenMouses = getMinTimeBetweenMouseMoves();
  1402. const uint32 now = Time::getMillisecondCounter();
  1403. if (now >= lastMouseTime + minTimeBetweenMouses)
  1404. {
  1405. lastMouseTime = now;
  1406. doMouseEvent (position);
  1407. }
  1408. }
  1409. void doMouseDown (Point<float> position, const WPARAM wParam)
  1410. {
  1411. if (GetCapture() != hwnd)
  1412. SetCapture (hwnd);
  1413. doMouseMove (position);
  1414. updateModifiersFromWParam (wParam);
  1415. isDragging = true;
  1416. doMouseEvent (position);
  1417. }
  1418. void doMouseUp (Point<float> position, const WPARAM wParam)
  1419. {
  1420. updateModifiersFromWParam (wParam);
  1421. const bool wasDragging = isDragging;
  1422. isDragging = false;
  1423. // release the mouse capture if the user has released all buttons
  1424. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  1425. ReleaseCapture();
  1426. // NB: under some circumstances (e.g. double-clicking a native title bar), a mouse-up can
  1427. // arrive without a mouse-down, so in that case we need to avoid sending a message.
  1428. if (wasDragging)
  1429. doMouseEvent (position);
  1430. }
  1431. void doCaptureChanged()
  1432. {
  1433. if (constrainerIsResizing)
  1434. {
  1435. if (constrainer != nullptr)
  1436. constrainer->resizeEnd();
  1437. constrainerIsResizing = false;
  1438. }
  1439. if (isDragging)
  1440. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  1441. }
  1442. void doMouseExit()
  1443. {
  1444. isMouseOver = false;
  1445. doMouseEvent (getCurrentMousePos());
  1446. }
  1447. ComponentPeer* findPeerUnderMouse (Point<float>& localPos)
  1448. {
  1449. const Point<int> globalPos (getCurrentMousePosGlobal().roundToInt());
  1450. // Because Windows stupidly sends all wheel events to the window with the keyboard
  1451. // focus, we have to redirect them here according to the mouse pos..
  1452. POINT p = { globalPos.x, globalPos.y };
  1453. HWNDComponentPeer* peer = getOwnerOfWindow (WindowFromPoint (p));
  1454. if (peer == nullptr)
  1455. peer = this;
  1456. localPos = peer->globalToLocal (globalPos.toFloat());
  1457. return peer;
  1458. }
  1459. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  1460. {
  1461. updateKeyModifiers();
  1462. const float amount = jlimit (-1000.0f, 1000.0f, 0.5f * (short) HIWORD (wParam));
  1463. MouseWheelDetails wheel;
  1464. wheel.deltaX = isVertical ? 0.0f : amount / -256.0f;
  1465. wheel.deltaY = isVertical ? amount / 256.0f : 0.0f;
  1466. wheel.isReversed = false;
  1467. wheel.isSmooth = false;
  1468. Point<float> localPos;
  1469. if (ComponentPeer* const peer = findPeerUnderMouse (localPos))
  1470. peer->handleMouseWheel (0, localPos, getMouseEventTime(), wheel);
  1471. }
  1472. bool doGestureEvent (LPARAM lParam)
  1473. {
  1474. GESTUREINFO gi;
  1475. zerostruct (gi);
  1476. gi.cbSize = sizeof (gi);
  1477. if (getGestureInfo != nullptr && getGestureInfo ((HGESTUREINFO) lParam, &gi))
  1478. {
  1479. updateKeyModifiers();
  1480. Point<float> localPos;
  1481. if (ComponentPeer* const peer = findPeerUnderMouse (localPos))
  1482. {
  1483. switch (gi.dwID)
  1484. {
  1485. case 3: /*GID_ZOOM*/
  1486. if (gi.dwFlags != 1 /*GF_BEGIN*/ && lastMagnifySize > 0)
  1487. peer->handleMagnifyGesture (0, localPos, getMouseEventTime(),
  1488. (float) (gi.ullArguments / (double) lastMagnifySize));
  1489. lastMagnifySize = gi.ullArguments;
  1490. return true;
  1491. case 4: /*GID_PAN*/
  1492. case 5: /*GID_ROTATE*/
  1493. case 6: /*GID_TWOFINGERTAP*/
  1494. case 7: /*GID_PRESSANDTAP*/
  1495. default:
  1496. break;
  1497. }
  1498. }
  1499. }
  1500. return false;
  1501. }
  1502. LRESULT doTouchEvent (const int numInputs, HTOUCHINPUT eventHandle)
  1503. {
  1504. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  1505. if (HWNDComponentPeer* const parent = getOwnerOfWindow (GetParent (hwnd)))
  1506. if (parent != this)
  1507. return parent->doTouchEvent (numInputs, eventHandle);
  1508. HeapBlock<TOUCHINPUT> inputInfo (numInputs);
  1509. if (getTouchInputInfo (eventHandle, numInputs, inputInfo, sizeof (TOUCHINPUT)))
  1510. {
  1511. for (int i = 0; i < numInputs; ++i)
  1512. {
  1513. const DWORD flags = inputInfo[i].dwFlags;
  1514. if ((flags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE | TOUCHEVENTF_UP)) != 0)
  1515. if (! handleTouchInput (inputInfo[i], (flags & TOUCHEVENTF_PRIMARY) != 0,
  1516. (flags & TOUCHEVENTF_DOWN) != 0, (flags & TOUCHEVENTF_UP) != 0))
  1517. return 0; // abandon method if this window was deleted by the callback
  1518. }
  1519. }
  1520. closeTouchInputHandle (eventHandle);
  1521. return 0;
  1522. }
  1523. bool handleTouchInput (const TOUCHINPUT& touch, const bool isPrimary, const bool isDown, const bool isUp)
  1524. {
  1525. bool isCancel = false;
  1526. const int touchIndex = currentTouches.getIndexOfTouch (touch.dwID);
  1527. const int64 time = getMouseEventTime();
  1528. const Point<float> pos (globalToLocal (Point<float> (static_cast<float> (TOUCH_COORD_TO_PIXEL (touch.x)),
  1529. static_cast<float> (TOUCH_COORD_TO_PIXEL (touch.y)))));
  1530. ModifierKeys modsToSend (currentModifiers);
  1531. if (isDown)
  1532. {
  1533. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1534. modsToSend = currentModifiers;
  1535. if (! isPrimary)
  1536. {
  1537. // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
  1538. handleMouseEvent (touchIndex, pos.toFloat(), modsToSend.withoutMouseButtons(), time);
  1539. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1540. return false;
  1541. }
  1542. }
  1543. else if (isUp)
  1544. {
  1545. modsToSend = modsToSend.withoutMouseButtons();
  1546. currentTouches.clearTouch (touchIndex);
  1547. if (! currentTouches.areAnyTouchesActive())
  1548. isCancel = true;
  1549. }
  1550. else
  1551. {
  1552. modsToSend = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  1553. }
  1554. if (isCancel)
  1555. {
  1556. currentTouches.clear();
  1557. currentModifiers = currentModifiers.withoutMouseButtons();
  1558. }
  1559. if (! isPrimary)
  1560. {
  1561. handleMouseEvent (touchIndex, pos.toFloat(), modsToSend, time);
  1562. if (! isValidPeer (this)) // (in case this component was deleted by the event)
  1563. return false;
  1564. }
  1565. if ((isUp || isCancel) && ! isPrimary)
  1566. {
  1567. handleMouseEvent (touchIndex, Point<float> (-10.0f, -10.0f), currentModifiers, time);
  1568. if (! isValidPeer (this))
  1569. return false;
  1570. }
  1571. return true;
  1572. }
  1573. //==============================================================================
  1574. void sendModifierKeyChangeIfNeeded()
  1575. {
  1576. if (modifiersAtLastCallback != currentModifiers)
  1577. {
  1578. modifiersAtLastCallback = currentModifiers;
  1579. handleModifierKeysChange();
  1580. }
  1581. }
  1582. bool doKeyUp (const WPARAM key)
  1583. {
  1584. updateKeyModifiers();
  1585. switch (key)
  1586. {
  1587. case VK_SHIFT:
  1588. case VK_CONTROL:
  1589. case VK_MENU:
  1590. case VK_CAPITAL:
  1591. case VK_LWIN:
  1592. case VK_RWIN:
  1593. case VK_APPS:
  1594. case VK_NUMLOCK:
  1595. case VK_SCROLL:
  1596. case VK_LSHIFT:
  1597. case VK_RSHIFT:
  1598. case VK_LCONTROL:
  1599. case VK_LMENU:
  1600. case VK_RCONTROL:
  1601. case VK_RMENU:
  1602. sendModifierKeyChangeIfNeeded();
  1603. }
  1604. return handleKeyUpOrDown (false)
  1605. || Component::getCurrentlyModalComponent() != nullptr;
  1606. }
  1607. bool doKeyDown (const WPARAM key)
  1608. {
  1609. updateKeyModifiers();
  1610. bool used = false;
  1611. switch (key)
  1612. {
  1613. case VK_SHIFT:
  1614. case VK_LSHIFT:
  1615. case VK_RSHIFT:
  1616. case VK_CONTROL:
  1617. case VK_LCONTROL:
  1618. case VK_RCONTROL:
  1619. case VK_MENU:
  1620. case VK_LMENU:
  1621. case VK_RMENU:
  1622. case VK_LWIN:
  1623. case VK_RWIN:
  1624. case VK_CAPITAL:
  1625. case VK_NUMLOCK:
  1626. case VK_SCROLL:
  1627. case VK_APPS:
  1628. sendModifierKeyChangeIfNeeded();
  1629. break;
  1630. case VK_LEFT:
  1631. case VK_RIGHT:
  1632. case VK_UP:
  1633. case VK_DOWN:
  1634. case VK_PRIOR:
  1635. case VK_NEXT:
  1636. case VK_HOME:
  1637. case VK_END:
  1638. case VK_DELETE:
  1639. case VK_INSERT:
  1640. case VK_F1:
  1641. case VK_F2:
  1642. case VK_F3:
  1643. case VK_F4:
  1644. case VK_F5:
  1645. case VK_F6:
  1646. case VK_F7:
  1647. case VK_F8:
  1648. case VK_F9:
  1649. case VK_F10:
  1650. case VK_F11:
  1651. case VK_F12:
  1652. case VK_F13:
  1653. case VK_F14:
  1654. case VK_F15:
  1655. case VK_F16:
  1656. used = handleKeyUpOrDown (true);
  1657. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  1658. break;
  1659. default:
  1660. used = handleKeyUpOrDown (true);
  1661. {
  1662. MSG msg;
  1663. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  1664. {
  1665. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  1666. // manually generate the key-press event that matches this key-down.
  1667. const UINT keyChar = MapVirtualKey ((UINT) key, 2);
  1668. const UINT scanCode = MapVirtualKey ((UINT) key, 0);
  1669. BYTE keyState[256];
  1670. GetKeyboardState (keyState);
  1671. WCHAR text[16] = { 0 };
  1672. if (ToUnicode ((UINT) key, scanCode, keyState, text, 8, 0) != 1)
  1673. text[0] = 0;
  1674. used = handleKeyPress ((int) LOWORD (keyChar), (juce_wchar) text[0]) || used;
  1675. }
  1676. }
  1677. break;
  1678. }
  1679. return used || (Component::getCurrentlyModalComponent() != nullptr);
  1680. }
  1681. bool doKeyChar (int key, const LPARAM flags)
  1682. {
  1683. updateKeyModifiers();
  1684. juce_wchar textChar = (juce_wchar) key;
  1685. const int virtualScanCode = (flags >> 16) & 0xff;
  1686. if (key >= '0' && key <= '9')
  1687. {
  1688. switch (virtualScanCode) // check for a numeric keypad scan-code
  1689. {
  1690. case 0x52:
  1691. case 0x4f:
  1692. case 0x50:
  1693. case 0x51:
  1694. case 0x4b:
  1695. case 0x4c:
  1696. case 0x4d:
  1697. case 0x47:
  1698. case 0x48:
  1699. case 0x49:
  1700. key = (key - '0') + KeyPress::numberPad0;
  1701. break;
  1702. default:
  1703. break;
  1704. }
  1705. }
  1706. else
  1707. {
  1708. // convert the scan code to an unmodified character code..
  1709. const UINT virtualKey = MapVirtualKey ((UINT) virtualScanCode, 1);
  1710. UINT keyChar = MapVirtualKey (virtualKey, 2);
  1711. keyChar = LOWORD (keyChar);
  1712. if (keyChar != 0)
  1713. key = (int) keyChar;
  1714. // avoid sending junk text characters for some control-key combinations
  1715. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  1716. textChar = 0;
  1717. }
  1718. return handleKeyPress (key, textChar);
  1719. }
  1720. void forwardMessageToParent (UINT message, WPARAM wParam, LPARAM lParam) const
  1721. {
  1722. if (HWND parentH = GetParent (hwnd))
  1723. PostMessage (parentH, message, wParam, lParam);
  1724. }
  1725. bool doAppCommand (const LPARAM lParam)
  1726. {
  1727. int key = 0;
  1728. switch (GET_APPCOMMAND_LPARAM (lParam))
  1729. {
  1730. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  1731. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  1732. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  1733. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  1734. default: break;
  1735. }
  1736. if (key != 0)
  1737. {
  1738. updateKeyModifiers();
  1739. if (hwnd == GetActiveWindow())
  1740. {
  1741. handleKeyPress (key, 0);
  1742. return true;
  1743. }
  1744. }
  1745. return false;
  1746. }
  1747. bool isConstrainedNativeWindow() const
  1748. {
  1749. return constrainer != nullptr
  1750. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
  1751. && ! isKioskMode();
  1752. }
  1753. Rectangle<int> getCurrentScaledBounds (float scale) const
  1754. {
  1755. return ScalingHelpers::unscaledScreenPosToScaled (scale, windowBorder.addedTo (ScalingHelpers::scaledScreenPosToUnscaled (scale, component.getBounds())));
  1756. }
  1757. LRESULT handleSizeConstraining (RECT& r, const WPARAM wParam)
  1758. {
  1759. if (isConstrainedNativeWindow())
  1760. {
  1761. const float scale = getComponent().getDesktopScaleFactor();
  1762. Rectangle<int> pos (ScalingHelpers::unscaledScreenPosToScaled (scale, rectangleFromRECT (r)));
  1763. const Rectangle<int> current (getCurrentScaledBounds (scale));
  1764. constrainer->checkBounds (pos, current,
  1765. Desktop::getInstance().getDisplays().getTotalBounds (true),
  1766. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  1767. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  1768. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  1769. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  1770. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  1771. r.left = pos.getX();
  1772. r.top = pos.getY();
  1773. r.right = pos.getRight();
  1774. r.bottom = pos.getBottom();
  1775. }
  1776. return TRUE;
  1777. }
  1778. LRESULT handlePositionChanging (WINDOWPOS& wp)
  1779. {
  1780. if (isConstrainedNativeWindow())
  1781. {
  1782. if ((wp.flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  1783. && ! Component::isMouseButtonDownAnywhere())
  1784. {
  1785. const float scale = getComponent().getDesktopScaleFactor();
  1786. Rectangle<int> pos (ScalingHelpers::unscaledScreenPosToScaled (scale, Rectangle<int> (wp.x, wp.y, wp.cx, wp.cy)));
  1787. const Rectangle<int> current (getCurrentScaledBounds (scale));
  1788. constrainer->checkBounds (pos, current,
  1789. Desktop::getInstance().getDisplays().getTotalBounds (true),
  1790. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  1791. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  1792. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  1793. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  1794. pos = ScalingHelpers::scaledScreenPosToUnscaled (scale, pos);
  1795. wp.x = pos.getX();
  1796. wp.y = pos.getY();
  1797. wp.cx = pos.getWidth();
  1798. wp.cy = pos.getHeight();
  1799. }
  1800. }
  1801. if (((wp.flags & SWP_SHOWWINDOW) != 0 && ! component.isVisible()))
  1802. component.setVisible (true);
  1803. else if (((wp.flags & SWP_HIDEWINDOW) != 0 && component.isVisible()))
  1804. component.setVisible (false);
  1805. return 0;
  1806. }
  1807. bool handlePositionChanged()
  1808. {
  1809. const Point<float> pos (getCurrentMousePos());
  1810. if (contains (pos.roundToInt(), false))
  1811. {
  1812. doMouseEvent (pos);
  1813. if (! isValidPeer (this))
  1814. return true;
  1815. }
  1816. handleMovedOrResized();
  1817. return ! dontRepaint; // to allow non-accelerated openGL windows to draw themselves correctly..
  1818. }
  1819. void handleAppActivation (const WPARAM wParam)
  1820. {
  1821. modifiersAtLastCallback = -1;
  1822. updateKeyModifiers();
  1823. if (isMinimised())
  1824. {
  1825. component.repaint();
  1826. handleMovedOrResized();
  1827. if (! isValidPeer (this))
  1828. return;
  1829. }
  1830. Component* underMouse = component.getComponentAt (component.getMouseXYRelative());
  1831. if (underMouse == nullptr)
  1832. underMouse = &component;
  1833. if (underMouse->isCurrentlyBlockedByAnotherModalComponent())
  1834. {
  1835. if (LOWORD (wParam) == WA_CLICKACTIVE)
  1836. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  1837. else
  1838. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1839. }
  1840. else
  1841. {
  1842. handleBroughtToFront();
  1843. }
  1844. }
  1845. void handleLeftClickInNCArea (WPARAM wParam)
  1846. {
  1847. if (! sendInputAttemptWhenModalMessage())
  1848. {
  1849. switch (wParam)
  1850. {
  1851. case HTBOTTOM:
  1852. case HTBOTTOMLEFT:
  1853. case HTBOTTOMRIGHT:
  1854. case HTGROWBOX:
  1855. case HTLEFT:
  1856. case HTRIGHT:
  1857. case HTTOP:
  1858. case HTTOPLEFT:
  1859. case HTTOPRIGHT:
  1860. if (isConstrainedNativeWindow())
  1861. {
  1862. constrainerIsResizing = true;
  1863. constrainer->resizeStart();
  1864. }
  1865. break;
  1866. default:
  1867. break;
  1868. }
  1869. }
  1870. }
  1871. void initialiseSysMenu (HMENU menu) const
  1872. {
  1873. if (! hasTitleBar())
  1874. {
  1875. if (isFullScreen())
  1876. {
  1877. EnableMenuItem (menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  1878. EnableMenuItem (menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  1879. }
  1880. else if (! isMinimised())
  1881. {
  1882. EnableMenuItem (menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  1883. }
  1884. }
  1885. }
  1886. void doSettingChange()
  1887. {
  1888. Desktop& desktop = Desktop::getInstance();
  1889. const_cast <Desktop::Displays&> (desktop.getDisplays()).refresh();
  1890. if (fullScreen && ! isMinimised())
  1891. {
  1892. const Desktop::Displays::Display& display
  1893. = desktop.getDisplays().getDisplayContaining (component.getScreenBounds().getCentre());
  1894. setWindowPos (hwnd, display.userArea * display.scale,
  1895. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  1896. }
  1897. }
  1898. void handleDPIChange() // happens when a window moves to a screen with a different DPI.
  1899. {
  1900. }
  1901. //==============================================================================
  1902. public:
  1903. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1904. {
  1905. if (HWNDComponentPeer* const peer = getOwnerOfWindow (h))
  1906. {
  1907. jassert (isValidPeer (peer));
  1908. return peer->peerWindowProc (h, message, wParam, lParam);
  1909. }
  1910. return DefWindowProcW (h, message, wParam, lParam);
  1911. }
  1912. private:
  1913. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  1914. {
  1915. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  1916. return callback (userData);
  1917. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  1918. }
  1919. static Point<float> getPointFromLParam (LPARAM lParam) noexcept
  1920. {
  1921. return Point<float> (static_cast<float> (GET_X_LPARAM (lParam)),
  1922. static_cast<float> (GET_Y_LPARAM (lParam)));
  1923. }
  1924. static Point<float> getCurrentMousePosGlobal() noexcept
  1925. {
  1926. return getPointFromLParam (GetMessagePos());
  1927. }
  1928. Point<float> getCurrentMousePos() noexcept
  1929. {
  1930. return globalToLocal (getCurrentMousePosGlobal());
  1931. }
  1932. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  1933. {
  1934. switch (message)
  1935. {
  1936. //==============================================================================
  1937. case WM_NCHITTEST:
  1938. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  1939. return HTTRANSPARENT;
  1940. if (! hasTitleBar())
  1941. return HTCLIENT;
  1942. break;
  1943. //==============================================================================
  1944. case WM_PAINT:
  1945. handlePaintMessage();
  1946. return 0;
  1947. case WM_NCPAINT:
  1948. if (wParam != 1) // (1 = a repaint of the entire NC region)
  1949. handlePaintMessage(); // this must be done, even with native titlebars, or there are rendering artifacts.
  1950. if (hasTitleBar())
  1951. break; // let the DefWindowProc handle drawing the frame.
  1952. return 0;
  1953. case WM_ERASEBKGND:
  1954. case WM_NCCALCSIZE:
  1955. if (hasTitleBar())
  1956. break;
  1957. return 1;
  1958. //==============================================================================
  1959. case WM_MOUSEMOVE: doMouseMove (getPointFromLParam (lParam)); return 0;
  1960. case WM_MOUSELEAVE: doMouseExit(); return 0;
  1961. case WM_LBUTTONDOWN:
  1962. case WM_MBUTTONDOWN:
  1963. case WM_RBUTTONDOWN: doMouseDown (getPointFromLParam (lParam), wParam); return 0;
  1964. case WM_LBUTTONUP:
  1965. case WM_MBUTTONUP:
  1966. case WM_RBUTTONUP: doMouseUp (getPointFromLParam (lParam), wParam); return 0;
  1967. case 0x020A: /* WM_MOUSEWHEEL */ doMouseWheel (wParam, true); return 0;
  1968. case 0x020E: /* WM_MOUSEHWHEEL */ doMouseWheel (wParam, false); return 0;
  1969. case WM_CAPTURECHANGED: doCaptureChanged(); return 0;
  1970. case WM_NCMOUSEMOVE:
  1971. if (hasTitleBar())
  1972. break;
  1973. return 0;
  1974. case WM_TOUCH:
  1975. if (getTouchInputInfo != nullptr)
  1976. return doTouchEvent ((int) wParam, (HTOUCHINPUT) lParam);
  1977. break;
  1978. case 0x119: /* WM_GESTURE */
  1979. if (doGestureEvent (lParam))
  1980. return 0;
  1981. break;
  1982. //==============================================================================
  1983. case WM_SIZING: return handleSizeConstraining (*(RECT*) lParam, wParam);
  1984. case WM_WINDOWPOSCHANGING: return handlePositionChanging (*(WINDOWPOS*) lParam);
  1985. case WM_WINDOWPOSCHANGED:
  1986. if (handlePositionChanged())
  1987. return 0;
  1988. break;
  1989. //==============================================================================
  1990. case WM_KEYDOWN:
  1991. case WM_SYSKEYDOWN:
  1992. if (doKeyDown (wParam))
  1993. return 0;
  1994. forwardMessageToParent (message, wParam, lParam);
  1995. break;
  1996. case WM_KEYUP:
  1997. case WM_SYSKEYUP:
  1998. if (doKeyUp (wParam))
  1999. return 0;
  2000. forwardMessageToParent (message, wParam, lParam);
  2001. break;
  2002. case WM_CHAR:
  2003. if (doKeyChar ((int) wParam, lParam))
  2004. return 0;
  2005. forwardMessageToParent (message, wParam, lParam);
  2006. break;
  2007. case WM_APPCOMMAND:
  2008. if (doAppCommand (lParam))
  2009. return TRUE;
  2010. break;
  2011. case WM_MENUCHAR: // triggered when alt+something is pressed
  2012. return MNC_CLOSE << 16; // (avoids making the default system beep)
  2013. //==============================================================================
  2014. case WM_SETFOCUS:
  2015. updateKeyModifiers();
  2016. handleFocusGain();
  2017. break;
  2018. case WM_KILLFOCUS:
  2019. if (hasCreatedCaret)
  2020. {
  2021. hasCreatedCaret = false;
  2022. DestroyCaret();
  2023. }
  2024. handleFocusLoss();
  2025. break;
  2026. case WM_ACTIVATEAPP:
  2027. // Windows does weird things to process priority when you swap apps,
  2028. // so this forces an update when the app is brought to the front
  2029. if (wParam != FALSE)
  2030. juce_repeatLastProcessPriority();
  2031. else
  2032. Desktop::getInstance().setKioskModeComponent (nullptr); // turn kiosk mode off if we lose focus
  2033. juce_checkCurrentlyFocusedTopLevelWindow();
  2034. modifiersAtLastCallback = -1;
  2035. return 0;
  2036. case WM_ACTIVATE:
  2037. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  2038. {
  2039. handleAppActivation (wParam);
  2040. return 0;
  2041. }
  2042. break;
  2043. case WM_NCACTIVATE:
  2044. // while a temporary window is being shown, prevent Windows from deactivating the
  2045. // title bars of our main windows.
  2046. if (wParam == 0 && ! shouldDeactivateTitleBar)
  2047. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  2048. break;
  2049. case WM_MOUSEACTIVATE:
  2050. if (! component.getMouseClickGrabsKeyboardFocus())
  2051. return MA_NOACTIVATE;
  2052. break;
  2053. case WM_SHOWWINDOW:
  2054. if (wParam != 0)
  2055. {
  2056. component.setVisible (true);
  2057. handleBroughtToFront();
  2058. }
  2059. break;
  2060. case WM_CLOSE:
  2061. if (! component.isCurrentlyBlockedByAnotherModalComponent())
  2062. handleUserClosingWindow();
  2063. return 0;
  2064. case WM_QUERYENDSESSION:
  2065. if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
  2066. {
  2067. app->systemRequestedQuit();
  2068. return MessageManager::getInstance()->hasStopMessageBeenSent();
  2069. }
  2070. return TRUE;
  2071. case WM_SYNCPAINT:
  2072. return 0;
  2073. case WM_DISPLAYCHANGE:
  2074. InvalidateRect (h, 0, 0);
  2075. // intentional fall-through...
  2076. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  2077. doSettingChange();
  2078. break;
  2079. case 0x2e0: // WM_DPICHANGED
  2080. handleDPIChange();
  2081. break;
  2082. case WM_INITMENU:
  2083. initialiseSysMenu ((HMENU) wParam);
  2084. break;
  2085. case WM_SYSCOMMAND:
  2086. switch (wParam & 0xfff0)
  2087. {
  2088. case SC_CLOSE:
  2089. if (sendInputAttemptWhenModalMessage())
  2090. return 0;
  2091. if (hasTitleBar())
  2092. {
  2093. PostMessage (h, WM_CLOSE, 0, 0);
  2094. return 0;
  2095. }
  2096. break;
  2097. case SC_KEYMENU:
  2098. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  2099. // situations that can arise if a modal loop is started from an alt-key keypress).
  2100. if (hasTitleBar() && h == GetCapture())
  2101. ReleaseCapture();
  2102. break;
  2103. case SC_MAXIMIZE:
  2104. if (! sendInputAttemptWhenModalMessage())
  2105. setFullScreen (true);
  2106. return 0;
  2107. case SC_MINIMIZE:
  2108. if (sendInputAttemptWhenModalMessage())
  2109. return 0;
  2110. if (! hasTitleBar())
  2111. {
  2112. setMinimised (true);
  2113. return 0;
  2114. }
  2115. break;
  2116. case SC_RESTORE:
  2117. if (sendInputAttemptWhenModalMessage())
  2118. return 0;
  2119. if (hasTitleBar())
  2120. {
  2121. if (isFullScreen())
  2122. {
  2123. setFullScreen (false);
  2124. return 0;
  2125. }
  2126. }
  2127. else
  2128. {
  2129. if (isMinimised())
  2130. setMinimised (false);
  2131. else if (isFullScreen())
  2132. setFullScreen (false);
  2133. return 0;
  2134. }
  2135. break;
  2136. }
  2137. break;
  2138. case WM_NCLBUTTONDOWN:
  2139. handleLeftClickInNCArea (wParam);
  2140. break;
  2141. case WM_NCRBUTTONDOWN:
  2142. case WM_NCMBUTTONDOWN:
  2143. sendInputAttemptWhenModalMessage();
  2144. break;
  2145. case WM_IME_SETCONTEXT:
  2146. imeHandler.handleSetContext (h, wParam == TRUE);
  2147. lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  2148. break;
  2149. case WM_IME_STARTCOMPOSITION: imeHandler.handleStartComposition (*this); return 0;
  2150. case WM_IME_ENDCOMPOSITION: imeHandler.handleEndComposition (*this, h); break;
  2151. case WM_IME_COMPOSITION: imeHandler.handleComposition (*this, h, lParam); return 0;
  2152. case WM_GETDLGCODE:
  2153. return DLGC_WANTALLKEYS;
  2154. default:
  2155. break;
  2156. }
  2157. return DefWindowProcW (h, message, wParam, lParam);
  2158. }
  2159. bool sendInputAttemptWhenModalMessage()
  2160. {
  2161. if (component.isCurrentlyBlockedByAnotherModalComponent())
  2162. {
  2163. if (Component* const current = Component::getCurrentlyModalComponent())
  2164. current->inputAttemptWhenModal();
  2165. return true;
  2166. }
  2167. return false;
  2168. }
  2169. //==============================================================================
  2170. class IMEHandler
  2171. {
  2172. public:
  2173. IMEHandler()
  2174. {
  2175. reset();
  2176. }
  2177. void handleSetContext (HWND hWnd, const bool windowIsActive)
  2178. {
  2179. if (compositionInProgress && ! windowIsActive)
  2180. {
  2181. compositionInProgress = false;
  2182. if (HIMC hImc = ImmGetContext (hWnd))
  2183. {
  2184. ImmNotifyIME (hImc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
  2185. ImmReleaseContext (hWnd, hImc);
  2186. }
  2187. }
  2188. }
  2189. void handleStartComposition (ComponentPeer& owner)
  2190. {
  2191. reset();
  2192. if (TextInputTarget* const target = owner.findCurrentTextInputTarget())
  2193. target->insertTextAtCaret (String::empty);
  2194. }
  2195. void handleEndComposition (ComponentPeer& owner, HWND hWnd)
  2196. {
  2197. if (compositionInProgress)
  2198. {
  2199. // If this occurs, the user has cancelled the composition, so clear their changes..
  2200. if (TextInputTarget* const target = owner.findCurrentTextInputTarget())
  2201. {
  2202. target->setHighlightedRegion (compositionRange);
  2203. target->insertTextAtCaret (String::empty);
  2204. compositionRange.setLength (0);
  2205. target->setHighlightedRegion (Range<int>::emptyRange (compositionRange.getEnd()));
  2206. target->setTemporaryUnderlining (Array<Range<int> >());
  2207. }
  2208. if (HIMC hImc = ImmGetContext (hWnd))
  2209. {
  2210. ImmNotifyIME (hImc, NI_CLOSECANDIDATE, 0, 0);
  2211. ImmReleaseContext (hWnd, hImc);
  2212. }
  2213. }
  2214. reset();
  2215. }
  2216. void handleComposition (ComponentPeer& owner, HWND hWnd, const LPARAM lParam)
  2217. {
  2218. TextInputTarget* const target = owner.findCurrentTextInputTarget();
  2219. HIMC hImc = ImmGetContext (hWnd);
  2220. if (target == nullptr || hImc == 0)
  2221. return;
  2222. if (compositionRange.getStart() < 0)
  2223. compositionRange = Range<int>::emptyRange (target->getHighlightedRegion().getStart());
  2224. if ((lParam & GCS_RESULTSTR) != 0) // (composition has finished)
  2225. {
  2226. replaceCurrentSelection (target, getCompositionString (hImc, GCS_RESULTSTR),
  2227. Range<int>::emptyRange (-1));
  2228. reset();
  2229. target->setTemporaryUnderlining (Array<Range<int> >());
  2230. }
  2231. else if ((lParam & GCS_COMPSTR) != 0) // (composition is still in-progress)
  2232. {
  2233. replaceCurrentSelection (target, getCompositionString (hImc, GCS_COMPSTR),
  2234. getCompositionSelection (hImc, lParam));
  2235. target->setTemporaryUnderlining (getCompositionUnderlines (hImc, lParam));
  2236. compositionInProgress = true;
  2237. }
  2238. moveCandidateWindowToLeftAlignWithSelection (hImc, owner, target);
  2239. ImmReleaseContext (hWnd, hImc);
  2240. }
  2241. private:
  2242. //==============================================================================
  2243. Range<int> compositionRange; // The range being modified in the TextInputTarget
  2244. bool compositionInProgress;
  2245. //==============================================================================
  2246. void reset()
  2247. {
  2248. compositionRange = Range<int>::emptyRange (-1);
  2249. compositionInProgress = false;
  2250. }
  2251. String getCompositionString (HIMC hImc, const DWORD type) const
  2252. {
  2253. jassert (hImc != 0);
  2254. const int stringSizeBytes = ImmGetCompositionString (hImc, type, 0, 0);
  2255. if (stringSizeBytes > 0)
  2256. {
  2257. HeapBlock<TCHAR> buffer;
  2258. buffer.calloc (stringSizeBytes / sizeof (TCHAR) + 1);
  2259. ImmGetCompositionString (hImc, type, buffer, (DWORD) stringSizeBytes);
  2260. return String (buffer);
  2261. }
  2262. return String::empty;
  2263. }
  2264. int getCompositionCaretPos (HIMC hImc, LPARAM lParam, const String& currentIMEString) const
  2265. {
  2266. jassert (hImc != 0);
  2267. if ((lParam & CS_NOMOVECARET) != 0)
  2268. return compositionRange.getStart();
  2269. if ((lParam & GCS_CURSORPOS) != 0)
  2270. {
  2271. const int localCaretPos = ImmGetCompositionString (hImc, GCS_CURSORPOS, 0, 0);
  2272. return compositionRange.getStart() + jmax (0, localCaretPos);
  2273. }
  2274. return compositionRange.getStart() + currentIMEString.length();
  2275. }
  2276. // Get selected/highlighted range while doing composition:
  2277. // returned range is relative to beginning of TextInputTarget, not composition string
  2278. Range<int> getCompositionSelection (HIMC hImc, LPARAM lParam) const
  2279. {
  2280. jassert (hImc != 0);
  2281. int selectionStart = 0;
  2282. int selectionEnd = 0;
  2283. if ((lParam & GCS_COMPATTR) != 0)
  2284. {
  2285. // Get size of attributes array:
  2286. const int attributeSizeBytes = ImmGetCompositionString (hImc, GCS_COMPATTR, 0, 0);
  2287. if (attributeSizeBytes > 0)
  2288. {
  2289. // Get attributes (8 bit flag per character):
  2290. HeapBlock<char> attributes ((size_t) attributeSizeBytes);
  2291. ImmGetCompositionString (hImc, GCS_COMPATTR, attributes, (DWORD) attributeSizeBytes);
  2292. selectionStart = 0;
  2293. for (selectionStart = 0; selectionStart < attributeSizeBytes; ++selectionStart)
  2294. if (attributes[selectionStart] == ATTR_TARGET_CONVERTED || attributes[selectionStart] == ATTR_TARGET_NOTCONVERTED)
  2295. break;
  2296. for (selectionEnd = selectionStart; selectionEnd < attributeSizeBytes; ++selectionEnd)
  2297. if (attributes [selectionEnd] != ATTR_TARGET_CONVERTED && attributes[selectionEnd] != ATTR_TARGET_NOTCONVERTED)
  2298. break;
  2299. }
  2300. }
  2301. return Range<int> (selectionStart, selectionEnd) + compositionRange.getStart();
  2302. }
  2303. void replaceCurrentSelection (TextInputTarget* const target, const String& newContent, Range<int> newSelection)
  2304. {
  2305. if (compositionInProgress)
  2306. target->setHighlightedRegion (compositionRange);
  2307. target->insertTextAtCaret (newContent);
  2308. compositionRange.setLength (newContent.length());
  2309. if (newSelection.getStart() < 0)
  2310. newSelection = Range<int>::emptyRange (compositionRange.getEnd());
  2311. target->setHighlightedRegion (newSelection);
  2312. }
  2313. Array<Range<int> > getCompositionUnderlines (HIMC hImc, LPARAM lParam) const
  2314. {
  2315. Array<Range<int> > result;
  2316. if (hImc != 0 && (lParam & GCS_COMPCLAUSE) != 0)
  2317. {
  2318. const int clauseDataSizeBytes = ImmGetCompositionString (hImc, GCS_COMPCLAUSE, 0, 0);
  2319. if (clauseDataSizeBytes > 0)
  2320. {
  2321. const size_t numItems = clauseDataSizeBytes / sizeof (uint32);
  2322. HeapBlock<uint32> clauseData (numItems);
  2323. if (ImmGetCompositionString (hImc, GCS_COMPCLAUSE, clauseData, (DWORD) clauseDataSizeBytes) > 0)
  2324. for (size_t i = 0; i + 1 < numItems; ++i)
  2325. result.add (Range<int> ((int) clauseData [i], (int) clauseData [i + 1]) + compositionRange.getStart());
  2326. }
  2327. }
  2328. return result;
  2329. }
  2330. void moveCandidateWindowToLeftAlignWithSelection (HIMC hImc, ComponentPeer& peer, TextInputTarget* target) const
  2331. {
  2332. if (Component* const targetComp = dynamic_cast <Component*> (target))
  2333. {
  2334. const Rectangle<int> area (peer.getComponent().getLocalArea (targetComp, target->getCaretRectangle()));
  2335. CANDIDATEFORM pos = { 0, CFS_CANDIDATEPOS, { area.getX(), area.getBottom() }, { 0, 0, 0, 0 } };
  2336. ImmSetCandidateWindow (hImc, &pos);
  2337. }
  2338. }
  2339. JUCE_DECLARE_NON_COPYABLE (IMEHandler)
  2340. };
  2341. IMEHandler imeHandler;
  2342. //==============================================================================
  2343. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HWNDComponentPeer)
  2344. };
  2345. ModifierKeys HWNDComponentPeer::currentModifiers;
  2346. ModifierKeys HWNDComponentPeer::modifiersAtLastCallback;
  2347. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  2348. {
  2349. return new HWNDComponentPeer (*this, styleFlags,
  2350. (HWND) nativeWindowToAttachTo, false);
  2351. }
  2352. ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component* component, void* parent)
  2353. {
  2354. jassert (component != nullptr);
  2355. return new HWNDComponentPeer (*component, ComponentPeer::windowIgnoresMouseClicks,
  2356. (HWND) parent, true);
  2357. }
  2358. juce_ImplementSingleton_SingleThreaded (HWNDComponentPeer::WindowClassHolder);
  2359. //==============================================================================
  2360. void ModifierKeys::updateCurrentModifiers() noexcept
  2361. {
  2362. currentModifiers = HWNDComponentPeer::currentModifiers;
  2363. }
  2364. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2365. {
  2366. HWNDComponentPeer::updateKeyModifiers();
  2367. int mouseMods = 0;
  2368. if (HWNDComponentPeer::isKeyDown (VK_LBUTTON)) mouseMods |= ModifierKeys::leftButtonModifier;
  2369. if (HWNDComponentPeer::isKeyDown (VK_RBUTTON)) mouseMods |= ModifierKeys::rightButtonModifier;
  2370. if (HWNDComponentPeer::isKeyDown (VK_MBUTTON)) mouseMods |= ModifierKeys::middleButtonModifier;
  2371. HWNDComponentPeer::currentModifiers
  2372. = HWNDComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2373. return HWNDComponentPeer::currentModifiers;
  2374. }
  2375. //==============================================================================
  2376. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  2377. {
  2378. SHORT k = (SHORT) keyCode;
  2379. if ((keyCode & extendedKeyModifier) == 0
  2380. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  2381. k += (SHORT) 'A' - (SHORT) 'a';
  2382. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  2383. (SHORT) '+', VK_OEM_PLUS,
  2384. (SHORT) '-', VK_OEM_MINUS,
  2385. (SHORT) '.', VK_OEM_PERIOD,
  2386. (SHORT) ';', VK_OEM_1,
  2387. (SHORT) ':', VK_OEM_1,
  2388. (SHORT) '/', VK_OEM_2,
  2389. (SHORT) '?', VK_OEM_2,
  2390. (SHORT) '[', VK_OEM_4,
  2391. (SHORT) ']', VK_OEM_6 };
  2392. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  2393. if (k == translatedValues [i])
  2394. k = translatedValues [i + 1];
  2395. return HWNDComponentPeer::isKeyDown (k);
  2396. }
  2397. #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client
  2398. bool offerKeyMessageToJUCEWindow (MSG& m) { return HWNDComponentPeer::offerKeyMessageToJUCEWindow (m); }
  2399. #endif
  2400. //==============================================================================
  2401. bool JUCE_CALLTYPE Process::isForegroundProcess()
  2402. {
  2403. HWND fg = GetForegroundWindow();
  2404. if (fg == 0)
  2405. return true;
  2406. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  2407. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  2408. // have to see if any of our windows are children of the foreground window
  2409. fg = GetAncestor (fg, GA_ROOT);
  2410. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  2411. if (HWNDComponentPeer* const wp = dynamic_cast <HWNDComponentPeer*> (ComponentPeer::getPeer (i)))
  2412. if (wp->isInside (fg))
  2413. return true;
  2414. return false;
  2415. }
  2416. // N/A on Windows as far as I know.
  2417. void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2418. void JUCE_CALLTYPE Process::hide() {}
  2419. //==============================================================================
  2420. static BOOL CALLBACK enumAlwaysOnTopWindows (HWND hwnd, LPARAM lParam)
  2421. {
  2422. if (IsWindowVisible (hwnd))
  2423. {
  2424. DWORD processID = 0;
  2425. GetWindowThreadProcessId (hwnd, &processID);
  2426. if (processID == GetCurrentProcessId())
  2427. {
  2428. WINDOWINFO info;
  2429. if (GetWindowInfo (hwnd, &info)
  2430. && (info.dwExStyle & WS_EX_TOPMOST) != 0)
  2431. {
  2432. *reinterpret_cast <bool*> (lParam) = true;
  2433. return FALSE;
  2434. }
  2435. }
  2436. }
  2437. return TRUE;
  2438. }
  2439. bool juce_areThereAnyAlwaysOnTopWindows()
  2440. {
  2441. bool anyAlwaysOnTopFound = false;
  2442. EnumWindows (&enumAlwaysOnTopWindows, (LPARAM) &anyAlwaysOnTopFound);
  2443. return anyAlwaysOnTopFound;
  2444. }
  2445. //==============================================================================
  2446. class WindowsMessageBox : public AsyncUpdater
  2447. {
  2448. public:
  2449. WindowsMessageBox (AlertWindow::AlertIconType iconType,
  2450. const String& boxTitle, const String& m,
  2451. Component* associatedComponent, UINT extraFlags,
  2452. ModalComponentManager::Callback* cb, const bool runAsync)
  2453. : flags (extraFlags | getMessageBoxFlags (iconType)),
  2454. owner (getWindowForMessageBox (associatedComponent)),
  2455. title (boxTitle), message (m), callback (cb)
  2456. {
  2457. if (runAsync)
  2458. triggerAsyncUpdate();
  2459. }
  2460. int getResult() const
  2461. {
  2462. const int r = MessageBox (owner, message.toWideCharPointer(), title.toWideCharPointer(), flags);
  2463. return (r == IDYES || r == IDOK) ? 1 : (r == IDNO ? 2 : 0);
  2464. }
  2465. void handleAsyncUpdate() override
  2466. {
  2467. const int result = getResult();
  2468. if (callback != nullptr)
  2469. callback->modalStateFinished (result);
  2470. delete this;
  2471. }
  2472. private:
  2473. UINT flags;
  2474. HWND owner;
  2475. String title, message;
  2476. ScopedPointer<ModalComponentManager::Callback> callback;
  2477. static UINT getMessageBoxFlags (AlertWindow::AlertIconType iconType) noexcept
  2478. {
  2479. UINT flags = MB_TASKMODAL | MB_SETFOREGROUND;
  2480. switch (iconType)
  2481. {
  2482. case AlertWindow::QuestionIcon: flags |= MB_ICONQUESTION; break;
  2483. case AlertWindow::WarningIcon: flags |= MB_ICONWARNING; break;
  2484. case AlertWindow::InfoIcon: flags |= MB_ICONINFORMATION; break;
  2485. default: break;
  2486. }
  2487. return flags;
  2488. }
  2489. static HWND getWindowForMessageBox (Component* associatedComponent)
  2490. {
  2491. return associatedComponent != nullptr ? (HWND) associatedComponent->getWindowHandle() : 0;
  2492. }
  2493. };
  2494. #if JUCE_MODAL_LOOPS_PERMITTED
  2495. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  2496. const String& title, const String& message,
  2497. Component* associatedComponent)
  2498. {
  2499. WindowsMessageBox box (iconType, title, message, associatedComponent, MB_OK, 0, false);
  2500. (void) box.getResult();
  2501. }
  2502. #endif
  2503. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  2504. const String& title, const String& message,
  2505. Component* associatedComponent,
  2506. ModalComponentManager::Callback* callback)
  2507. {
  2508. new WindowsMessageBox (iconType, title, message, associatedComponent, MB_OK, callback, true);
  2509. }
  2510. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  2511. const String& title, const String& message,
  2512. Component* associatedComponent,
  2513. ModalComponentManager::Callback* callback)
  2514. {
  2515. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  2516. MB_OKCANCEL, callback, callback != nullptr));
  2517. if (callback == nullptr)
  2518. return mb->getResult() != 0;
  2519. mb.release();
  2520. return false;
  2521. }
  2522. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  2523. const String& title, const String& message,
  2524. Component* associatedComponent,
  2525. ModalComponentManager::Callback* callback)
  2526. {
  2527. ScopedPointer<WindowsMessageBox> mb (new WindowsMessageBox (iconType, title, message, associatedComponent,
  2528. MB_YESNOCANCEL, callback, callback != nullptr));
  2529. if (callback == nullptr)
  2530. return mb->getResult();
  2531. mb.release();
  2532. return 0;
  2533. }
  2534. //==============================================================================
  2535. bool MouseInputSource::SourceList::addSource()
  2536. {
  2537. const int numSources = sources.size();
  2538. if (numSources == 0 || canUseMultiTouch())
  2539. {
  2540. addSource (numSources, numSources == 0);
  2541. return true;
  2542. }
  2543. return false;
  2544. }
  2545. Point<float> MouseInputSource::getCurrentRawMousePosition()
  2546. {
  2547. POINT mousePos;
  2548. GetCursorPos (&mousePos);
  2549. return Point<float> ((float) mousePos.x, (float) mousePos.y);
  2550. }
  2551. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  2552. {
  2553. SetCursorPos (roundToInt (newPosition.x),
  2554. roundToInt (newPosition.y));
  2555. }
  2556. //==============================================================================
  2557. class ScreenSaverDefeater : public Timer
  2558. {
  2559. public:
  2560. ScreenSaverDefeater()
  2561. {
  2562. startTimer (10000);
  2563. timerCallback();
  2564. }
  2565. void timerCallback() override
  2566. {
  2567. if (Process::isForegroundProcess())
  2568. {
  2569. INPUT input = { 0 };
  2570. input.type = INPUT_MOUSE;
  2571. input.mi.mouseData = MOUSEEVENTF_MOVE;
  2572. SendInput (1, &input, sizeof (INPUT));
  2573. }
  2574. }
  2575. };
  2576. static ScopedPointer<ScreenSaverDefeater> screenSaverDefeater;
  2577. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  2578. {
  2579. if (isEnabled)
  2580. screenSaverDefeater = nullptr;
  2581. else if (screenSaverDefeater == nullptr)
  2582. screenSaverDefeater = new ScreenSaverDefeater();
  2583. }
  2584. bool Desktop::isScreenSaverEnabled()
  2585. {
  2586. return screenSaverDefeater == nullptr;
  2587. }
  2588. //==============================================================================
  2589. void LookAndFeel::playAlertSound()
  2590. {
  2591. MessageBeep (MB_OK);
  2592. }
  2593. //==============================================================================
  2594. void SystemClipboard::copyTextToClipboard (const String& text)
  2595. {
  2596. if (OpenClipboard (0) != 0)
  2597. {
  2598. if (EmptyClipboard() != 0)
  2599. {
  2600. const size_t bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  2601. if (bytesNeeded > 0)
  2602. {
  2603. if (HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR)))
  2604. {
  2605. if (WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH)))
  2606. {
  2607. text.copyToUTF16 (data, bytesNeeded);
  2608. GlobalUnlock (bufH);
  2609. SetClipboardData (CF_UNICODETEXT, bufH);
  2610. }
  2611. }
  2612. }
  2613. }
  2614. CloseClipboard();
  2615. }
  2616. }
  2617. String SystemClipboard::getTextFromClipboard()
  2618. {
  2619. String result;
  2620. if (OpenClipboard (0) != 0)
  2621. {
  2622. if (HANDLE bufH = GetClipboardData (CF_UNICODETEXT))
  2623. {
  2624. if (const WCHAR* const data = (const WCHAR*) GlobalLock (bufH))
  2625. {
  2626. result = String (data, (size_t) (GlobalSize (bufH) / sizeof (WCHAR)));
  2627. GlobalUnlock (bufH);
  2628. }
  2629. }
  2630. CloseClipboard();
  2631. }
  2632. return result;
  2633. }
  2634. //==============================================================================
  2635. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  2636. {
  2637. if (TopLevelWindow* tlw = dynamic_cast<TopLevelWindow*> (kioskModeComponent))
  2638. tlw->setUsingNativeTitleBar (! enableOrDisable);
  2639. if (enableOrDisable)
  2640. kioskModeComponent->setBounds (getDisplays().getMainDisplay().totalArea);
  2641. }
  2642. //==============================================================================
  2643. struct MonitorInfo
  2644. {
  2645. MonitorInfo (Rectangle<int> rect, bool main, double d) noexcept
  2646. : bounds (rect), dpi (d), isMain (main) {}
  2647. Rectangle<int> bounds;
  2648. double dpi;
  2649. bool isMain;
  2650. };
  2651. static BOOL CALLBACK enumMonitorsProc (HMONITOR hm, HDC, LPRECT r, LPARAM userInfo)
  2652. {
  2653. MONITORINFO info = { 0 };
  2654. info.cbSize = sizeof (info);
  2655. GetMonitorInfo (hm, &info);
  2656. const bool isMain = (info.dwFlags & 1 /* MONITORINFOF_PRIMARY */) != 0;
  2657. double dpi = 0;
  2658. if (getDPIForMonitor != nullptr)
  2659. {
  2660. UINT dpiX = 0, dpiY = 0;
  2661. if (SUCCEEDED (getDPIForMonitor (hm, MDT_Default, &dpiX, &dpiY)))
  2662. dpi = (dpiX + dpiY) / 2.0;
  2663. }
  2664. ((Array<MonitorInfo>*) userInfo)->add (MonitorInfo (rectangleFromRECT (*r), isMain, dpi));
  2665. return TRUE;
  2666. }
  2667. void Desktop::Displays::findDisplays (float masterScale)
  2668. {
  2669. setDPIAwareness();
  2670. Array<MonitorInfo> monitors;
  2671. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitors);
  2672. const double globalDPI = getGlobalDPI();
  2673. if (monitors.size() == 0)
  2674. monitors.add (MonitorInfo (rectangleFromRECT (getWindowRect (GetDesktopWindow())), true, globalDPI));
  2675. // make sure the first in the list is the main monitor
  2676. for (int i = 1; i < monitors.size(); ++i)
  2677. if (monitors.getReference(i).isMain)
  2678. monitors.swap (i, 0);
  2679. RECT workArea;
  2680. SystemParametersInfo (SPI_GETWORKAREA, 0, &workArea, 0);
  2681. for (int i = 0; i < monitors.size(); ++i)
  2682. {
  2683. Display d;
  2684. d.userArea = d.totalArea = monitors.getReference(i).bounds / masterScale;
  2685. d.isMain = monitors.getReference(i).isMain;
  2686. d.dpi = monitors.getReference(i).dpi;
  2687. if (d.dpi == 0)
  2688. {
  2689. d.scale = masterScale;
  2690. d.dpi = globalDPI;
  2691. }
  2692. else
  2693. {
  2694. d.scale = d.dpi / 96.0;
  2695. }
  2696. if (d.isMain)
  2697. d.userArea = d.userArea.getIntersection (rectangleFromRECT (workArea) / masterScale);
  2698. displays.add (d);
  2699. }
  2700. }
  2701. //==============================================================================
  2702. static HICON extractFileHICON (const File& file)
  2703. {
  2704. WORD iconNum = 0;
  2705. WCHAR name [MAX_PATH * 2];
  2706. file.getFullPathName().copyToUTF16 (name, sizeof (name));
  2707. return ExtractAssociatedIcon ((HINSTANCE) Process::getCurrentModuleInstanceHandle(),
  2708. name, &iconNum);
  2709. }
  2710. Image juce_createIconForFile (const File& file)
  2711. {
  2712. Image image;
  2713. if (HICON icon = extractFileHICON (file))
  2714. {
  2715. image = IconConverters::createImageFromHICON (icon);
  2716. DestroyIcon (icon);
  2717. }
  2718. return image;
  2719. }
  2720. //==============================================================================
  2721. void* CustomMouseCursorInfo::create() const
  2722. {
  2723. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  2724. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  2725. Image im (image);
  2726. int hotspotX = hotspot.x;
  2727. int hotspotY = hotspot.y;
  2728. if (im.getWidth() > maxW || im.getHeight() > maxH)
  2729. {
  2730. im = im.rescaled (maxW, maxH);
  2731. hotspotX = (hotspotX * maxW) / image.getWidth();
  2732. hotspotY = (hotspotY * maxH) / image.getHeight();
  2733. }
  2734. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  2735. }
  2736. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  2737. {
  2738. if (cursorHandle != nullptr && ! isStandard)
  2739. DestroyCursor ((HCURSOR) cursorHandle);
  2740. }
  2741. enum
  2742. {
  2743. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  2744. };
  2745. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  2746. {
  2747. LPCTSTR cursorName = IDC_ARROW;
  2748. switch (type)
  2749. {
  2750. case NormalCursor:
  2751. case ParentCursor: break;
  2752. case NoCursor: return (void*) hiddenMouseCursorHandle;
  2753. case WaitCursor: cursorName = IDC_WAIT; break;
  2754. case IBeamCursor: cursorName = IDC_IBEAM; break;
  2755. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  2756. case CrosshairCursor: cursorName = IDC_CROSS; break;
  2757. case CopyingCursor: break; // can't seem to find one of these in the system list..
  2758. case LeftRightResizeCursor:
  2759. case LeftEdgeResizeCursor:
  2760. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  2761. case UpDownResizeCursor:
  2762. case TopEdgeResizeCursor:
  2763. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  2764. case TopLeftCornerResizeCursor:
  2765. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  2766. case TopRightCornerResizeCursor:
  2767. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  2768. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  2769. case DraggingHandCursor:
  2770. {
  2771. static void* dragHandCursor = nullptr;
  2772. if (dragHandCursor == nullptr)
  2773. {
  2774. static const unsigned char dragHandData[] =
  2775. { 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,
  2776. 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,
  2777. 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 };
  2778. dragHandCursor = CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7).create();
  2779. }
  2780. return dragHandCursor;
  2781. }
  2782. default:
  2783. jassertfalse; break;
  2784. }
  2785. HCURSOR cursorH = LoadCursor (0, cursorName);
  2786. if (cursorH == 0)
  2787. cursorH = LoadCursor (0, IDC_ARROW);
  2788. return cursorH;
  2789. }
  2790. //==============================================================================
  2791. void MouseCursor::showInWindow (ComponentPeer*) const
  2792. {
  2793. HCURSOR c = (HCURSOR) getHandle();
  2794. if (c == 0)
  2795. c = LoadCursor (0, IDC_ARROW);
  2796. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  2797. c = 0;
  2798. SetCursor (c);
  2799. }
  2800. void MouseCursor::showInAllWindows() const
  2801. {
  2802. showInWindow (nullptr);
  2803. }