The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4183 lines
144KB

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