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.

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