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.

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