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.

4186 lines
144KB

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