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.

3517 lines
121KB

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