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.

4184 lines
144KB

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