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.

4148 lines
143KB

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