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.

3242 lines
111KB

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