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.

4205 lines
145KB

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