fix(titlebar): do not start a stuck window drag when activating on Windows (#7146)

* fix(titlebar): do not start a stuck window drag when activating on Windows (#7142)

A click on the title bar of a background window raised it and also started
Tauri's caption drag. start_dragging posts WM_NCLBUTTONDOWN/HTCAPTION; if
the button is already up when that message runs, Win32 follows the cursor
until the next click.

On Windows the title bar now uses the same custom drag path as macOS: a
press only arms the drag, and the native drag starts on a move while the
button is still held. window_start_drag also checks GetAsyncKeyState.
Double-click zoom still happens on the second press. Linux is unchanged.

* chore(bindings): regenerate windowStartDrag docs for the Windows drag fix

`cargo test -p openidea --test export_bindings` copies the new
window_start_drag rustdoc into src/bindings.ts. commands.snap is unchanged.

* fix(titlebar): preserve native Windows maximize, swapped mouse buttons, and drag state cleanup

---------

Co-authored-by: l0ng-ai <[email protected]>
Цей коміт міститься в:
科里亚таl0ng-ai authored and GitHub committed 2026-12-05 22:16:16 +08:00
1 джерело 452d897032
коміт 13b8024588
6 files changed
+251 -18

No files matched your search

+37
Переглянути файл
@@ -9,6 +9,10 @@ use tauri::WebviewWindow;
///
/// macOS WebKit can deliver a tap's `mousedown` after the button is already up. AppKit would then run
/// its drag loop with no release left to end it, and the window follows the pointer until the next click.
///
/// On Windows, `start_dragging` posts `WM_NCLBUTTONDOWN`/`HTCAPTION`. If the button is already up
/// (a short click that only activated a background window, after an async invoke), Win32's move loop
/// follows the pointer until the next click (#7142).
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
@@ -17,10 +21,31 @@ pub fn window_start_drag(window: WebviewWindow) -> IdeResult<bool> {
if objc2_app_kit::NSEvent::pressedMouseButtons() & 1 == 0 {
return Ok(false);
}
#[cfg(windows)]
if !primary_mouse_button_down() {
return Ok(false);
}
window.start_dragging().map_err(|e| IdeError::internal(e.to_string()))?;
Ok(true)
}
#[cfg(windows)]
fn primary_button_vk(swapped: bool) -> u16 {
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{VK_LBUTTON, VK_RBUTTON};
if swapped { VK_RBUTTON } else { VK_LBUTTON }
}
#[cfg(windows)]
fn primary_mouse_button_down() -> bool {
use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_SWAPBUTTON};
// GetAsyncKeyState reads physical buttons; map logical primary when left-handed swap is active.
let swapped = unsafe { GetSystemMetrics(SM_SWAPBUTTON) != 0 };
let vk = primary_button_vk(swapped);
// High-order bit is set while the button is down.
unsafe { GetAsyncKeyState(i32::from(vk)) as u16 & 0x8000 != 0 }
}
/// Drags `paths` (local files and folders) out of `window` while the primary mouse button is
/// still down, so the app they are dropped on copies them (#2867). Resolves when the drag ends,
/// with whether a target took the files.
@@ -59,3 +84,15 @@ pub async fn window_drag_files(window: WebviewWindow, paths: Vec<PathBuf>) -> Id
}
ide_command::desktop_domain!(window_start_drag, window_drag_files);
#[cfg(all(test, windows))]
mod tests {
use super::primary_button_vk;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{VK_LBUTTON, VK_RBUTTON};
#[test]
fn primary_button_vk_respects_swapped_setting() {
assert_eq!(primary_button_vk(false), VK_LBUTTON);
assert_eq!(primary_button_vk(true), VK_RBUTTON);
}
}
+4
Переглянути файл
@@ -3139,6 +3139,10 @@ export const commands = {
*
* macOS WebKit can deliver a tap's `mousedown` after the button is already up. AppKit would then run
* its drag loop with no release left to end it, and the window follows the pointer until the next click.
*
* On Windows, `start_dragging` posts `WM_NCLBUTTONDOWN`/`HTCAPTION`. If the button is already up
* (a short click that only activated a background window, after an async invoke), Win32's move loop
* follows the pointer until the next click (#7142).
*/
windowStartDrag: () => typedError<boolean, IdeError>(__TAURI_INVOKE("window_start_drag")),
/** What this window was opened for (taken once). */
+11 -4
Переглянути файл
@@ -56,13 +56,20 @@ export async function installCommonWindowBoot(): Promise<void> {
installMiddleClickPasteGuard();
}
if (desktop) {
// A double click on the title bar fills the work area; the backend steps the frame once per
// presented webview frame, because AppKit's own zoom hides the page until the resize ends.
const fullscreen = os !== "macos" ? trackFullscreen() : () => false;
// On macOS, a double click on the title bar fills the work area; the backend steps the frame
// once per presented webview frame, because AppKit's own zoom hides the page until the resize
// ends. On Windows, leave toggleMaximize unset to use native Win32 maximize/restore.
installWindowDrag({
toggleMaximize: () => call(commands.windowToggleZoom()).catch((e) => console.warn("cannot zoom the window", e)),
toggleMaximize:
os === "macos"
? () => call(commands.windowToggleZoom()).catch((e) => console.warn("cannot zoom the window", e))
: undefined,
// Windows title-bar drag must not run in full screen (#6029).
isFullscreen: os === "windows" ? fullscreen : undefined,
});
if (os !== "macos") installFullscreenDragGuard(fullscreen);
}
if (os !== "macos" && desktop) installFullscreenDragGuard(trackFullscreen());
installPointerFocus();
installMiddleClickLinks();
installImeKeyGuard();
+1 -1
Переглянути файл
@@ -218,7 +218,7 @@ describe("distraction free shell", () => {
expect(screen.queryByRole("button", { name: "Project" })).toBeNull();
expect(screen.queryByRole("button", { name: "Search Everywhere" })).toBeNull();
const bar = document.querySelector("header[data-titlebar='compact']");
// macOS uses its own drag region attribute (window-drag.ts); jsdom reports the host OS.
// macOS and Windows use their own drag region attribute (window-drag.ts); jsdom reports the host OS.
expect(bar?.hasAttribute("data-tauri-drag-region") || bar?.hasAttribute("data-window-drag-region")).toBe(true);
act(() => setDistractionFree(false));
+124 -1
Переглянути файл
@@ -1,6 +1,13 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { installFullscreenDragGuard, installWindowDrag } from "./window-drag";
const invokeMock = vi.hoisted(() => vi.fn<(...args: unknown[]) => Promise<unknown>>());
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
invoke: invokeMock,
}));
describe("installWindowDrag", () => {
let uninstall: () => void;
let bar: HTMLElement;
@@ -23,7 +30,7 @@ describe("installWindowDrag", () => {
bar.remove();
});
const mouse = (el: Element, type: string, init: MouseEventInit = {}) => {
const mouse = (el: EventTarget, type: string, init: MouseEventInit = {}) => {
const e = new MouseEvent(type, { bubbles: true, cancelable: true, composed: true, button: 0, detail: 1, ...init });
el.dispatchEvent(e);
return e;
@@ -67,6 +74,122 @@ describe("installWindowDrag", () => {
});
});
describe("installWindowDrag startOnMove (Windows)", () => {
let uninstall: () => void;
let bar: HTMLElement;
let region: HTMLElement;
const start = vi.fn();
const toggleMaximize = vi.fn();
beforeEach(() => {
start.mockClear();
toggleMaximize.mockClear();
uninstall = installWindowDrag({ enabled: true, start, toggleMaximize, startOnMove: true });
bar = document.body.appendChild(document.createElement("header"));
region = bar.appendChild(document.createElement("div"));
region.setAttribute("data-window-drag-region", "");
});
afterEach(() => {
uninstall();
bar.remove();
});
const mouse = (el: EventTarget, type: string, init: MouseEventInit = {}) => {
const e = new MouseEvent(type, { bubbles: true, cancelable: true, composed: true, button: 0, detail: 1, ...init });
el.dispatchEvent(e);
return e;
};
it("does not start a drag on a title-bar press alone", () => {
mouse(region, "mousedown", { buttons: 1, clientX: 10, clientY: 10 });
expect(start).not.toHaveBeenCalled();
});
it("starts a drag once the pointer moves far enough while the button is held", () => {
mouse(region, "mousedown", { buttons: 1, clientX: 10, clientY: 10 });
mouse(document, "mousemove", { buttons: 1, clientX: 12, clientY: 10 });
expect(start).not.toHaveBeenCalled();
mouse(document, "mousemove", { buttons: 1, clientX: 20, clientY: 10 });
expect(start).toHaveBeenCalledOnce();
mouse(document, "mousemove", { buttons: 1, clientX: 30, clientY: 10 });
expect(start).toHaveBeenCalledOnce();
});
it("does not start a drag if the button is released before the pointer moves", () => {
mouse(region, "mousedown", { buttons: 1, clientX: 10, clientY: 10 });
mouse(document, "mouseup", { clientX: 10, clientY: 10 });
mouse(document, "mousemove", { buttons: 0, clientX: 20, clientY: 10 });
expect(start).not.toHaveBeenCalled();
});
it("does not arm a drag when mousedown arrives with the button already released", () => {
mouse(region, "mousedown", { buttons: 0, clientX: 10, clientY: 10 });
mouse(document, "mousemove", { buttons: 1, clientX: 20, clientY: 10 });
expect(start).not.toHaveBeenCalled();
});
it("toggles maximize on the second press of a double click, without dragging", () => {
mouse(region, "mousedown", { detail: 2, buttons: 1, clientX: 10, clientY: 10 });
expect(toggleMaximize).toHaveBeenCalledOnce();
expect(start).not.toHaveBeenCalled();
mouse(document, "mousemove", { buttons: 1, clientX: 20, clientY: 10 });
expect(start).not.toHaveBeenCalled();
});
it("does not start a drag or zoom while full screen", () => {
uninstall();
uninstall = installWindowDrag({
enabled: true,
start,
toggleMaximize,
startOnMove: true,
isFullscreen: () => true,
});
mouse(region, "mousedown", { buttons: 1, clientX: 10, clientY: 10 });
mouse(document, "mousemove", { buttons: 1, clientX: 20, clientY: 10 });
mouse(region, "mousedown", { detail: 2, buttons: 1, clientX: 10, clientY: 10 });
expect(start).not.toHaveBeenCalled();
expect(toggleMaximize).not.toHaveBeenCalled();
});
it("disarms a pending drag on window blur after a missed mouseup", () => {
mouse(region, "mousedown", { buttons: 1, clientX: 10, clientY: 10 });
window.dispatchEvent(new Event("blur"));
mouse(document, "mousemove", { buttons: 1, clientX: 30, clientY: 10 });
expect(start).not.toHaveBeenCalled();
});
it("disarms a pending drag when mousemove arrives with the primary button released", () => {
mouse(region, "mousedown", { buttons: 1, clientX: 10, clientY: 10 });
mouse(document, "mousemove", { buttons: 0, clientX: 11, clientY: 10 });
mouse(document, "mousemove", { buttons: 1, clientX: 30, clientY: 10 });
expect(start).not.toHaveBeenCalled();
});
it("disarms a pending drag when a later mousedown happens outside the drag region", () => {
const content = document.body.appendChild(document.createElement("div"));
try {
mouse(region, "mousedown", { buttons: 1, clientX: 10, clientY: 10 });
mouse(content, "mousedown", { buttons: 1, clientX: 12, clientY: 100 });
mouse(content, "mousemove", { buttons: 1, clientX: 50, clientY: 100 });
expect(start).not.toHaveBeenCalled();
} finally {
content.remove();
}
});
it("uses native internal_toggle_maximize by default and ignores rejections", async () => {
invokeMock.mockReset();
invokeMock.mockRejectedValueOnce(new Error("window is not maximizable"));
uninstall();
uninstall = installWindowDrag({ enabled: true, start, startOnMove: true });
mouse(region, "mousedown", { detail: 2, buttons: 1, clientX: 10, clientY: 10 });
expect(invokeMock).toHaveBeenCalledWith("plugin:window|internal_toggle_maximize");
// Flush microtasks so an unhandled rejection would surface in vitest.
await new Promise((resolve) => setTimeout(resolve, 0));
});
});
describe("installFullscreenDragGuard", () => {
it("keeps title bar presses from Tauri's drag script only while in full screen", () => {
let fullscreen = true;
+74 -12
Переглянути файл
@@ -3,20 +3,32 @@ import { commands } from "@/platform/ipc";
import { guessOs } from "@/platform/platformInfo";
/**
* Title bar drag on macOS, replacing Tauri's injected `data-tauri-drag-region` script there.
* That script starts the native drag on any `mousedown`, but WebKit can deliver a tap's `mousedown`
* after the button is already up; AppKit then drags the window until the next click. Here the drag
* starts only while the button is down (`buttons` here, and again natively in `window_start_drag`).
* Windows and Linux keep the Tauri attribute.
* Title bar drag on macOS and Windows, replacing Tauri's injected `data-tauri-drag-region` script
* there. That script starts the native drag on any `mousedown`.
*
* On macOS, WebKit can deliver a tap's `mousedown` after the button is already up; AppKit then
* drags the window until the next click. Here the drag starts only while the button is down
* (`buttons` here, and again natively in `window_start_drag`).
*
* On Windows, a click that activates a background window also starts that drag. `start_dragging`
* posts `WM_NCLBUTTONDOWN`/`HTCAPTION`; if the button is already up when that message runs (the
* invoke is async, and an activation click is a short press), Win32's move loop follows the cursor
* until the next click (#7142). A press only arms the drag; the native drag starts on a move while
* the button is still held, and `window_start_drag` checks `GetAsyncKeyState` before
* `start_dragging`.
*
* Linux keeps the Tauri attribute.
*/
const REGION = "data-window-drag-region";
/** Attribute that makes an element a title bar drag region on this OS. */
export const windowDragRegion: Record<string, string> =
guessOs() === "macos" ? { [REGION]: "" } : { "data-tauri-drag-region": "" };
guessOs() === "macos" || guessOs() === "windows" ? { [REGION]: "" } : { "data-tauri-drag-region": "" };
const CLICKABLE_TAGS = new Set(["A", "BUTTON", "INPUT", "SELECT", "TEXTAREA", "LABEL", "SUMMARY"]);
const INTERACTIVE_ROLES = new Set(["button", "link", "menuitem", "tab", "checkbox", "radio", "switch", "option"]);
/** Pixels of movement while the button is held before a Windows title-bar drag starts. */
const DRAG_MOVE_THRESHOLD = 4;
function isClickable(el: HTMLElement) {
const editable = el.getAttribute("contenteditable");
@@ -49,39 +61,86 @@ interface Deps {
enabled?: boolean;
start?: () => unknown;
toggleMaximize?: () => unknown;
/**
* When true (Windows), start the native drag on a move while the button is still held, not on
* the press. A double-click still toggles maximize on the second press, as Tauri's script does.
*/
startOnMove?: boolean;
/** When true, a press on the drag region does nothing (full-screen Windows, see #6029). */
isFullscreen?: () => boolean;
}
/** Installs the handlers on macOS (no-op elsewhere); returns the uninstall function. */
/** Installs the handlers on macOS and Windows (no-op elsewhere); returns the uninstall function. */
export function installWindowDrag({
enabled = guessOs() === "macos",
enabled = guessOs() === "macos" || guessOs() === "windows",
start = () => commands.windowStartDrag(),
toggleMaximize = () => invoke("plugin:window|internal_toggle_maximize"),
toggleMaximize = () => invoke("plugin:window|internal_toggle_maximize").catch(() => {}),
startOnMove = guessOs() === "windows",
isFullscreen = () => false,
}: Deps = {}): () => void {
if (!enabled) return () => {};
let down = { x: 0, y: 0 };
let pending = false;
const inRegion = (e: MouseEvent) =>
e.button === 0 && (e.detail === 1 || e.detail === 2) && isDragRegion(e.composedPath()) && !isFullscreen();
const onMouseDown = (e: MouseEvent) => {
if (e.button !== 0 || (e.detail !== 1 && e.detail !== 2) || !isDragRegion(e.composedPath())) return;
// Zoom happens on mouseup, as in AppKit, so moving away cancels it.
pending = false;
if (!inRegion(e)) return;
// Zoom happens on mouseup on macOS, as in AppKit, so moving away cancels it.
// On Windows it happens on the second press, matching Tauri's drag-region script.
if (e.detail === 2) {
down = { x: e.clientX, y: e.clientY };
if (startOnMove) {
e.preventDefault();
e.stopImmediatePropagation();
void toggleMaximize();
}
return;
}
e.preventDefault(); // no text cursor
e.stopImmediatePropagation();
if (startOnMove) {
// Arm only while the button is down; a click that already released must not stick the window.
down = { x: e.clientX, y: e.clientY };
pending = (e.buttons & 1) !== 0;
return;
}
// A tap's mousedown arrives with the button already released: nothing to drag.
if (e.buttons & 1) void start();
};
const onMouseMove = (e: MouseEvent) => {
if (!pending) return;
if (!(e.buttons & 1)) {
pending = false;
return;
}
if (Math.hypot(e.clientX - down.x, e.clientY - down.y) < DRAG_MOVE_THRESHOLD) return;
pending = false;
void start();
};
const onMouseUp = (e: MouseEvent) => {
pending = false;
if (startOnMove) return;
if (e.button !== 0 || e.detail !== 2 || e.clientX !== down.x || e.clientY !== down.y) return;
if (isDragRegion(e.composedPath())) void toggleMaximize();
if (isDragRegion(e.composedPath()) && !isFullscreen()) void toggleMaximize();
};
const clearPending = () => {
pending = false;
};
document.addEventListener("mousedown", onMouseDown);
if (startOnMove) {
document.addEventListener("mousemove", onMouseMove);
window.addEventListener("blur", clearPending);
}
document.addEventListener("mouseup", onMouseUp);
return () => {
document.removeEventListener("mousedown", onMouseDown);
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
window.removeEventListener("blur", clearPending);
};
}
@@ -90,6 +149,9 @@ export function installWindowDrag({
* maximize on a double click, in full screen too, where neither applies: dragging a full-screen
* window or maximizing it under the full-screen frame left it in a broken state (#6029). While
* `isFullscreen()`, a press on a drag region stops before that script (a `document` listener) sees it.
*
* On Windows the title bar itself uses `data-window-drag-region` and `installWindowDrag`; this guard
* still covers leftover `data-tauri-drag-region` elements (the splash).
*/
export function installFullscreenDragGuard(isFullscreen: () => boolean, target: Window = window): () => void {
const onMouseDown = (e: MouseEvent) => {