win32windowcontext.cpp 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415
  1. // Copyright (C) 2023-2024 Stdware Collections (https://www.github.com/stdware)
  2. // Copyright (C) 2021-2023 wangwenx190 (Yuhang Zhao)
  3. // SPDX-License-Identifier: Apache-2.0
  4. #include "win32windowcontext_p.h"
  5. #include <optional>
  6. #include <QtCore/QAbstractEventDispatcher>
  7. #include <QtCore/QDateTime>
  8. #include <QtCore/QHash>
  9. #include <QtCore/QScopeGuard>
  10. #include <QtCore/QTimer>
  11. #include <QtGui/QGuiApplication>
  12. #include <QtGui/QPainter>
  13. #include <QtGui/QPalette>
  14. #include <QtGui/qpa/qwindowsysteminterface.h>
  15. #include <QtGui/private/qhighdpiscaling_p.h>
  16. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  17. # include <QtGui/private/qguiapplication_p.h>
  18. #endif
  19. #include <QtGui/qpa/qplatformwindow.h>
  20. #if QT_VERSION < QT_VERSION_CHECK(6, 2, 0)
  21. # include <QtGui/qpa/qplatformnativeinterface.h>
  22. #else
  23. # include <QtGui/qpa/qplatformwindow_p.h>
  24. #endif
  25. #include <widgets/qwkconfig.h>
  26. #include <core/qwkglobal_p.h>
  27. #include <core/shared/qwkwindowsextra_p.h>
  28. #include <shellapi.h>
  29. #if (QT_VERSION >= QT_VERSION_CHECK(6, 6, 0)) && (QT_VERSION <= QT_VERSION_CHECK(6, 6, 1))
  30. # error Current Qt version has a critical bug which will break QWK functionality. Please upgrade to > 6.6.1 or downgrade to < 6.6.0
  31. #endif
  32. #ifndef DWM_BB_ENABLE
  33. # define DWM_BB_ENABLE 0x00000001
  34. #endif
  35. #ifndef ABM_GETAUTOHIDEBAREX
  36. # define ABM_GETAUTOHIDEBAREX 0x0000000b
  37. #endif
  38. namespace QWK {
  39. enum IconButtonClickLevelFlag {
  40. IconButtonClicked = 1,
  41. IconButtonDoubleClicked = 2,
  42. IconButtonTriggersClose = 4,
  43. };
  44. // The thickness of an auto-hide taskbar in pixels.
  45. static constexpr const quint8 kAutoHideTaskBarThickness = 2;
  46. QWK_USED static constexpr const struct {
  47. const uint32_t activeLight = MAKE_RGBA_COLOR(110, 110, 110, 255); // #6E6E6E
  48. const uint32_t activeDark = MAKE_RGBA_COLOR(51, 51, 51, 255); // #333333
  49. const uint32_t inactiveLight = MAKE_RGBA_COLOR(167, 167, 167, 255); // #A7A7A7
  50. const uint32_t inactiveDark = MAKE_RGBA_COLOR(61, 61, 62, 255); // #3D3D3E
  51. } kWindowsColorSet;
  52. // hWnd -> context
  53. using WndProcHash = QHash<HWND, Win32WindowContext *>;
  54. Q_GLOBAL_STATIC(WndProcHash, g_wndProcHash)
  55. // Original Qt window proc function
  56. static WNDPROC g_qtWindowProc = nullptr;
  57. static inline bool
  58. #if !QWINDOWKIT_CONFIG(ENABLE_WINDOWS_SYSTEM_BORDERS)
  59. constexpr
  60. #endif
  61. isSystemBorderEnabled() {
  62. return
  63. #if QWINDOWKIT_CONFIG(ENABLE_WINDOWS_SYSTEM_BORDERS)
  64. isWin10OrGreater()
  65. #else
  66. false
  67. #endif
  68. ;
  69. }
  70. static inline void triggerFrameChange(HWND hwnd) {
  71. ::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0,
  72. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER |
  73. SWP_FRAMECHANGED);
  74. }
  75. static void setInternalWindowFrameMargins(QWindow *window, const QMargins &margins) {
  76. const QVariant marginsVar = QVariant::fromValue(margins);
  77. // We need to tell Qt we have set a custom margin, because we are hiding
  78. // the title bar by pretending the whole window is filled by client area,
  79. // this however confuses Qt's internal logic. We need to do the following
  80. // hack to let Qt consider the extra margin when changing window geometry.
  81. window->setProperty("_q_windowsCustomMargins", marginsVar);
  82. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  83. if (QPlatformWindow *platformWindow = window->handle()) {
  84. if (const auto ni = QGuiApplication::platformNativeInterface()) {
  85. ni->setWindowProperty(platformWindow, QStringLiteral("WindowsCustomMargins"),
  86. marginsVar);
  87. }
  88. }
  89. #else
  90. if (const auto platformWindow =
  91. dynamic_cast<QNativeInterface::Private::QWindowsWindow *>(window->handle())) {
  92. platformWindow->setCustomMargins(margins);
  93. }
  94. #endif
  95. }
  96. static inline MONITORINFOEXW getMonitorForWindow(HWND hwnd) {
  97. // Use "MONITOR_DEFAULTTONEAREST" here so that we can still get the correct
  98. // monitor even if the window is minimized.
  99. HMONITOR monitor = ::MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
  100. MONITORINFOEXW monitorInfo{};
  101. monitorInfo.cbSize = sizeof(monitorInfo);
  102. ::GetMonitorInfoW(monitor, &monitorInfo);
  103. return monitorInfo;
  104. }
  105. static inline void moveWindowToMonitor(HWND hwnd, const MONITORINFOEXW &activeMonitor) {
  106. RECT currentMonitorRect = getMonitorForWindow(hwnd).rcMonitor;
  107. RECT activeMonitorRect = activeMonitor.rcMonitor;
  108. // We are in the same monitor, nothing to adjust here.
  109. if (currentMonitorRect == activeMonitorRect) {
  110. return;
  111. }
  112. RECT currentWindowRect{};
  113. ::GetWindowRect(hwnd, &currentWindowRect);
  114. auto newWindowX =
  115. activeMonitorRect.left + (currentWindowRect.left - currentMonitorRect.left);
  116. auto newWindowY = activeMonitorRect.top + (currentWindowRect.top - currentMonitorRect.top);
  117. ::SetWindowPos(hwnd, nullptr, newWindowX, newWindowY, RECT_WIDTH(currentWindowRect),
  118. RECT_HEIGHT(currentWindowRect),
  119. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  120. }
  121. static inline bool isFullScreen(HWND hwnd) {
  122. RECT windowRect{};
  123. ::GetWindowRect(hwnd, &windowRect);
  124. // Compare to the full area of the screen, not the work area.
  125. return (windowRect == getMonitorForWindow(hwnd).rcMonitor);
  126. }
  127. static inline bool isMaximized(HWND hwnd) {
  128. return ::IsZoomed(hwnd);
  129. }
  130. static inline bool isMinimized(HWND hwnd) {
  131. return ::IsIconic(hwnd);
  132. }
  133. static inline bool isWindowNoState(HWND hwnd) {
  134. #if 0
  135. WINDOWPLACEMENT wp{};
  136. wp.length = sizeof(wp);
  137. ::GetWindowPlacement(hwnd, &wp);
  138. return ((wp.showCmd == SW_NORMAL) || (wp.showCmd == SW_RESTORE));
  139. #else
  140. if (isFullScreen(hwnd)) {
  141. return false;
  142. }
  143. const auto style = static_cast<DWORD>(::GetWindowLongPtrW(hwnd, GWL_STYLE));
  144. return (!(style & (WS_MINIMIZE | WS_MAXIMIZE)));
  145. #endif
  146. }
  147. static inline void bringWindowToFront(HWND hwnd) {
  148. HWND oldForegroundWindow = ::GetForegroundWindow();
  149. if (!oldForegroundWindow) {
  150. // The foreground window can be NULL, it's not an API error.
  151. return;
  152. }
  153. MONITORINFOEXW activeMonitor = getMonitorForWindow(oldForegroundWindow);
  154. // We need to show the window first, otherwise we won't be able to bring it to front.
  155. if (!::IsWindowVisible(hwnd)) {
  156. ::ShowWindow(hwnd, SW_SHOW);
  157. }
  158. if (isMinimized(hwnd)) {
  159. // Restore the window if it is minimized.
  160. ::ShowWindow(hwnd, SW_RESTORE);
  161. // Once we've been restored, throw us on the active monitor.
  162. moveWindowToMonitor(hwnd, activeMonitor);
  163. // When the window is restored, it will always become the foreground window.
  164. // So return early here, we don't need the following code to bring it to front.
  165. return;
  166. }
  167. // SUCCESS, our window is not minimized, so now we will try to bring it to front manually.
  168. // First try to send a message to the current foreground window to check whether
  169. // it is currently hanging or not.
  170. if (!::SendMessageTimeoutW(oldForegroundWindow, WM_NULL, 0, 0,
  171. SMTO_BLOCK | SMTO_ABORTIFHUNG | SMTO_NOTIMEOUTIFNOTHUNG, 1000,
  172. nullptr)) {
  173. // The foreground window hangs, can't activate current window.
  174. return;
  175. }
  176. DWORD windowThreadProcessId = ::GetWindowThreadProcessId(oldForegroundWindow, nullptr);
  177. DWORD currentThreadId = ::GetCurrentThreadId();
  178. // We won't be able to change a window's Z order if it's not our own window,
  179. // so we use this small technique to pretend the foreground window is ours.
  180. ::AttachThreadInput(windowThreadProcessId, currentThreadId, TRUE);
  181. [[maybe_unused]] const auto &cleaner =
  182. qScopeGuard([windowThreadProcessId, currentThreadId]() {
  183. ::AttachThreadInput(windowThreadProcessId, currentThreadId, FALSE);
  184. });
  185. ::BringWindowToTop(hwnd);
  186. // Activate the window too. This will force us to the virtual desktop this
  187. // window is on, if it's on another virtual desktop.
  188. ::SetActiveWindow(hwnd);
  189. // Throw us on the active monitor.
  190. moveWindowToMonitor(hwnd, activeMonitor);
  191. }
  192. // Returns false if the menu is canceled
  193. static bool showSystemMenu_sys(HWND hWnd, const POINT &pos, const bool selectFirstEntry,
  194. const bool fixedSize) {
  195. HMENU hMenu = ::GetSystemMenu(hWnd, FALSE);
  196. if (!hMenu) {
  197. // The corresponding window doesn't have a system menu, most likely due to the
  198. // lack of the "WS_SYSMENU" window style. This situation should not be treated
  199. // as an error so just ignore it and return early.
  200. return true;
  201. }
  202. const auto windowStyles = ::GetWindowLongPtrW(hWnd, GWL_STYLE);
  203. const bool allowMaximize = windowStyles & WS_MAXIMIZEBOX;
  204. const bool allowMinimize = windowStyles & WS_MINIMIZEBOX;
  205. const bool maxOrFull = isMaximized(hWnd) || isFullScreen(hWnd);
  206. ::EnableMenuItem(hMenu, SC_CLOSE, (MF_BYCOMMAND | MFS_ENABLED));
  207. ::EnableMenuItem(
  208. hMenu, SC_MAXIMIZE,
  209. (MF_BYCOMMAND |
  210. ((maxOrFull || fixedSize || !allowMaximize) ? MFS_DISABLED : MFS_ENABLED)));
  211. ::EnableMenuItem(
  212. hMenu, SC_RESTORE,
  213. (MF_BYCOMMAND |
  214. ((maxOrFull && !fixedSize && allowMaximize) ? MFS_ENABLED : MFS_DISABLED)));
  215. // The first menu item should be selected by default if the menu is brought
  216. // up by keyboard. I don't know how to pre-select a menu item but it seems
  217. // highlight can do the job. However, there's an annoying issue if we do
  218. // this manually: the highlighted menu item is really only highlighted,
  219. // not selected, so even if the mouse cursor hovers on other menu items
  220. // or the user navigates to other menu items through keyboard, the original
  221. // highlight bar will not move accordingly, the OS will generate another
  222. // highlight bar to indicate the current selected menu item, which will make
  223. // the menu look kind of weird. Currently I don't know how to fix this issue.
  224. ::HiliteMenuItem(hWnd, hMenu, SC_RESTORE,
  225. (MF_BYCOMMAND | (selectFirstEntry ? MFS_HILITE : MFS_UNHILITE)));
  226. ::EnableMenuItem(hMenu, SC_MINIMIZE,
  227. (MF_BYCOMMAND | (allowMinimize ? MFS_ENABLED : MFS_DISABLED)));
  228. ::EnableMenuItem(hMenu, SC_SIZE,
  229. (MF_BYCOMMAND | ((maxOrFull || fixedSize) ? MFS_DISABLED : MFS_ENABLED)));
  230. ::EnableMenuItem(hMenu, SC_MOVE, (MF_BYCOMMAND | (maxOrFull ? MFS_DISABLED : MFS_ENABLED)));
  231. // The default menu item will appear in bold font. There can only be one default
  232. // menu item per menu at most. Set the item ID to "UINT_MAX" (or simply "-1")
  233. // can clear the default item for the given menu.
  234. UINT defaultItemId = UINT_MAX;
  235. if (isWin11OrGreater()) {
  236. if (maxOrFull) {
  237. defaultItemId = SC_RESTORE;
  238. } else {
  239. defaultItemId = SC_MAXIMIZE;
  240. }
  241. }
  242. if (defaultItemId == UINT_MAX) {
  243. defaultItemId = SC_CLOSE;
  244. }
  245. ::SetMenuDefaultItem(hMenu, defaultItemId, FALSE);
  246. // Popup the system menu at the required position.
  247. const auto result = ::TrackPopupMenu(
  248. hMenu,
  249. (TPM_RETURNCMD | (QGuiApplication::isRightToLeft() ? TPM_RIGHTALIGN : TPM_LEFTALIGN) |
  250. TPM_RIGHTBUTTON),
  251. pos.x, pos.y, 0, hWnd, nullptr);
  252. // Unhighlight the first menu item after the popup menu is closed, otherwise it will keep
  253. // highlighting until we unhighlight it manually.
  254. ::HiliteMenuItem(hWnd, hMenu, SC_RESTORE, (MF_BYCOMMAND | MFS_UNHILITE));
  255. if (!result) {
  256. // The user canceled the menu, no need to continue.
  257. return false;
  258. }
  259. // Send the command that the user chooses to the corresponding window.
  260. ::PostMessageW(hWnd, WM_SYSCOMMAND, result, 0);
  261. return true;
  262. }
  263. static inline Win32WindowContext::WindowPart getHitWindowPart(int hitTestResult) {
  264. switch (hitTestResult) {
  265. case HTCLIENT:
  266. return Win32WindowContext::ClientArea;
  267. case HTCAPTION:
  268. return Win32WindowContext::TitleBar;
  269. case HTSYSMENU:
  270. case HTHELP:
  271. case HTREDUCE:
  272. case HTZOOM:
  273. case HTCLOSE:
  274. return Win32WindowContext::ChromeButton;
  275. case HTLEFT:
  276. case HTRIGHT:
  277. case HTTOP:
  278. case HTTOPLEFT:
  279. case HTTOPRIGHT:
  280. case HTBOTTOM:
  281. case HTBOTTOMLEFT:
  282. case HTBOTTOMRIGHT:
  283. return Win32WindowContext::ResizeBorder;
  284. case HTBORDER:
  285. return Win32WindowContext::FixedBorder;
  286. default:
  287. break;
  288. }
  289. return Win32WindowContext::Outside;
  290. }
  291. static bool isValidWindow(HWND hWnd, bool checkVisible, bool checkTopLevel) {
  292. if (!::IsWindow(hWnd)) {
  293. return false;
  294. }
  295. const LONG_PTR styles = ::GetWindowLongPtrW(hWnd, GWL_STYLE);
  296. if (styles & WS_DISABLED) {
  297. return false;
  298. }
  299. const LONG_PTR exStyles = ::GetWindowLongPtrW(hWnd, GWL_EXSTYLE);
  300. if (exStyles & WS_EX_TOOLWINDOW) {
  301. return false;
  302. }
  303. RECT rect{};
  304. if (!::GetWindowRect(hWnd, &rect)) {
  305. return false;
  306. }
  307. if ((rect.left >= rect.right) || (rect.top >= rect.bottom)) {
  308. return false;
  309. }
  310. if (checkVisible) {
  311. if (!::IsWindowVisible(hWnd)) {
  312. return false;
  313. }
  314. }
  315. if (checkTopLevel) {
  316. if (::GetAncestor(hWnd, GA_ROOT) != hWnd) {
  317. return false;
  318. }
  319. }
  320. return true;
  321. }
  322. static inline constexpr bool isNonClientMessage(const UINT message) {
  323. if (((message >= WM_NCCREATE) && (message <= WM_NCACTIVATE)) ||
  324. ((message >= WM_NCMOUSEMOVE) && (message <= WM_NCMBUTTONDBLCLK)) ||
  325. ((message >= WM_NCXBUTTONDOWN) && (message <= WM_NCXBUTTONDBLCLK))
  326. #if (WINVER >= _WIN32_WINNT_WIN8)
  327. || ((message >= WM_NCPOINTERUPDATE) && (message <= WM_NCPOINTERUP))
  328. #endif
  329. || ((message == WM_NCMOUSEHOVER) || (message == WM_NCMOUSELEAVE))) {
  330. return true;
  331. } else {
  332. return false;
  333. }
  334. }
  335. static MSG createMessageBlock(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
  336. MSG msg;
  337. msg.hwnd = hWnd;
  338. msg.message = message;
  339. msg.wParam = wParam;
  340. msg.lParam = lParam;
  341. const DWORD dwScreenPos = ::GetMessagePos();
  342. msg.pt.x = GET_X_LPARAM(dwScreenPos);
  343. msg.pt.y = GET_Y_LPARAM(dwScreenPos);
  344. if (!isNonClientMessage(message)) {
  345. ::ScreenToClient(hWnd, &msg.pt);
  346. }
  347. msg.time = ::GetMessageTime();
  348. return msg;
  349. }
  350. static inline constexpr bool isInputMessage(UINT m) {
  351. switch (m) {
  352. case WM_IME_STARTCOMPOSITION:
  353. case WM_IME_ENDCOMPOSITION:
  354. case WM_IME_COMPOSITION:
  355. case WM_INPUT:
  356. case WM_TOUCH:
  357. case WM_MOUSEHOVER:
  358. case WM_MOUSELEAVE:
  359. case WM_NCMOUSEHOVER:
  360. case WM_NCMOUSELEAVE:
  361. case WM_SIZING:
  362. case WM_MOVING:
  363. case WM_SYSCOMMAND:
  364. case WM_COMMAND:
  365. case WM_DWMNCRENDERINGCHANGED:
  366. case WM_PAINT:
  367. return true;
  368. default:
  369. break;
  370. }
  371. return (m >= WM_MOUSEFIRST && m <= WM_MOUSELAST) ||
  372. (m >= WM_NCMOUSEMOVE && m <= WM_NCXBUTTONDBLCLK) ||
  373. (m >= WM_KEYFIRST && m <= WM_KEYLAST);
  374. }
  375. static inline QByteArray nativeEventType() {
  376. return QByteArrayLiteral("windows_generic_MSG");
  377. }
  378. // Send to QAbstractEventDispatcher
  379. static bool filterNativeEvent(MSG *msg, LRESULT *result) {
  380. auto dispatcher = QAbstractEventDispatcher::instance();
  381. QT_NATIVE_EVENT_RESULT_TYPE filterResult = *result;
  382. if (dispatcher && dispatcher->filterNativeEvent(nativeEventType(), msg, &filterResult)) {
  383. *result = LRESULT(filterResult);
  384. return true;
  385. }
  386. return false;
  387. }
  388. // Send to QWindowSystemInterface
  389. static bool filterNativeEvent(QWindow *window, MSG *msg, LRESULT *result) {
  390. QT_NATIVE_EVENT_RESULT_TYPE filterResult = *result;
  391. if (QWindowSystemInterface::handleNativeEvent(window, nativeEventType(), msg,
  392. &filterResult)) {
  393. *result = LRESULT(filterResult);
  394. return true;
  395. }
  396. return false;
  397. }
  398. static inline bool forwardFilteredEvent(QWindow *window, HWND hWnd, UINT message, WPARAM wParam,
  399. LPARAM lParam, LRESULT *result) {
  400. MSG msg = createMessageBlock(hWnd, message, wParam, lParam);
  401. // https://github.com/qt/qtbase/blob/e26a87f1ecc40bc8c6aa5b889fce67410a57a702/src/plugins/platforms/windows/qwindowscontext.cpp#L1025
  402. // Do exact the same as what Qt Windows plugin does.
  403. // Run the native event filters. QTBUG-67095: Exclude input messages which are sent
  404. // by QEventDispatcherWin32::processEvents()
  405. if (!isInputMessage(msg.message) && filterNativeEvent(&msg, result))
  406. return true;
  407. auto platformWindow = window->handle();
  408. if (platformWindow && filterNativeEvent(platformWindow->window(), &msg, result))
  409. return true;
  410. return false;
  411. }
  412. // https://github.com/qt/qtbase/blob/e26a87f1ecc40bc8c6aa5b889fce67410a57a702/src/plugins/platforms/windows/qwindowscontext.cpp#L1556
  413. // In QWindowsContext::windowsProc(), the messages will be passed to all global native event
  414. // filters, but because we have already filtered the messages in the hook WndProc function for
  415. // convenience, Qt does not know we may have already processed the messages and thus will call
  416. // DefWindowProc(). Consequently, we have to add a global native filter that forwards the result
  417. // of the hook function, telling Qt whether we have filtered the events before. Since Qt only
  418. // handles Windows window messages in the main thread, it is safe to do so.
  419. class WindowsNativeEventFilter : public AppNativeEventFilter {
  420. public:
  421. bool nativeEventFilter(const QByteArray &eventType, void *message,
  422. QT_NATIVE_EVENT_RESULT_TYPE *result) override {
  423. Q_UNUSED(eventType)
  424. // It has been observed that the pointer that Qt gives us is sometimes null on some
  425. // machines. We need to guard against it in such scenarios.
  426. if (!result) {
  427. return false;
  428. }
  429. auto msg = static_cast<const MSG *>(message);
  430. switch (msg->message) {
  431. case WM_NCCALCSIZE: {
  432. // https://github.com/qt/qtbase/blob/e26a87f1ecc40bc8c6aa5b889fce67410a57a702/src/plugins/platforms/windows/qwindowscontext.cpp#L1546
  433. // Qt needs to refer to the WM_NCCALCSIZE message data that hasn't been
  434. // processed, so we have to process it after Qt acquires the initial data.
  435. if (lastMessageContext) {
  436. LRESULT res;
  437. if (lastMessageContext->nonClientCalcSizeHandler(
  438. msg->hwnd, msg->message, msg->wParam, msg->lParam, &res)) {
  439. *result = decltype(*result)(res);
  440. return true;
  441. }
  442. }
  443. break;
  444. }
  445. // case WM_NCHITTEST: {
  446. // // The child window must return HTTRANSPARENT when processing
  447. // WM_NCHITTEST for
  448. // // the parent window to receive WM_NCHITTEST.
  449. // if (!lastMessageContext) {
  450. // auto rootHWnd = ::GetAncestor(msg->hwnd, GA_ROOT);
  451. // if (rootHWnd != msg->hwnd) {
  452. // if (auto ctx = g_wndProcHash->value(rootHWnd)) {
  453. // *result = HTTRANSPARENT;
  454. // return true;
  455. // }
  456. // }
  457. // }
  458. // break;
  459. // }
  460. }
  461. return false;
  462. }
  463. static inline WindowsNativeEventFilter *instance = nullptr;
  464. static inline Win32WindowContext *lastMessageContext = nullptr;
  465. static inline void install() {
  466. if (instance) {
  467. return;
  468. }
  469. instance = new WindowsNativeEventFilter();
  470. }
  471. static inline void uninstall() {
  472. if (!instance) {
  473. return;
  474. }
  475. delete instance;
  476. instance = nullptr;
  477. }
  478. };
  479. // https://github.com/qt/qtbase/blob/e26a87f1ecc40bc8c6aa5b889fce67410a57a702/src/plugins/platforms/windows/qwindowscontext.cpp#L1025
  480. // We can see from the source code that Qt will filter out some messages first and then send the
  481. // unfiltered messages to the event dispatcher. To activate the Snap Layout feature on Windows
  482. // 11, we must process some non-client area messages ourselves, but unfortunately these messages
  483. // have been filtered out already in that line, and thus we'll never have the chance to process
  484. // them ourselves. This is Qt's low level platform specific code, so we don't have any official
  485. // ways to change this behavior. But luckily we can replace the window procedure function of
  486. // Qt's windows, and in this hooked window procedure function, we finally have the chance to
  487. // process window messages before Qt touches them. So we reconstruct the MSG structure and send
  488. // it to our own custom native event filter to do all the magic works. But since the system menu
  489. // feature doesn't necessarily belong to the native implementation, we seperate the handling
  490. // code and always process the system menu part in this function for both implementations.
  491. //
  492. // Original event flow:
  493. // [Entry] Windows Message Queue
  494. // |
  495. // [Qt Window Proc] qwindowscontext.cpp#L1547: qWindowsWndProc()
  496. // ```
  497. // const bool handled = QWindowsContext::instance()->windowsProc
  498. // (hwnd, message, et, wParam, lParam, &result,
  499. // &platformWindow);
  500. // ```
  501. // |
  502. // [Non-Input Filter] qwindowscontext.cpp#L1025: QWindowsContext::windowsProc()
  503. // ```
  504. // if (!isInputMessage(msg.message) &&
  505. // filterNativeEvent(&msg, result))
  506. // return true;
  507. // ```
  508. // |
  509. // [User Filter] qwindowscontext.cpp#L1588: QWindowsContext::windowsProc()
  510. // ```
  511. // QAbstractEventDispatcher *dispatcher =
  512. // QAbstractEventDispatcher::instance();
  513. // qintptr filterResult = 0;
  514. // if (dispatcher &&
  515. // dispatcher->filterNativeEvent(nativeEventType(), msg,
  516. // &filterResult)) {
  517. // *result = LRESULT(filterResult);
  518. // return true;
  519. // }
  520. // ```
  521. // |
  522. // [Extra work] The rest of QWindowsContext::windowsProc() and qWindowsWndProc()
  523. //
  524. // Notice: Only non-input messages will be processed by the user-defined global native event
  525. // filter!!! These events are then passed to the widget class's own overridden
  526. // QWidget::nativeEvent() as a local filter, where all native events can be handled, but we must
  527. // create a new class derived from QWidget which we don't intend to. Therefore, we don't expect
  528. // to process events from the global native event filter, but instead hook Qt's window
  529. // procedure.
  530. extern "C" LRESULT QT_WIN_CALLBACK QWKHookedWndProc(HWND hWnd, UINT message, WPARAM wParam,
  531. LPARAM lParam) {
  532. Q_ASSERT(hWnd);
  533. if (!hWnd) {
  534. return FALSE;
  535. }
  536. // Search window context
  537. auto ctx = g_wndProcHash->value(hWnd);
  538. if (!ctx) {
  539. return ::DefWindowProcW(hWnd, message, wParam, lParam);
  540. }
  541. WindowsNativeEventFilter::lastMessageContext = ctx;
  542. const auto &contextCleaner = qScopeGuard([]() {
  543. WindowsNativeEventFilter::lastMessageContext = nullptr; //
  544. });
  545. // Since Qt does the necessary processing of the WM_NCCALCSIZE message, we need to
  546. // forward it right away and process it in our native event filter.
  547. if (message == WM_NCCALCSIZE) {
  548. return ::CallWindowProcW(g_qtWindowProc, hWnd, message, wParam, lParam);
  549. }
  550. // Try hooked procedure and save result
  551. LRESULT result;
  552. if (ctx->windowProc(hWnd, message, wParam, lParam, &result)) {
  553. // https://github.com/stdware/qwindowkit/issues/45
  554. // Forward the event to user-defined native event filters, there may be some messages
  555. // that need to be processed by the user.
  556. std::ignore =
  557. forwardFilteredEvent(ctx->window(), hWnd, message, wParam, lParam, &result);
  558. return result;
  559. }
  560. // Continue dispatching.
  561. return ::CallWindowProcW(g_qtWindowProc, hWnd, message, wParam, lParam);
  562. }
  563. static inline void addManagedWindow(QWindow *window, HWND hWnd, Win32WindowContext *ctx) {
  564. if (isSystemBorderEnabled()) {
  565. // Inform Qt we want and have set custom margins
  566. setInternalWindowFrameMargins(window, QMargins(0, -int(getTitleBarHeight(hWnd)), 0, 0));
  567. }
  568. // Store original window proc
  569. if (!g_qtWindowProc) {
  570. g_qtWindowProc = reinterpret_cast<WNDPROC>(::GetWindowLongPtrW(hWnd, GWLP_WNDPROC));
  571. }
  572. // Hook window proc
  573. ::SetWindowLongPtrW(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(QWKHookedWndProc));
  574. // Install global native event filter
  575. WindowsNativeEventFilter::install();
  576. // Save window handle mapping
  577. g_wndProcHash->insert(hWnd, ctx);
  578. // Force a WM_NCCALCSIZE message manually to avoid the title bar become visible
  579. // while Qt is re-creating the window (such as setWindowFlag(s) calls). It has
  580. // been observed by our users.
  581. triggerFrameChange(hWnd);
  582. }
  583. static inline void removeManagedWindow(HWND hWnd) {
  584. // Remove window handle mapping
  585. if (!g_wndProcHash->remove(hWnd))
  586. return;
  587. // Remove event filter if the all windows has been destroyed
  588. if (g_wndProcHash->empty()) {
  589. WindowsNativeEventFilter::uninstall();
  590. }
  591. }
  592. Win32WindowContext::Win32WindowContext() : AbstractWindowContext() {
  593. }
  594. Win32WindowContext::~Win32WindowContext() {
  595. if (m_windowId) {
  596. removeManagedWindow(reinterpret_cast<HWND>(m_windowId));
  597. }
  598. }
  599. QString Win32WindowContext::key() const {
  600. return QStringLiteral("win32");
  601. }
  602. void Win32WindowContext::virtual_hook(int id, void *data) {
  603. switch (id) {
  604. case RaiseWindowHook: {
  605. if (!m_windowId)
  606. return;
  607. m_delegate->setWindowVisible(m_host, true);
  608. const auto hwnd = reinterpret_cast<HWND>(m_windowId);
  609. bringWindowToFront(hwnd);
  610. return;
  611. }
  612. case ShowSystemMenuHook: {
  613. if (!m_windowId)
  614. return;
  615. const auto &pos = *static_cast<const QPoint *>(data);
  616. auto hWnd = reinterpret_cast<HWND>(m_windowId);
  617. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  618. const QPoint nativeGlobalPos =
  619. QHighDpi::toNativeGlobalPosition(pos, m_windowHandle.data());
  620. #else
  621. const QPoint nativeGlobalPos = QHighDpi::toNativePixels(pos, m_windowHandle.data());
  622. #endif
  623. std::ignore = showSystemMenu_sys(hWnd, qpoint2point(nativeGlobalPos), false,
  624. isHostSizeFixed());
  625. return;
  626. }
  627. case DefaultColorsHook: {
  628. auto &map = *static_cast<QMap<QString, QColor> *>(data);
  629. map.clear();
  630. map.insert(QStringLiteral("activeLight"), kWindowsColorSet.activeLight);
  631. map.insert(QStringLiteral("activeDark"), kWindowsColorSet.activeDark);
  632. map.insert(QStringLiteral("inactiveLight"), kWindowsColorSet.inactiveLight);
  633. map.insert(QStringLiteral("inactiveDark"), kWindowsColorSet.inactiveDark);
  634. return;
  635. }
  636. #if QWINDOWKIT_CONFIG(ENABLE_WINDOWS_SYSTEM_BORDERS)
  637. case DrawWindows10BorderHook_Emulated: {
  638. if (!m_windowId)
  639. return;
  640. auto args = static_cast<void **>(data);
  641. auto &painter = *static_cast<QPainter *>(args[0]);
  642. const auto &rect = *static_cast<const QRect *>(args[1]);
  643. const auto &region = *static_cast<const QRegion *>(args[2]);
  644. const auto hwnd = reinterpret_cast<HWND>(m_windowId);
  645. QPen pen;
  646. pen.setWidth(int(getWindowFrameBorderThickness(hwnd)) * 2);
  647. const bool dark = isDarkThemeActive() && isDarkWindowFrameEnabled(hwnd);
  648. if (m_delegate->isWindowActive(m_host)) {
  649. if (isWindowFrameBorderColorized()) {
  650. pen.setColor(getAccentColor());
  651. } else {
  652. static QColor frameBorderActiveColorLight(kWindowsColorSet.activeLight);
  653. static QColor frameBorderActiveColorDark(kWindowsColorSet.activeDark);
  654. pen.setColor(dark ? frameBorderActiveColorDark
  655. : frameBorderActiveColorLight);
  656. }
  657. } else {
  658. static QColor frameBorderInactiveColorLight(kWindowsColorSet.inactiveLight);
  659. static QColor frameBorderInactiveColorDark(kWindowsColorSet.inactiveDark);
  660. pen.setColor(dark ? frameBorderInactiveColorDark
  661. : frameBorderInactiveColorLight);
  662. }
  663. painter.save();
  664. // We need antialiasing to give us better result.
  665. painter.setRenderHint(QPainter::Antialiasing);
  666. painter.setPen(pen);
  667. painter.drawLine(QLine{
  668. QPoint{0, 0},
  669. QPoint{m_windowHandle->width(), 0}
  670. });
  671. painter.restore();
  672. return;
  673. }
  674. case DrawWindows10BorderHook_Native: {
  675. if (!m_windowId)
  676. return;
  677. // https://github.com/microsoft/terminal/blob/71a6f26e6ece656084e87de1a528c4a8072eeabd/src/cascadia/WindowsTerminal/NonClientIslandWindow.cpp#L1025
  678. // https://docs.microsoft.com/en-us/windows/win32/dwm/customframe#extending-the-client-frame
  679. // Draw a black rectangle to make Windows native top border show
  680. auto hWnd = reinterpret_cast<HWND>(m_windowId);
  681. HDC hdc = ::GetDC(hWnd);
  682. RECT windowRect{};
  683. ::GetClientRect(hWnd, &windowRect);
  684. RECT rcTopBorder = {
  685. 0,
  686. 0,
  687. RECT_WIDTH(windowRect),
  688. int(getWindowFrameBorderThickness(hWnd)),
  689. };
  690. ::FillRect(hdc, &rcTopBorder,
  691. reinterpret_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH)));
  692. ::ReleaseDC(hWnd, hdc);
  693. return;
  694. }
  695. #endif
  696. default:
  697. break;
  698. }
  699. AbstractWindowContext::virtual_hook(id, data);
  700. }
  701. QVariant Win32WindowContext::windowAttribute(const QString &key) const {
  702. if (key == QStringLiteral("window-rect")) {
  703. if (!m_windowId)
  704. return {};
  705. RECT frame{};
  706. auto hwnd = reinterpret_cast<HWND>(m_windowId);
  707. // According to MSDN, WS_OVERLAPPED is not allowed for AdjustWindowRect.
  708. auto style = static_cast<DWORD>(::GetWindowLongPtrW(hwnd, GWL_STYLE) & ~WS_OVERLAPPED);
  709. auto exStyle = static_cast<DWORD>(::GetWindowLongPtrW(hwnd, GWL_EXSTYLE));
  710. const DynamicApis &apis = DynamicApis::instance();
  711. if (apis.pAdjustWindowRectExForDpi) {
  712. apis.pAdjustWindowRectExForDpi(&frame, style, FALSE, exStyle,
  713. getDpiForWindow(hwnd));
  714. } else {
  715. ::AdjustWindowRectEx(&frame, style, FALSE, exStyle);
  716. }
  717. return QVariant::fromValue(rect2qrect(frame));
  718. }
  719. if (key == QStringLiteral("win10-border-needed")) {
  720. return isSystemBorderEnabled() && !isWin11OrGreater();
  721. }
  722. if (key == QStringLiteral("windows-system-border-enabled")) {
  723. return isSystemBorderEnabled();
  724. }
  725. if (key == QStringLiteral("border-thickness")) {
  726. return m_windowId
  727. ? int(getWindowFrameBorderThickness(reinterpret_cast<HWND>(m_windowId)))
  728. : 0;
  729. }
  730. if (key == QStringLiteral("title-bar-height")) {
  731. return m_windowId ? int(getTitleBarHeight(reinterpret_cast<HWND>(m_windowId))) : 0;
  732. }
  733. return AbstractWindowContext::windowAttribute(key);
  734. }
  735. void Win32WindowContext::winIdChanged(WId winId, WId oldWinId) {
  736. // Reset the context data
  737. mouseLeaveBlocked = false;
  738. lastHitTestResult = WindowPart::Outside;
  739. lastHitTestResultRaw = HTNOWHERE;
  740. // If the original window id is valid, remove all resources related
  741. if (oldWinId) {
  742. removeManagedWindow(reinterpret_cast<HWND>(oldWinId));
  743. }
  744. if (!winId) {
  745. return;
  746. }
  747. // Install window hook
  748. auto hWnd = reinterpret_cast<HWND>(winId);
  749. if (!isSystemBorderEnabled()) {
  750. static auto margins = QVariant::fromValue(QMargins(1, 1, 1, 1));
  751. // If we remove the system border, the window will lose its shadow. If dwm is enabled,
  752. // then we need to set at least 1px margins, otherwise the following operation will
  753. // fail with no effect.
  754. setWindowAttribute(QStringLiteral("extra-margins"), margins);
  755. }
  756. // We should disable WS_SYSMENU, otherwise the system button icons will be visible if mica
  757. // is enabled and the title bar is transparent.
  758. {
  759. auto style = ::GetWindowLongPtrW(hWnd, GWL_STYLE);
  760. if (isSystemBorderEnabled()) {
  761. ::SetWindowLongPtrW(hWnd, GWL_STYLE, style & (~WS_SYSMENU));
  762. } else {
  763. ::SetWindowLongPtrW(hWnd, GWL_STYLE,
  764. (style | WS_THICKFRAME | WS_CAPTION) & (~WS_SYSMENU));
  765. }
  766. }
  767. // Add managed window
  768. addManagedWindow(m_windowHandle, hWnd, this);
  769. }
  770. bool Win32WindowContext::windowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam,
  771. LRESULT *result) {
  772. *result = FALSE;
  773. // We should skip these messages otherwise we will get crashes.
  774. // NOTE: WM_QUIT won't be posted to the WindowProc function.
  775. switch (message) {
  776. case WM_DESTROY:
  777. case WM_CLOSE:
  778. case WM_NCDESTROY:
  779. // Undocumented messages:
  780. case WM_UAHDESTROYWINDOW:
  781. case WM_UNREGISTER_WINDOW_SERVICES:
  782. return false;
  783. default:
  784. break;
  785. }
  786. if (!isValidWindow(hWnd, false, true)) {
  787. return false;
  788. }
  789. // Test snap layout
  790. if (snapLayoutHandler(hWnd, message, wParam, lParam, result)) {
  791. return true;
  792. }
  793. // Main implementation
  794. if (customWindowHandler(hWnd, message, wParam, lParam, result)) {
  795. return true;
  796. }
  797. // Whether to show system menu
  798. if (systemMenuHandler(hWnd, message, wParam, lParam, result)) {
  799. return true;
  800. }
  801. // Forward to native event filter subscribers
  802. if (!m_nativeEventFilters.isEmpty()) {
  803. MSG msg = createMessageBlock(hWnd, message, wParam, lParam);
  804. QT_NATIVE_EVENT_RESULT_TYPE res = 0;
  805. if (nativeDispatch(nativeEventType(), &msg, &res)) {
  806. *result = LRESULT(res);
  807. return true;
  808. }
  809. }
  810. return false; // Not handled
  811. }
  812. bool Win32WindowContext::windowAttributeChanged(const QString &key, const QVariant &attribute,
  813. const QVariant &oldAttribute) {
  814. Q_UNUSED(oldAttribute)
  815. const auto hwnd = reinterpret_cast<HWND>(m_windowId);
  816. Q_ASSERT(hwnd);
  817. const DynamicApis &apis = DynamicApis::instance();
  818. const auto &extendMargins = [this, &apis, hwnd]() {
  819. // For some unknown reason, the window background is totally black and extending
  820. // the window frame into the client area seems to fix it magically.
  821. // After many times of trying, we found that the Acrylic/Mica/Mica Alt background
  822. // only appears on the native Win32 window's background, so naturally we want to
  823. // extend the window frame into the whole client area to be able to let the special
  824. // material fill the whole window. Previously we are using negative margins because
  825. // it's widely known that using negative margins will let the window frame fill
  826. // the whole window and that's indeed what we wanted to do, however, later we found
  827. // that doing so is causing issues. When the user enabled the "show accent color on
  828. // window title bar and borders" option on system personalize settings, a 30px bar
  829. // would appear on window top. It has the same color with the system accent color.
  830. // Actually it's the original title bar we've already hidden, and it magically
  831. // appears again when we use negative margins to extend the window frame. And again
  832. // after some experiments, I found that the title bar won't appear if we don't extend
  833. // from the top side. In the end I found that we only need to extend from the left
  834. // side if we extend long enough. In this way we can see the special material even
  835. // when the host object is a QWidget and the title bar still remain hidden. But even
  836. // though this solution seems perfect, I really don't know why it works. The following
  837. // hack is totally based on experiments.
  838. static constexpr const MARGINS margins = {65536, 0, 0, 0};
  839. apis.pDwmExtendFrameIntoClientArea(hwnd, &margins);
  840. };
  841. const auto &restoreMargins = [this, &apis, hwnd]() {
  842. auto margins = qmargins2margins(
  843. windowAttribute(QStringLiteral("extra-margins")).value<QMargins>());
  844. apis.pDwmExtendFrameIntoClientArea(hwnd, &margins);
  845. };
  846. const auto &effectBugWorkaround = [this, hwnd]() {
  847. // We don't need the following *HACK* for QWidget windows.
  848. // Completely based on actual experiments, root reason is totally unknown.
  849. if (m_host->isWidgetType()) {
  850. return;
  851. }
  852. static QSet<WId> bugWindowSet{};
  853. if (bugWindowSet.contains(m_windowId)) {
  854. return;
  855. }
  856. bugWindowSet.insert(m_windowId);
  857. RECT rect{};
  858. ::GetWindowRect(hwnd, &rect);
  859. ::MoveWindow(hwnd, rect.left, rect.top, 1, 1, FALSE);
  860. ::MoveWindow(hwnd, rect.right - 1, rect.bottom - 1, 1, 1, FALSE);
  861. ::MoveWindow(hwnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
  862. FALSE);
  863. };
  864. if (key == QStringLiteral("extra-margins")) {
  865. auto margins = qmargins2margins(attribute.value<QMargins>());
  866. return SUCCEEDED(apis.pDwmExtendFrameIntoClientArea(hwnd, &margins));
  867. }
  868. if (key == QStringLiteral("dark-mode")) {
  869. if (!isWin101809OrGreater()) {
  870. return false;
  871. }
  872. BOOL enable = attribute.toBool();
  873. if (isWin101903OrGreater()) {
  874. apis.pSetPreferredAppMode(enable ? PAM_AUTO : PAM_DEFAULT);
  875. } else {
  876. apis.pAllowDarkModeForApp(enable);
  877. }
  878. const auto attr = isWin1020H1OrGreater() ? _DWMWA_USE_IMMERSIVE_DARK_MODE
  879. : _DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1;
  880. apis.pDwmSetWindowAttribute(hwnd, attr, &enable, sizeof(enable));
  881. apis.pFlushMenuThemes();
  882. return true;
  883. }
  884. // For Win11 or later
  885. if (key == QStringLiteral("mica")) {
  886. if (!isWin11OrGreater()) {
  887. return false;
  888. }
  889. if (attribute.toBool()) {
  890. extendMargins();
  891. if (isWin1122H2OrGreater()) {
  892. // Use official DWM API to enable Mica, available since Windows 11 22H2
  893. // (10.0.22621).
  894. const _DWM_SYSTEMBACKDROP_TYPE backdropType = _DWMSBT_MAINWINDOW;
  895. apis.pDwmSetWindowAttribute(hwnd, _DWMWA_SYSTEMBACKDROP_TYPE, &backdropType,
  896. sizeof(backdropType));
  897. } else {
  898. // Use undocumented DWM API to enable Mica, available since Windows 11
  899. // (10.0.22000).
  900. const BOOL enable = TRUE;
  901. apis.pDwmSetWindowAttribute(hwnd, _DWMWA_MICA_EFFECT, &enable, sizeof(enable));
  902. }
  903. } else {
  904. if (isWin1122H2OrGreater()) {
  905. const _DWM_SYSTEMBACKDROP_TYPE backdropType = _DWMSBT_AUTO;
  906. apis.pDwmSetWindowAttribute(hwnd, _DWMWA_SYSTEMBACKDROP_TYPE, &backdropType,
  907. sizeof(backdropType));
  908. } else {
  909. const BOOL enable = FALSE;
  910. apis.pDwmSetWindowAttribute(hwnd, _DWMWA_MICA_EFFECT, &enable, sizeof(enable));
  911. }
  912. restoreMargins();
  913. }
  914. effectBugWorkaround();
  915. return true;
  916. }
  917. if (key == QStringLiteral("mica-alt")) {
  918. if (!isWin1122H2OrGreater()) {
  919. return false;
  920. }
  921. if (attribute.toBool()) {
  922. extendMargins();
  923. // Use official DWM API to enable Mica Alt, available since Windows 11 22H2
  924. // (10.0.22621).
  925. const _DWM_SYSTEMBACKDROP_TYPE backdropType = _DWMSBT_TABBEDWINDOW;
  926. apis.pDwmSetWindowAttribute(hwnd, _DWMWA_SYSTEMBACKDROP_TYPE, &backdropType,
  927. sizeof(backdropType));
  928. } else {
  929. const _DWM_SYSTEMBACKDROP_TYPE backdropType = _DWMSBT_AUTO;
  930. apis.pDwmSetWindowAttribute(hwnd, _DWMWA_SYSTEMBACKDROP_TYPE, &backdropType,
  931. sizeof(backdropType));
  932. restoreMargins();
  933. }
  934. effectBugWorkaround();
  935. return true;
  936. }
  937. if (key == QStringLiteral("acrylic-material")) {
  938. if (!isWin11OrGreater()) {
  939. return false;
  940. }
  941. if (attribute.toBool()) {
  942. extendMargins();
  943. const _DWM_SYSTEMBACKDROP_TYPE backdropType = _DWMSBT_TRANSIENTWINDOW;
  944. apis.pDwmSetWindowAttribute(hwnd, _DWMWA_SYSTEMBACKDROP_TYPE, &backdropType,
  945. sizeof(backdropType));
  946. // PRIVATE API REFERENCE:
  947. // QColor gradientColor = {};
  948. // ACCENT_POLICY policy{};
  949. // policy.dwAccentState = ACCENT_ENABLE_ACRYLICBLURBEHIND;
  950. // policy.dwAccentFlags = ACCENT_ENABLE_ACRYLIC_WITH_LUMINOSITY;
  951. // // This API expects the #AABBGGRR format.
  952. // policy.dwGradientColor =
  953. // DWORD(qRgba(gradientColor.blue(), gradientColor.green(),
  954. // gradientColor.red(), gradientColor.alpha()));
  955. // WINDOWCOMPOSITIONATTRIBDATA wcad{};
  956. // wcad.Attrib = WCA_ACCENT_POLICY;
  957. // wcad.pvData = &policy;
  958. // wcad.cbData = sizeof(policy);
  959. // apis.pSetWindowCompositionAttribute(hwnd, &wcad);
  960. } else {
  961. const _DWM_SYSTEMBACKDROP_TYPE backdropType = _DWMSBT_AUTO;
  962. apis.pDwmSetWindowAttribute(hwnd, _DWMWA_SYSTEMBACKDROP_TYPE, &backdropType,
  963. sizeof(backdropType));
  964. // PRIVATE API REFERENCE:
  965. // ACCENT_POLICY policy{};
  966. // policy.dwAccentState = ACCENT_DISABLED;
  967. // policy.dwAccentFlags = ACCENT_NONE;
  968. // WINDOWCOMPOSITIONATTRIBDATA wcad{};
  969. // wcad.Attrib = WCA_ACCENT_POLICY;
  970. // wcad.pvData = &policy;
  971. // wcad.cbData = sizeof(policy);
  972. // apis.pSetWindowCompositionAttribute(hwnd, &wcad);
  973. restoreMargins();
  974. }
  975. effectBugWorkaround();
  976. return true;
  977. }
  978. if (key == QStringLiteral("dwm-blur")) {
  979. // Extending window frame would break this effect for some unknown reason.
  980. restoreMargins();
  981. if (attribute.toBool()) {
  982. if (isWin8OrGreater()) {
  983. ACCENT_POLICY policy{};
  984. policy.dwAccentState = ACCENT_ENABLE_BLURBEHIND;
  985. policy.dwAccentFlags = ACCENT_NONE;
  986. WINDOWCOMPOSITIONATTRIBDATA wcad{};
  987. wcad.Attrib = WCA_ACCENT_POLICY;
  988. wcad.pvData = &policy;
  989. wcad.cbData = sizeof(policy);
  990. apis.pSetWindowCompositionAttribute(hwnd, &wcad);
  991. } else {
  992. DWM_BLURBEHIND bb{};
  993. bb.fEnable = TRUE;
  994. bb.dwFlags = DWM_BB_ENABLE;
  995. apis.pDwmEnableBlurBehindWindow(hwnd, &bb);
  996. }
  997. } else {
  998. if (isWin8OrGreater()) {
  999. ACCENT_POLICY policy{};
  1000. policy.dwAccentState = ACCENT_DISABLED;
  1001. policy.dwAccentFlags = ACCENT_NONE;
  1002. WINDOWCOMPOSITIONATTRIBDATA wcad{};
  1003. wcad.Attrib = WCA_ACCENT_POLICY;
  1004. wcad.pvData = &policy;
  1005. wcad.cbData = sizeof(policy);
  1006. apis.pSetWindowCompositionAttribute(hwnd, &wcad);
  1007. } else {
  1008. DWM_BLURBEHIND bb{};
  1009. bb.fEnable = FALSE;
  1010. bb.dwFlags = DWM_BB_ENABLE;
  1011. apis.pDwmEnableBlurBehindWindow(hwnd, &bb);
  1012. }
  1013. }
  1014. effectBugWorkaround();
  1015. return true;
  1016. }
  1017. return false;
  1018. }
  1019. QWK_USED static constexpr const struct {
  1020. const WPARAM wParam = MAKEWPARAM(44500, 61897);
  1021. const LPARAM lParam = MAKELPARAM(62662, 44982); // Not used. Reserve for future use.
  1022. } kMessageTag;
  1023. static inline quint64 getKeyState() {
  1024. quint64 result = 0;
  1025. const auto &get = [](const int virtualKey) -> bool {
  1026. return (::GetAsyncKeyState(virtualKey) < 0);
  1027. };
  1028. const bool buttonSwapped = ::GetSystemMetrics(SM_SWAPBUTTON);
  1029. if (get(VK_LBUTTON)) {
  1030. result |= (buttonSwapped ? MK_RBUTTON : MK_LBUTTON);
  1031. }
  1032. if (get(VK_RBUTTON)) {
  1033. result |= (buttonSwapped ? MK_LBUTTON : MK_RBUTTON);
  1034. }
  1035. if (get(VK_SHIFT)) {
  1036. result |= MK_SHIFT;
  1037. }
  1038. if (get(VK_CONTROL)) {
  1039. result |= MK_CONTROL;
  1040. }
  1041. if (get(VK_MBUTTON)) {
  1042. result |= MK_MBUTTON;
  1043. }
  1044. if (get(VK_XBUTTON1)) {
  1045. result |= MK_XBUTTON1;
  1046. }
  1047. if (get(VK_XBUTTON2)) {
  1048. result |= MK_XBUTTON2;
  1049. }
  1050. return result;
  1051. }
  1052. static void emulateClientAreaMessage(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam,
  1053. const std::optional<int> &overrideMessage = std::nullopt) {
  1054. const int myMsg = overrideMessage.value_or(message);
  1055. const auto wParamNew = [myMsg, wParam]() -> WPARAM {
  1056. if (myMsg == WM_NCMOUSELEAVE) {
  1057. // wParam is always ignored in mouse leave messages, but here we
  1058. // give them a special tag to be able to distinguish which messages
  1059. // are sent by ourselves.
  1060. return kMessageTag.wParam;
  1061. }
  1062. const quint64 keyState = getKeyState();
  1063. if ((myMsg >= WM_NCXBUTTONDOWN) && (myMsg <= WM_NCXBUTTONDBLCLK)) {
  1064. const auto xButtonMask = GET_XBUTTON_WPARAM(wParam);
  1065. return MAKEWPARAM(keyState, xButtonMask);
  1066. }
  1067. return keyState;
  1068. }();
  1069. const auto lParamNew = [myMsg, lParam, hWnd]() -> LPARAM {
  1070. if (myMsg == WM_NCMOUSELEAVE) {
  1071. // lParam is always ignored in mouse leave messages.
  1072. return 0;
  1073. }
  1074. const auto screenPos = POINT{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
  1075. POINT clientPos = screenPos;
  1076. ::ScreenToClient(hWnd, &clientPos);
  1077. return MAKELPARAM(clientPos.x, clientPos.y);
  1078. }();
  1079. #if 0
  1080. # define SEND_MESSAGE ::SendMessageW
  1081. #else
  1082. # define SEND_MESSAGE ::PostMessageW
  1083. #endif
  1084. switch (myMsg) {
  1085. case WM_NCHITTEST: // Treat hit test messages as mouse move events.
  1086. case WM_NCMOUSEMOVE:
  1087. SEND_MESSAGE(hWnd, WM_MOUSEMOVE, wParamNew, lParamNew);
  1088. break;
  1089. case WM_NCLBUTTONDOWN:
  1090. SEND_MESSAGE(hWnd, WM_LBUTTONDOWN, wParamNew, lParamNew);
  1091. break;
  1092. case WM_NCLBUTTONUP:
  1093. SEND_MESSAGE(hWnd, WM_LBUTTONUP, wParamNew, lParamNew);
  1094. break;
  1095. case WM_NCLBUTTONDBLCLK:
  1096. SEND_MESSAGE(hWnd, WM_LBUTTONDBLCLK, wParamNew, lParamNew);
  1097. break;
  1098. case WM_NCRBUTTONDOWN:
  1099. SEND_MESSAGE(hWnd, WM_RBUTTONDOWN, wParamNew, lParamNew);
  1100. break;
  1101. case WM_NCRBUTTONUP:
  1102. SEND_MESSAGE(hWnd, WM_RBUTTONUP, wParamNew, lParamNew);
  1103. break;
  1104. case WM_NCRBUTTONDBLCLK:
  1105. SEND_MESSAGE(hWnd, WM_RBUTTONDBLCLK, wParamNew, lParamNew);
  1106. break;
  1107. case WM_NCMBUTTONDOWN:
  1108. SEND_MESSAGE(hWnd, WM_MBUTTONDOWN, wParamNew, lParamNew);
  1109. break;
  1110. case WM_NCMBUTTONUP:
  1111. SEND_MESSAGE(hWnd, WM_MBUTTONUP, wParamNew, lParamNew);
  1112. break;
  1113. case WM_NCMBUTTONDBLCLK:
  1114. SEND_MESSAGE(hWnd, WM_MBUTTONDBLCLK, wParamNew, lParamNew);
  1115. break;
  1116. case WM_NCXBUTTONDOWN:
  1117. SEND_MESSAGE(hWnd, WM_XBUTTONDOWN, wParamNew, lParamNew);
  1118. break;
  1119. case WM_NCXBUTTONUP:
  1120. SEND_MESSAGE(hWnd, WM_XBUTTONUP, wParamNew, lParamNew);
  1121. break;
  1122. case WM_NCXBUTTONDBLCLK:
  1123. SEND_MESSAGE(hWnd, WM_XBUTTONDBLCLK, wParamNew, lParamNew);
  1124. break;
  1125. #if 0 // ### TODO: How to handle touch events?
  1126. case WM_NCPOINTERUPDATE:
  1127. case WM_NCPOINTERDOWN:
  1128. case WM_NCPOINTERUP:
  1129. break;
  1130. #endif
  1131. case WM_NCMOUSEHOVER:
  1132. SEND_MESSAGE(hWnd, WM_MOUSEHOVER, wParamNew, lParamNew);
  1133. break;
  1134. case WM_NCMOUSELEAVE:
  1135. SEND_MESSAGE(hWnd, WM_MOUSELEAVE, wParamNew, lParamNew);
  1136. break;
  1137. default:
  1138. // unreachable
  1139. break;
  1140. }
  1141. #undef SEND_MESSAGE
  1142. }
  1143. static inline void requestForMouseLeaveMessage(HWND hWnd, bool nonClient) {
  1144. TRACKMOUSEEVENT tme{};
  1145. tme.cbSize = sizeof(tme);
  1146. tme.dwFlags = TME_LEAVE;
  1147. if (nonClient) {
  1148. tme.dwFlags |= TME_NONCLIENT;
  1149. }
  1150. tme.hwndTrack = hWnd;
  1151. tme.dwHoverTime = HOVER_DEFAULT;
  1152. ::TrackMouseEvent(&tme);
  1153. }
  1154. bool Win32WindowContext::snapLayoutHandler(HWND hWnd, UINT message, WPARAM wParam,
  1155. LPARAM lParam, LRESULT *result) {
  1156. switch (message) {
  1157. case WM_MOUSELEAVE: {
  1158. if (wParam != kMessageTag.wParam) {
  1159. // Qt will call TrackMouseEvent() to get the WM_MOUSELEAVE message when it
  1160. // receives WM_MOUSEMOVE messages, and since we are converting every
  1161. // WM_NCMOUSEMOVE message to WM_MOUSEMOVE message and send it back to the window
  1162. // to be able to hover our controls, we also get lots of WM_MOUSELEAVE messages
  1163. // at the same time because of the reason above, and these superfluous mouse
  1164. // leave events cause Qt to think the mouse has left the control, and thus we
  1165. // actually lost the hover state. So we filter out these superfluous mouse leave
  1166. // events here to avoid this issue.
  1167. DWORD dwScreenPos = ::GetMessagePos();
  1168. POINT screenPoint{GET_X_LPARAM(dwScreenPos), GET_Y_LPARAM(dwScreenPos)};
  1169. ::ScreenToClient(hWnd, &screenPoint);
  1170. QPoint qtScenePos = QHighDpi::fromNativeLocalPosition(point2qpoint(screenPoint),
  1171. m_windowHandle.data());
  1172. auto dummy = WindowAgentBase::Unknown;
  1173. if (isInSystemButtons(qtScenePos, &dummy)) {
  1174. // We must record whether the last WM_MOUSELEAVE was filtered, because if
  1175. // Qt does not receive this message it will not call TrackMouseEvent()
  1176. // again, resulting in the client area not responding to any mouse event.
  1177. mouseLeaveBlocked = true;
  1178. *result = FALSE;
  1179. return true;
  1180. }
  1181. }
  1182. mouseLeaveBlocked = false;
  1183. break;
  1184. }
  1185. case WM_MOUSEMOVE: {
  1186. // At appropriate time, we will call TrackMouseEvent() for Qt. Simultaneously,
  1187. // we unset `mouseLeaveBlocked` mark and pretend as if Qt has received
  1188. // WM_MOUSELEAVE.
  1189. if (lastHitTestResult != WindowPart::ChromeButton && mouseLeaveBlocked) {
  1190. mouseLeaveBlocked = false;
  1191. requestForMouseLeaveMessage(hWnd, false);
  1192. }
  1193. break;
  1194. }
  1195. case WM_NCMOUSEMOVE:
  1196. case WM_NCLBUTTONDOWN:
  1197. case WM_NCLBUTTONUP:
  1198. case WM_NCLBUTTONDBLCLK:
  1199. case WM_NCRBUTTONDOWN:
  1200. case WM_NCRBUTTONUP:
  1201. case WM_NCRBUTTONDBLCLK:
  1202. case WM_NCMBUTTONDOWN:
  1203. case WM_NCMBUTTONUP:
  1204. case WM_NCMBUTTONDBLCLK:
  1205. case WM_NCXBUTTONDOWN:
  1206. case WM_NCXBUTTONUP:
  1207. case WM_NCXBUTTONDBLCLK:
  1208. #if 0 // ### TODO: How to handle touch events?
  1209. case WM_NCPOINTERUPDATE:
  1210. case WM_NCPOINTERDOWN:
  1211. case WM_NCPOINTERUP:
  1212. #endif
  1213. case WM_NCMOUSEHOVER: {
  1214. if (message == WM_NCMOUSEMOVE) {
  1215. if (lastHitTestResult != WindowPart::ChromeButton) {
  1216. // https://github.com/qt/qtbase/blob/e26a87f1ecc40bc8c6aa5b889fce67410a57a702/src/widgets/kernel/qwidgetwindow.cpp#L472
  1217. // When the mouse press event arrives, QWidgetWindow will implicitly grab
  1218. // the top widget right under the mouse, and set `qt_button_down` to this
  1219. // widget. At this time, no other widgets will accept the mouse event until
  1220. // QWidgetWindow receives the mouse release event, then set `qt_button_down`
  1221. // to null.
  1222. // Imagine the following situation, now the main window has a pop-up menu,
  1223. // the focus is not on the main window, if we click outside the pop-up menu,
  1224. // the menu will close, which seems to be completely fine. But if we close
  1225. // the menu by clicking on the title bar draggable area, then other widgets
  1226. // won't accept the mouse message afterwards.
  1227. // Here's the reason.
  1228. // When the mouse is placed in the draggable area of the title bar, there
  1229. // are two situations.
  1230. // 1. If the focus is on the main window, and the last result of
  1231. // WM_NCHITTEST is HTCAPTION, the mouse click event in the title bar is
  1232. // taken over by Windows and Qt does not receive the mouse click event.
  1233. // 2. If the main window has a pop-up menu, it is completely different. When
  1234. // the mouse is pressed on the title bar, Windows sends the WM_LBUTTONDOWN
  1235. // message to the window plane of the pop-up menu, the menu is closed, but
  1236. // Qt will continue to forward the event to the QWidget under the mouse, and
  1237. // the event will be processed by QWidgetWindow, causing the title bar
  1238. // widget to be implicitly grabbed. After the menu is closed, Windows
  1239. // immediately sends WM_NCHITTEST, because the mouse is in the title bar
  1240. // draggable area, the result is HTCAPTION, so when the mouse is released,
  1241. // Windows sends WM_NCLBUTTONUP, which is a non-client message, and it
  1242. // will be ignored by Qt. As a consequence, QWidgetWindow can't receive a
  1243. // mouse release message in the client area, so the grab remains, and other
  1244. // widgets cannot receive mouse events.
  1245. // Since we didn't watch the menu window, we cannot capture any mouse
  1246. // press events sent by Windows, so we cannot solve this problem by
  1247. // recording mouse events. Fortunately, we found that the main window will
  1248. // receive a WM_NCMOUSEMOVE message immediately after the menu is closed, so
  1249. // we just manually send a mouse release event when this message arrives and
  1250. // set qt_button_down to null. Don't worry, when receiving WM_NCMOUSEMOVE,
  1251. // there shouldn't be any control in the state of being grabbed.
  1252. // In the native window, although QWidgetWindow handles the forwarded mouse
  1253. // press event when the menu is closed, since the native title bar is not a
  1254. // QWidget, no widget will be grabbed, and `qt_button_down` remains empty,
  1255. // the above problems would not arise.
  1256. m_delegate->resetQtGrabbedControl(m_host);
  1257. // If the mouse moves from chrome buttons to other non-client areas, a
  1258. // WM_MOUSELEAVE message should be sent.
  1259. if (mouseLeaveBlocked) {
  1260. emulateClientAreaMessage(hWnd, message, wParam, lParam,
  1261. WM_NCMOUSELEAVE);
  1262. }
  1263. }
  1264. }
  1265. if (lastHitTestResult == WindowPart::ChromeButton) {
  1266. if (message == WM_NCMOUSEMOVE) {
  1267. // ### FIXME FIXME FIXME
  1268. // ### FIXME: Calling DefWindowProc() here is really dangerous, investigate
  1269. // how to avoid doing this.
  1270. // ### FIXME FIXME FIXME
  1271. *result = ::DefWindowProcW(hWnd, WM_NCMOUSEMOVE, wParam, lParam);
  1272. emulateClientAreaMessage(hWnd, message, wParam, lParam);
  1273. return true;
  1274. }
  1275. if (lastHitTestResultRaw == HTSYSMENU) {
  1276. switch (message) {
  1277. case WM_NCLBUTTONDOWN:
  1278. if (iconButtonClickLevel == 0) {
  1279. // A message of WM_SYSCOMMAND with SC_MOUSEMENU will be sent by
  1280. // Windows, and the current control flow will be blocked by the
  1281. // menu while Windows will create and execute a new event loop
  1282. // until the menu returns
  1283. iconButtonClickTime = ::GetTickCount64();
  1284. *result = ::DefWindowProcW(hWnd, message, wParam, lParam);
  1285. iconButtonClickTime = 0;
  1286. if (iconButtonClickLevel & IconButtonTriggersClose) {
  1287. ::PostMessageW(hWnd, WM_SYSCOMMAND, SC_CLOSE, 0);
  1288. }
  1289. if (iconButtonClickLevel & IconButtonDoubleClicked) {
  1290. iconButtonClickLevel = 0;
  1291. }
  1292. // Otherwise, no need to reset `iconButtonClickLevel` if not to
  1293. // close, if it has value, there must be another incoming
  1294. // WM_NCLBUTTONDOWN
  1295. } else {
  1296. iconButtonClickLevel = 0;
  1297. }
  1298. break;
  1299. case WM_NCLBUTTONDBLCLK:
  1300. // A message of WM_SYSCOMMAND with SC_CLOSE will be sent by Windows
  1301. *result = ::DefWindowProcW(hWnd, message, wParam, lParam);
  1302. break;
  1303. default:
  1304. *result = FALSE;
  1305. emulateClientAreaMessage(hWnd, message, wParam, lParam);
  1306. break;
  1307. }
  1308. } else {
  1309. // According to MSDN, we should return non-zero for X button messages to
  1310. // indicate we have handled these messages (due to historical reasons), for
  1311. // all other messages we should return zero instead.
  1312. *result =
  1313. (((message >= WM_NCXBUTTONDOWN) && (message <= WM_NCXBUTTONDBLCLK))
  1314. ? TRUE
  1315. : FALSE);
  1316. emulateClientAreaMessage(hWnd, message, wParam, lParam);
  1317. }
  1318. return true;
  1319. }
  1320. break;
  1321. }
  1322. case WM_NCMOUSELEAVE: {
  1323. const WindowPart currentWindowPart = lastHitTestResult;
  1324. if (currentWindowPart == WindowPart::ChromeButton) {
  1325. // If we press on the chrome button and move mouse, Windows will take the
  1326. // pressing area as HTCLIENT which maybe because of our former retransmission of
  1327. // WM_NCLBUTTONDOWN, as a result, a WM_NCMOUSELEAVE will come immediately and a
  1328. // lot of WM_MOUSEMOVE will come if we move the mouse, we should track the mouse
  1329. // in advance. (May be redundant?)
  1330. if (mouseLeaveBlocked) {
  1331. mouseLeaveBlocked = false;
  1332. requestForMouseLeaveMessage(hWnd, false);
  1333. }
  1334. } else {
  1335. if (mouseLeaveBlocked) {
  1336. // The mouse is moving from the chrome button to other non-client area, we
  1337. // should emulate a WM_MOUSELEAVE message to reset the button state.
  1338. emulateClientAreaMessage(hWnd, message, wParam, lParam, WM_NCMOUSELEAVE);
  1339. }
  1340. if (currentWindowPart == WindowPart::Outside) {
  1341. // Notice: we're not going to clear window part cache when the mouse leaves
  1342. // window from client area, which means we will get previous window part as
  1343. // HTCLIENT if the mouse leaves window from client area and enters window
  1344. // from non-client area, but it has no bad effect.
  1345. // Why do we need to call this function here?
  1346. m_delegate->resetQtGrabbedControl(m_host);
  1347. }
  1348. }
  1349. break;
  1350. }
  1351. default:
  1352. break;
  1353. }
  1354. return false;
  1355. }
  1356. bool Win32WindowContext::customWindowHandler(HWND hWnd, UINT message, WPARAM wParam,
  1357. LPARAM lParam, LRESULT *result) {
  1358. switch (message) {
  1359. case WM_NCHITTEST: {
  1360. // 原生Win32窗口只有顶边是在窗口内部resize的,其余三边都是在窗口
  1361. // 外部进行resize的,其原理是,WS_THICKFRAME这个窗口样式会在窗
  1362. // 口的左、右和底边添加三个透明的resize区域,这三个区域在正常状态
  1363. // 下是完全不可见的,它们由DWM负责绘制和控制。这些区域的宽度等于
  1364. // (SM_CXSIZEFRAME + SM_CXPADDEDBORDER),高度等于
  1365. // (SM_CYSIZEFRAME + SM_CXPADDEDBORDER),在100%缩放时,均等
  1366. // 于8像素。它们属于窗口区域的一部分,但不属于客户区,而是属于非客
  1367. // 户区,因此GetWindowRect获取的区域中是包含这三个resize区域的,
  1368. // 而GetClientRect获取的区域是不包含它们的。当把
  1369. // DWMWA_EXTENDED_FRAME_BOUNDS作为参数调用
  1370. // DwmGetWindowAttribute时,也能获取到一个窗口大小,这个大小介
  1371. // 于前面两者之间,暂时不知道这个数据的意义及其作用。我们在
  1372. // WM_NCCALCSIZE消息的处理中,已经把整个窗口都设置为客户区了,也
  1373. // 就是说,我们的窗口已经没有非客户区了,因此那三个透明的resize区
  1374. // 域,此刻也已经成为窗口客户区的一部分了,从而变得不透明了。所以
  1375. // 现在的resize,看起来像是在窗口内部resize,是因为原本透明的地方
  1376. // 现在变得不透明了,实际上,单纯从范围上来看,现在我们resize的地方,
  1377. // 就是普通窗口的边框外部,那三个透明区域的范围。
  1378. // 因此,如果我们把边框完全去掉(就是我们正在做的事情),resize就
  1379. // 会看起来是在内部进行,这个问题通过常规方法非常难以解决。我测试过
  1380. // QQ和钉钉的窗口,它们的窗口就是在外部resize,但实际上它们是通过
  1381. // 把窗口实际的内容,嵌入到一个完全透明的但尺寸要大一圈的窗口中实现
  1382. // 的,虽然看起来效果还不错,但对于此项目而言,代码和窗口结构过于复
  1383. // 杂,因此我没有采用此方案。然而,对于具体的软件项目而言,其做法也
  1384. // 不失为一个优秀的解决方案,毕竟其在大多数条件下的表现都还可以。
  1385. //
  1386. // 和1.x的做法不同,现在的2.x选择了保留窗口三边,去除整个窗口顶部,
  1387. // 好处是保留了系统的原生边框,外观较好,且与系统结合紧密,而且resize
  1388. // 的表现也有很大改善,缺点是需要自行绘制顶部边框线。原本以为只能像
  1389. // Windows Terminal那样在WM_PAINT里搞黑魔法,但后来发现,其实只
  1390. // 要颜色相近,我们自行绘制一根实线也几乎能以假乱真,而且这样也不会
  1391. // 破坏Qt自己的绘制系统,能做到不依赖黑魔法就能实现像Windows Terminal
  1392. // 那样外观和功能都比较完美的自定义边框。
  1393. // A normal Win32 window can be resized outside of it. Here is the
  1394. // reason: the WS_THICKFRAME window style will cause a window has three
  1395. // transparent areas beside the window's left, right and bottom
  1396. // edge. Their width or height is eight pixels if the window is not
  1397. // scaled. In most cases, they are totally invisible. It's DWM's
  1398. // responsibility to draw and control them. They exist to let the
  1399. // user resize the window, visually outside of it. They are in the
  1400. // window area, but not the client area, so they are in the
  1401. // non-client area actually. But we have turned the whole window
  1402. // area into client area in WM_NCCALCSIZE, so the three transparent
  1403. // resize areas also become a part of the client area and thus they
  1404. // become visible. When we resize the window, it looks like we are
  1405. // resizing inside of it, however, that's because the transparent
  1406. // resize areas are visible now, we ARE resizing outside of the
  1407. // window actually. But I don't know how to make them become
  1408. // transparent again without breaking the frame shadow drawn by DWM.
  1409. // If you really want to solve it, you can try to embed your window
  1410. // into a larger transparent window and draw the frame shadow
  1411. // yourself. As what we have said in WM_NCCALCSIZE, you can only
  1412. // remove the top area of the window, this will let us be able to
  1413. // resize outside of the window and don't need much process in this
  1414. // message, it looks like a perfect plan, however, the top border is
  1415. // missing due to the whole top area is removed, and it's very hard
  1416. // to bring it back because we have to use a trick in WM_PAINT
  1417. // (learned from Windows Terminal), but no matter what we do in
  1418. // WM_PAINT, it will always break the backing store mechanism of Qt,
  1419. // so actually we can't do it. And it's very difficult to do such
  1420. // things in NativeEventFilters as well. What's worse, if we really
  1421. // do this, the four window borders will become white and they look
  1422. // horrible in dark mode. This solution only supports Windows 10
  1423. // because the border width on Win10 is only one pixel, however it's
  1424. // eight pixels on Windows 7 so preserving the three window borders
  1425. // looks terrible on old systems.
  1426. //
  1427. // Unlike the 1.x code, we choose to preserve the three edges of the
  1428. // window in 2.x, and get rid of the whole top part of the window.
  1429. // There are quite some advantages such as the appearance looks much
  1430. // better and due to we have the original system window frame, our
  1431. // window can behave just like a normal Win32 window even if we now
  1432. // doesn't have a title bar at all. Most importantly, the flicker and
  1433. // jitter during window resizing is totally gone now. The disadvantage
  1434. // is we have to draw a top frame border ourselves. Previously I thought
  1435. // we have to do the black magic in WM_PAINT just like what Windows
  1436. // Terminal does, however, later I found that if we choose a proper
  1437. // color, our homemade top border can almost have exactly the same
  1438. // appearance with the system's one.
  1439. [[maybe_unused]] const auto &hitTestRecorder = qScopeGuard([this, result]() {
  1440. lastHitTestResultRaw = int(*result);
  1441. lastHitTestResult = getHitWindowPart(lastHitTestResultRaw);
  1442. });
  1443. POINT nativeGlobalPos{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
  1444. POINT nativeLocalPos = nativeGlobalPos;
  1445. ::ScreenToClient(hWnd, &nativeLocalPos);
  1446. RECT clientRect{0, 0, 0, 0};
  1447. ::GetClientRect(hWnd, &clientRect);
  1448. auto clientWidth = RECT_WIDTH(clientRect);
  1449. auto clientHeight = RECT_HEIGHT(clientRect);
  1450. QPoint qtScenePos = QHighDpi::fromNativeLocalPosition(point2qpoint(nativeLocalPos),
  1451. m_windowHandle.data());
  1452. int frameSize = getResizeBorderThickness(hWnd);
  1453. bool isFixedWidth = isHostWidthFixed();
  1454. bool isFixedHeight = isHostHeightFixed();
  1455. bool isFixedSize = isHostSizeFixed();
  1456. bool isInLeftBorder = nativeLocalPos.x <= frameSize;
  1457. bool isInTopBorder = nativeLocalPos.y <= frameSize;
  1458. bool isInRightBorder = nativeLocalPos.x > clientWidth - frameSize;
  1459. bool isInBottomBorder = nativeLocalPos.y > clientHeight - frameSize;
  1460. bool isInTitleBar = isInTitleBarDraggableArea(qtScenePos);
  1461. WindowAgentBase::SystemButton sysButtonType = WindowAgentBase::Unknown;
  1462. bool isInCaptionButtons = isInSystemButtons(qtScenePos, &sysButtonType);
  1463. static constexpr bool dontOverrideCursor = false; // ### TODO
  1464. if (isInCaptionButtons) {
  1465. // Firstly, we set the hit test result to a default value to be able to detect
  1466. // whether we have changed it or not afterwards.
  1467. *result = HTNOWHERE;
  1468. // Even if the mouse is inside the chrome button area now, we should still allow
  1469. // the user to be able to resize the window with the top or right window border,
  1470. // this is also the normal behavior of a native Win32 window (but only when the
  1471. // window is not maximized/fullscreen/minimized, of course).
  1472. if (isWindowNoState(hWnd)) {
  1473. static constexpr const quint8 kBorderSize = 2;
  1474. bool isTop = nativeLocalPos.y <= kBorderSize;
  1475. bool isLeft = nativeLocalPos.x <= kBorderSize;
  1476. bool isRight = nativeLocalPos.x > clientWidth - kBorderSize;
  1477. if (isTop || isLeft || isRight) {
  1478. if (isFixedSize || dontOverrideCursor) {
  1479. // The user doesn't want the window to be resized, so we tell
  1480. // Windows we are in the client area so that the controls beneath
  1481. // the mouse cursor can still be hovered or clicked.
  1482. *result = isInTitleBar ? HTCAPTION : HTCLIENT;
  1483. } else {
  1484. if (isTop) {
  1485. if (isLeft) {
  1486. if (isFixedWidth) {
  1487. *result = HTTOP;
  1488. } else if (isFixedHeight) {
  1489. *result = HTLEFT;
  1490. } else {
  1491. *result = HTTOPLEFT;
  1492. }
  1493. } else if (isRight) {
  1494. if (isFixedWidth) {
  1495. *result = HTTOP;
  1496. } else if (isFixedHeight) {
  1497. *result = HTRIGHT;
  1498. } else {
  1499. *result = HTTOPRIGHT;
  1500. }
  1501. } else {
  1502. *result = isFixedHeight ? HTBORDER : HTTOP;
  1503. }
  1504. } else {
  1505. if (isFixedWidth) {
  1506. *result = HTBORDER;
  1507. } else {
  1508. *result = isLeft ? HTLEFT : HTRIGHT;
  1509. }
  1510. }
  1511. }
  1512. }
  1513. }
  1514. if (*result == HTNOWHERE) {
  1515. // SUCCESS, we are now really inside one of the chrome buttons, tell Windows the
  1516. // exact role of our button. The Snap Layout feature introduced in Windows
  1517. // 11 won't work without this.
  1518. switch (sysButtonType) {
  1519. case WindowAgentBase::WindowIcon:
  1520. *result = HTSYSMENU;
  1521. break;
  1522. case WindowAgentBase::Help:
  1523. *result = HTHELP;
  1524. break;
  1525. case WindowAgentBase::Minimize:
  1526. *result = HTREDUCE;
  1527. break;
  1528. case WindowAgentBase::Maximize:
  1529. *result = HTZOOM;
  1530. break;
  1531. case WindowAgentBase::Close:
  1532. *result = HTCLOSE;
  1533. break;
  1534. default:
  1535. // unreachable
  1536. break;
  1537. }
  1538. }
  1539. if (*result == HTNOWHERE) {
  1540. // SUCCESS, it seems we are not inside the window resize area, nor inside the
  1541. // chrome buttons, tell Windows we are in the client area to let Qt handle
  1542. // this event.
  1543. *result = HTCLIENT;
  1544. }
  1545. return true;
  1546. }
  1547. // SUCCESS, we are not inside any chrome buttons, try to find out which part of the
  1548. // window are we hitting.
  1549. bool max = isMaximized(hWnd);
  1550. bool full = isFullScreen(hWnd);
  1551. if (isSystemBorderEnabled()) {
  1552. // This will handle the left, right and bottom parts of the frame
  1553. // because we didn't change them.
  1554. LRESULT originalHitTestResult = ::DefWindowProcW(hWnd, WM_NCHITTEST, 0, lParam);
  1555. if (originalHitTestResult != HTCLIENT) {
  1556. // Even if the window is not resizable, we still can't return HTCLIENT here
  1557. // because when we enter this code path, it means the mouse cursor is
  1558. // outside the window, that is, the three transparent window resize area.
  1559. // Returning HTCLIENT will confuse Windows, we can't put our controls there
  1560. // anyway.
  1561. *result = HTNOWHERE; // Make sure we can know we don't set any value
  1562. // explicitly later.
  1563. if (originalHitTestResult == HTCAPTION) {
  1564. } else if (isFixedSize || dontOverrideCursor) {
  1565. *result = HTBORDER;
  1566. } else if (isFixedWidth || isFixedHeight) {
  1567. if (originalHitTestResult == HTTOPLEFT) {
  1568. if (isFixedWidth) {
  1569. *result = HTTOP;
  1570. } else {
  1571. *result = HTLEFT;
  1572. }
  1573. } else if (originalHitTestResult == HTTOPRIGHT) {
  1574. if (isFixedWidth) {
  1575. *result = HTTOP;
  1576. } else {
  1577. *result = HTRIGHT;
  1578. }
  1579. } else if (originalHitTestResult == HTBOTTOMRIGHT) {
  1580. if (isFixedWidth) {
  1581. *result = HTBOTTOM;
  1582. } else {
  1583. *result = HTRIGHT;
  1584. }
  1585. } else if (originalHitTestResult == HTBOTTOMLEFT) {
  1586. if (isFixedWidth) {
  1587. *result = HTBOTTOM;
  1588. } else {
  1589. *result = HTLEFT;
  1590. }
  1591. } else if (originalHitTestResult == HTLEFT ||
  1592. originalHitTestResult == HTRIGHT) {
  1593. if (isFixedWidth) {
  1594. *result = HTBORDER;
  1595. }
  1596. } else if (originalHitTestResult == HTTOP ||
  1597. originalHitTestResult == HTBOTTOM) {
  1598. if (isFixedHeight) {
  1599. *result = HTBORDER;
  1600. }
  1601. }
  1602. }
  1603. if (*result == HTNOWHERE) {
  1604. *result = originalHitTestResult;
  1605. }
  1606. return true;
  1607. }
  1608. if (full) {
  1609. *result = HTCLIENT;
  1610. return true;
  1611. }
  1612. if (max) {
  1613. *result = isInTitleBar ? HTCAPTION : HTCLIENT;
  1614. return true;
  1615. }
  1616. // At this point, we know that the cursor is inside the client area,
  1617. // so it has to be either the little border at the top of our custom
  1618. // title bar or the drag bar. Apparently, it must be the drag bar or
  1619. // the little border at the top which the user can use to move or
  1620. // resize the window.
  1621. if (isInTopBorder) {
  1622. // Return HTCLIENT instead of HTBORDER here, because the mouse is
  1623. // inside our homemade title bar now, return HTCLIENT to let our
  1624. // title bar can still capture mouse events.
  1625. *result = [&]() {
  1626. if (isFixedSize || isFixedHeight || dontOverrideCursor ||
  1627. (isFixedWidth && (isInLeftBorder || isInRightBorder))) {
  1628. if (isInTitleBar) {
  1629. return HTCAPTION;
  1630. } else {
  1631. return HTCLIENT;
  1632. }
  1633. } else {
  1634. return HTTOP;
  1635. }
  1636. }();
  1637. return true;
  1638. }
  1639. if (isInTitleBar) {
  1640. *result = HTCAPTION;
  1641. return true;
  1642. }
  1643. *result = HTCLIENT;
  1644. return true;
  1645. } else {
  1646. if (full) {
  1647. *result = HTCLIENT;
  1648. return true;
  1649. }
  1650. if (max || isFixedSize || dontOverrideCursor) {
  1651. *result = isInTitleBar ? HTCAPTION : HTCLIENT;
  1652. return true;
  1653. }
  1654. if (isFixedWidth || isFixedHeight) {
  1655. if (isInLeftBorder && isInTopBorder) {
  1656. if (isFixedWidth) {
  1657. *result = HTTOP;
  1658. } else {
  1659. *result = HTLEFT;
  1660. }
  1661. } else if (isInRightBorder && isInTopBorder) {
  1662. if (isFixedWidth) {
  1663. *result = HTTOP;
  1664. } else {
  1665. *result = HTRIGHT;
  1666. }
  1667. } else if (isInRightBorder && isInBottomBorder) {
  1668. if (isFixedWidth) {
  1669. *result = HTBOTTOM;
  1670. } else {
  1671. *result = HTRIGHT;
  1672. }
  1673. } else if (isInLeftBorder && isInBottomBorder) {
  1674. if (isFixedWidth) {
  1675. *result = HTBOTTOM;
  1676. } else {
  1677. *result = HTLEFT;
  1678. }
  1679. } else if (isInLeftBorder || isInRightBorder) {
  1680. if (isFixedWidth) {
  1681. *result = HTCLIENT;
  1682. } else {
  1683. *result = isInLeftBorder ? HTLEFT : HTRIGHT;
  1684. }
  1685. } else if (isInTopBorder || isInBottomBorder) {
  1686. if (isFixedHeight) {
  1687. *result = HTCLIENT;
  1688. } else {
  1689. *result = isInTopBorder ? HTTOP : HTBOTTOM;
  1690. }
  1691. } else {
  1692. *result = HTCLIENT;
  1693. }
  1694. return true;
  1695. } else {
  1696. if (isInTopBorder) {
  1697. if (isInLeftBorder) {
  1698. *result = HTTOPLEFT;
  1699. return true;
  1700. }
  1701. if (isInRightBorder) {
  1702. *result = HTTOPRIGHT;
  1703. return true;
  1704. }
  1705. *result = HTTOP;
  1706. return true;
  1707. }
  1708. if (isInBottomBorder) {
  1709. if (isInLeftBorder) {
  1710. *result = HTBOTTOMLEFT;
  1711. return true;
  1712. }
  1713. if (isInRightBorder) {
  1714. *result = HTBOTTOMRIGHT;
  1715. return true;
  1716. }
  1717. *result = HTBOTTOM;
  1718. return true;
  1719. }
  1720. if (isInLeftBorder) {
  1721. *result = HTLEFT;
  1722. return true;
  1723. }
  1724. if (isInRightBorder) {
  1725. *result = HTRIGHT;
  1726. return true;
  1727. }
  1728. }
  1729. if (isInTitleBar) {
  1730. *result = HTCAPTION;
  1731. return true;
  1732. }
  1733. *result = HTCLIENT;
  1734. return true;
  1735. }
  1736. }
  1737. case WM_WINDOWPOSCHANGING: {
  1738. // ### FIXME: How does this problem happen and why is it solved?
  1739. // When toggling the "Show theme color in title bar and window border" setting in
  1740. // Windows Settings, or calling `DrawMenuBar()`, Windows sends a message of
  1741. // WM_WINDOWPOSCHANGING with flags 0x37. If we do not process this message,
  1742. // the client area as a whole will shift to the left, which looks very abnormal if
  1743. // we don't repaint it. This exception disappears if we add SWP_NOCOPYBITS flag.
  1744. // But I don't know what caused the problem, or why this would solve it.
  1745. static constexpr const auto kBadWindowPosFlag =
  1746. SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED;
  1747. const auto windowPos = reinterpret_cast<LPWINDOWPOS>(lParam);
  1748. if (windowPos->flags == kBadWindowPosFlag) {
  1749. windowPos->flags |= SWP_NOCOPYBITS;
  1750. }
  1751. break;
  1752. }
  1753. case WM_SHOWWINDOW: {
  1754. if (!wParam || !isWindowNoState(hWnd) || isFullScreen(hWnd)) {
  1755. break;
  1756. }
  1757. RECT windowRect{};
  1758. ::GetWindowRect(hWnd, &windowRect);
  1759. static constexpr const auto swpFlags = SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED | SWP_NOOWNERZORDER;
  1760. ::SetWindowPos(hWnd, nullptr, 0, 0, RECT_WIDTH(windowRect) + 1, RECT_HEIGHT(windowRect) + 1, swpFlags);
  1761. ::SetWindowPos(hWnd, nullptr, 0, 0, RECT_WIDTH(windowRect), RECT_HEIGHT(windowRect), swpFlags);
  1762. break;
  1763. }
  1764. default:
  1765. break;
  1766. }
  1767. if (!isSystemBorderEnabled()) {
  1768. switch (message) {
  1769. case WM_NCUAHDRAWCAPTION:
  1770. case WM_NCUAHDRAWFRAME: {
  1771. // These undocumented messages are sent to draw themed window
  1772. // borders. Block them to prevent drawing borders over the client
  1773. // area.
  1774. *result = FALSE;
  1775. return true;
  1776. }
  1777. case WM_NCPAINT: {
  1778. // 边框阴影处于非客户区的范围,因此如果直接阻止非客户区的绘制,会导致边框阴影丢失
  1779. if (!isDwmCompositionEnabled()) {
  1780. // Only block WM_NCPAINT when DWM composition is disabled. If
  1781. // it's blocked when DWM composition is enabled, the frame
  1782. // shadow won't be drawn.
  1783. *result = FALSE;
  1784. return true;
  1785. } else {
  1786. break;
  1787. }
  1788. }
  1789. case WM_NCACTIVATE: {
  1790. if (isDwmCompositionEnabled()) {
  1791. // DefWindowProc won't repaint the window border if lParam (normally a HRGN)
  1792. // is -1. See the following link's "lParam" section:
  1793. // https://docs.microsoft.com/en-us/windows/win32/winmsg/wm-ncactivate
  1794. // Don't use "*result = 0" here, otherwise the window won't respond to the
  1795. // window activation state change.
  1796. *result = ::DefWindowProcW(hWnd, WM_NCACTIVATE, wParam, -1);
  1797. } else {
  1798. *result = TRUE;
  1799. }
  1800. return true;
  1801. }
  1802. case WM_SETICON:
  1803. case WM_SETTEXT: {
  1804. // Disable painting while these messages are handled to prevent them
  1805. // from drawing a window caption over the client area.
  1806. const auto oldStyle = static_cast<DWORD>(::GetWindowLongPtrW(hWnd, GWL_STYLE));
  1807. // Prevent Windows from drawing the default title bar by temporarily
  1808. // toggling the WS_VISIBLE style.
  1809. const DWORD newStyle = (oldStyle & ~WS_VISIBLE);
  1810. ::SetWindowLongPtrW(hWnd, GWL_STYLE, static_cast<LONG_PTR>(newStyle));
  1811. triggerFrameChange(hWnd);
  1812. const LRESULT originalResult = ::DefWindowProcW(hWnd, message, wParam, lParam);
  1813. ::SetWindowLongPtrW(hWnd, GWL_STYLE, static_cast<LONG_PTR>(oldStyle));
  1814. triggerFrameChange(hWnd);
  1815. *result = originalResult;
  1816. return true;
  1817. }
  1818. default:
  1819. break;
  1820. }
  1821. }
  1822. return false;
  1823. }
  1824. bool Win32WindowContext::nonClientCalcSizeHandler(HWND hWnd, UINT message, WPARAM wParam,
  1825. LPARAM lParam, LRESULT *result) {
  1826. Q_UNUSED(message)
  1827. Q_UNUSED(this)
  1828. // Windows是根据这个消息的返回值来设置窗口的客户区(窗口中真正显示的内容)
  1829. // 和非客户区(标题栏、窗口边框、菜单栏和状态栏等Windows系统自行提供的部分
  1830. // ,不过对于Qt来说,除了标题栏和窗口边框,非客户区基本也都是自绘的)的范
  1831. // 围的,lParam里存放的就是新客户区的几何区域,默认是整个窗口的大小,正常
  1832. // 的程序需要修改这个参数,告知系统窗口的客户区和非客户区的范围(一般来说可
  1833. // 以完全交给Windows,让其自行处理,使用默认的客户区和非客户区),因此如果
  1834. // 我们不修改lParam,就可以使客户区充满整个窗口,从而去掉标题栏和窗口边框
  1835. // (因为这些东西都被客户区给盖住了。但边框阴影也会因此而丢失,不过我们会使
  1836. // 用其他方式将其带回,请参考其他消息的处理,此处不过多提及)。但有个情况要
  1837. // 特别注意,那就是窗口最大化后,窗口的实际尺寸会比屏幕的尺寸大一点,从而使
  1838. // 用户看不到窗口的边界,这样用户就不能在窗口最大化后调整窗口的大小了(虽然
  1839. // 这个做法听起来特别奇怪,但Windows确实就是这样做的),因此如果我们要自行
  1840. // 处理窗口的非客户区,就要在窗口最大化后,将窗口边框的宽度和高度(一般是相
  1841. // 等的)从客户区裁剪掉,否则我们窗口所显示的内容就会超出屏幕边界,显示不全。
  1842. // 如果用户开启了任务栏自动隐藏,在窗口最大化后,还要考虑任务栏的位置。因为
  1843. // 如果窗口最大化后,其尺寸和屏幕尺寸相等(因为任务栏隐藏了,所以窗口最大化
  1844. // 后其实是充满了整个屏幕,变相的全屏了),Windows会认为窗口已经进入全屏的
  1845. // 状态,从而导致自动隐藏的任务栏无法弹出。要避免这个状况,就要使窗口的尺寸
  1846. // 小于屏幕尺寸。我下面的做法参考了火狐、Chromium和Windows Terminal
  1847. // 如果没有开启任务栏自动隐藏,是不存在这个问题的,所以要先进行判断。
  1848. // 一般情况下,*result设置为0(相当于DefWindowProc的返回值为0)就可以了,
  1849. // 根据MSDN的说法,返回0意为此消息已经被程序自行处理了,让Windows跳过此消
  1850. // 息,否则Windows会添加对此消息的默认处理,对于当前这个消息而言,就意味着
  1851. // 标题栏和窗口边框又会回来,这当然不是我们想要的结果。根据MSDN,当wParam
  1852. // 为FALSE时,只能返回0,但当其为TRUE时,可以返回0,也可以返回一个WVR_常
  1853. // 量。根据Chromium的注释,当存在非客户区时,如果返回WVR_REDRAW会导致子
  1854. // 窗口/子控件出现奇怪的bug(自绘控件错位),并且Lucas在Windows 10
  1855. // 上成功复现,说明这个bug至今都没有解决。我查阅了大量资料,发现唯一的解决
  1856. // 方案就是返回0。但如果不存在非客户区,且wParam为TRUE,最好返回
  1857. // WVR_REDRAW,否则窗口在调整大小可能会产生严重的闪烁现象。
  1858. // 虽然对大多数消息来说,返回0都代表让Windows忽略此消息,但实际上不同消息
  1859. // 能接受的返回值是不一样的,请注意自行查阅MSDN。
  1860. // Sent when the size and position of a window's client area must be
  1861. // calculated. By processing this message, an application can
  1862. // control the content of the window's client area when the size or
  1863. // position of the window changes. If wParam is TRUE, lParam points
  1864. // to an NCCALCSIZE_PARAMS structure that contains information an
  1865. // application can use to calculate the new size and position of the
  1866. // client rectangle. If wParam is FALSE, lParam points to a RECT
  1867. // structure. On entry, the structure contains the proposed window
  1868. // rectangle for the window. On exit, the structure should contain
  1869. // the screen coordinates of the corresponding window client area.
  1870. // The client area is the window's content area, the non-client area
  1871. // is the area which is provided by the system, such as the title
  1872. // bar, the four window borders, the frame shadow, the menu bar, the
  1873. // status bar, the scroll bar, etc. But for Qt, it draws most of the
  1874. // window area (client + non-client) itself. We now know that the
  1875. // title bar and the window frame is in the non-client area, and we
  1876. // can set the scope of the client area in this message, so we can
  1877. // remove the title bar and the window frame by let the non-client
  1878. // area be covered by the client area (because we can't really get
  1879. // rid of the non-client area, it will always be there, all we can
  1880. // do is to hide it) , which means we should let the client area's
  1881. // size the same with the whole window's size. So there is no room
  1882. // for the non-client area and then the user won't be able to see it
  1883. // again. But how to achieve this? Very easy, just leave lParam (the
  1884. // re-calculated client area) untouched. But of course you can
  1885. // modify lParam, then the non-client area will be seen and the
  1886. // window borders and the window frame will show up. However, things
  1887. // are quite different when you try to modify the top margin of the
  1888. // client area. DWM will always draw the whole title bar no matter
  1889. // what margin value you set for the top, unless you don't modify it
  1890. // and remove the whole top area (the title bar + the one pixel
  1891. // height window border). This can be confirmed in Windows
  1892. // Terminal's source code, you can also try yourself to verify
  1893. // it. So things will become quite complicated if you want to
  1894. // preserve the four window borders.
  1895. // If `wParam` is `FALSE`, `lParam` points to a `RECT` that contains
  1896. // the proposed window rectangle for our window. During our
  1897. // processing of the `WM_NCCALCSIZE` message, we are expected to
  1898. // modify the `RECT` that `lParam` points to, so that its value upon
  1899. // our return is the new client area. We must return 0 if `wParam`
  1900. // is `FALSE`.
  1901. // If `wParam` is `TRUE`, `lParam` points to a `NCCALCSIZE_PARAMS`
  1902. // struct. This struct contains an array of 3 `RECT`s, the first of
  1903. // which has the exact same meaning as the `RECT` that is pointed to
  1904. // by `lParam` when `wParam` is `FALSE`. The remaining `RECT`s, in
  1905. // conjunction with our return value, can
  1906. // be used to specify portions of the source and destination window
  1907. // rectangles that are valid and should be preserved. We opt not to
  1908. // implement an elaborate client-area preservation technique, and
  1909. // simply return 0, which means "preserve the entire old client area
  1910. // and align it with the upper-left corner of our new client area".
  1911. const auto clientRect = wParam ? &(reinterpret_cast<LPNCCALCSIZE_PARAMS>(lParam))->rgrc[0]
  1912. : reinterpret_cast<LPRECT>(lParam);
  1913. [[maybe_unused]] const auto &flickerReducer = qScopeGuard([this]() {
  1914. // When we receive this message, it means the window size has changed
  1915. // already, and it seems this message always come before any client
  1916. // area size notifications (eg. WM_WINDOWPOSCHANGED and WM_SIZE). Let
  1917. // D3D/VK paint immediately to let user see the latest result as soon
  1918. // as possible.
  1919. const auto &isTargetSurface = [](const QSurface::SurfaceType st) {
  1920. return st != QSurface::RasterSurface && st != QSurface::OpenGLSurface &&
  1921. st != QSurface::RasterGLSurface && st != QSurface::OpenVGSurface;
  1922. };
  1923. if (m_windowHandle && isTargetSurface(m_windowHandle->surfaceType()) &&
  1924. isDwmCompositionEnabled() && DynamicApis::instance().pDwmFlush) {
  1925. DynamicApis::instance().pDwmFlush();
  1926. }
  1927. });
  1928. if (isSystemBorderEnabled()) {
  1929. // Store the original top margin before the default window procedure applies the
  1930. // default frame.
  1931. const LONG originalTop = clientRect->top;
  1932. // Apply the default frame because we don't want to remove the whole window
  1933. // frame, we still need the standard window frame (the resizable frame border
  1934. // and the frame shadow) for the left, bottom and right edges. If we return 0
  1935. // here directly, the whole window frame will be removed (which means there will
  1936. // be no resizable frame border and the frame shadow will also disappear), and
  1937. // that's also how most applications customize their title bars on Windows. It's
  1938. // totally SUCCESS but since we want to preserve as much original frame as possible,
  1939. // we can't use that solution.
  1940. const LRESULT originalResult = ::DefWindowProcW(hWnd, WM_NCCALCSIZE, wParam, lParam);
  1941. if (originalResult != 0) {
  1942. *result = originalResult;
  1943. return true;
  1944. }
  1945. // Re-apply the original top from before the size of the default frame was
  1946. // applied, and the whole top frame (the title bar and the top border) is gone
  1947. // now. For the top frame, we only has 2 choices: (1) remove the top frame
  1948. // entirely, or (2) don't touch it at all. We can't preserve the top border by
  1949. // adjusting the top margin here. If we try to modify the top margin, the
  1950. // original title bar will always be painted by DWM regardless what margin we
  1951. // set, so here we can only remove the top frame entirely and use some special
  1952. // technique to bring the top border back.
  1953. clientRect->top = originalTop;
  1954. }
  1955. const bool max = isMaximized(hWnd);
  1956. const bool full = isFullScreen(hWnd);
  1957. // We don't need this correction when we're fullscreen. We will
  1958. // have the WS_POPUP size, so we don't have to worry about
  1959. // borders, and the default frame will be fine.
  1960. if (max && !full) {
  1961. // When a window is maximized, its size is actually a little bit more
  1962. // than the monitor's work area. The window is positioned and sized in
  1963. // such a way that the resize handles are outside the monitor and
  1964. // then the window is clipped to the monitor so that the resize handle
  1965. // do not appear because you don't need them (because you can't resize
  1966. // a window when it's maximized unless you restore it).
  1967. const quint32 frameSize = getResizeBorderThickness(hWnd);
  1968. clientRect->top += frameSize;
  1969. if (!isSystemBorderEnabled()) {
  1970. clientRect->bottom -= frameSize;
  1971. clientRect->left += frameSize;
  1972. clientRect->right -= frameSize;
  1973. }
  1974. }
  1975. // Attempt to detect if there's an autohide taskbar, and if
  1976. // there is, reduce our size a bit on the side with the taskbar,
  1977. // so the user can still mouse-over the taskbar to reveal it.
  1978. // Make sure to use MONITOR_DEFAULTTONEAREST, so that this will
  1979. // still find the right monitor even when we're restoring from
  1980. // minimized.
  1981. if (max || full) {
  1982. APPBARDATA abd{};
  1983. abd.cbSize = sizeof(abd);
  1984. const UINT taskbarState = ::SHAppBarMessage(ABM_GETSTATE, &abd);
  1985. // First, check if we have an auto-hide taskbar at all:
  1986. if (taskbarState & ABS_AUTOHIDE) {
  1987. bool top = false, bottom = false, left = false, right = false;
  1988. // Due to ABM_GETAUTOHIDEBAREX was introduced in Windows 8.1,
  1989. // we have to use another way to judge this if we are running
  1990. // on Windows 7 or Windows 8.
  1991. if (isWin8Point1OrGreater()) {
  1992. const RECT monitorRect = getMonitorForWindow(hWnd).rcMonitor;
  1993. // This helper can be used to determine if there's an
  1994. // auto-hide taskbar on the given edge of the monitor
  1995. // we're currently on.
  1996. const auto hasAutohideTaskbar = [monitorRect](const UINT edge) -> bool {
  1997. APPBARDATA abd2{};
  1998. abd2.cbSize = sizeof(abd2);
  1999. abd2.uEdge = edge;
  2000. abd2.rc = monitorRect;
  2001. const auto hTaskbar =
  2002. reinterpret_cast<HWND>(::SHAppBarMessage(ABM_GETAUTOHIDEBAREX, &abd2));
  2003. return (hTaskbar != nullptr);
  2004. };
  2005. top = hasAutohideTaskbar(ABE_TOP);
  2006. bottom = hasAutohideTaskbar(ABE_BOTTOM);
  2007. left = hasAutohideTaskbar(ABE_LEFT);
  2008. right = hasAutohideTaskbar(ABE_RIGHT);
  2009. } else {
  2010. int edge = -1;
  2011. APPBARDATA abd2{};
  2012. abd2.cbSize = sizeof(abd2);
  2013. abd2.hWnd = ::FindWindowW(L"Shell_TrayWnd", nullptr);
  2014. HMONITOR windowMonitor = ::MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);
  2015. HMONITOR taskbarMonitor =
  2016. ::MonitorFromWindow(abd2.hWnd, MONITOR_DEFAULTTOPRIMARY);
  2017. if (taskbarMonitor == windowMonitor) {
  2018. ::SHAppBarMessage(ABM_GETTASKBARPOS, &abd2);
  2019. edge = int(abd2.uEdge);
  2020. }
  2021. top = (edge == ABE_TOP);
  2022. bottom = (edge == ABE_BOTTOM);
  2023. left = (edge == ABE_LEFT);
  2024. right = (edge == ABE_RIGHT);
  2025. }
  2026. // If there's a taskbar on any side of the monitor, reduce
  2027. // our size a little bit on that edge.
  2028. // Note to future code archeologists:
  2029. // This doesn't seem to work for fullscreen on the primary
  2030. // display. However, testing a bunch of other apps with
  2031. // fullscreen modes and an auto-hiding taskbar has
  2032. // shown that _none_ of them reveal the taskbar from
  2033. // fullscreen mode. This includes Edge, Firefox, Chrome,
  2034. // Sublime Text, PowerPoint - none seemed to support this.
  2035. // This does however work fine for maximized.
  2036. if (top) {
  2037. // Peculiarly, when we're fullscreen,
  2038. clientRect->top += kAutoHideTaskBarThickness;
  2039. } else if (bottom) {
  2040. clientRect->bottom -= kAutoHideTaskBarThickness;
  2041. } else if (left) {
  2042. clientRect->left += kAutoHideTaskBarThickness;
  2043. } else if (right) {
  2044. clientRect->right -= kAutoHideTaskBarThickness;
  2045. }
  2046. }
  2047. }
  2048. // By returning WVR_REDRAW we can make the window resizing look
  2049. // less broken. But we must return 0 if wParam is FALSE, according to Microsoft
  2050. // Docs.
  2051. // **IMPORTANT NOTE**:
  2052. // If you are drawing something manually through D3D in your window, don't
  2053. // try to return WVR_REDRAW here, otherwise Windows exhibits bugs where
  2054. // client pixels and child windows are mispositioned by the width/height
  2055. // of the upper-left non-client area. It's confirmed that this issue exists
  2056. // from Windows 7 to Windows 10. Not tested on Windows 11 yet. Don't know
  2057. // whether it exists on Windows XP to Windows Vista or not.
  2058. // https://github.com/chromium/chromium/blob/5d297da3cf2a642e9ace2b23fed097370bc70814/ui/views/win/hwnd_message_handler.cc#L2330
  2059. // Do not return WVR_REDRAW otherwise child HWNDs will be mispositioned.
  2060. *result = FALSE;
  2061. return true;
  2062. }
  2063. bool Win32WindowContext::systemMenuHandler(HWND hWnd, UINT message, WPARAM wParam,
  2064. LPARAM lParam, LRESULT *result) {
  2065. const auto getNativePosFromMouse = [lParam]() -> POINT {
  2066. return {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
  2067. };
  2068. const auto getNativeGlobalPosFromKeyboard = [hWnd]() -> POINT {
  2069. const bool maxOrFull = isMaximized(hWnd) || isFullScreen(hWnd);
  2070. const quint32 frameSize = getResizeBorderThickness(hWnd);
  2071. const quint32 horizontalOffset =
  2072. ((maxOrFull || !isSystemBorderEnabled()) ? 0 : frameSize);
  2073. const auto verticalOffset = [hWnd, maxOrFull, frameSize]() -> quint32 {
  2074. const quint32 titleBarHeight = getTitleBarHeight(hWnd);
  2075. if (!isSystemBorderEnabled()) {
  2076. return titleBarHeight;
  2077. }
  2078. if (isWin11OrGreater()) {
  2079. if (maxOrFull) {
  2080. return (titleBarHeight + frameSize);
  2081. }
  2082. return titleBarHeight;
  2083. }
  2084. if (maxOrFull) {
  2085. return titleBarHeight;
  2086. }
  2087. return titleBarHeight - frameSize;
  2088. }();
  2089. RECT windowPos{};
  2090. ::GetWindowRect(hWnd, &windowPos);
  2091. return {static_cast<LONG>(windowPos.left + horizontalOffset),
  2092. static_cast<LONG>(windowPos.top + verticalOffset)};
  2093. };
  2094. bool shouldShowSystemMenu = false;
  2095. bool broughtByKeyboard = false;
  2096. POINT nativeGlobalPos{};
  2097. switch (message) {
  2098. case WM_RBUTTONUP: {
  2099. const POINT nativeLocalPos = getNativePosFromMouse();
  2100. const QPoint qtScenePos = QHighDpi::fromNativeLocalPosition(
  2101. point2qpoint(nativeLocalPos), m_windowHandle.data());
  2102. WindowAgentBase::SystemButton sysButtonType = WindowAgentBase::Unknown;
  2103. if (isInTitleBarDraggableArea(qtScenePos) ||
  2104. (isInSystemButtons(qtScenePos, &sysButtonType) &&
  2105. sysButtonType == WindowAgentBase::WindowIcon)) {
  2106. shouldShowSystemMenu = true;
  2107. nativeGlobalPos = nativeLocalPos;
  2108. ::ClientToScreen(hWnd, &nativeGlobalPos);
  2109. }
  2110. break;
  2111. }
  2112. case WM_NCRBUTTONUP: {
  2113. if (wParam == HTCAPTION) {
  2114. shouldShowSystemMenu = true;
  2115. nativeGlobalPos = getNativePosFromMouse();
  2116. }
  2117. break;
  2118. }
  2119. case WM_SYSCOMMAND: {
  2120. const WPARAM filteredWParam = (wParam & 0xFFF0);
  2121. switch (filteredWParam) {
  2122. case SC_MOUSEMENU:
  2123. shouldShowSystemMenu = true;
  2124. nativeGlobalPos = getNativeGlobalPosFromKeyboard();
  2125. break;
  2126. case SC_KEYMENU:
  2127. if (lParam == VK_SPACE) {
  2128. shouldShowSystemMenu = true;
  2129. broughtByKeyboard = true;
  2130. nativeGlobalPos = getNativeGlobalPosFromKeyboard();
  2131. }
  2132. break;
  2133. default:
  2134. break;
  2135. }
  2136. break;
  2137. }
  2138. case WM_KEYDOWN:
  2139. case WM_SYSKEYDOWN: {
  2140. const bool altPressed = ((wParam == VK_MENU) || (::GetKeyState(VK_MENU) < 0));
  2141. const bool spacePressed = ((wParam == VK_SPACE) || (::GetKeyState(VK_SPACE) < 0));
  2142. if (altPressed && spacePressed) {
  2143. shouldShowSystemMenu = true;
  2144. broughtByKeyboard = true;
  2145. nativeGlobalPos = getNativeGlobalPosFromKeyboard();
  2146. }
  2147. break;
  2148. }
  2149. default:
  2150. break;
  2151. }
  2152. if (shouldShowSystemMenu) {
  2153. static HHOOK mouseHook = nullptr;
  2154. static std::optional<POINT> mouseClickPos;
  2155. static bool mouseDoubleClicked = false;
  2156. bool mouseHookedLocal = false;
  2157. // The menu is triggered by a click on icon button
  2158. if (iconButtonClickTime > 0) {
  2159. POINT menuPos{0, static_cast<LONG>(getTitleBarHeight(hWnd))};
  2160. if (const auto tb = titleBar()) {
  2161. auto titleBarHeight = qreal(m_delegate->mapGeometryToScene(tb).height());
  2162. titleBarHeight *= m_windowHandle->devicePixelRatio();
  2163. menuPos.y = qRound(titleBarHeight);
  2164. }
  2165. ::ClientToScreen(hWnd, &menuPos);
  2166. nativeGlobalPos = menuPos;
  2167. // Install mouse hook
  2168. if (!mouseHook) {
  2169. mouseHook = ::SetWindowsHookExW(
  2170. WH_MOUSE,
  2171. [](int nCode, WPARAM wParam, LPARAM lParam) -> LRESULT {
  2172. if (nCode >= 0) {
  2173. switch (wParam) {
  2174. case WM_LBUTTONDBLCLK:
  2175. mouseDoubleClicked = true;
  2176. Q_FALLTHROUGH();
  2177. // case WM_POINTERDOWN:
  2178. case WM_LBUTTONDOWN: {
  2179. auto pMouseStruct =
  2180. reinterpret_cast<MOUSEHOOKSTRUCT *>(lParam);
  2181. if (pMouseStruct) {
  2182. mouseClickPos = pMouseStruct->pt;
  2183. }
  2184. break;
  2185. }
  2186. default:
  2187. break;
  2188. }
  2189. }
  2190. return ::CallNextHookEx(nullptr, nCode, wParam, lParam);
  2191. },
  2192. nullptr, ::GetCurrentThreadId());
  2193. mouseHookedLocal = true;
  2194. }
  2195. }
  2196. bool res =
  2197. showSystemMenu_sys(hWnd, nativeGlobalPos, broughtByKeyboard, isHostSizeFixed());
  2198. // Uninstall mouse hook and check if it's a double-click
  2199. if (mouseHookedLocal) {
  2200. ::UnhookWindowsHookEx(mouseHook);
  2201. // Emulate the Windows icon button's behavior
  2202. if (!res && mouseClickPos.has_value()) {
  2203. POINT nativeLocalPos = mouseClickPos.value();
  2204. ::ScreenToClient(hWnd, &nativeLocalPos);
  2205. QPoint qtScenePos = QHighDpi::fromNativeLocalPosition(
  2206. point2qpoint(nativeLocalPos), m_windowHandle.data());
  2207. WindowAgentBase::SystemButton sysButtonType = WindowAgentBase::Unknown;
  2208. if (isInSystemButtons(qtScenePos, &sysButtonType) &&
  2209. sysButtonType == WindowAgentBase::WindowIcon) {
  2210. iconButtonClickLevel |= IconButtonClicked;
  2211. if (::GetTickCount64() - iconButtonClickTime <= ::GetDoubleClickTime()) {
  2212. iconButtonClickLevel |= IconButtonTriggersClose;
  2213. }
  2214. }
  2215. }
  2216. if (mouseDoubleClicked) {
  2217. iconButtonClickLevel |= IconButtonDoubleClicked;
  2218. }
  2219. mouseHook = nullptr;
  2220. mouseClickPos.reset();
  2221. mouseDoubleClicked = false;
  2222. }
  2223. // QPA's internal code will handle system menu events separately, and its
  2224. // behavior is not what we would want to see because it doesn't know our
  2225. // window doesn't have any window frame now, so return early here to avoid
  2226. // entering Qt's own handling logic.
  2227. *result = FALSE;
  2228. return true;
  2229. }
  2230. return false;
  2231. }
  2232. }