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.

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