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.

3655 lines
126KB

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