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