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.

4199 lines
145KB

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