Audio plugin host https://kx.studio/carla
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.

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