The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3338 lines
114KB

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