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.

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