Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 566631b6b8 fix(debugger): debug Python with a Windows venv interpreter given by its path
A Python run configuration whose command is a Windows path
(C:\…\.venv\Scripts\python.exe) was not recognised as an interpreter:
the path was only split at '/', so debugpy got a bare `python` from PATH
and the whole path as the module to run. When PATH has no usable
python, the launcher debugpy asks the IDE to start never connects
("Timed out waiting for launcher to connect"). Command names now split
at both separators, and a venv tool given by a backslash path debugs
with the python.exe next to it.

Fixes #3907
2026-11-17 20:28:21 +08:00
32 змінених файлів з 79 додано та 578 видалено

No files matched your search

+1 -1
Переглянути файл
@@ -142,7 +142,7 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
}
const FMT: &str = "{{json .}}";
let (containers, images, volumes, networks) = std::thread::scope(|s| {
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", PS_FORMAT], QUICK));
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", FMT], QUICK));
let i = s.spawn(|| run(ep, &["image", "ls", "--no-trunc", "--format", FMT], QUICK));
let v = s.spawn(|| run(ep, &["volume", "ls", "--format", FMT], QUICK));
let n = s.spawn(|| run(ep, &["network", "ls", "--no-trunc", "--format", FMT], QUICK));
+1 -11
Переглянути файл
@@ -226,16 +226,6 @@ fn lines<T: for<'de> Deserialize<'de>>(text: &str) -> impl Iterator<Item = T> +
})
}
/// The `docker ps --format` template: only the fields [`RawContainer`] reads. `{{json .}}`
/// would also include `Size`, which makes the daemon compute every container's writable
/// layer and can take tens of seconds.
pub const PS_FORMAT: &str = concat!(
r#"{"ID":{{json .ID}},"Names":{{json .Names}},"Image":{{json .Image}},"#,
r#""Command":{{json .Command}},"State":{{json .State}},"Status":{{json .Status}},"#,
r#""Ports":{{json .Ports}},"CreatedAt":{{json .CreatedAt}},"Labels":{{json .Labels}},"#,
r#""Mounts":{{json .Mounts}},"Networks":{{json .Networks}}}"#,
);
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawContainer {
@@ -257,7 +247,7 @@ fn split_csv(raw: &str) -> Vec<String> {
raw.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
}
/// `docker ps -a --no-trunc --format` [`PS_FORMAT`] (or `'{{json .}}'`).
/// `docker ps -a --no-trunc --format '{{json .}}'`.
pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
let mut out: Vec<DockerContainer> = lines::<RawContainer>(text)
.map(|r| {
+2 -23
Переглянути файл
@@ -1,8 +1,8 @@
//! Parsing of recorded `docker … --format '{{json .}}'` output.
use ide_docker::{
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
parse_networks, parse_volumes,
parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images, parse_networks,
parse_volumes,
};
const PS: &str = include_str!("fixtures/ps.jsonl");
@@ -10,27 +10,6 @@ const IMAGES: &str = include_str!("fixtures/images.jsonl");
const VOLUMES: &str = include_str!("fixtures/volumes.jsonl");
const NETWORKS: &str = include_str!("fixtures/networks.jsonl");
/// Fills `{{json .Field}}` placeholders of a `--format` template from a `{{json .}}` line.
fn render(template: &str, line: &str) -> String {
let fields: serde_json::Map<String, serde_json::Value> = serde_json::from_str(line).unwrap();
let mut out = template.to_owned();
while let Some(start) = out.find("{{json .") {
let end = start + out[start..].find("}}").unwrap() + 2;
let key = &out[start + "{{json .".len()..end - 2];
let value = fields.get(key).unwrap_or_else(|| panic!("fixture lacks {key}"));
out.replace_range(start..end, &value.to_string());
}
out
}
#[test]
fn ps_format_carries_everything_the_parser_reads_but_size() {
assert!(!PS_FORMAT.contains("Size"), "Size makes the daemon compute container sizes");
let rendered: Vec<String> = PS.lines().filter(|l| l.starts_with('{')).map(|l| render(PS_FORMAT, l)).collect();
assert_eq!(rendered.len(), 2);
assert_eq!(parse_containers(&rendered.join("\n")), parse_containers(PS));
}
#[test]
fn containers_with_compose_labels() {
let c = parse_containers(PS);
+1 -4
Переглянути файл
@@ -529,12 +529,9 @@ pub enum CheckoutOutcome {
LocalChanges {
files: Vec<String>,
},
/// These untracked files (repository-relative paths) would be overwritten by the
/// checkout; with `removed`, they would be removed by it (tracked here, absent
/// from the target).
/// These untracked files (repository-relative paths) would be overwritten.
UntrackedFiles {
files: Vec<String>,
removed: bool,
},
/// Local branch `local` has commits that remote branch `remote` does not.
LocalBranchAhead {
+5 -10
Переглянути файл
@@ -771,14 +771,9 @@ fn overwritten_files(stderr: &str) -> Option<Vec<String>> {
listed_files(stderr, "local changes to the following files would be overwritten")
}
/// Untracked files git refuses to lose, from its error message: they would be *removed*
/// by the checkout (tracked here, absent from the target) or *overwritten* by it (present
/// in the target). Returns the files and whether they would be removed.
fn refused_untracked(stderr: &str) -> Option<(Vec<String>, bool)> {
if let Some(files) = listed_files(stderr, "untracked working tree files would be removed") {
return Some((files, true));
}
Some((listed_files(stderr, "untracked working tree files would be")?, false))
/// Untracked files git refuses to overwrite, from its error message.
fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
listed_files(stderr, "untracked working tree files would be")
}
/// The branch git refused to check out or update because another worktree has it, from
@@ -845,8 +840,8 @@ pub(crate) fn checkout_with(
if let Some((branch, path)) = branch_of_other_worktree(&stderr) {
return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() });
}
if let Some((files, removed)) = refused_untracked(&stderr) {
return Ok(CheckoutOutcome::UntrackedFiles { files, removed });
if let Some(files) = overwritten_untracked(&stderr) {
return Ok(CheckoutOutcome::UntrackedFiles { files });
}
let Some(files) = overwritten_files(&stderr) else {
return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
+1 -26
Переглянути файл
@@ -2074,37 +2074,12 @@ fn checkout_reports_untracked_files_it_would_overwrite() {
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
let opts = CheckoutOptions { mode, ..Default::default() };
let outcome = repo.checkout_with("other", false, &opts).unwrap();
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()], removed: false });
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.read("dir/new.txt"), "mine\n");
}
}
/// Untracked on disk but tracked on the current branch and gone from the target
/// (as after `git rm --cached`): git refuses to *remove* the file, and the outcome
/// says so (#3980).
#[test]
fn checkout_reports_untracked_files_it_would_remove() {
let fx = Fixture::new();
fx.write("TEST.md", "hi\n");
fx.commit_all("base");
fx.git(&["checkout", "-q", "-b", "feature/x"]);
fx.git(&["rm", "-q", "TEST.md"]);
fx.commit_all("remove TEST.md on feature/x");
fx.git(&["checkout", "-q", "main"]);
fx.git(&["rm", "--cached", "TEST.md"]);
fx.write("TEST.md", "local dirty version\n");
let repo = fx.repo();
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
// The refusal leaves the repository untouched, so both modes see the same state.
let opts = CheckoutOptions { mode, ..Default::default() };
let outcome = repo.checkout_with("feature/x", false, &opts).unwrap();
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["TEST.md".into()], removed: true });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.read("TEST.md"), "local dirty version\n");
}
}
#[test]
fn reword_keeps_local_changes_and_can_be_undone() {
let fx = Fixture::new();
+23
Переглянути файл
@@ -180,6 +180,29 @@ unsafe extern "C-unwind" fn should_terminate(_this: *mut AnyObject, _selector: S
static APP: std::sync::OnceLock<AppHandle> = std::sync::OnceLock::new();
/// Escape the page leaves unhandled reaches the window as `cancelOperation:`, on which NSWindow
/// leaves full screen, so pressing Escape once more after closing a popup left full screen. The
/// IDE's windows answer it with nothing; View › Appearance › Toggle Full Screen (⌃⌘F) leaves it.
pub fn keep_full_screen_on_escape() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| unsafe {
let Some(class) = AnyClass::get(c"TaoWindow") else {
tracing::warn!("no TaoWindow class: Escape leaves full screen");
return;
};
let imp: Imp = std::mem::transmute(ignore_cancel_operation as CancelOperation);
let class = class as *const AnyClass as *mut AnyClass;
let added = objc2::ffi::class_addMethod(class, objc2::sel!(cancelOperation:), imp, c"v@:@".as_ptr());
if !added.as_bool() {
tracing::warn!("could not handle cancelOperation:");
}
});
}
type CancelOperation = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject);
unsafe extern "C-unwind" fn ignore_cancel_operation(_this: *mut AnyObject, _selector: Sel, _sender: *mut AnyObject) {}
/// Whether AppKit is handling a key press right now. A menu item performed at this point
/// was chosen by its key equivalent: a click, arrow keys plus Return and accessibility
/// presses all run with a non-key current event.
+2
Переглянути файл
@@ -730,6 +730,8 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
decorate_csd(&window);
#[cfg(target_os = "macos")]
crate::page_swipe::install(&window);
#[cfg(target_os = "macos")]
crate::macos::keep_full_screen_on_escape();
apply_zoom(app, &window);
#[cfg(target_os = "macos")]
align_titlebar(app, &window, app.try_state::<WindowsState>().is_some_and(|w| w.opens_project(window.label())));
+2 -6
Переглянути файл
@@ -3293,12 +3293,8 @@ export type CheckoutOptions = {
export type CheckoutOutcome = { kind: "done" } |
/** These local changes (repository-relative paths) would be overwritten. */
{ kind: "localChanges"; files: string[] } |
/**
* These untracked files (repository-relative paths) would be overwritten by the
* checkout; with `removed`, they would be removed by it (tracked here, absent
* from the target).
*/
{ kind: "untrackedFiles"; files: string[]; removed: boolean } |
/** These untracked files (repository-relative paths) would be overwritten. */
{ kind: "untrackedFiles"; files: string[] } |
/** Local branch `local` has commits that remote branch `remote` does not. */
{ kind: "localBranchAhead"; local: string; remote: string } |
/**
+2 -4
Переглянути файл
@@ -57,7 +57,6 @@ import { stringClipboard } from "./stringClipboard";
import { filterCopiedText } from "./clipboard";
import { LINE_INSET } from "./lineInset";
import { codeLensPositions } from "./codeLens";
import { wheelZoomStep } from "@/platform/wheelZoom";
// --- soft wraps ---------------------------------------------------------------
@@ -453,10 +452,9 @@ export function resetConfiguredEditorsFontZoom(origin: EditorView): void {
/** Exported for tests: the ⌘/Ctrl+wheel handler of the prefs compartment. */
export const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
const step = wheelZoomStep(e);
if (step === null) return false;
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
if (step) stepConfiguredEditorsFontZoom(view, step);
stepConfiguredEditorsFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
-29
Переглянути файл
@@ -1,6 +1,4 @@
import { describe, expect, it } from "vitest";
import { getIndentation } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { findLanguageDescription, loadSupport } from "./languages";
describe("vue language mode", () => {
@@ -25,31 +23,4 @@ describe("vue language mode", () => {
expect(tree).toContain("Declaration");
expect(tree).not.toContain("SassVariableName");
});
it("indents the top-level <template>'s children only, not <script setup> or <style> code", async () => {
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
const doc = [
"<template>",
"<div>",
"</div>",
"</template>",
'<script setup lang="ts">',
"const a = 1",
"function f() {",
"return a",
"}",
"</script>",
"<style>",
".a { color: red; }",
"</style>",
].join("\n");
const state = EditorState.create({ doc, extensions: [support!, EditorState.tabSize.of(2)] });
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
expect(indent(2)).toBe(2);
expect(indent(6)).toBe(0);
expect(indent(7)).toBe(0);
expect(indent(8)).toBe(2);
expect(indent(10)).toBe(0);
expect(indent(12)).toBe(0);
});
});
+14 -28
Переглянути файл
@@ -4,38 +4,24 @@
* stock `vue()` parses every `<style>` as plain CSS, which loses the SCSS
* colours.
*/
import { indentNodeProp, LanguageSupport, type LRLanguage, type TreeIndentContext } from "@codemirror/language";
import { LanguageSupport } from "@codemirror/language";
import { html } from "@codemirror/lang-html";
import { sassLanguage } from "@codemirror/lang-sass";
import { vue } from "@codemirror/lang-vue";
/**
* WebStorm's Vue code style indents the children of the top-level `<template>` only: code in
* `<script setup>` or `<style>` starts at the margin, as `npm create vue` writes it.
*/
function elementIndent(context: TreeIndentContext): number | null {
const after = /^(\s*)(<\/)?/.exec(context.textAfter)!;
const node = context.node;
if (node.to <= context.pos + after[0].length) return context.continue();
const tag = node.firstChild?.getChild("TagName");
const flat =
node.parent?.name === "Document" && !!tag && context.state.sliceDoc(tag.from, tag.to).toLowerCase() !== "template";
return context.lineIndent(node.from) + (after[2] || flat ? 0 : context.unit);
}
export function vueLanguage(): LanguageSupport {
const base = html({
selfClosingTags: true,
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
// nesting; only an explicit SCSS/Sass dialect re-parses it.
nestedLanguages: [
{
tag: "style",
attrs: (a) => a.lang === "scss" || a.lang === "sass",
parser: sassLanguage.parser,
},
],
return vue({
base: html({
selfClosingTags: true,
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
// nesting; only an explicit SCSS/Sass dialect re-parses it.
nestedLanguages: [
{
tag: "style",
attrs: (a) => a.lang === "scss" || a.lang === "sass",
parser: sassLanguage.parser,
},
],
}),
});
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
return vue({ base: new LanguageSupport(language, base.support) });
}
-12
Переглянути файл
@@ -4,7 +4,6 @@ import { EditorView } from "@codemirror/view";
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { useProject } from "@/platform/project";
import { fontZoom, resetAllEditorsFontZoom, setFontZoom, stepAllEditorsFontZoom, wheelZoom } from "./cm/prefs";
import { resetWheelZoomGesture } from "@/platform/wheelZoom";
const zoomOf = (view: EditorView) => view.state.field(fontZoom, false);
@@ -20,7 +19,6 @@ describe("editor font zoom (active editor by default, all editors when configure
return view;
};
beforeEach(() => {
resetWheelZoomGesture();
resetAllEditorsFontZoom();
useProject.setState({ settings: null });
});
@@ -47,16 +45,6 @@ describe("editor font zoom (active editor by default, all editors when configure
expect(zoomOf(second)).toBe(-1);
});
it("doesn't zoom from the inertia of a scroll when ⌘/Ctrl is pressed during it", () => {
const view = makeView();
const plain = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -40 });
view.contentDOM.dispatchEvent(plain);
const coasting = new WheelEvent("wheel", { bubbles: true, cancelable: true, metaKey: true, deltaY: -20 });
view.contentDOM.dispatchEvent(coasting);
expect(coasting.defaultPrevented).toBe(false);
expect(zoomOf(view)).toBe(0);
});
it("zooms every open editor from ⌘/Ctrl+wheel when wheelZoomScope is 'all' (#2480)", () => {
useProject.setState({ settings: { editor: { general: { wheelZoomScope: "all" } } } } as never);
const first = makeView();
+2 -9
Переглянути файл
@@ -35,14 +35,9 @@ const hintField = StateField.define<Hint | null>({
pos: h.pos,
above: true,
strictSide: false,
create: (view) => {
create: () => {
const dom = document.createElement("div");
dom.className = `cm-lsp-hint cm-lsp-hint-${h.tone}`;
// Clicked or focused (a value tree expanded in it): the user works in the hint, so
// it stays until an edit, a caret move or Escape.
const keep = () => clearTimeout(timers.get(view));
dom.addEventListener("pointerdown", keep);
dom.addEventListener("focusin", keep);
dom.setAttribute("role", "status");
if (h.pending) dom.dataset.pending = "true";
Object.assign(dom.dataset, h.data);
@@ -68,8 +63,7 @@ const timers = new WeakMap<EditorView, ReturnType<typeof setTimeout>>();
export function showHint(
view: EditorView,
content: Hint["content"],
/** `timeout: null`: the hint stays until an edit, a caret move or Escape. */
opts: { pos?: number; tone?: Hint["tone"]; timeout?: number | null; pending?: boolean; data?: Hint["data"] } = {},
opts: { pos?: number; tone?: Hint["tone"]; timeout?: number; pending?: boolean; data?: Hint["data"] } = {},
) {
const pos = opts.pos ?? view.state.selection.main.head;
const effects: StateEffect<unknown>[] = [
@@ -78,7 +72,6 @@ export function showHint(
if (!view.state.field(hintField, false)) effects.push(StateEffect.appendConfig.of(hintExtension()));
view.dispatch({ effects });
clearTimeout(timers.get(view));
if (opts.timeout === null) return;
timers.set(
view,
// Also while the view is hidden: it would show the hint again when its tab is shown.
+2 -5
Переглянути файл
@@ -3,7 +3,6 @@ import { create } from "zustand";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { registerFontZoomSurface, useEditorShown, useEditorTabId, useToolWindowShown } from "@/workbench/contributions";
import { wheelZoomStep } from "@/platform/wheelZoom";
const MIN_FONT_ZOOM = -6;
const MAX_FONT_ZOOM = 36;
@@ -75,12 +74,10 @@ export function useAgentFontZoomSurface(
if (!active || !el) return;
const step = (delta: number) => stepAgentSurfaceFontZoom(surfaceKey, delta);
const onWheel = (e: WheelEvent) => {
if (!editorPrefs().general.wheelZoom) return;
const zoom = wheelZoomStep(e);
if (zoom === null) return;
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
e.preventDefault();
e.stopPropagation();
if (zoom) step(zoom);
step(e.deltaY < 0 ? 1 : -1);
};
el.addEventListener("wheel", onWheel, { capture: true, passive: false });
const release = registerFontZoomSurface(el, step, { isolated: true });
-29
Переглянути файл
@@ -1,29 +0,0 @@
import { describe, expect, it, vi } from "vitest";
const opened = vi.hoisted(() => [] as string[]);
vi.mock("@/platform/ipc", async (importOriginal) => {
const ipc = await importOriginal<typeof import("@/platform/ipc")>();
const doc = (path: string) => Promise.resolve({ status: "ok", data: { id: 3, path } });
return {
...ipc,
isTauri: () => true,
commands: {
...ipc.commands,
docOpen: (path: string) => (opened.push(`file ${path}`), doc(path)),
docOpenVirtual: (uri: string) => (opened.push(`virtual ${uri}`), doc(uri)),
docClose: () => Promise.resolve(),
},
};
});
const { withDocument } = await import("./ipc");
describe("withDocument", () => {
it("opens a library type through its language server, a project file from disk", async () => {
const uri = "jdt://contents/java.base/java.util/UUID.class?=demo/%5C/jdk%5C/lib%5C/jrt-fs.jar%60java.base";
await withDocument(uri, async (doc) => doc);
await withDocument("/p/src/App.java", async (doc) => doc);
expect(opened).toEqual([`virtual ${uri}`, "file /p/src/App.java"]);
});
});
+1 -2
Переглянути файл
@@ -134,8 +134,7 @@ export async function readManyFileLines(
export async function withDocument<T>(path: string, fn: (doc: number) => Promise<T>): Promise<T> {
const open = editorsFor(path)[0];
if (open) return fn(open.ctx.doc);
// Library types (`jdt://…`) are documents the language server provides, not files on disk.
const info = await lspRequest(() => (isVirtualUri(path) ? commands.docOpenVirtual(path) : commands.docOpen(path)));
const info = await lspRequest(() => commands.docOpen(path));
try {
return await fn(info.id);
} finally {
-55
Переглянути файл
@@ -1,55 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { DebugSessionId, Variable } from "@/bindings";
import { showHint } from "@/editor/lsp/hint";
import { valueHint } from "../editor/valueTooltip";
vi.mock("../ui/ValueHintTree", () => ({
mountValueTree: (host: HTMLElement) => {
host.append(Object.assign(document.createElement("div"), { className: "tree" }));
return { unmount: () => {} };
},
}));
const session = 7 as DebugSessionId;
const order: Variable = {
name: "order",
value: "Order@12",
typeName: "Order",
variablesReference: 3,
evaluateName: "order",
} as Variable;
let view: EditorView;
const expand = () => {
const button = document.querySelector<HTMLButtonElement>("[aria-label='Expand value']")!;
button.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
button.click();
};
beforeEach(() => {
vi.useFakeTimers();
view = new EditorView({ state: EditorState.create({ doc: "order.total" }), parent: document.body });
});
afterEach(() => {
view.destroy();
vi.useRealTimers();
});
describe("value hint", () => {
it("keeps a hint whose value was expanded past the hint's timeout", () => {
showHint(view, () => valueHint("order", order, session), { pos: 0, timeout: 4000 });
expand();
expect(document.querySelector(".cm-lsp-hint .tree")).not.toBeNull();
vi.advanceTimersByTime(60_000);
expect(document.querySelector(".cm-lsp-hint .tree")).not.toBeNull();
});
it("hands an expanded hover hint to its pin instead of growing in place", () => {
const pin = vi.fn();
showHint(view, () => valueHint("order", order, session, 400, { pin }), { pos: 0 });
expand();
expect(pin).toHaveBeenCalled();
expect(document.querySelector(".tree")).toBeNull();
});
});
+9 -51
Переглянути файл
@@ -5,11 +5,11 @@
*/
import type { EditorState, Extension } from "@codemirror/state";
import type { DebugSessionId, Variable } from "@/bindings";
import { closeHoverTooltips, hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { hideHint, showHint } from "@/editor/lsp/hint";
import { hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { showHint } from "@/editor/lsp/hint";
import { workflowSettings } from "@/platform/workflowSettings";
import { navigationModifierHeld } from "@/platform/navigationModifier";
import { activeSession, evaluate, useDebug } from "../state";
import { activeSession, evaluate } from "../state";
import { inlineValue, shownValue } from "../values";
import { tx } from "@/platform/i18n";
import { iconMarkup, selectableText } from "@/ui";
@@ -45,20 +45,10 @@ export function valueHint(
value: Variable,
session: DebugSessionId,
max: number | null = 400,
opts: { expanded?: boolean; pin?: () => void } = {},
): { dom: HTMLElement; destroy: () => void } {
const dom = document.createElement("div");
dom.className = `${styles.valueTooltip} ${selectableText}`;
let tree: { unmount(): void } | null = null;
const expandTree = () => {
dom.classList.replace(selectableText, styles.valueTooltipTree!);
dom.replaceChildren();
tree = mountValueTree(dom, expression, value, session);
};
if (value.variablesReference > 0 && opts.expanded) {
expandTree();
return { dom, destroy: () => tree?.unmount() };
}
if (value.variablesReference > 0) {
// IDEA's value hint: the "+" expands the object into a variables tree in place.
const expand = document.createElement("button");
@@ -70,9 +60,10 @@ export function valueHint(
expand.addEventListener("mousedown", (e) => e.preventDefault());
expand.addEventListener("click", () => {
if (tree) return;
if (opts.pin) return opts.pin();
expand.remove();
expandTree();
dom.classList.replace(selectableText, styles.valueTooltipTree!);
dom.replaceChildren();
tree = mountValueTree(dom, expression, value, session);
});
dom.append(expand);
}
@@ -118,48 +109,15 @@ export function valueTooltip(): Extension {
pos: expr.from,
end: expr.to,
above: true,
create: (view) =>
valueHint(expr.text, value, session.id, 400, {
// The tree outgrows the hint and may move to the other side of the line, away from the
// mouse, which closed the hover tooltip before it could be reached. Like IDEA's value
// popup it stays until Escape, a click in the editor or the next step.
pin: () => {
view.dispatch({ effects: closeHoverTooltips });
showHint(view, () => pinnedTree(view, expr.text, value, session.id), {
pos: expr.from,
timeout: null,
});
},
}),
create: () => {
return valueHint(expr.text, value, session.id);
},
};
},
{ hoverTime: BASE_HOVER },
);
}
/** An expanded value tree, closed when its session leaves the stop it was evaluated in. */
function pinnedTree(view: EditorView, expression: string, value: Variable, session: DebugSessionId) {
const stop = useDebug.getState().stopSeq;
const unsubscribe = useDebug.subscribe((s) => {
if (s.stopSeq !== stop || s.sessions[session]?.status !== "paused") hideHint(view);
});
const hint = valueHint(expression, value, session, 400, { expanded: true });
// The tree has the focus, so the editor's Escape doesn't reach the hint.
hint.dom.addEventListener("keydown", (e) => {
if (e.key !== "Escape" || e.defaultPrevented) return;
e.preventDefault();
hideHint(view);
view.focus();
});
return {
dom: hint.dom,
destroy: () => {
unsubscribe();
hint.destroy();
},
};
}
const SELECTION_DELAY = 400;
const MAX_SELECTION = 200;
+2 -4
Переглянути файл
@@ -32,7 +32,6 @@ import {
openPluginDiff,
type PluginContentEditorData,
} from "./contentTab";
import { wheelZoomStep } from "@/platform/wheelZoom";
export function pluginContentEditorTitle(input: EditorInput): string {
const s = sessions.get(input.key);
@@ -172,10 +171,9 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
const step = wheelZoomStep(e);
if (step === null) return false;
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
if (step) stepFontZoom(view, step);
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
+2 -4
Переглянути файл
@@ -26,7 +26,6 @@ import { boundedLog, type PluginLogEditorData } from "./logTab";
import { logTabPtyBackend, webPtyBackend } from "./ptyBackend";
import { outputKey, usePluginOutput } from "./outputStore";
import { ptyBridge } from "./ptyBridge";
import { wheelZoomStep } from "@/platform/wheelZoom";
export const PLUGIN_LOG_EDITOR_KIND = "pluginLog";
@@ -43,10 +42,9 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
const step = wheelZoomStep(e);
if (step === null) return false;
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
if (step) stepFontZoom(view, step);
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
+2 -4
Переглянути файл
@@ -28,7 +28,6 @@ import logStyles from "@/ui/LogPane.module.css";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { isRunning } from "./model";
import { connectionState, endpointOf, errorMessage, useServices } from "./store";
import { wheelZoomStep } from "@/platform/wheelZoom";
export const DOCKER_LOG_EDITOR_KIND = "dockerLog";
@@ -72,10 +71,9 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
const step = wheelZoomStep(e);
if (step === null) return false;
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
if (step) stepFontZoom(view, step);
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
+2 -5
Переглянути файл
@@ -42,7 +42,6 @@ import {
type TerminalFontSettings,
MIN_CONTRAST_RATIO,
} from "./theme";
import { wheelZoomStep } from "@/platform/wheelZoom";
export interface TerminalSearchOptions {
caseSensitive: boolean;
@@ -465,12 +464,10 @@ export class TerminalSession {
}
private onWheelZoom = (e: WheelEvent) => {
if (!editorPrefs().general.wheelZoom) return;
const zoom = wheelZoomStep(e);
if (zoom === null) return;
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
e.preventDefault();
e.stopPropagation();
if (zoom) this.stepFontSize(zoom);
this.stepFontSize(e.deltaY < 0 ? 1 : -1);
};
private onMiddleClick = (e: MouseEvent) => {
-28
Переглянути файл
@@ -219,34 +219,6 @@ it("does not open the worktree when the checkout offer is declined", async () =>
expect(mocks.executeAction).not.toHaveBeenCalled();
});
it("names the files git would remove when untracked ones block the checkout", async () => {
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["TEST.md"], removed: true }));
await checkoutBranch("feature/x");
expect(mocks.checkout).toHaveBeenCalledTimes(1);
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "error",
title: "Untracked files prevent checkout",
body: expect.stringContaining(
"The following untracked working tree files would be removed by checkout:\nTEST.md",
),
}),
);
});
it("still says overwritten when untracked files would be overwritten", async () => {
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["dir/new.txt"], removed: false }));
await checkoutBranch("feature/x");
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "error",
body: expect.stringContaining(
"The following untracked working tree files would be overwritten by checkout:\ndir/new.txt",
),
}),
);
});
it("keeps the branch when the worktree question is turned down", async () => {
mocks.worktrees.mockResolvedValue(ok([worktree("/p/front-feature-wt", "feature/wt")]));
mocks.confirm.mockResolvedValue(false);
+1 -7
Переглянути файл
@@ -104,17 +104,11 @@ async function performCheckout(
return true;
case "untrackedFiles": {
const files = outcome.files.join("\n");
// git refuses untracked files in two ways: they would be overwritten by the
// checkout (present in the target), or removed by it (tracked here, absent
// from the target); each names its files the way git's own message does.
const body = outcome.removed
? tx`The following untracked working tree files would be removed by checkout:\n${files}\nPlease move or remove them before you switch branches.`
: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`;
notifications().notify({
group: "vcs",
level: "error",
title: "Untracked files prevent checkout",
body,
body: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`,
});
return false;
}
+2 -5
Переглянути файл
@@ -54,7 +54,6 @@ import {
import { applyImageZoomWidth, svgDataUrlSize } from "@/ui/svgSize";
import styles from "./Markdown.module.css";
import { tx } from "@/platform/i18n";
import { wheelZoomStep } from "@/platform/wheelZoom";
/** Loaded local images by absolute path (data URLs), shared by all previews. */
const imageCache = new Map<string, Promise<string>>();
@@ -381,13 +380,11 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const root = ref.current;
if (!root) return;
const onWheel = (e: WheelEvent) => {
if (!editorPrefs().general.wheelZoom) return;
const zoom = wheelZoomStep(e);
if (zoom === null) return;
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
if ((e.target as Element | null)?.closest?.('.mermaid-output[data-zoomed="true"]')) return;
e.preventDefault();
e.stopPropagation();
if (zoom) stepMarkdownPreviewFontZoom(path, root, zoom);
stepMarkdownPreviewFontZoom(path, root, e.deltaY < 0 ? 1 : -1);
};
root.addEventListener("wheel", onWheel, { capture: true, passive: false });
const release = registerFontZoomSurface(root, (delta) => stepMarkdownPreviewFontZoom(path, root, delta));
-3
Переглянути файл
@@ -28,7 +28,6 @@ import { call, commands, isTauri } from "./platform/ipc";
import { hideSplash } from "./platform/splash";
import { prefetchLazyComponents } from "./ui";
import { installWindowDrag } from "./workbench/window-drag";
import { installFullscreenEscapeGuard } from "./workbench/fullscreenEscape";
if (import.meta.env.DEV && isTauri()) {
// The Tauri MCP bridge returns eval results via `window.__TAURI__` on Windows/Linux
@@ -72,8 +71,6 @@ if (aux?.kind === "settings") {
activateSecondaryWindow();
activateDeploymentWindowFeatures(aux.parent);
} else {
// Before the features' and the dispatcher's key handlers: it wraps the Escape they see.
installFullscreenEscapeGuard();
activateWorkbench();
// `vite build --mode perf` is a production bundle for the performance harness (`perf/`).
const perfBuild = import.meta.env.MODE === "perf";
-1
Переглянути файл
@@ -7001,7 +7001,6 @@
"Choose Declaration": "选择声明",
"Go to mapping: {target}": "跳转到映射:{target}",
"Untracked files prevent checkout": "未跟踪的文件阻止了签出",
"The following untracked working tree files would be removed by checkout:\n{files}\nPlease move or remove them before you switch branches.": "签出将删除以下未跟踪的工作区文件:\n{files}\n请在切换分支前移动或删除它们。",
"The following untracked working tree files would be overwritten by checkout:\n{files}\nPlease move or remove them before you switch branches.": "签出将覆盖以下未跟踪的工作区文件:\n{files}\n请在切换分支前移动或删除它们。",
"Select Target Changelist": "选择目标更改列表",
"Rebase undone": "已撤销变基",
-53
Переглянути файл
@@ -1,53 +0,0 @@
import { beforeEach, describe, expect, it } from "vitest";
import { resetWheelZoomGesture, wheelZoomStep } from "./wheelZoom";
let t = 0;
const wheel = (deltaY: number, mod = true, gap = 16) => {
t += gap;
return wheelZoomStep({ deltaY, metaKey: mod, ctrlKey: false, timeStamp: t });
};
describe("wheelZoomStep", () => {
beforeEach(() => {
resetWheelZoomGesture();
t = 1000;
});
it("zooms in and out with ⌘ held from the start of the gesture", () => {
expect(wheel(-4)).toBe(1);
expect(wheel(-6)).toBe(1);
expect(wheel(10, true, 500)).toBe(-1);
});
it("leaves plain scrolling alone", () => {
expect(wheel(-10, false)).toBeNull();
});
it("keeps scrolling the inertia of a plain scroll when ⌘ is pressed during it", () => {
expect(wheel(-40, false)).toBeNull();
expect(wheel(-30)).toBeNull();
expect(wheel(-20)).toBeNull();
expect(wheel(-10, true, 500)).toBe(1);
});
it("stops zooming once the deltas decay like inertia, without scrolling", () => {
for (const d of [-8, -12, -15]) expect(wheel(d)).toBe(1);
expect(wheel(-14)).toBe(1);
expect(wheel(-12)).toBe(1);
expect(wheel(-9)).toBe(1);
expect(wheel(-6)).toBe(0);
expect(wheel(-4)).toBe(0);
expect(wheel(-5)).toBe(0);
});
it("never swallows a plain wheel event, even during a zoom gesture", () => {
expect(wheel(-10)).toBe(1);
expect(wheel(-10, false)).toBeNull();
});
it("gives the same answer for repeated calls with one event", () => {
const e = { deltaY: -10, metaKey: true, ctrlKey: false, timeStamp: 5000 };
expect(wheelZoomStep(e)).toBe(1);
expect(wheelZoomStep(e)).toBe(1);
});
});
-59
Переглянути файл
@@ -1,59 +0,0 @@
/**
* ⌘/Ctrl+wheel font zoom that ignores scroll inertia.
*
* WebViews don't expose macOS momentum phases, so a gesture is a run of wheel events
* less than `GESTURE_GAP_MS` apart (momentum continues the run of the swipe that started it).
* A run that started without ⌘/Ctrl (a scroll still coasting when ⌘ is pressed) never zooms
* and keeps scrolling; a run that started with it stops zooming (and scrolling) once the deltas
* keep shrinking, which is the inertia after the fingers left the trackpad. A wheel event
* without ⌘/Ctrl always scrolls.
*/
const GESTURE_GAP_MS = 150;
/** Consecutive shrinking deltas after which the rest of the run is inertia. */
const INERTIA_SHRINKS = 4;
type WheelLike = Pick<WheelEvent, "deltaY" | "metaKey" | "ctrlKey" | "timeStamp">;
let lastTime = Number.NEGATIVE_INFINITY;
let run = { zoom: false, prev: 0, shrinks: 0, inertia: false };
let lastEvent: WheelLike | null = null;
let lastResult: number | null = null;
/**
* The font zoom step for a wheel event: `1` / `-1` to zoom in / out, `0` for a ⌘/Ctrl
* event of a zoom gesture that must neither zoom nor scroll (its inertia), `null` for one
* that isn't a zoom (scroll as usual), which includes every event without ⌘/Ctrl. Repeated calls for one event agree.
*/
export function wheelZoomStep(e: WheelLike): number | null {
if (e === lastEvent) return lastResult;
const mod = e.metaKey || e.ctrlKey;
const abs = Math.abs(e.deltaY);
if (e.timeStamp - lastTime > GESTURE_GAP_MS) {
run = { zoom: mod, prev: abs, shrinks: 0, inertia: false };
} else {
run.shrinks = abs < run.prev ? run.shrinks + 1 : 0;
run.prev = abs;
if (run.shrinks >= INERTIA_SHRINKS) run.inertia = true;
}
lastTime = e.timeStamp;
lastEvent = e;
lastResult = !mod || !run.zoom ? null : e.deltaY === 0 || run.inertia ? 0 : e.deltaY < 0 ? 1 : -1;
return lastResult;
}
// Track every wheel event, not only those reaching a zoom surface, so a scroll that started
// elsewhere and coasts into one is still known as a scroll.
if (typeof window !== "undefined") {
window.addEventListener("wheel", (e) => void wheelZoomStep(e), {
capture: true,
passive: true,
});
}
/** Tests: forget the current gesture. */
export function resetWheelZoomGesture(): void {
lastTime = Number.NEGATIVE_INFINITY;
lastEvent = null;
lastResult = null;
}
-53
Переглянути файл
@@ -1,53 +0,0 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { usePlatform } from "@/platform/platformInfo";
import { installFullscreenEscapeGuard } from "./fullscreenEscape";
let fullscreen = true;
let dispose = () => {};
const escape = (target: EventTarget) => {
const e = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });
target.dispatchEvent(e);
return e;
};
beforeEach(() => {
fullscreen = true;
usePlatform.setState({ os: "macos" });
dispose = installFullscreenEscapeGuard(window, () => fullscreen);
});
afterEach(() => {
dispose();
document.body.replaceChildren();
});
describe("Escape in full screen", () => {
it("is marked handled when nothing handles it, so the window stays in full screen", () => {
expect(escape(document.body).defaultPrevented).toBe(true);
});
it("is marked handled when a handler stops it", () => {
const popup = document.body.appendChild(document.createElement("div"));
popup.addEventListener("keydown", (e) => e.stopPropagation());
expect(escape(popup).defaultPrevented).toBe(true);
// The next key press is not affected by a listener left behind.
fullscreen = false;
expect(escape(document.body).defaultPrevented).toBe(false);
});
it("reaches other handlers not yet default-prevented", () => {
let seen: boolean | null = null;
const onKey = (e: KeyboardEvent) => (seen = e.defaultPrevented);
window.addEventListener("keydown", onKey);
escape(document.body);
window.removeEventListener("keydown", onKey);
expect(seen).toBe(false);
});
it("is left alone outside full screen and on other systems", () => {
fullscreen = false;
expect(escape(document.body).defaultPrevented).toBe(false);
fullscreen = true;
usePlatform.setState({ os: "windows" });
expect(escape(document.body).defaultPrevented).toBe(false);
});
});
-47
Переглянути файл
@@ -1,47 +0,0 @@
/**
* macOS: an Escape key press the page leaves unhandled (not default-prevented) goes back from
* WebKit to AppKit as the web view's `cancelOperation:`, and AppKit answers it in a full-screen
* window by leaving full screen, so pressing Escape once more after closing a popup dropped the
* IDE out of full screen. While this window is in full screen, Escape is marked handled after
* everything else has seen it; View › Appearance › Toggle Full Screen (⌃⌘F) leaves full screen.
*/
import { commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
/** Installs the guard on `target`; `isFullscreen` is this window's state (tests pass their own). */
export function installFullscreenEscapeGuard(
target: Window = window,
isFullscreen: () => boolean = trackFullscreen(),
): () => void {
const onCapture = (e: KeyboardEvent) => {
if (e.key !== "Escape" || e.isComposing || usePlatform.getState().os !== "macos" || !isFullscreen()) return;
// Runs last in the bubble phase: handlers that check `defaultPrevented` see the event as it was.
const handled = () => e.preventDefault();
target.addEventListener("keydown", handled, { once: true });
// A handler that stops the event has handled it; the bubble listener above won't run then.
for (const name of ["stopPropagation", "stopImmediatePropagation"] as const) {
const stop = e[name].bind(e);
e[name] = () => {
target.removeEventListener("keydown", handled);
e.preventDefault();
stop();
};
}
};
// Capture on the window before anything else is installed: it runs first.
target.addEventListener("keydown", onCapture, true);
return () => target.removeEventListener("keydown", onCapture, true);
}
function trackFullscreen(): () => boolean {
let fullscreen = false;
if (!isTauri()) return () => fullscreen;
const sync = () =>
void commands
.windowIsFullscreen()
.then((on) => (fullscreen = on))
.catch(() => {});
sync();
onIdeEvent("windowFullscreenChanged", sync);
return () => fullscreen;
}