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.

4231 lines
147KB

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