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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 205241c0b3 fix(notebook): Vim u and Ctrl-R undo and redo in notebook cells
Notebook cells have no CodeMirror history: source and structural edits
share the notebook's backend history, which Cmd+Z already uses. Vim's u /
Ctrl-R called CodeMirror's history and did nothing. An editor can now
provide externalHistory, and the Vim engine sends undo / redo there.
2026-11-16 00:11:25 +08:00
Akbar Husain cf444a31f7 perf(index): allocation-free hump scoring and byte-scan name boosts (#3573)
hump_bonus walks the candidate's chars once with a cursor into the sorted, deduplicated match indices instead of collecting a Vec<char> per ranked survivor, and name_boost finds the extension dot with a byte scan. Results are unchanged; find_symbols/OCo goes from 3.71 ms to 3.36 ms in the index bench.

Co-authored-by: akbar1214 <[email protected]>
2026-11-16 00:05:57 +08:00
Mr0Bread c3763fb806 feat(agent): steer agents that advertise _session/steering (#3568)
Messages typed while a task is running join the running turn for agents that advertise the _session/steering extension (_meta.steering.supported in the initialize response, as OMP does), not only those advertising _meta.openidea.steer. An outcome other than injected (promptRequired, failed) queues the message for the next turn.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-16 00:01:30 +08:00
Mr0Bread 9a518e734b refactor(styles): put gap on the spacing scale (#3562)
Extends the 4px-grid spacing scale with --space-0-5 (2px), --space-1 (4px) and --space-1-5 (6px) and replaces the literal 2/4/6/8/12/16px gap, row-gap and column-gap values with the tokens; computed values are unchanged. src/styles/spacingScale.test.ts flags an on-scale literal gap.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 23:59:47 +08:00
Mr0Bread 2913c12a19 chore(styles): remove CSS module classes no component reads (#3560)
35 CSS-module classes in 10 modules were defined but never read (no styles.x use, no composes, no dynamic access in their importers): leftovers of removed UI such as the settings code-preview block, the GitHub tool window's layout helpers and SDK tree rows.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 23:58:00 +08:00
Mr0Bread 3044518b88 fix(styles): restore CSS classes components still reference (#3559)
Components read CSS-module classes no module defined, which are undefined at runtime. The archived-task banner in agent sessions (.banner, .bannerText, .bannerSpacer, dropped in #2083) and the Create Patch directory row (.cloneDirRow, .cloneDirInput, dropped in #866) are restored; references to classes that never existed are removed. src/styles/cssModules.test.ts lists any styles.x the imported module lacks.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 23:56:20 +08:00
Vadim LazukтаInf1mum 778472854e fix(markdown): keep the Preview only scroll position when switching tabs back (#3569)
Tab switches unmount the preview, and its saved offset was applied once at remount, before images and diagrams had drawn. A restore that clamped to the short document is applied again on each settle until it fits or the reader scrolls; the clamped write no longer replaces the saved offset. The preview opts out of scroll anchoring, which in WebView2 kept a later block in view while images above it loaded.

Fixes #3537

Co-authored-by: Inf1mum <[email protected]>
2026-11-15 23:54:36 +08:00
l0ng-ai 1679d61a6a fix(services): list the SSH configurations in the Docker connection dialog (#3570)
SshConfigSelect reads the settings window's staged ssh.configs unless given a list, and that list is empty outside the settings window, so the Docker connection dialog offered only None. The dialog now passes the live list; the None choice gets its Chinese text.

Closes #3535
2026-11-15 23:51:21 +08:00
l0ng-ai 937008a6fe fix(lsp): highlight a library class the Kotlin server shows as Java as Java (#3565)
A virtual .class document has no language by its name, so it took its server's first language: the Kotlin language server's Java stubs of jar classes were highlighted as Kotlin and their Java keywords stayed uncoloured. A .class stub whose package or import line ends with ';' is now Java (virtual_doc::is_java_class_stub).
2026-11-15 23:40:00 +08:00
l0ng-ai dc3d2050cb fix(editor): colour this and super as keywords in Java, JavaScript, TypeScript and C++ (#3564)
The Lezer grammars tag `this` as `self`, which the colour scheme paints with Python's self-parameter colour, and @lezer/javascript tags `super` as an atom. JAVA_TAGS (also used by JSP), JS_TAGS and a new C++ entry restyle them as keywords. Python's `self` is unchanged.
2026-11-15 23:37:06 +08:00
Mr0Bread 732baf8f1e fix(styles): use defined tokens where CSS read --bg-subtle, --bg-toolbar and --fg-primary (#3550)
Three custom properties were read without a fallback and declared nowhere, so they resolved to their initial values: no background on the Working Status and Command Permissions rows, none on the console Find button (its icon sat over console text), and an inherited hover colour. They now use --bg-hover, --bg-elev and --fg-strong; a dead var(--bg) fallback in Run.module.css is dropped. A test lists any var(--x) without a fallback whose --x is declared nowhere.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 23:31:12 +08:00
Mansur Akhmadiтаmansur-akhmadi 9b6e5a5a62 feat(vcs): copy a file's link on its Git remote from Copy Path/Reference… (#3553)
Copy Path/Reference… gains a <hosting> Link item (GitHub Link, GitLab Link, Bitbucket Link) that copies the page Open In › <hosting> opens; in the editor the link covers the selected lines (#L2-L3 / #L2-3 / #lines-2:3). A copyPath menu id lets features add items to the chooser, so editor/core and project-tree stay free of Git code.

Closes #3552

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-15 23:29:54 +08:00
l0ng-ai 8c2c701517 feat(keymap): list Cut, Copy, Paste, Undo, Redo and Select All in Settings › Keymap (#3563)
The Edit actions are hidden from Search Everywhere, and the Keymap page skipped hidden actions with no preset shortcut, so they could not get a second key (Ctrl+Shift+C / V / X for Vim users). A keymap flag on an action keeps it listed; the settings window's action list (describeActions) carries it too.
2026-11-15 23:25:59 +08:00
l0ng-ai aeb689c632 test(app): the command-line diff opens with Swap Sides (#3557)
#3540 made the command-line diff swappable; the launch tests in windows.test.ts still expected the diff data without the flag.
2026-11-15 23:17:53 +08:00
l0ng-ai 80c25be389 fix(keymap): list the data editor actions in the VS Code preset (#3556)
The VS Code preset must name every IntelliJ action id; #3551 added the db.* data editor actions to the IntelliJ presets only, failing keymap.test.ts on main.
2026-11-15 23:16:27 +08:00
Sameh Elhawaryтаsamehelhawary acea7e6235 feat(php): Phoxite as a selectable PHP language server (#3541)
languages/php.toml gains a phoxite entry (phoxite-lsp over stdio), a fallback listed after phpactor; Intelephense stays the default and users pick Phoxite under Language Servers. ide-tools installs it from the samehelhawary/phoxite GitHub releases (a binary per platform with a .sha256 beside it). A server entry can now name the servers it replaces: those stay away while it serves the file (Phoxite replaces laravel-lsp, which it covers), including when the replacing fallback takes over after a server gives up.

Co-authored-by: samehelhawary <[email protected]>
2026-11-15 23:14:32 +08:00
l0ng-ai 25197b3215 fix(vcs): show a committed directory symlink's target in revision diffs (#3554)
Revision content was decoded with the working file's encoding, read whenever the path existed. For a symlink to a folder that path is a directory, so loading failed and the Git Log diff showed '<path> is a directory'. The working file is now consulted only when it is a regular file; otherwise the encoding is detected from the revision's blob.

Closes #3528
2026-11-15 23:11:50 +08:00
Vadim LazukтаInf1mum 55786a7030 fix(vcs): the Git Log rename label names the original directory (#3546)
The changed-file label trimmed a rename's old path to its base name, so a move between directories looked like a rename in place. A shared renameFrom() now says 'renamed from <name>' within one directory and 'moved from <old path relative to the new directory>' otherwise, as IDEA does; Git Log and the GitHub create / pull request change trees use it.

Closes #3529

Co-authored-by: Inf1mum <[email protected]>
2026-11-15 23:09:13 +08:00
Vadim LazukтаInf1mum b7adbbb17c fix(project): mark symlinks with a link arrow in the tree (#3547)
Directory and file symlinks used the same icons as real folders and files. The Project view now overlays IDEA's link arrow (expui nodes/symlink) on every entry the listing reports as a symlink; the model already carried the flag, so no extra stat calls.

Closes #3527

Co-authored-by: Inf1mum <[email protected]>
2026-11-15 23:06:39 +08:00
l0ng-ai d1290c76ea feat(database): data editor row and toolbar commands as actions (#3551)
Reload Page, First / Previous / Next / Last Page, Add Row, Export Data, Delete Rows, Restore Rows, Edit Cell and the cell copy commands were menu items or toolbar buttons only. They are now db.* actions supplied by the table editor and the console result grid through their focus handle, so they appear in Find Action and take Keymap shortcuts; menus and buttons run the same actions. DataGrip's defaults bind Reload Page, Previous / Next Page and Add Row, and Delete Rows on Windows and Linux.

Closes #3506
2026-11-15 23:03:35 +08:00
l0ng-ai 0febd3e170 fix(editor): Sort Lines orders by character code (#3548)
Sort Lines used a locale-aware collator, which interleaves upper- and lowercase letters. It now compares UTF-16 code units, the order IDEA's Sort Lines uses (String.compareTo) and LC_ALL=C sort gives.

Closes #3516
2026-11-15 22:47:11 +08:00
Akbar Husain acee0d5edb feat(libraries): show the Zig standard library and build.zig.zon packages in External Libraries (#3526)
A zig detector joins the External Libraries pipeline: the standard library from zig env (struct-literal and JSON output), and the fetched build.zig.zon dependencies from the global package cache, as p/<hash> folders (Zig <= 0.14) or p/<hash>.tar.gz blobs (Zig >= 0.15) browsed read-only through the archive VFS, which now reads gzip'd tars. Nothing is downloaded; path dependencies stay in the project tree. New setting languages.zig.zig (directory of zig, empty = PATH).

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 22:45:18 +08:00
Akbar Husain a02a594010 perf(text): byte-parallel scans in ide-text, ide-syntax and ide-language (#3539)
Document open/diff and UTF-16 position mapping decoded whole files char by char. common_ends compares bytes and backs off to char boundaries, utf16_len classifies bytes with an ASCII fast path, LF-only text skips line-ending normalisation, and memchr_newlines uses memchr. Outputs are unchanged; text/open_1mb -60%, diff_two_edits_1mb -38%.

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 22:38:51 +08:00
PONK 6bb4a6375a docs: add Turkish README translation (#3519)
Adds README.tr.md and a Türkçe link in the README language switcher.

Co-authored-by: lprvy <[email protected]>
2026-11-15 22:37:30 +08:00
Mr0Bread f15c2c2b5e perf(startup): load DiffEditor, the Run console and the file-revision chooser on demand (#3544)
DiffWindow, the Services detail pane and Compare with Revision imported these statically, which kept their chunks in the startup set despite lazy imports elsewhere. They now load on demand; initial JS drops by about 34 KB gzip.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 22:35:26 +08:00
Mr0Bread a83a1a54e5 fix(agents): refresh stale agent versions after CLI updates (#3538)
The New Task page reused a probe cached for the whole session, so an updated CLI kept showing its old version. The selected agent is probed again (initialize only, no session) when the page is shown or the window regains focus, without overlapping probes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 22:35:21 +08:00
Mr0Bread 0d499f3af6 fix(agents): render Nerd Font icons in agent task titles (#3523)
No font in the UI stack had private-use icons, so OMP task titles showed a missing-glyph box. The UI stack now ends with --font-icons, the first installed Nerd Font (proportional faces first), resolved once when the window is idle. The terminal's Nerd Font list moved to platform/fonts unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 22:35:17 +08:00
zhzhsxтаzhzhsx e06c890ca4 fix(editor): show completion documentation beside the list (#3522)
The completion documentation was drawn inside the lookup popup, which clipped it or let it cover the options. positionInfo now places it beside the list on the side with more room, top edges aligned, with capped width and height.

Co-authored-by: zhzhsx <[email protected]>
2026-11-15 22:35:12 +08:00
Muuтаmuutot 6295cc2237 fix(vcs): keep inline blame on its line when soft wraps are on (#3518)
The line-end blame was an in-flow nowrap inline-block, so with soft wrap a label that did not fit was folded onto a new visual row and stretched the line. It is now a zero-width anchor with an absolutely positioned label, like code-vision hints and plugin line-end messages; the inner box is the hover and click target.

Co-authored-by: muutot <[email protected]>
2026-11-15 22:35:07 +08:00
Mamaev Igor 8349938481 fix(vim): enable Vim in notebook cells (#3515)
Notebook cell editors did not include the embedded editor contributions, so Vim (an embedded contribution) never attached to them. CellEditor now adds embeddedEditorExtensions like the other embedded editors.

Co-authored-by: pxc1984 <[email protected]>
2026-11-15 22:35:03 +08:00
Alexanderтаformiat cb2c4345d1 fix(vcs): a branch whose remote branch is gone tracks nothing (#3533)
upstream_of returned the configured upstream name even when its tracking ref had been deleted and pruned, so Git Branches still showed origin/<name>, Update stayed enabled and incoming commits were polled against a missing ref. It now reports an upstream only while the tracking ref exists; branches() and branch_info() share it.

Closes #3530

Co-authored-by: formiat <[email protected]>
2026-11-15 22:25:02 +08:00
l0ng-ai 22f409ae76 feat(diff): external diff tool and Show Diff for Lines (#3543)
- Settings › Tools › External Diff Tools: a program and its parameters
  (%1 the left file, %2 the right file, %3 the title). Diff viewers then
  offer Show Diff in External Tool (toolbar button and action). Saved
  files are passed as they are (saved first); revisions and texts go to
  temporary files named after the file. The program is always read from
  the global settings, never a project's, and runs on this machine.
- Show Diff for Lines (vcs.showDiffForLines): with the caret on changed
  lines in the editor, opens the file's diff at that line.
2026-11-15 22:18:58 +08:00
l0ng-ai b2dc59eb0f feat(diff): blank diff window, Swap Sides, and Search In Changes (#3540)
- Open Blank Diff Window: a new diff tab with two empty, editable sides;
  the editor's selection fills the left one. Text typed into either side
  survives viewer changes (mode, highlighting, Swap Sides).
- Swap Sides: a toolbar button and action for diffs whose sides the user
  picked (Compare With…, Compare Files, Compare with Clipboard, the
  command-line diff and blank diffs). Diffs of revisions keep their order.
- Search In Changes: a find bar filter in diffs that limits matches to the
  changed ranges of the searched side. It is per diff and applies to
  finding only; the replace bar searches the whole side.
2026-11-15 21:59:59 +08:00
Mr0Bread f5641f9c6f feat(agents): say what the agent is doing in the working status, with opt-in playful words (#3459)
The row under a working conversation showed a constant Working…. It now follows the turn's latest entry: Thinking…, Writing…, Reading…, Editing…, Running a command…, Running a subagent… and so on, with Working… for the rest.

Settings › Agents › Working Status adds playful words per activity, off by default. When on, they rotate from the start or after a configurable quiet time (0–600 s). Each word stays 8 s, or at least 3 s once the activity changes. Screen readers keep hearing the plain status. Users can replace or clear each activity's words.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 21:55:09 +08:00
l0ng-ai dcd4f150bd fix(kotlin): stop notifying about every Kotlin compiler error in Maven projects (#3521)
The Kotlin-to-Java bridge popped an error notification for each new failure message, so mid-edit Kotlin with autosave produced a balloon per save for errors its editor already shows. Compiler errors in project sources now only update the Problems entry on pom.xml; a build that fails without one (Maven, a goal that didn't run, the bridge bundle or JDT snapshot) still notifies once per message.
2026-11-15 19:26:00 +08:00
l0ng-ai 8caeb1305f fix(editor): indent Kotlin, Scala, Dart and Groovy brackets opened after a string (#3520)
The string-interpolation wrapper let the stock clike tokenizer consume an empty string on a new stream at column 0 whenever a literal opened; clike read that as a new line and reset the line's indentation to 0, so a bracket opened later on the same line indented its contents from column 0. Enter and paste with Reformat on Paste put the following lines at the wrong column. The empty string is now tokenized at the literal's own column, which fixes all dialects served by the wrapper (Kotlin, Scala, Dart, Groovy; C# shares the code path).
2026-11-15 19:21:48 +08:00
l0ng-ai 7ec0a4fed2 feat(diff): Esc closes a diff tab; switch panes with ⌃⇧⇥; move a diff window back to a tab (#3517)
Close Diff Editor: Esc in a diff editor tab closes it once the find bar, a selection, completion or a popup don't take it; panels, dialogs and diff windows keep their own Esc. Select Opposite Diff Pane (⌃⇧⇥ in the IntelliJ keymaps) moves focus to the other side of a side-by-side diff and wins over the Switcher while a diff is focused. A diff window's Show Diff in Editor Tab saves its edits, opens the diff as a tab in its project window and closes the window.
2026-11-15 18:42:16 +08:00
l0ng-ai 733b6cff1d feat(run): pin Run and Debug tabs; a new run replaces one finished, unpinned tab (#3514)
Run and Debug tabs can be pinned (context menu, Pin Active Tab, or the pin in place of the close button). A new run or debug session takes the place of one finished, unpinned tab: the same configuration's, else the selected one, else the first; Run used to add a tab per configuration, so finished tabs piled up. Rerun on a pinned tab restarts it in place and keeps it pinned. Settings > Run/Debug gets "Make configurations pinned by default".

Siblings: Run, Debug, Find and Usages tabs share one context menu (Close Tab, Close All Tabs, Close Other Tabs, Pin/Unpin Tab); Find and Usages show a pinned tab with the pin in place of its close button.
2026-11-15 18:29:15 +08:00
l0ng-ai b0860ed1e2 fix(debugger): a new debug session replaces one finished tab, not all of them (#3512)
Starting a session dropped every finished Debug tab, so ended sessions of other configurations disappeared with it. The new session now takes the place of a single finished tab: the same-named one, else the selected one, else the first; other finished tabs stay. A prepared start replaces it when its build begins and doesn't replace another when the adapter starts.
2026-11-15 18:01:31 +08:00
l0ng-ai 48a13cb8fa fix(terminal): paste paths of files dragged from the Project view (#3511)
The terminal took file paths only from OS drops (Finder / Explorer). A
file or folder dragged from the Project view onto the terminal did nothing.
The terminal is now a drop target for Project view drags too and pastes the
paths at the prompt, shell-quoted, without executing; it also works in a
remote window, where the paths are the remote project's.

Fixes #3503
2026-11-15 17:28:05 +08:00
l0ng-ai c9488df786 fix(appearance): red-green vision setting also adjusts editor colours (#3510)
Adjust colors for red-green vision deficiency only recoloured VCS file
status, change markers and success, so in a file without changes it had no
visible effect. With the bundled dark and light schemes it now also uses the
schemes' red-green variants for syntax (keywords, strings, numbers, fields,
functions, annotations, TODO), errors (orange instead of red), warnings,
identifier-under-caret and search highlights, breakpoint lines and coverage.
Other colour themes and plugin themes keep their own editor colours.

Fixes #3500
2026-11-15 17:28:01 +08:00
l0ng-ai 4427ec2c07 fix(ui): restore hover backgrounds on the main menu and Review Mode buttons (#3509)
The main menu button (Windows and Linux title bar) and the Review Mode comment navigation buttons are plain buttons, so #2990's IconButton hover did not reach them. They paint --bg-toolbar-hover again; the main menu button keeps it while its menu is open. Gutter run markers, diff arrows and the database banner close button keep their icon-only hover.
2026-11-15 17:26:02 +08:00
Mr0Bread cf71a61cdf fix(ui): restore toolbar icon hover feedback (#2990)
Toolbar and tool window icon buttons (IconButton) paint --bg-toolbar-hover across their hit target again, so hovering shows the clickable area. Disabled buttons stay transparent; pressed, selected, focus ring and icon colours are unchanged. The hover colours match the toolbar tokens already used for the pressed state in Islands Light and Dark.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 17:23:13 +08:00
l0ng-ai f9af0e7bff fix(editor): offer to make a read-only file writable when editing it (#3508)
A file with the read-only attribute set (often kept when copying files in
Explorer) opened read-only, and typing into it did nothing beyond the
banner. Typing, pasting or dropping into such a file now asks to make it
writable (the same question as Toggle Read-only Attribute) and clears the
attribute on confirm. Binary, too-large and library documents still refuse
edits without asking.

Fixes #3479
2026-11-15 17:15:50 +08:00
Akbar Husain 6449b68bb0 feat(debug): debug Zig under CodeLLDB (#3392)
Zig programs now debug under CodeLLDB with sourceLanguages: [] so expressions aren't evaluated as Rust; the context menu of a closed .zig file reads its content; rerunning failed tests of a zig build test step derives a standalone zig test from the module root detect/zig.rs records per step (zig build forwards no args to the test binary). Adds the zig-app fixture's failing test step and run/debug smoke cases. The Language smoke CI job for zig is left for a separate change.

Part of #3260

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 17:13:12 +08:00
Mr0Bread 5d2d814610 fix(trust): list Restricted Mode commands by name; snapshot every command's trust class (#3394)
Restricted Mode allowed commands by 19 name prefixes, so any new command matching a prefix was allowed without review. It now lists each allowed command by exact name; a new command is denied until it is listed. src-tauri/tests/commands.snap records every command's trust class, remote placement, bindings presence and sync/async mode, regenerated by the export_bindings test and checked for drift in CI next to src/bindings.ts. The unused bytes_ prefix is gone; doc_open_untitled, doc_save_as and doc_python_facts, added on main since, stay allowed by name.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 17:11:59 +08:00
l0ng-ai 3f18a8a274 fix(project-view): paste a clipboard image as img.png (#3507)
Pasting into the Project view only handled files, so a screenshot on the
clipboard did nothing. With no files to paste, Paste now saves the clipboard
image in the target folder as img.png (img_1.png, img_2.png ... when taken)
and selects it; Paste is enabled while the clipboard holds an image.

The image is read natively: public.png, or public.tiff converted, on macOS;
the registered PNG format, or CF_DIB (24/32-bit) encoded as PNG, on Windows;
GTK on Linux as before.

Fixes #3486
2026-11-15 17:10:11 +08:00
l0ng-ai f8a8ecb662 fix(tools): name a tool relative to its Windows wrapper so a non-ASCII user directory works (#3376)
Windows tool wrappers held the tool's absolute path as UTF-8, which cmd.exe reads in the console code page, so a non-ASCII user directory broke every language server and debugger. Wrappers now name paths inside the tool directory via %~dp0 (plain ASCII), and installed wrappers are rewritten at startup with the existing relocate_shims; GEM_HOME lines are covered too.

Fixes #3338
2026-11-15 17:06:56 +08:00
Deng Liuтаdengliu e2b1a2d732 fix(markdown): scale Mermaid diagrams, SVGs and images with preview font zoom (#3481)
Editor font zoom scaled the Markdown preview's text but left Mermaid diagrams, embedded SVGs and raster images at 1x: Mermaid writes a pixel max-width on its svg and images were only capped at 100%. The preview now publishes --markdown-zoom-scale and records each diagram's and image's intrinsic width (SVG viewBox/width/height, data-URL SVG headers, naturalWidth), sizing them as min(base, 100%) * scale so they follow zoom in/out/reset while staying clamped to the pane at 1x. Agent chat diagrams keep scale 1; Mermaid full-screen and PNG export share the same size helper.

Co-authored-by: dengliu <[email protected]>
2026-11-15 16:57:09 +08:00
382 змінених файлів з 8738 додано та 1682 видалено

No files matched your search

+3 -3
Переглянути файл
@@ -98,10 +98,10 @@ jobs:
# Test fixtures write LF files; keep Git from converting them on checkout.
- run: git config --global core.autocrlf false
- run: cargo nextest run --workspace --no-fail-fast
# nextest ran export_bindings, which rewrites src/bindings.ts.
- name: Bindings are up to date
# nextest ran export_bindings, which rewrites src/bindings.ts and the command snapshot.
- name: Bindings and command snapshot are up to date
if: runner.os == 'Linux'
run: git diff --exit-code src/bindings.ts
run: git diff --exit-code src/bindings.ts src-tauri/tests/commands.snap
# The remote development server ships as a static Linux binary (release-build.yml):
# keep that build working.
+1
Переглянути файл
@@ -42,6 +42,7 @@ Visual style: dark, low-contrast greys, one cool accent
shortcuts live in `src/platform/keymaps/`.
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
- User-visible text goes through the text catalog: add every new string to both
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
Other locales may lack entries; their UI shows the English text until a translator adds it.
Створено
+6
Переглянути файл
@@ -4232,6 +4232,7 @@ dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"png 0.18.1",
]
[[package]]
@@ -4577,6 +4578,7 @@ dependencies = [
"ide-core",
"ide-extension",
"ide-text",
"memchr",
"parking_lot",
"regex-lite",
"serde",
@@ -4797,6 +4799,7 @@ name = "ide-sdk"
version = "0.1.45"
dependencies = [
"dunce",
"flate2",
"ide-core",
"ide-language",
"ide-run",
@@ -4806,6 +4809,7 @@ dependencies = [
"serde",
"serde_json",
"specta",
"tar",
"tempfile",
"toml 0.9.12+spec-1.1.0",
"tracing",
@@ -4962,6 +4966,7 @@ dependencies = [
"chardetng",
"dunce",
"encoding_rs",
"flate2",
"gix",
"globset",
"ide-core",
@@ -4972,6 +4977,7 @@ dependencies = [
"serde",
"serde_json",
"specta",
"tar",
"tempfile",
"tracing",
"trash",
+2
Переглянути файл
@@ -90,6 +90,8 @@ dunce = "1"
dirs = "6"
memmap2 = "0.9"
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
flate2 = "1"
tar = "0.4"
# search, index, language
grep-searcher = "0.1"
+1 -1
Переглянути файл
@@ -10,7 +10,7 @@
</p>
<p align="center">
English · <a href="README.zh-CN.md">简体中文</a>
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
</p>
<p align="center">
+79
Переглянути файл
@@ -0,0 +1,79 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
</picture>
</p>
<p align="center">
Bildiğin IDE, Rust ile yeniden yazıldı.
</p>
<p align="center">
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
</p>
<p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>İndir</b></a>
&nbsp;·&nbsp;
<a href="https://openidea.sh">Belgeler</a>
&nbsp;·&nbsp;
<a href="#performans-karşılaştırması">Performans</a>
&nbsp;·&nbsp;
<a href="#eklentiler">Eklentiler</a>
&nbsp;·&nbsp;
<a href="#topluluk">Topluluk</a>
</p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
OpenIDEA, IntelliJ IDEA'nın çalışma biçimini (kısayol tuşlarını, araç pencerelerini,
her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir uygulamaya taşır.
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
## Performans karşılaştırması
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
önbellekler hazırken açma, 5 çalıştırmanın ortancası:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| ---------------------------------- | --------------------- | ---------------------- |
| Projeyle pencerenin açılması | **0,9 sn** | 3,1 sn |
| Hazır (CPU sakinleşti) | **1,1 sn** | 13,2 sn |
| Bellek (USS, tüm işlemler) | **169 MB** | 2011 MB |
| Hazır olana kadar CPU süresi | **2,4 sn** | 47,9 sn |
| Boştayken CPU | Bir çekirdeğin **%4**'ü | Bir çekirdeğin %7'si |
| Kapanma | **0,3 sn** | 5,9 sn |
`main` dalından derlenmiş bir OpenIDEA sürümü ve varsayılan ayar ve eklentilerle IDEA;
Windows 11, 32 çekirdekli AMD, 62 GB RAM.
IDEA, Python'u daha derinlemesine analiz eder; yani "hazır" iki tarafta aynı işi ifade etmez.
İkisi de dışarıdan, aynı yöntemle ölçüldü: kendi makinende ve projelerinde denemek için
[`perf/compare`](perf/compare) klasörüne bak.
## Eklentiler
Eklentiler; eylemler, kod tamamlama, hızlı düzeltmeler, araç pencereleri, özel editörler,
temalar, dosya simgeleri ve diller ekler. Korumalı (sandbox) WebAssembly bileşenleri olarak çalışırlar;
temalar, simge temaları ve diller için hiç kod yazmak gerekmez.
Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya da
`openidea-plugin new` ile kendininkini başlat. Ayrıntılar için [OpenIDEA eklentisi yazmak](https://openidea.sh/en/plugins) sayfasına ve
[resmi eklentilere](plugins/official) bak. Eklenti API'si hâlâ önizleme aşamasında.
## Topluluk
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
## Lisans
[Apache 2.0](LICENSE). Pakete dahil üçüncü taraf varlıklar [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md) dosyasında listelenir.
<sub>JetBrains ile bağlantılı değildir. IntelliJ IDEA, JetBrains s.r.o.'nun ticari markasıdır.</sub>
+29 -3
Переглянути файл
@@ -1861,12 +1861,24 @@ impl Task {
let s = self.state.lock();
s.busy && s.task.status == AgentStatus::Running
};
let Some(live) = live.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images)) else {
let Some((live, method)) = live
.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images))
.and_then(|l| steer_method(&l.init).map(|m| (l, m)))
else {
return Err(prompt);
};
let content = self.content(&live, &prompt).await;
let sent: Result<Value, RpcError> =
live.peer.request("_openidea/steer", json!({ "sessionId": live.session, "prompt": content }), None).await;
live.peer.request(method, json!({ "sessionId": live.session, "prompt": content }), None).await;
// `_session/steering` answers with an outcome: only `injected` joined the turn
// (`promptRequired`: no turn is running any more).
let sent = match sent {
Ok(reply) => match reply.get("outcome").and_then(Value::as_str) {
None | Some("injected") => Ok(()),
Some(outcome) => Err(reply.get("reason").and_then(Value::as_str).unwrap_or(outcome).to_owned()),
},
Err(e) => Err(e.to_string()),
};
if let Err(e) = sent {
// The turn ended meanwhile: the message waits for the next one instead.
tracing::debug!("agent task {}: steering failed: {e}", self.id);
@@ -2865,13 +2877,27 @@ fn shown_background(tasks: &[Value], known: &[AgentBackgroundTask]) -> Vec<Agent
.collect()
}
/// The method that adds a message to the running turn: OpenIDEA's own, or the
/// `_session/steering` extension an agent advertises in the response's top-level `_meta`
/// (OMP).
fn steer_method(init: &acp::Negotiated) -> Option<&'static str> {
let supported = |v: Option<&Value>| v.and_then(Value::as_bool) == Some(true);
if supported(init.meta("/openidea/steer")) {
Some("_openidea/steer")
} else if supported(init.meta.as_ref().and_then(|m| m.pointer("/steering/supported"))) {
Some("_session/steering")
} else {
None
}
}
fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
let meta = |p: &str| init.meta(p).and_then(Value::as_bool) == Some(true);
let capabilities = AgentCapabilities {
images: init.prompt("image"),
fork: init.session("fork"),
rollback: meta("/openidea/rollback"),
steer: meta("/openidea/steer"),
steer: steer_method(init).is_some(),
background_tasks: meta("/openidea/backgroundTasks"),
read_only: false,
};
+50
Переглянути файл
@@ -51,6 +51,9 @@ struct FakeAgent {
/// Config options `session/new` reports after the model one (per-model efforts, say).
extra_options: Mutex<Vec<Value>>,
model_options: Mutex<HashMap<String, Vec<Value>>>,
/// Advertises steering as OMP does (`_meta.steering` at the top of `initialize`)
/// instead of `_meta.openidea.steer`.
session_steering: bool,
}
impl FakeAgent {
@@ -156,6 +159,10 @@ impl Handler for FakeAgent {
if params.pointer("/clientCapabilities/subagents").is_some_and(Value::is_object) {
self.calls.lock().push("subagents".into());
}
if self.session_steering {
return Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true},
"_meta": {"steering": {"supported": true}}}));
}
Ok(
json!({"protocolVersion": 1, "authMethods": self.auth_methods, "agentCapabilities": {"loadSession": !self.no_load,
"sessionCapabilities": {"fork": {}}, "_meta": {"openidea": {"rollback": true, "steer": true, "backgroundTasks": true}}}}),
@@ -183,6 +190,13 @@ impl Handler for FakeAgent {
self.calls.lock().push(format!("{method} {detail}"));
Ok(json!({}))
}
"_session/steering" => {
let text = params["prompt"][0]["text"].clone();
self.calls.lock().push(format!("{method} {text}"));
// OMP answers whether the message joined the turn rather than failing.
let outcome = if text == "too late" { "promptRequired" } else { "injected" };
Ok(json!({"outcome": outcome, "queue": "steering"}))
}
"session/load" => {
self.say(&session, "replayed history");
Ok(json!({}))
@@ -1060,6 +1074,42 @@ fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
#[tokio::test(flavor = "multi_thread")]
async fn steers_through_session_steering() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent { session_steering: true, ..FakeAgent::default() });
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("wait"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
assert!(mgr.task(&task.id).unwrap().state.lock().task.capabilities.steer);
mgr.prompt(&task.id, text("also this"), true).await.unwrap();
assert!(agent.calls.lock().iter().any(|c| c == "_session/steering \"also this\""));
let entries = mgr.entries(&task.id, None).unwrap();
assert!(matches!(entries.last(), Some(AgentEntry::User { steered: true, .. })));
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
// The agent didn't take it into the turn: the turn stops and it goes next, as without
// steering (the fake agent's next turn asks for permission).
mgr.prompt(&task.id, text("too late"), true).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::User { text, steered: false, .. } if text == "too late")));
assert!(!entries.iter().any(|e| matches!(e, AgentEntry::User { text, steered: true, .. } if text == "too late")));
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
let tmp = tempfile::tempdir().unwrap();
+9 -3
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP or macOS NSPasteboard file URLs, no window or message loop"
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -9,8 +9,14 @@ license.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = { version = "0.6", default-features = false, features = ["std"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSBitmapImageRep", "NSImageRep", "NSPasteboard"] }
[target.'cfg(windows)'.dependencies]
png = "0.18"
[target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.18"
[dev-dependencies]
png = "0.18"
+222 -3
Переглянути файл
@@ -18,6 +18,10 @@
//!
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
//!
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
//! `PNG` format or `CF_DIB` on Windows. Linux reads it through GTK in the app.
use std::path::PathBuf;
@@ -34,6 +38,19 @@ pub fn text() -> Option<String> {
imp::text()
}
/// The clipboard's image as PNG bytes, None when it holds none. Call on the main
/// thread on macOS.
#[cfg(any(windows, target_os = "macos"))]
pub fn png() -> Option<Vec<u8>> {
imp::png()
}
/// Whether the clipboard holds an image, without reading it. Call on the main
/// thread on macOS and Linux.
pub fn has_image() -> bool {
imp::has_image()
}
/// Size of `DROPFILES`: `pFiles`, `pt` (two `LONG`s), `fNC`, `fWide`.
const HEADER: usize = 20;
@@ -134,9 +151,62 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
out
}
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
#[cfg(any(windows, test))]
const BI_RGB: u32 = 0;
#[cfg(any(windows, test))]
const BI_BITFIELDS: u32 = 3;
/// A packed DIB (`BITMAPINFOHEADER` or a later header, then the pixels) as PNG.
/// Only 24- and 32-bit uncompressed bitmaps, which is what screenshots and
/// copied images are; None for anything else. A 32-bit bitmap whose alpha is
/// all zero (most writers leave it unset) is opaque.
#[cfg(any(windows, test))]
fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
let u32_at = |at: usize| dib.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let header = u32_at(0)? as usize;
let width = u32_at(4)? as i32;
let height = u32_at(8)? as i32;
let bits = u16::from_le_bytes([*dib.get(14)?, *dib.get(15)?]);
let compression = u32_at(16)?;
if header < 40 || width <= 0 || height == 0 || !matches!(bits, 24 | 32) {
return None;
}
if compression != BI_RGB && !(compression == BI_BITFIELDS && bits == 32) {
return None;
}
// A `BITMAPINFOHEADER` keeps the three bitfield masks after it; later
// headers hold them inside. Masks other than BGRA's are not supported.
let masks = if compression == BI_BITFIELDS && header == 40 { 12 } else { 0 };
let colors = u32_at(32)? as usize;
let (width, rows) = (width as usize, height.unsigned_abs() as usize);
let stride = (width * bits as usize).div_ceil(32) * 4;
let start = header + masks + colors * 4;
let pixels = dib.get(start..start.checked_add(stride.checked_mul(rows)?)?)?;
let step = bits as usize / 8;
let mut rgba = Vec::with_capacity(width * rows * 4);
for row in 0..rows {
// A positive height stores the bottom row first.
let source = if height > 0 { rows - 1 - row } else { row };
let line = &pixels[source * stride..source * stride + width * step];
for px in line.chunks_exact(step) {
rgba.extend_from_slice(&[px[2], px[1], px[0], if step == 4 { px[3] } else { 255 }]);
}
}
if step == 4 && rgba.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {
rgba.as_chunks_mut::<4>().0.iter_mut().for_each(|px| px[3] = 255);
}
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width as u32, rows as u32);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().ok()?.write_image_data(&rgba).ok()?;
Some(out)
}
#[cfg(windows)]
mod imp {
use super::{HEADER, decode, encode, names_text};
use super::{HEADER, decode, dib_to_png, encode, names_text};
use std::ffi::c_void;
use std::path::PathBuf;
use std::ptr;
@@ -164,6 +234,59 @@ mod imp {
fn GetClipboardData(format: u32) -> Handle;
fn SetClipboardData(format: u32, memory: Handle) -> Handle;
fn IsClipboardFormatAvailable(format: u32) -> i32;
fn RegisterClipboardFormatW(name: *const u16) -> u32;
}
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
/// bitmap on the clipboard reads as one.
const CF_DIB: u32 = 8;
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
/// keeps transparency, so it is read first.
fn png_format() -> u32 {
let name: Vec<u16> = "PNG\0".encode_utf16().collect();
unsafe { RegisterClipboardFormatW(name.as_ptr()) }
}
pub fn has_image() -> bool {
let png = png_format();
(png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0)
|| unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0
}
/// A copy of the clipboard's `format` block. Call with the clipboard open.
fn read_block(format: u32) -> Option<Vec<u8>> {
// SAFETY: the clipboard keeps the block alive while it is open, and
// `GlobalSize` bounds the bytes read from it.
unsafe {
let memory = GetClipboardData(format);
if memory.is_null() {
return None;
}
let data = GlobalLock(memory);
if data.is_null() {
return None;
}
let bytes = std::slice::from_raw_parts(data as *const u8, GlobalSize(memory)).to_vec();
GlobalUnlock(memory);
Some(bytes)
}
}
pub fn png() -> Option<Vec<u8>> {
if !open() {
return None;
}
let png = png_format();
let image = if png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0 {
read_block(png)
} else if unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0 {
read_block(CF_DIB).and_then(|dib| dib_to_png(&dib))
} else {
None
};
unsafe { CloseClipboard() };
image
}
#[link(name = "kernel32")]
@@ -327,8 +450,8 @@ mod imp {
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
use objc2::{ClassType, MainThreadMarker};
use objc2_app_kit::{
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypeString, NSPasteboardURLReadingFileURLsOnlyKey,
NSPasteboardWriting,
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
use std::path::PathBuf;
@@ -380,6 +503,33 @@ mod imp {
})
}
pub fn has_image() -> bool {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
let types = NSArray::from_slice(&[unsafe { NSPasteboardTypePNG }, unsafe { NSPasteboardTypeTIFF }]);
NSPasteboard::generalPasteboard().availableTypeFromArray(&types).is_some()
})
}
/// PNG as copied, else TIFF (what macOS screenshots and most apps write) converted.
pub fn png() -> Option<Vec<u8>> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
let board = NSPasteboard::generalPasteboard();
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
if let Some(png) = board.dataForType(unsafe { NSPasteboardTypePNG }) {
return Some(png.to_vec());
}
let tiff = board.dataForType(unsafe { NSPasteboardTypeTIFF })?;
let image = NSBitmapImageRep::imageRepWithData(&tiff)?;
// SAFETY: an empty property dictionary is valid for every file type.
let png =
unsafe { image.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new()) }?;
Some(png.to_vec())
})
}
pub fn text() -> Option<String> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
@@ -448,6 +598,17 @@ mod imp {
false
}
pub fn has_image() -> bool {
#[cfg(target_os = "linux")]
{
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).wait_is_image_available()
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
pub fn files() -> std::io::Result<Vec<PathBuf>> {
Ok(Vec::new())
}
@@ -521,4 +682,62 @@ mod tests {
bytes.extend_from_slice(b"C:\\a\\b.txt\0C:\\c\0\0");
assert_eq!(decode(&bytes), paths(&["C:\\a\\b.txt", "C:\\c"]));
}
/// A `BITMAPINFOHEADER` DIB of `width` × `height` (positive: bottom-up).
fn dib(width: i32, height: i32, bits: u16, compression: u32, rows: &[&[u8]]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&40u32.to_le_bytes());
out.extend_from_slice(&width.to_le_bytes());
out.extend_from_slice(&height.to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&bits.to_le_bytes());
out.extend_from_slice(&compression.to_le_bytes());
out.extend_from_slice(&[0u8; 20]);
if compression == super::BI_BITFIELDS {
for mask in [0x00ff_0000u32, 0x0000_ff00, 0x0000_00ff] {
out.extend_from_slice(&mask.to_le_bytes());
}
}
for row in rows {
out.extend_from_slice(row);
}
out
}
fn decode_png(png: &[u8]) -> (u32, u32, Vec<u8>) {
let mut reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().unwrap();
let mut buf = vec![0; reader.output_buffer_size().unwrap()];
let info = reader.next_frame(&mut buf).unwrap();
buf.truncate(info.buffer_size());
(info.width, info.height, buf)
}
#[test]
fn a_bottom_up_24_bit_bitmap_becomes_an_upright_opaque_png() {
// Rows are padded to 4 bytes; the first stored row is the bottom one.
let bottom: &[u8] = &[255, 0, 0, 0, 255, 0, 0, 0];
let top: &[u8] = &[0, 0, 255, 255, 255, 255, 0, 0];
let png = super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[bottom, top])).unwrap();
let (w, h, rgba) = decode_png(&png);
assert_eq!((w, h), (2, 2));
assert_eq!(rgba, [255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 255, 255, 0, 255, 0, 255]);
}
#[test]
fn a_32_bit_bitmap_keeps_its_alpha_unless_none_was_written() {
let row: &[u8] = &[10, 20, 30, 0, 40, 50, 60, 0];
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_BITFIELDS, &[row])).unwrap());
assert_eq!(rgba, [30, 20, 10, 255, 60, 50, 40, 255]);
let row: &[u8] = &[10, 20, 30, 128, 40, 50, 60, 0];
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_RGB, &[row])).unwrap());
assert_eq!(rgba, [30, 20, 10, 128, 60, 50, 40, 0]);
}
#[test]
fn unsupported_or_truncated_bitmaps_are_not_images() {
let row: &[u8] = &[1, 2, 3, 4];
assert!(super::dib_to_png(&dib(4, 1, 8, super::BI_RGB, &[row])).is_none());
assert!(super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[row])).is_none());
assert!(super::dib_to_png(&[0; 10]).is_none());
}
}
+25
Переглянути файл
@@ -42,6 +42,8 @@ pub struct Settings {
pub terminal: TerminalSettings,
pub actions_on_save: ActionsOnSaveSettings,
pub external_tools: Vec<ExternalTool>,
/// Tools › Diff & Merge › External Diff Tools.
pub external_diff: ExternalDiffSettings,
/// Language servers / debug adapters at a user-chosen location, by the
/// command the language definition launches (`elixir-ls`, `codelldb`).
pub tools: BTreeMap<String, ToolSettings>,
@@ -88,6 +90,16 @@ pub struct AgentSettings {
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
pub fit_window_width: bool,
/// While the agent works, playful words fill the pauses in what it reports.
pub playful_status: bool,
/// Seconds the agent reports nothing new before the playful words take over; 0 shows them
/// from the start.
pub playful_after_seconds: u32,
/// The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
/// the built-in ones of that activity; an empty list keeps its status factual.
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, Vec<String>>)]
pub playful_words: BTreeMap<String, Vec<String>>,
#[serde(deserialize_with = "or_default")]
#[specta(type = ThinkingDisplay)]
pub thinking: ThinkingDisplay,
@@ -130,6 +142,9 @@ impl Default for AgentSettings {
fold_turns: true,
smooth_text: true,
fit_window_width: false,
playful_status: false,
playful_after_seconds: 0,
playful_words: BTreeMap::new(),
thinking: ThinkingDisplay::Auto,
tool_calls: ToolCallDisplay::Grouped,
expand_tool_output: false,
@@ -469,6 +484,7 @@ impl Default for Settings {
debugger: DebuggerSettings::default(),
run: RunSettings::default(),
terminal: TerminalSettings::default(),
external_diff: ExternalDiffSettings::default(),
actions_on_save: ActionsOnSaveSettings::default(),
external_tools: Vec::new(),
tools: BTreeMap::new(),
@@ -973,6 +989,7 @@ pub struct LanguagesSettings {
pub ruby: RubySettings,
pub markdown: MarkdownSettings,
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
}
impl Default for LanguagesSettings {
@@ -995,6 +1012,7 @@ impl Default for LanguagesSettings {
ruby: RubySettings::default(),
markdown: MarkdownSettings::default(),
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
}
}
}
@@ -1206,6 +1224,13 @@ impl Default for RustSettings {
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ZigSettings {
/// Directory holding the `zig` executable; empty = the one on `PATH`.
pub zig: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GoSettings {
+21
Переглянути файл
@@ -175,6 +175,24 @@ impl Default for VcsConfirmationSettings {
}
}
/// Tools › Diff & Merge › External Diff Tools: a program that shows two files' differences.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalDiffSettings {
/// Offer Show Diff in External Tool in diff viewers.
pub enabled: bool,
/// The program to start.
pub path: String,
/// Its arguments: `%1` the left file, `%2` the right file, `%3` the diff's title.
pub parameters: String,
}
impl Default for ExternalDiffSettings {
fn default() -> Self {
Self { enabled: false, path: String::new(), parameters: "%1 %2 %3".into() }
}
}
/// Version Control › Shelf.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -327,6 +345,8 @@ pub struct RunSettings {
/// Ask before closing a Run tab whose process is still running.
pub confirm_terminate: bool,
pub show_on_start: bool,
/// New Run/Debug tabs start pinned: a later run doesn't take their place once finished.
pub pin_tabs: bool,
/// Grace period between interrupt and kill when stopping a process.
pub termination_timeout_ms: u32,
}
@@ -338,6 +358,7 @@ impl Default for RunSettings {
confirm_rerun: true,
confirm_terminate: true,
show_on_start: true,
pin_tabs: false,
termination_timeout_ms: 3000,
}
}
+30
Переглянути файл
@@ -325,6 +325,20 @@ pub fn migrate(data: &Path, local: &Path) {
if cfg!(target_os = "windows") && data != local {
migrate_entries(data, local);
}
if cfg!(target_os = "windows") {
relative_tool_shims(&local.join("tools"));
}
}
/// Wrappers written before they named their tool relative to themselves hold its absolute
/// path, which cmd.exe can't find through a non-ASCII user directory (#3338).
fn relative_tool_shims(tools: &Path) {
let Ok(entries) = fs::read_dir(tools) else { return };
for dir in entries.flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
if let Err(error) = relocate_shims(&dir, &dir) {
tracing::warn!(%error, ?dir, "cannot make the tool's wrappers relative");
}
}
}
fn migrate_entries(data: &Path, local: &Path) {
@@ -651,6 +665,22 @@ mod tests {
fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
}
#[test]
fn installed_tool_wrappers_become_relative() {
let tmp = tempfile::tempdir().unwrap();
let tools = tmp.path().join("tools");
let tool = tools.join("taplo");
fs::create_dir_all(tool.join("bin")).unwrap();
let shim = tool.join("bin/taplo.cmd");
fs::write(&shim, format!("@echo off\r\n\"{}\\taplo.exe\" %*\r\n", tool.display())).unwrap();
// A wrapper the user re-saved in another encoding is left alone.
fs::create_dir_all(tools.join("other/bin")).unwrap();
fs::write(tools.join("other/bin/x.cmd"), b"@echo off\r\n\"C:\\\xd5\xc5\" %*\r\n").unwrap();
relative_tool_shims(&tools);
assert_eq!(fs::read_to_string(&shim).unwrap(), "@echo off\r\n\"%~dp0..\\taplo.exe\" %*\r\n");
relative_tool_shims(&tmp.path().join("missing"));
}
#[test]
fn wrappers_accept_mixed_separators_without_rewriting_neighbor_paths() {
let text = "@echo off\r\n\"C:\\old\\tools/demo\\payload.exe\" \"C:\\old\\tools/demo-other\\x\" %*\r\n";
+38 -12
Переглянути файл
@@ -251,18 +251,12 @@ impl KotlinBridge {
}
}
other => {
let text = match other {
Ok(Ok(outcome)) => outcome
.messages
.iter()
.filter(|m| m.severity == Severity::Error)
.map(|m| m.text.as_str())
.collect::<Vec<_>>()
.join("\n"),
Ok(Err(error)) => error.message,
Err(error) => error.to_string(),
let (text, notify) = match other {
Ok(Ok(outcome)) => failed_build(&outcome),
Ok(Err(error)) => (error.message, true),
Err(error) => (error.to_string(), true),
};
self.failure(text, &mut diagnostics, &mut last_failure);
self.report(text, notify, &mut diagnostics, &mut last_failure);
remove_directory(directory).await;
}
}
@@ -276,6 +270,12 @@ impl KotlinBridge {
}
fn failure(&self, text: String, paths: &mut BTreeSet<PathBuf>, previous: &mut String) {
self.report(text, true, paths, previous);
}
/// Publishes a failed build in Problems (on `pom.xml`) and, when `notify`, as a
/// notification once per distinct message.
fn report(&self, text: String, notify: bool, paths: &mut BTreeSet<PathBuf>, previous: &mut String) {
let text = if text.is_empty() { "Kotlin compilation failed".to_owned() } else { text };
let text = format!("{text}\nJava temporarily uses the last successfully compiled Kotlin API.");
self.clear_diagnostics(paths);
@@ -295,7 +295,7 @@ impl KotlinBridge {
deprecated: false,
}],
});
if previous != &text {
if notify && previous != &text {
self.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Error,
title: "Kotlin editor compilation failed".into(),
@@ -306,6 +306,15 @@ impl KotlinBridge {
}
}
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
fn failed_build(outcome: &Outcome) -> (String, bool) {
let errors: Vec<_> = outcome.messages.iter().filter(|m| m.severity == Severity::Error).collect();
let text = errors.iter().map(|m| m.text.as_str()).collect::<Vec<_>>().join("\n");
(text, !errors.iter().any(|m| m.path.is_some()))
}
fn relevant_change(root: &Path, path: &Path, settings: &ide_core::settings::Settings) -> bool {
let input = path.extension().is_some_and(|e| e == "kt")
|| path.file_name().is_some_and(|n| n == "pom.xml" || n == "mvnw" || n == "mvnw.cmd")
@@ -383,6 +392,23 @@ mod tests {
assert!(!relevant_change(dir.path(), &dir.path().join("module/src/build/pkg"), &Default::default()));
}
#[test]
fn source_errors_stay_out_of_notifications() {
let message = |text: &str, path: Option<&str>| ide_build::compile::BuildMessage {
severity: Severity::Error,
text: text.into(),
path: path.map(|p| PathBuf::from(p).into()),
range: None,
code: None,
};
let outcome = |messages| Outcome { projects: Vec::new(), messages, success: false };
let (text, notify) = failed_build(&outcome(vec![message("No value passed", Some("/p/src/A.kt"))]));
assert_eq!((text.as_str(), notify), ("No value passed", false));
let (text, notify) = failed_build(&outcome(vec![message("Plugin not found", None)]));
assert_eq!((text.as_str(), notify), ("Plugin not found", true));
assert!(failed_build(&outcome(Vec::new())).1);
}
#[test]
fn extensionless_root_file_does_not_trigger() {
let dir = tempfile::tempdir().unwrap();
+3 -1
Переглянути файл
@@ -1275,7 +1275,9 @@ impl Project {
}
let defaults = self.documents.file_defaults();
let fallback = defaults.fallback_for(path);
if path.exists() {
// The working file only when it is a regular file: a path that is a directory there
// (a committed symlink to a folder, a file replaced by a folder) has only its blob.
if path.is_file() {
let loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
+144 -30
Переглянути файл
@@ -296,39 +296,144 @@ impl crate::Host {
}
}
/// Commands which only inspect/edit source or operate user-owned application state.
/// New execution commands are denied until deliberately classified here.
/// Commands allowed in Restricted Mode, by exact name: those which only inspect/edit source or
/// operate user-owned application state. A new command is denied until deliberately listed here.
pub fn restricted_command_allowed(cmd: &str) -> bool {
if [
"fs_",
"doc_",
"syntax_",
"search_",
"nav_",
"history_",
"spell_",
"analysis_",
"structural_",
"refactor_",
"bytes_",
"window_",
"window_group_",
"term_",
"settings_",
"project_trust_",
// New Project writes only where the user chose and runs no code of an open project.
"scaffold_",
"ssh_",
"git_credential",
]
.iter()
.any(|p| cmd.starts_with(p))
{
return true;
}
matches!(
cmd,
"app_info"
"fs_compare_directories"
| "fs_copy"
| "fs_copy_merge"
| "fs_create_dir"
| "fs_create_file"
| "fs_create_file_bytes"
| "fs_delete"
| "fs_entry_kind"
| "fs_open_with_system"
// The user's own diff program (global settings) on the diff's two sides.
| "diff_external_tool"
| "fs_probe"
| "fs_read_dir"
| "fs_read_image"
| "fs_read_range"
| "fs_read_text"
| "fs_rename"
| "fs_resolve_reference"
| "fs_set_writable"
| "doc_close"
| "doc_edit"
| "doc_folding"
| "doc_highlights"
| "doc_open"
| "doc_open_untitled"
| "doc_open_virtual"
| "doc_outline"
| "doc_python_facts"
| "doc_save"
| "doc_save_as"
| "doc_save_all"
| "doc_selection_ranges"
| "doc_set_bom"
| "doc_set_encoding"
| "doc_set_line_ending"
| "doc_snapshot"
| "doc_sync_from_disk"
| "doc_ui_mode"
| "syntax_errors"
| "syntax_expression_at"
| "syntax_identifiers"
| "syntax_identifiers_in_files"
| "syntax_locals"
| "syntax_node_at"
| "syntax_structural_ranges"
| "syntax_support"
| "search_start"
| "search_validate"
| "nav_index_definitions"
| "nav_inheritance"
| "nav_resolve_module"
| "history_content"
| "history_list"
| "history_list_dir"
| "history_put_label"
| "history_restore"
| "spell_check"
| "spell_suggest"
| "analysis_locate_duplicates"
| "structural_languages"
| "structural_search"
| "structural_validate"
| "refactor_can_undo_file_move"
| "refactor_file_move_edits"
| "refactor_file_move_text_edits"
| "refactor_move_files"
| "refactor_undo_file_move"
| "window_close_context"
| "window_complete_launch"
| "window_cycle"
| "window_flash_taskbar"
| "window_group_cancel_close"
| "window_group_close"
| "window_group_close_tabs"
| "window_group_current"
| "window_group_detach"
| "window_group_merge"
| "window_group_reorder"
| "window_group_restore"
| "window_group_select"
| "window_is_fullscreen"
| "window_new"
| "window_open_comparison"
| "window_open_deployment"
| "window_open_diff"
| "window_open_file_in_new_window"
| "window_open_files"
| "window_open_project"
| "window_open_projects"
| "window_open_remote"
| "window_open_settings"
| "window_set_titlebar_height"
| "window_start_drag"
| "window_take_launch"
| "window_toggle_fullscreen"
| "window_toggle_zoom"
| "term_available_shells"
| "term_default_shell"
| "term_is_busy"
| "term_kill"
| "term_resize"
| "term_spawn"
| "term_store_image"
| "term_write"
| "settings_export"
| "settings_get"
| "settings_get_global"
| "settings_import"
| "settings_list_jetbrains_ides"
| "settings_read_jetbrains"
| "settings_set"
| "project_trust_add_location"
| "project_trust_list"
| "project_trust_remove_location"
| "project_trust_set"
| "project_trust_status"
// New Project writes only where the user chose and runs no code of an open project.
| "scaffold_catalog"
| "scaffold_create"
| "scaffold_options"
| "scaffold_requirements"
| "ssh_askpass_answer"
| "ssh_connected"
| "ssh_disconnect"
| "ssh_needs_secret"
| "ssh_open_terminal"
| "ssh_password_saved"
| "ssh_set_secret"
| "ssh_test"
| "ssh_trust_host"
| "git_credential_forget"
| "git_credentials"
| "app_info"
| "app_build_info"
| "app_cli_install"
| "app_cli_uninstall"
@@ -342,6 +447,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "clear_caches"
| "clipboard_file_list"
| "clipboard_has_files"
| "clipboard_has_image"
| "clipboard_image"
| "clipboard_set_file_list"
| "clipboard_write_text"
@@ -572,6 +678,14 @@ mod tests {
assert!(super::restricted_command_allowed("clipboard_write_text"));
}
#[test]
fn restricted_mode_denies_new_commands_whatever_their_name() {
for cmd in ["fs_new_command", "term_new_command", "ssh_new_command", "settings_new_command", "git_credential_x"]
{
assert!(!super::restricted_command_allowed(cmd), "{cmd} is allowed without being listed");
}
}
#[test]
fn remote_project_decisions_are_kept_on_this_machine() {
let tmp = tempfile::tempdir().unwrap();
+1
Переглянути файл
@@ -46,6 +46,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
"clear_caches",
"clipboard_file_list",
"clipboard_has_files",
"clipboard_has_image",
"clipboard_image",
"clipboard_set_file_list",
"clipboard_write_text",
+46
Переглянути файл
@@ -111,3 +111,49 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
assert_eq!(vcs::vcs_file_at(&host, "main", utf8, None).await.unwrap().as_deref(), Some(old));
host.close_project("main");
}
/// A committed symlink to a folder (#3528): its revision is the link target, even though the
/// working path is a directory.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_directory_symlink_revision_is_its_target() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(root.join("target")).unwrap();
git(&root, &["init", "-b", "main"]);
git(&root, &["config", "user.name", "Test"]);
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
std::fs::write(root.join("target/file.txt"), "example\n").unwrap();
std::os::unix::fs::symlink("target", root.join("dir-link")).unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "Add a directory symlink"]);
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let link = root.join("dir-link");
assert!(link.is_dir());
assert_eq!(
vcs::vcs_file_at(&host, "main", link.clone(), Some("HEAD".into())).await.unwrap().as_deref(),
Some("target")
);
assert_eq!(vcs::vcs_file_mode(&host, "main", link, Some("HEAD".into())).await.unwrap().as_deref(), Some("120000"));
host.close_project("main");
}
+25 -11
Переглянути файл
@@ -78,8 +78,8 @@ impl Needle {
let mut b = 0;
if n.eq_ignore_ascii_case(q) {
b += EXACT;
} else if let Some(dot) = name.find('.')
&& name.as_bytes()[..dot].eq_ignore_ascii_case(q)
} else if let Some(dot) = n.iter().position(|&b| b == b'.')
&& n[..dot].eq_ignore_ascii_case(q)
{
b += EXACT_STEM;
} else if n.len() >= q.len() && n[..q.len()].eq_ignore_ascii_case(q) {
@@ -97,17 +97,31 @@ fn hump_bonus(s: &str, indices: &[u32]) -> u32 {
if indices.is_empty() {
return 0;
}
let chars: Vec<char> = s.chars().collect();
let is_start = |i: usize| {
if i == 0 {
return true;
// One pass over `s`: `indices` is sorted, and whether position `i` is a
// word start only needs the char before it, so no `Vec<char>` is collected.
let is_start = |prev: Option<char>, c: char| match prev {
None => true,
Some(p) => {
!p.is_alphanumeric()
|| (p.is_lowercase() && c.is_uppercase())
|| (!p.is_ascii_digit() && c.is_ascii_digit())
}
let (p, c) = (chars[i - 1], chars[i]);
!p.is_alphanumeric() || (p.is_lowercase() && c.is_uppercase()) || (!p.is_ascii_digit() && c.is_ascii_digit())
};
let humps = indices.iter().filter(|&&i| (i as usize) < chars.len() && is_start(i as usize)).count() as u32;
let first = if is_start(indices[0] as usize) { FIRST_AT_START } else { 0 };
humps * HUMP + first
let (mut humps, mut next, mut first_start) = (0u32, 0usize, false);
let (mut prev, mut at) = (None, 0u32);
for c in s.chars() {
if next < indices.len() && indices[next] == at {
let started = is_start(prev, c);
humps += u32::from(started);
if next == 0 {
first_start = started;
}
next += 1;
}
prev = Some(c);
at += 1;
}
humps * HUMP + u32::from(first_start) * FIRST_AT_START
}
#[derive(Clone, Copy)]
+1
Переглянути файл
@@ -16,6 +16,7 @@ toml.workspace = true
tree-sitter.workspace = true
parking_lot.workspace = true
tracing.workspace = true
memchr = "2"
regex-lite = "0.1"
blake3.workspace = true
tree-sitter-language = "0.1"
+5
Переглянути файл
@@ -170,6 +170,11 @@ pub struct LanguageServerConfig {
/// basedpyright): only used while none of those is installed.
#[serde(default)]
pub fallback: bool,
/// Names of servers listed after this one that it makes redundant (a PHP server
/// with its own Laravel support replaces `laravel-lsp`): they aren't used while
/// this one serves the file.
#[serde(default)]
pub replaces: Vec<String>,
/// What the server is used for (`completion`, `code-action`, `diagnostics`,
/// … `FEATURES` in `ide-lsp/src/caps.rs`); empty means everything. The other
/// capabilities it announces are ignored, so a refactoring-only server next
+4 -1
Переглянути файл
@@ -758,7 +758,10 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpactor", "laravel-lsp"]);
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "laravel-lsp"]);
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
let lsp = cfg.language_servers.iter().find(|s| s.name == "laravel-lsp").unwrap();
assert_eq!(lsp.command.as_str(), "laravel-lsp");
// Its `lsp` command takes no options and speaks over stdio; `--stdio` stops it at startup.
+7 -2
Переглянути файл
@@ -79,11 +79,16 @@ impl<'a> LineIndex<'a> {
}
fn memchr_newlines(bytes: &[u8]) -> impl Iterator<Item = usize> + '_ {
bytes.iter().enumerate().filter(|&(_, &b)| b == b'\n').map(|(i, _)| i + 1)
memchr::memchr_iter(b'\n', bytes).map(|i| i + 1)
}
pub(crate) fn utf16_len(s: &str) -> u32 {
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
if s.is_ascii() {
return s.len() as u32;
}
// One unit per char (each starts with a non-continuation byte), two for
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
s.as_bytes().iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
}
/// Byte offset of `pos` (line, UTF-16 column) in `text`; None past the last line.
+26 -9
Переглянути файл
@@ -660,15 +660,17 @@ impl LspManager {
/// The servers serving `path`: every regular one, and each `fallback` one
/// only while all servers listed before it have given up (missing, not
/// launchable, or crashed for good). One that requires a root marker serves
/// only files below one, and stands in for no other.
/// only files below one, and stands in for no other. One that a server before
/// it `replaces` is left out while that server serves the file.
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
if let Some(servers) = self.arduino_servers(language, path) {
return servers;
}
let mut out = Vec::new();
let mut available_before = false;
let mut replaced: Vec<String> = Vec::new();
for sc in &self.language_servers(language) {
if sc.fallback && available_before {
if (sc.fallback && available_before) || replaced.contains(&sc.name) {
continue;
}
if sc.require_root_marker
@@ -678,6 +680,9 @@ impl LspManager {
}
let server = self.server_for(sc, language, path);
available_before |= !sc.require_root_marker && !server.gave_up();
if !server.gave_up() {
replaced.extend(sc.replaces.iter().cloned());
}
out.push(server);
}
out
@@ -865,7 +870,7 @@ impl LspManager {
ide_core::event::ServerStatus::Missing,
Some(message),
) {
self.attach_fallbacks();
self.fallbacks_take_over().await;
}
return;
}
@@ -878,7 +883,7 @@ impl LspManager {
ide_core::event::ServerStatus::Misconfigured,
Some(message),
) {
self.attach_fallbacks();
self.fallbacks_take_over().await;
}
return;
}
@@ -891,7 +896,7 @@ impl LspManager {
ide_core::event::ServerStatus::Crashed,
Some(message),
) {
self.attach_fallbacks();
self.fallbacks_take_over().await;
}
return;
}
@@ -1039,7 +1044,7 @@ impl LspManager {
}
}
// Gave up (crashed repeatedly, or its build expired): the fallbacks it hid take over.
None => self.attach_fallbacks(),
None => self.fallbacks_take_over().await,
}
}
@@ -3464,7 +3469,10 @@ impl LspManager {
virtual_doc::is_decompiled(&text)
};
let title = title.unwrap_or_else(|| virtual_doc::title(uri, decompiled));
let detected = self.languages.detect(Path::new(&title), None);
let mut detected = self.languages.detect(Path::new(&title), None);
if let Some(stem) = title.strip_suffix(".class").filter(|_| virtual_doc::is_java_class_stub(&text)) {
detected = self.languages.detect(Path::new(&format!("{stem}.java")), None);
}
let language_id = if detected == LanguageId::plain_text() {
languages.first().cloned().unwrap_or(detected)
} else {
@@ -3828,8 +3836,16 @@ impl LspManager {
}
}
/// A server enabled again shadows the fallbacks attached in its place: they
/// leave the open documents, and stop once no document uses them.
/// A server gave up: its fallbacks take over the open documents, and the servers
/// they replace leave.
async fn fallbacks_take_over(&self) {
self.attach_fallbacks();
self.detach_shadowed_fallbacks().await;
}
/// A server enabled again shadows the fallbacks attached in its place, and a
/// fallback that took over may replace a server attached earlier: they leave the
/// open documents, and stop once no document uses them.
async fn detach_shadowed_fallbacks(&self) {
let open: Vec<(DocId, LanguageId, PathBuf)> =
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
@@ -3845,6 +3861,7 @@ impl LspManager {
.filter(|a| {
!wanted.iter().any(|w| w.id == a.server.id)
&& (configs.iter().any(|c| c.fallback && c.name == a.server.name)
|| configs.iter().any(|c| c.replaces.contains(&a.server.name))
|| (a.server.name == "clangd" && wanted.iter().any(|s| s.name == arduino::SERVER)))
})
.map(|a| a.server.id)
+22
Переглянути файл
@@ -110,6 +110,17 @@ pub fn is_decompiled(text: &str) -> bool {
})
}
/// Whether a `.class` stub is written in Java: its first `package` or `import` line ends with `;`.
/// The Kotlin language server shows Java classes from jars as Java and Kotlin ones as Kotlin, under
/// the same `.class` name.
pub fn is_java_class_stub(text: &str) -> bool {
text.lines()
.take(200)
.map(str::trim)
.find(|line| line.starts_with("package ") || line.starts_with("import "))
.is_some_and(|line| line.ends_with(';'))
}
/// `scheme` of a URI (`jdt` for `jdt://…`).
pub fn scheme(uri: &str) -> &str {
uri.split_once(':').map(|(s, _)| s).unwrap_or("")
@@ -205,6 +216,17 @@ mod tests {
const JDT: &str = "jdt://contents/spring-boot-4.1.1.jar/org.springframework.boot/SpringApplication.class?=spring-demo/%5C/Users%5C/me%5C/.m2%5C/repository%5C/spring-boot-4.1.1.jar%3Corg.springframework.boot%28SpringApplication.class";
#[test]
fn class_stubs_in_java_or_kotlin() {
let java = "// IntelliJ API Decompiler stub source generated from a class file\n\npackage com.boydti.fawe.util;\n\npublic class EditSessionBuilder {\n}\n";
let kotlin = "// IntelliJ API Decompiler stub source generated from a class file\n// Implementation of methods is not available\n\npackage kotlin.collections\n\npublic fun <T> listOf(): List<T> { /* compiled code */ }\n";
let imports_only = "import java.util.List;\n\npublic class A {}\n";
assert!(is_java_class_stub(java));
assert!(is_java_class_stub(imports_only));
assert!(!is_java_class_stub(kotlin));
assert!(!is_java_class_stub("public class A {}"));
}
#[test]
fn csharp_metadata_titles_and_kinds() {
for (uri, expected) in [
+62
Переглянути файл
@@ -264,6 +264,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
install_hint: Some(format!("install {name}")),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -3286,6 +3287,67 @@ async fn a_server_requiring_a_root_marker_serves_only_files_below_one() {
h.wait_status("alt", ServerStatus::Ready).await;
}
/// A server that `replaces` another (a PHP server with its own Laravel support and
/// `laravel-lsp`) keeps it away while it serves, and only then.
#[tokio::test(flavor = "multi_thread")]
async fn a_replaced_server_stays_away_while_its_replacement_serves() {
let servers = [("main", incremental_caps()), ("alt", incremental_caps()), ("framework", incremental_caps())];
let configure = |cfg: &mut LanguageServerConfig| match cfg.name.as_str() {
"alt" => {
cfg.fallback = true;
cfg.replaces = vec!["framework".into()];
}
"framework" => cfg.require_root_marker = true,
_ => {}
};
let h = harness_configured("mock", "mk", &servers, configure);
let disabled: Arc<Mutex<Vec<String>>> = Default::default();
{
let disabled = disabled.clone();
h.mgr.set_servers_hook(Box::new(move |_, defined| {
defined.iter().filter(|c| !disabled.lock().contains(&c.name)).cloned().collect()
}));
}
std::fs::write(h.root.join("mock.toml"), "").unwrap();
let (_, path) = h.open("a.mk", "x");
let uri = uri_of(&path);
// The preferred server serves: the framework's server joins it, the alternative stays away.
h.wait_status("main", ServerStatus::Ready).await;
h.wait_status("framework", ServerStatus::Ready).await;
eventually(|| h.launcher.state("framework").docs.lock().contains_key(&uri)).await;
assert!(h.statuses("alt").is_empty());
// The alternative takes over: the server it replaces closes the document and stops.
disabled.lock().push("main".into());
h.mgr.reconfigure().await;
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
assert!(!h.launcher.state("framework").notified("textDocument/didClose").is_empty());
assert_eq!(h.statuses("framework").last(), Some(&ServerStatus::Stopped));
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["alt"]);
// The preferred server again: the framework's server comes back with it.
disabled.lock().clear();
h.mgr.reconfigure().await;
h.wait_status("main", ServerStatus::Ready).await;
eventually(|| h.statuses("framework").last() == Some(&ServerStatus::Ready)).await;
assert_eq!(h.statuses("alt").last(), Some(&ServerStatus::Stopped));
// A preferred server that is not installed: the alternative replaces the framework's
// server although that one attached first.
let servers = [("ghost", json!({})), ("alt", incremental_caps()), ("framework", incremental_caps())];
let h = harness_configured("mock", "mk", &servers, configure);
h.launcher.state("ghost").missing.store(true, Ordering::SeqCst);
std::fs::write(h.root.join("mock.toml"), "").unwrap();
let (_, path) = h.open("a.mk", "x");
let uri = uri_of(&path);
h.wait_status("ghost", ServerStatus::Missing).await;
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
eventually(|| !h.mgr.servers().iter().any(|s| s.name == "framework")).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
let h = harness_with_fallbacks(&[("main", incremental_caps()), ("alt", incremental_caps())], &["alt"]);
+3
Переглянути файл
@@ -419,6 +419,7 @@ async fn missing_binary_is_reported_with_install_hint() {
install_hint: Some("npm i -g nope-ls".into()),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -692,6 +693,7 @@ async fn typescript_language_server_end_to_end() {
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -745,6 +747,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
+171
Переглянути файл
@@ -12,6 +12,7 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
let Some(src) = read(&dir.join("build.zig")) else { return };
let src = code_only(&src);
out.push(config(BUILD_ID, "zig build", "zig", "zig", &["build"]));
let roots = test_roots(&src);
for step in steps(&src) {
// `install` is what plain `zig build` runs.
if step == "install" || step == "uninstall" {
@@ -20,6 +21,9 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
let mut c = config(format!("zig:{step}"), format!("zig build {step}"), "zig", "zig", &["build", &step]);
if step == "test" || step.starts_with("test-") || step.starts_with("test_") {
c = c.test();
if let Some((_, root)) = roots.iter().find(|(name, _)| *name == step) {
c.extras.params.insert("testRoot".into(), root.clone());
}
}
out.push(c);
}
@@ -161,6 +165,137 @@ fn executables(src: &str) -> Vec<Executable> {
out
}
/// The call's argument text: from just after its `(` to the matching `)`.
fn call_body(src: &str, start: usize) -> &str {
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
for (i, c) in src[start..].char_indices() {
if in_string {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'"' => in_string = false,
_ => {}
}
continue;
}
match c {
'"' => in_string = true,
'(' | '{' | '[' => depth += 1,
')' | '}' | ']' => {
depth -= 1;
if depth == 0 {
return &src[start..start + i];
}
}
_ => {}
}
}
src
}
/// The first `.root_source_file = <receiver>.path("…")` in `body`.
fn root_source_file(body: &str) -> Option<String> {
for (i, _) in body.match_indices(".root_source_file") {
let Some(v) = body[i + ".root_source_file".len()..].trim_start().strip_prefix('=') else { continue };
let v = v.trim_start();
if let Some(call) = v.find(".path(")
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
{
return string_at(&v[call + ".path(".len()..]);
}
}
None
}
/// The identifier assigned just before `at`: `const mod = b.addModule(…` → `mod`.
fn assigned_var(src: &str, at: usize) -> Option<&str> {
let before = src[..at].trim_end();
let before = before.strip_suffix('.')?.trim_end();
// Drop the receiver (`b`) that sits between the `=` and the call.
let receiver =
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
let before = before[..receiver].trim_end();
let before = before.strip_suffix('=')?.trim_end();
let start =
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
Some(&before[start..])
}
/// The test root behind each test-named step (`zig build <step>`): the step's `dependOn` runs
/// an `addTest` artifact — a variable (`const tests = b.addTest(…)`) or an inline call — whose
/// module's `root_source_file` this resolves (through `addModule`/`createModule` variables).
/// `zig build` forwards no args to the test binary, so rerunning a single failed test goes
/// through a standalone `zig test <root> --test-filter …` on the step's own test module.
fn test_roots(src: &str) -> Vec<(String, String)> {
let mut modules: Vec<(String, String)> = Vec::new();
for key in ["addModule(", "createModule("] {
for (i, _) in src.match_indices(key) {
let Some(root) = root_source_file(call_body(src, i + key.len())) else { continue };
if let Some(var) = assigned_var(src, i)
&& !modules.iter().any(|(m, _)| *m == var)
{
modules.push((var.to_owned(), root));
}
}
}
let module_root = |body: &str| -> Option<String> {
root_source_file(body).or_else(|| {
let at = body.find(".root_module")?;
let v = body[at + ".root_module".len()..].trim_start().strip_prefix('=')?.trim_start();
let var: String = v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
modules.iter().find(|(m, _)| *m == var).map(|(_, root)| root.clone())
})
};
let mut tests: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices("addTest(") {
let Some(root) = module_root(call_body(src, i + "addTest(".len())) else { continue };
if let Some(var) = assigned_var(src, i)
&& !tests.iter().any(|(v, _)| *v == var)
{
tests.push((var.to_owned(), root));
}
}
let mut steps: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices(".step(\"") {
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
// The match includes the dot, so the assignment ends one character earlier.
if let Some(var) = assigned_var(src, i + 1) {
steps.push((var.to_owned(), name));
}
}
let mut out: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices(".dependOn(&") {
let Some(step) = receiver_var(src, i + 1) else { continue };
let Some((_, name)) = steps.iter().find(|(v, _)| v == step) else { continue };
let after = &src[i + ".dependOn(&".len()..];
let artifact = if let Some(at) = after.find("addRunArtifact(") {
let v = &after[at + "addRunArtifact(".len()..];
let var: String = v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
tests.iter().find(|(v, _)| *v == var).map(|(_, root)| root.clone())
} else if let Some(at) = after.find("addTest(") {
module_root(call_body(after, at + "addTest(".len()))
} else {
None
};
if let Some(root) = artifact
&& name.starts_with("test")
&& !out.iter().any(|(n, _)| n == name)
{
out.push((name.clone(), root));
}
}
out
}
/// The identifier a method is called on just before `at`: `test_step.dependOn(…` → `test_step`.
fn receiver_var(src: &str, at: usize) -> Option<&str> {
let before = src[..at].trim_end();
let before = before.strip_suffix('.')?;
let start =
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
Some(&before[start..])
}
#[cfg(test)]
mod tests {
use super::*;
@@ -190,7 +325,9 @@ pub fn build(b: *std.Build) void {
}) });
_ = tool;
const run_step = b.step("run", "Run the app");
const tests = b.addTest(.{ .root_module = mod });
const test_step = b.step("test", "Run tests");
test_step.dependOn(&b.addRunArtifact(tests).step);
const docs = b.step("docs", "Generate docs // not a comment");
_ = .{ run_step, test_step, docs };
}
@@ -228,5 +365,39 @@ pub fn build(b: *std.Build) void {
assert_eq!(app.extras.before_launch[0].kind, "run");
assert_eq!(app.extras.before_launch[0].target, BUILD_ID);
assert_eq!(app.extras.params.get("source").map(String::as_str), Some("src/main.zig"));
assert_eq!(test.extras.params.get("testRoot").map(String::as_str), Some("src/root.zig"));
}
const TEST_ROOTS: &str = r#"const std = @import("std");
pub fn build(b: *std.Build) void {
const tally = b.addModule("tally", .{ .root_source_file = b.path("src/tally.zig") });
const unit = b.addTest(.{ .root_module = tally });
const test_step = b.step("test", "Run the unit tests");
test_step.dependOn(&b.addRunArtifact(unit).step);
const failing = b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/failing.zig"),
}) });
const test_failing_step = b.step("test-failing", "Run the failing tests");
test_failing_step.dependOn(&b.addRunArtifact(failing).step);
const direct = b.addTest(.{ .root_source_file = b.path("src/direct.zig") });
const test_direct_step = b.step("test-direct", "Run the direct tests");
test_direct_step.dependOn(&b.addRunArtifact(direct).step);
const run_step = b.step("run", "Run the app");
run_step.dependOn(&b.addRunArtifact(unit).step);
}
"#;
#[test]
fn test_roots_come_from_the_step_s_own_artifact() {
let src = code_only(TEST_ROOTS);
assert_eq!(
test_roots(&src),
[
("test".to_owned(), "src/tally.zig".to_owned()),
("test-failing".to_owned(), "src/failing.zig".to_owned()),
("test-direct".to_owned(), "src/direct.zig".to_owned()),
]
);
}
}
+4
Переглянути файл
@@ -21,3 +21,7 @@ toml.workspace = true
tracing.workspace = true
url = "2"
zip.workspace = true
[dev-dependencies]
flate2.workspace = true
tar.workspace = true
+7
Переглянути файл
@@ -141,6 +141,12 @@ pub(crate) fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_install(root, Tool::Go).and_then(|(dir, _)| pinned::goroot_in_install(&dir)))
}
/// The directory of the configured Zig install (holding `zig`), else `None` for `PATH`.
pub(crate) fn zig_bin(root: &Path, s: &Settings) -> Option<PathBuf> {
setting_path(root, &s.languages.zig.zig)
.map(|p| if p.is_file() { p.parent().map(Path::to_path_buf).unwrap_or(p) } else { p })
}
/// Runtime choices for package-manager based IDE tool installs.
#[derive(Default)]
pub struct ToolInstallEnvironment {
@@ -1300,6 +1306,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
}),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
+1
Переглянути файл
@@ -26,6 +26,7 @@ pub mod pinned;
pub mod python;
pub mod ruby;
mod vue;
mod zig;
use serde::{Deserialize, Serialize};
use specta::Type;
+206 -3
Переглянути файл
@@ -2,7 +2,8 @@
//! Project view): the folders holding the sources of the project's SDKs and
//! dependencies — the Python interpreter's standard library and site-packages,
//! the JDK, `node_modules` packages, Cargo crates and the Rust standard
//! library, GOROOT and the Go module cache.
//! library, GOROOT and the Go module cache, the Zig standard library and the
//! fetched packages of `build.zig.zon`.
//!
//! Ecosystems are detected in the project and its modules. SDK and graph probes
//! are cached until manifests or settings change; Node packages are read on refresh.
@@ -28,7 +29,7 @@ use std::time::{Duration, SystemTime};
pub struct LibraryGroup {
/// Display name, e.g. `Python 3.12 (.venv)`.
pub name: String,
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`.
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath` | `zig` | `zigPackages`.
pub kind: String,
pub roots: Vec<LibraryRoot>,
}
@@ -56,6 +57,7 @@ const JAVA_MANIFESTS: &[&str] =
const CARGO_MANIFESTS: &[&str] = &["Cargo.toml", "Cargo.lock", "rust-toolchain", "rust-toolchain.toml"];
const GO_MANIFESTS: &[&str] = &["go.mod", "go.sum", "go.work"];
const RUBY_MANIFESTS: &[&str] = &["Gemfile", "Gemfile.lock", ".ruby-version", ".tool-versions", "mise.toml"];
const ZIG_MANIFESTS: &[&str] = &["build.zig.zon", "build.zig"];
/// A Maven / Gradle dependency of the project, from the build model.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -83,7 +85,7 @@ pub fn project_libraries_stream(
on_groups: &(dyn Fn(Vec<LibraryGroup>) + Sync),
) -> Vec<LibraryGroup> {
type Detect = fn(&Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
let detectors: [Detect; 5] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups];
let detectors: [Detect; 6] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups, zig_groups];
let roots = library_project_roots(root, cancel);
let settings = module_settings(root, settings);
std::thread::scope(|s| {
@@ -193,6 +195,8 @@ fn library_project_roots(root: &Path, cancel: &CancellationToken) -> Vec<PathBuf
"setup.py",
"requirements.txt",
".python-version",
"build.zig",
"build.zig.zon",
".tool-versions",
"mise.toml",
]
@@ -252,6 +256,7 @@ fn module_settings(root: &Path, settings: &Settings) -> Settings {
&mut l.rust.stdlib,
&mut l.go.goroot,
&mut l.go.gopath,
&mut l.zig.zig,
&mut l.java.jdk,
] {
// `target:<id>` names a run target, not a path.
@@ -998,6 +1003,80 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
.collect()
}
// ------------------------------------------------------------------ zig
fn zig_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, ZIG_MANIFESTS) else { return Vec::new() };
let Some(zig) = tool(crate::apply::zig_bin(root, s), "zig") else { return Vec::new() };
cached_cancellable(root, "zig", zig.display().to_string(), &files, cancel, || {
let Some(env) = query_in_cancellable(&zig, &["env"], root, &[], QUERY_TIMEOUT, cancel)
.as_deref()
.and_then(crate::zig::parse_zig_env)
else {
return Vec::new();
};
let mut out = Vec::new();
let version =
env.version.clone().or_else(|| query_in_cancellable(&zig, &["version"], root, &[], QUERY_TIMEOUT, cancel));
let name = match version.as_deref().map(str::trim) {
Some(v) if !v.is_empty() => format!("Zig {v}"),
_ => "Zig".into(),
};
out.extend(env.std_sources().and_then(|std| group(name, "zig", library_roots(vec![std]))));
if let Some(cache) = env.global_cache_dir.as_deref() {
let zon = std::fs::read_to_string(root.join("build.zig.zon")).unwrap_or_default();
let deps = crate::zig::zon_dependencies(&zon);
out.extend(group("Zig packages", "zigPackages", zig_package_roots(cache, &deps)));
}
out
})
}
/// The fetched sources of a `build.zig.zon`'s dependencies: `p/<hash>` folders
/// (Zig ≤ 0.14 unpacks them) or the package root inside `p/<hash>.tar.gz` (Zig
/// ≥ 0.15 keeps packages as blobs, browsed through the archive VFS). Path
/// dependencies stay in the project tree; unfetched packages are simply absent —
/// listing libraries never downloads.
fn zig_package_roots(cache: &Path, deps: &[crate::zig::ZonDependency]) -> Vec<LibraryRoot> {
let mut seen = std::collections::HashSet::new();
deps.iter()
.filter_map(|d| {
let hash = d.hash.as_deref()?;
let dir = cache.join("p").join(hash);
if dir.is_dir() {
let zon = std::fs::read_to_string(dir.join("build.zig.zon")).unwrap_or_default();
let name =
match (crate::zig::zon_string_field(&zon, "name"), crate::zig::zon_string_field(&zon, "version")) {
(Some(name), Some(version)) => format!("{name} {version}"),
(Some(name), None) => name,
_ => hash.to_owned(),
};
return Some((name, dir));
}
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
blob.is_file().then_some(hash).map(|hash| {
// The blob's only top-level folder is the package (`<hash>/`); fall back to
// the archive root should that layout ever change.
let entry = if ide_vfs::read_archive_dir(&blob, hash).is_ok() { hash } else { "" };
(package_label(d, hash), ide_vfs::archive_entry_path(&blob, entry))
})
})
.filter(|(_, path)| seen.insert(path.to_string_lossy().into_owned()))
.map(|(name, path)| LibraryRoot { name, path: path.into() })
.collect()
}
/// `probe_pkg 0.1.0` from a Zig ≥ 0.15 package hash (`name-version-<hash>`).
fn package_label(dep: &crate::zig::ZonDependency, hash: &str) -> String {
let Some((rest, _)) = hash.rsplit_once('-') else { return dep.name.clone() };
let mut parts: Vec<&str> = rest.split('-').collect();
let version = parts.pop().unwrap_or_default();
match parts.is_empty() || !version.starts_with(|c: char| c.is_ascii_digit()) || !version.contains('.') {
true => dep.name.clone(),
false => format!("{} {version}", parts.join("-")),
}
}
#[cfg(test)]
mod go_cache_tests {
use super::*;
@@ -1387,3 +1466,127 @@ mod idea_project_tests {
assert!(idea_java_project(root));
}
}
#[cfg(test)]
mod zig_tests {
use super::*;
use crate::zig::ZonDependency;
/// Writes a Zig package blob (`p/<hash>.tar.gz`) with a `<hash>/` root folder.
fn write_package_blob(cache: &Path, hash: &str, files: &[(&str, &str)]) {
use flate2::write::GzEncoder;
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
std::fs::create_dir_all(blob.parent().unwrap()).unwrap();
let enc = GzEncoder::new(std::fs::File::create(blob).unwrap(), flate2::Compression::default());
let mut tar = tar::Builder::new(enc);
for (name, text) in files {
let mut header = tar::Header::new_gnu();
header.set_size(text.len() as u64);
header.set_mode(0o644);
header.set_cksum();
tar.append_data(&mut header, name, text.as_bytes()).unwrap();
}
tar.into_inner().unwrap().finish().unwrap();
}
#[test]
fn zig_packages_come_from_the_global_cache_without_fetching() {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path();
let (hash, old) = ("zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8", "1220b7c0");
write_package_blob(cache, hash, &[(&format!("{hash}/src/lib.zig"), "pub fn hello() {}\n")]);
let unpacked = cache.join("p").join(old);
std::fs::create_dir_all(&unpacked).unwrap();
std::fs::write(unpacked.join("build.zig.zon"), r#".{ .name = .old_pkg, .version = "0.2.0" }"#).unwrap();
let deps = [
ZonDependency { name: "zap".into(), hash: Some(hash.into()), path: None, lazy: false },
ZonDependency { name: "shared".into(), hash: None, path: Some("../shared".into()), lazy: false },
ZonDependency { name: "gone".into(), hash: Some("gone-1.0.0-BBBBBBBBBB".into()), path: None, lazy: true },
ZonDependency { name: "old".into(), hash: Some(old.into()), path: None, lazy: false },
];
let roots = zig_package_roots(cache, &deps);
let summary: Vec<(String, String)> =
roots.iter().map(|r| (r.name.clone(), r.path.to_string_lossy().into_owned())).collect();
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
assert_eq!(
summary,
[
("zap 0.1.0".into(), format!("{}!/{hash}", blob.display())),
("old_pkg 0.2.0".into(), unpacked.to_string_lossy().into_owned())
]
);
}
#[test]
fn zig_package_labels_parse_from_the_hash() {
let dep = |name: &str| ZonDependency { name: name.into(), hash: None, path: None, lazy: false };
assert_eq!(package_label(&dep("zap"), "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8"), "zap 0.1.0");
assert_eq!(
package_label(&dep("diffz"), "diffz-0.0.1-G2tlISvOAQDORzPTSxDgiKwlHuADKeJMdJrw4kRfLufj"),
"diffz 0.0.1"
);
assert_eq!(
package_label(&dep("zig-anytype"), "zig-anytype-0.1.0-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
"zig-anytype 0.1.0"
);
assert_eq!(package_label(&dep("old"), "1220b7c0"), "old");
}
#[cfg(unix)]
#[test]
fn zig_libraries_list_the_stdlib_and_fetched_packages() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let stdlib = root.join("stdlib");
std::fs::create_dir_all(&stdlib).unwrap();
std::fs::write(root.join("build.zig"), "").unwrap();
let hash = "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8";
let cache = root.join("zig-cache");
write_package_blob(&cache, hash, &[(&format!("{hash}/src/lib.zig"), "pub fn hello() {}\n")]);
std::fs::write(
root.join("build.zig.zon"),
r#".{
.name = .app,
.dependencies = .{
// the package cache holds this one
.zap = .{ .url = "https://example.com/zap.tar.gz", .hash = "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8" },
.local = .{ .path = "../shared" },
.gone = .{ .url = "https://example.com/gone.tar.gz", .hash = "gone-1.0.0-BBBBBBBBBB" },
},
}
"#,
)
.unwrap();
let bin = root.join("tools");
std::fs::create_dir(&bin).unwrap();
let zig = bin.join("zig");
std::fs::write(
&zig,
format!(
"#!/bin/sh\ncase \"$1\" in\n env) printf '%s\\n' '.{{\n .zig_exe = \"{}\",\n .std_dir = \"{}\",\n .global_cache_dir = \"{}\",\n .version = \"0.16.0\",\n}}' ;;\n version) echo 0.16.0 ;;\nesac\n",
zig.display(),
stdlib.display(),
cache.display(),
),
)
.unwrap();
std::fs::set_permissions(&zig, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut settings = Settings::default();
settings.languages.zig.zig = "tools".into();
let groups = zig_groups(root, &settings, &CancellationToken::new());
let summary: Vec<(&str, &str, Vec<&str>)> = groups
.iter()
.map(|g| (g.name.as_str(), g.kind.as_str(), g.roots.iter().map(|r| r.name.as_str()).collect()))
.collect();
assert_eq!(
summary,
[("Zig 0.16.0", "zig", vec!["stdlib"]), ("Zig packages", "zigPackages", vec!["zap 0.1.0"])]
);
let packages = groups.iter().find(|g| g.kind == "zigPackages").unwrap();
assert_eq!(
packages.roots[0].path.to_string_lossy(),
format!("{}!/{hash}", cache.join("p").join(format!("{hash}.tar.gz")).display())
);
}
}
+80
Переглянути файл
@@ -35,6 +35,7 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -1589,6 +1590,85 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
);
}
#[test]
fn build_zig_zon_dependencies_are_parsed() {
let zon = r#"// the manifest is a Zig struct literal
.{
.name = .app,
.version = "0.1.0",
.fingerprint = 0x348e9ddfb4b9e03c,
.dependencies = .{
.zap = .{ .url = "https://example.com/zap.tar.gz", .hash = "zap-0.1.0-AAA" },
.@"weird name" = .{
.url = "https://example.com/w.tar.gz",
.hash = "weird-2.0.0-BBB",
.lazy = true,
},
.shared = .{ .path = "../shared" },
},
.paths = .{ "build.zig", "src" },
}
"#;
assert_eq!(
crate::zig::zon_dependencies(zon),
[
crate::zig::ZonDependency {
name: "zap".into(),
hash: Some("zap-0.1.0-AAA".into()),
path: None,
lazy: false
},
crate::zig::ZonDependency {
name: "weird name".into(),
hash: Some("weird-2.0.0-BBB".into()),
path: None,
lazy: true
},
crate::zig::ZonDependency {
name: "shared".into(),
hash: None,
path: Some("../shared".into()),
lazy: false
},
]
);
assert!(crate::zig::zon_dependencies(".{ .name = .app, .dependencies = .{} }").is_empty());
assert!(crate::zig::zon_dependencies(".{ .name = .app }").is_empty());
assert!(crate::zig::zon_dependencies("{ broken").is_empty());
assert_eq!(
crate::zig::zon_string_field(".{ .name = .probe_pkg, .version = \"0.1.0\" }", "name").as_deref(),
Some("probe_pkg")
);
}
#[test]
fn zig_env_is_parsed_from_json_and_struct_literals() {
let env = crate::zig::parse_zig_env(
r#"{"zig_exe":"/opt/zig/zig","lib_dir":"/opt/zig/lib","std_dir":"/opt/zig/lib/std","global_cache_dir":"/home/u/.cache/zig","version":"0.14.1"}"#,
)
.unwrap();
assert_eq!(env.std_sources().as_deref(), Some(std::path::Path::new("/opt/zig/lib/std")));
assert_eq!(env.global_cache_dir.as_deref(), Some(std::path::Path::new("/home/u/.cache/zig")));
// Zig ≥ 0.15 prints a struct literal; a relative std_dir resolves against the install dir.
let env = crate::zig::parse_zig_env(
r#".{
.zig_exe = "/opt/zig/zig",
.lib_dir = "/opt/zig/lib",
.std_dir = "lib/std",
.global_cache_dir = "/home/u/.cache/zig",
.version = "0.16.0",
.target = "aarch64-macos",
.env = .{ .ZIG_GLOBAL_CACHE_DIR = null, .HOME = "/home/u" },
}"#,
)
.unwrap();
assert_eq!(env.std_sources().as_deref(), Some(std::path::Path::new("/opt/zig/lib/std")));
assert_eq!(env.version.as_deref(), Some("0.16.0"));
assert_eq!(env.global_cache_dir.as_deref(), Some(std::path::Path::new("/home/u/.cache/zig")));
assert!(crate::zig::parse_zig_env("error: nothing").is_none());
}
#[test]
fn jdk_library_is_the_jdk_home() {
let tmp = tempfile::tempdir().unwrap();
+261
Переглянути файл
@@ -0,0 +1,261 @@
//! Reading Zig's own text formats for External Libraries, without running Zig:
//! the package manifest (`build.zig.zon`) and the `zig env` output. Both are
//! Zig struct literals; `zig env` printed JSON before Zig 0.15.
use serde::Deserialize;
use std::path::{Path, PathBuf};
/// One `.dependencies` entry of a `build.zig.zon`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ZonDependency {
pub name: String,
/// Package hash: its sources are fetched into the global cache as `p/<hash>`
/// (Zig ≤ 0.14 unpacks them, Zig ≥ 0.15 keeps `p/<hash>.tar.gz` blobs).
pub hash: Option<String>,
/// A path dependency, part of the project tree rather than the package cache.
pub path: Option<String>,
/// Fetched only when the build actually references it.
pub lazy: bool,
}
/// The `.dependencies` entries of a `build.zig.zon`, in order. Tolerant of
/// partially edited files: whatever does not parse is skipped.
pub(crate) fn zon_dependencies(zon: &str) -> Vec<ZonDependency> {
let src = code_only(zon);
let Some(top) = struct_body(&src) else { return Vec::new() };
let Some((_, value)) = fields(top).into_iter().find(|(name, _)| *name == "dependencies") else {
return Vec::new();
};
let Some(deps) = struct_body(value) else { return Vec::new() };
fields(deps)
.into_iter()
.map(|(name, value)| {
let entry = struct_body(value).map(|body| fields(body)).unwrap_or_default();
ZonDependency {
name: name.to_owned(),
hash: field(&entry, "hash"),
path: field(&entry, "path"),
lazy: entry.iter().any(|(n, v)| *n == "lazy" && v.trim() == "true"),
}
})
.collect()
}
/// A top-level string (or enum-literal, `.name`) field of a Zig struct literal.
pub(crate) fn zon_string_field(text: &str, name: &str) -> Option<String> {
let src = code_only(text);
let top = struct_body(&src)?;
field(&fields(top), name)
}
/// What `zig env` reports that External Libraries needs.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct ZigEnv {
pub zig_exe: Option<PathBuf>,
pub lib_dir: Option<PathBuf>,
pub std_dir: Option<PathBuf>,
pub global_cache_dir: Option<PathBuf>,
pub version: Option<String>,
}
impl ZigEnv {
/// The standard library sources: `std_dir`, else `lib_dir/std`. A relative
/// path resolves against the zig install dir (stage builds print relative paths).
pub(crate) fn std_sources(&self) -> Option<PathBuf> {
let resolve = |p: &Path| match (p.is_relative(), self.zig_exe.as_ref().and_then(|e| e.parent())) {
(true, Some(install)) => install.join(p),
_ => p.to_path_buf(),
};
self.std_dir
.as_deref()
.map(Path::new)
.map(resolve)
.or_else(|| self.lib_dir.as_deref().map(Path::new).map(|dir| resolve(dir).join("std")))
}
}
/// The `zig env` output: JSON (older Zig) or a struct literal (Zig ≥ 0.15).
pub(crate) fn parse_zig_env(out: &str) -> Option<ZigEnv> {
#[derive(Deserialize)]
struct Json {
zig_exe: Option<PathBuf>,
lib_dir: Option<PathBuf>,
std_dir: Option<PathBuf>,
global_cache_dir: Option<PathBuf>,
version: Option<String>,
}
if let Ok(json) = serde_json::from_str::<Json>(out.trim()) {
return Some(ZigEnv {
zig_exe: json.zig_exe,
lib_dir: json.lib_dir,
std_dir: json.std_dir,
global_cache_dir: json.global_cache_dir,
version: json.version,
});
}
let src = code_only(out);
let top = struct_body(&src)?;
let f = fields(top);
Some(ZigEnv {
zig_exe: field(&f, "zig_exe").map(PathBuf::from),
lib_dir: field(&f, "lib_dir").map(PathBuf::from),
std_dir: field(&f, "std_dir").map(PathBuf::from),
global_cache_dir: field(&f, "global_cache_dir").map(PathBuf::from),
version: field(&f, "version"),
})
}
/// The string (or enum-literal, `.foo`) value of a field of a struct body.
fn field<'a>(entry: &[(&'a str, &'a str)], name: &str) -> Option<String> {
let value = entry.iter().find(|(n, _)| *n == name)?.1;
if let Some(string) = string_value(value) {
return Some(string);
}
value
.strip_prefix('.')
.filter(|v| v.chars().next().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_'))
.map(str::to_owned)
}
/// The contents of the string literal starting at `value`, `\"` unescaped.
fn string_value(value: &str) -> Option<String> {
let rest = value.trim_start().strip_prefix('"')?;
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'"' => return Some(out),
'\\' => out.push(chars.next()?),
c => out.push(c),
}
}
None
}
/// `src` with comments blanked out and string contents kept.
fn code_only(src: &str) -> String {
let mut out = String::with_capacity(src.len());
for line in src.lines() {
let bytes = line.as_bytes();
let mut in_string = false;
let mut escaped = false;
let mut end = line.len();
for (i, &b) in bytes.iter().enumerate() {
if in_string {
match b {
_ if escaped => escaped = false,
b'\\' => escaped = true,
b'"' => in_string = false,
_ => {}
}
} else if b == b'"' {
in_string = true;
} else if b == b'/' && bytes.get(i + 1) == Some(&b'/') {
end = i;
break;
}
}
out.push_str(&line[..end]);
out.push('\n');
}
out
}
/// The inside of the first `{ … }` of `text`, strings respected.
fn struct_body(text: &str) -> Option<&str> {
let bytes = text.as_bytes();
let mut start = 0;
while start < bytes.len() {
match bytes[start] {
b'"' => start = skip_string(text, start),
b'{' => break,
_ => start += 1,
}
}
let mut depth = 0;
let mut i = start;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(text, i),
b'{' => {
depth += 1;
i += 1;
}
b'}' => {
if depth == 1 {
return Some(&text[start + 1..i]);
}
depth -= 1;
i += 1;
}
_ => i += 1,
}
}
None
}
/// The index just past the string literal starting at `i` (an opening `"`).
fn skip_string(text: &str, i: usize) -> usize {
let bytes = text.as_bytes();
let mut i = i + 1;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b'"' => return i + 1,
_ => i += 1,
}
}
i
}
/// The `.name = value` fields of a struct literal body, in order: `name` is the
/// identifier (or `@"…"` unquoted), `value` trimmed and may itself be `.{ … }`.
fn fields(body: &str) -> Vec<(&str, &str)> {
let bytes = body.as_bytes();
let mut out = Vec::new();
let mut depth = 0;
let mut field: Option<usize> = None;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(body, i),
b'{' | b'[' | b'(' => {
depth += 1;
i += 1;
}
b'}' | b']' | b')' => {
if depth == 0 {
break;
}
depth -= 1;
i += 1;
}
b',' if depth == 0 => {
if let Some(start) = field.take() {
push_field(&mut out, body, start, i);
}
i += 1;
}
b'.' if depth == 0 && field.is_none() => {
if bytes.get(i + 1).is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'@') {
field = Some(i + 1);
}
i += 1;
}
_ => i += 1,
}
}
if let Some(start) = field {
push_field(&mut out, body, start, bytes.len());
}
out
}
fn push_field<'a>(out: &mut Vec<(&'a str, &'a str)>, body: &'a str, start: usize, end: usize) {
let text = &body[start..end];
let Some(eq) = text.find('=') else { return };
let name = text[..eq].trim().trim_start_matches('@').trim_matches('"');
if !name.is_empty() {
out.push((name, text[eq + 1..].trim()));
}
}
+6 -1
Переглянути файл
@@ -56,7 +56,12 @@ impl<'a> Lines<'a> {
}
pub(crate) fn utf16_len(s: &str) -> u32 {
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
if s.is_ascii() {
return s.len() as u32;
}
// One unit per char (each starts with a non-continuation byte), two for
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
s.as_bytes().iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
}
fn utf16_to_byte(s: &str, offset: usize) -> usize {
+30 -9
Переглянути файл
@@ -39,6 +39,10 @@ impl LineEnding {
/// The dominant line ending of `text`; ties and text without any line
/// break resolve to [`LineEnding::Lf`].
pub fn detect(text: &str) -> Self {
// Without `\r` both other counts are zero and `Lf` wins outright.
if !text.contains('\r') {
return Self::Lf;
}
let (mut lf, mut crlf, mut cr) = (0usize, 0usize, 0usize);
let bytes = text.as_bytes();
let mut i = 0;
@@ -72,13 +76,20 @@ const DIFF_BUDGET: Duration = Duration::from_millis(50);
type LineRange = std::ops::Range<usize>;
/// Byte lengths of the common prefix and suffix; they never overlap.
/// Byte lengths of the common prefix and suffix; they never overlap. Compared
/// byte-wise (equal bytes imply equal chars) so the scan vectorizes, with the
/// ends backed off to char boundaries.
fn common_ends(a: &str, b: &str) -> (usize, usize) {
let shared = |a: &mut dyn Iterator<Item = char>, b: &mut dyn Iterator<Item = char>| -> usize {
a.zip(b).take_while(|(x, y)| x == y).map(|(x, _)| x.len_utf8()).sum()
};
let prefix = shared(&mut a.chars(), &mut b.chars());
let suffix = shared(&mut a[prefix..].chars().rev(), &mut b[prefix..].chars().rev());
let (ab, bb) = (a.as_bytes(), b.as_bytes());
let mut prefix = ab.iter().zip(bb).take_while(|(x, y)| x == y).count();
while !a.is_char_boundary(prefix) {
prefix -= 1;
}
let limit = ab.len().min(bb.len()) - prefix;
let mut suffix = ab.iter().rev().zip(bb.iter().rev()).take(limit).take_while(|(x, y)| x == y).count();
while suffix > 0 && !a.is_char_boundary(a.len() - suffix) {
suffix -= 1;
}
(prefix, suffix)
}
@@ -94,7 +105,13 @@ fn line_starts(lines: &[&str]) -> Vec<usize> {
}
fn utf16_len(text: &str) -> u32 {
text.chars().map(|c| c.len_utf16() as u32).sum()
let bytes = text.as_bytes();
if bytes.is_ascii() {
return bytes.len() as u32;
}
// One unit per char (each starts with a non-continuation byte), two for
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
bytes.iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
}
/// Converts `\r\n` and lone `\r` to `\n`. Borrows when there is nothing to do.
@@ -158,8 +175,12 @@ pub struct Document {
impl Document {
/// Builds a document from text with any line endings; detects and normalizes them.
pub fn new(text: &str) -> Self {
let line_ending = LineEnding::detect(text);
let rope = ropey::Rope::from_str(&normalize_line_endings(text));
// One `\r` scan decides both: LF text needs no normalization pass.
let (line_ending, rope) = if text.contains('\r') {
(LineEnding::detect(text), ropey::Rope::from_str(&normalize_line_endings(text)))
} else {
(LineEnding::Lf, ropey::Rope::from_str(text))
};
Self { rope, version: 0, line_ending }
}
+28 -3
Переглянути файл
@@ -331,8 +331,8 @@ pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &
#[cfg(not(unix))]
{
let link = bin_dir.join(format!("{command}.cmd"));
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", v.display())).collect();
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", target.display()))?;
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", cmd_path(bin_dir, v))).collect();
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
Ok(link)
}
}
@@ -357,11 +357,25 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul
{
let link = bin_dir.join(format!("{command}.cmd"));
let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" };
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", target.display()))?;
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
Ok(link)
}
}
/// `path` as a `.cmd` shim in `bin_dir` names it: relative to the shim (`%~dp0..\…`) when it
/// is in the tool's own directory. cmd.exe reads a batch file in the console's code page, so
/// an absolute path through a non-ASCII user directory, written as UTF-8, isn't found (#3338).
#[cfg_attr(unix, allow(dead_code))]
fn cmd_path(bin_dir: &Path, path: &Path) -> String {
match bin_dir.parent().and_then(|tool| path.strip_prefix(tool).ok()) {
Some(rest) => {
let rest: Vec<_> = rest.components().map(|c| c.as_os_str().to_string_lossy()).collect();
format!("%~dp0..\\{}", rest.join("\\"))
}
None => path.display().to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -743,6 +757,17 @@ mod tests {
assert!(found.ends_with("server/com.microsoft.java.debug.plugin-0.53.2.jar"));
}
#[test]
fn windows_shims_name_the_tool_relative_to_themselves() {
let tool = Path::new("/Users/张三/AppData/Local/ai.l0ng.openidea/tools/taplo");
let bin = tool.join("bin");
assert_eq!(cmd_path(&bin, &tool.join("taplo.exe")), "%~dp0..\\taplo.exe");
assert_eq!(cmd_path(&bin, &tool.join("gems/bin/solargraph")), "%~dp0..\\gems\\bin\\solargraph");
// Outside the tool's directory (a system SDK) stays absolute.
let sdk = Path::new("/usr/local/share/dotnet");
assert_eq!(cmd_path(&bin, sdk), sdk.display().to_string());
}
#[cfg(unix)]
#[test]
fn wrapper_runs_target() {
+22
Переглянути файл
@@ -170,6 +170,28 @@ mod tests {
assert_eq!(select_asset(&["laravel-lsp"], rules, LINUX_X64), None);
}
#[test]
fn phoxite_assets() {
let names = [
"phoxite-lsp-aarch64-apple-darwin",
"phoxite-lsp-x86_64-apple-darwin",
"phoxite-lsp-aarch64-unknown-linux-gnu",
"phoxite-lsp-x86_64-unknown-linux-gnu",
"phoxite-lsp-x86_64-pc-windows-msvc.exe",
// Not for any platform here: the musl build, the checksums, the VS Code packages.
"phoxite-lsp-x86_64-unknown-linux-musl",
"phoxite-lsp-x86_64-unknown-linux-gnu.sha256",
"phoxite-lsp-x86_64-pc-windows-msvc.exe.sha256",
"phoxite-linux-x64-0.2.1.vsix",
];
let rules = crate::registry::find("phoxite").unwrap().asset_rules();
assert_eq!(select_asset(&names, rules, MAC_ARM), Some(names[0]));
assert_eq!(select_asset(&names, rules, MAC_X64), Some(names[1]));
assert_eq!(select_asset(&names, rules, LINUX_ARM), Some(names[2]));
assert_eq!(select_asset(&names, rules, LINUX_X64), Some(names[3]));
assert_eq!(select_asset(&names, rules, WIN), Some(names[4]));
}
#[test]
fn kmp_lsp_assets_include_the_native_jar_indexer() {
let names = [
+32
Переглянути файл
@@ -458,6 +458,38 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/laravel/lsp",
needs: &[],
},
ToolSpec {
name: "phoxite",
display: "Phoxite",
kind: LanguageServer,
commands: &["phoxite-lsp"],
// Plain binaries per platform (`phoxite-lsp-<target triple>[.exe]`), each with a
// `.sha256` beside it.
method: Method::Release {
source: ReleaseSource::GitHub { repo: "samehelhawary/phoxite" },
assets: &[
rule(Mac, Arm64, "phoxite-lsp-aarch64-apple-darwin"),
rule(Mac, X64, "phoxite-lsp-x86_64-apple-darwin"),
rule(Linux, Arm64, "phoxite-lsp-aarch64-unknown-linux-gnu"),
rule(Linux, X64, "phoxite-lsp-x86_64-unknown-linux-gnu"),
rule(Windows, Arm64, "phoxite-lsp-aarch64-pc-windows-msvc.exe"),
rule(Windows, X64, "phoxite-lsp-x86_64-pc-windows-msvc.exe"),
],
locate: &[
"phoxite-lsp",
"phoxite-lsp-aarch64-apple-darwin",
"phoxite-lsp-x86_64-apple-darwin",
"phoxite-lsp-aarch64-unknown-linux-gnu",
"phoxite-lsp-x86_64-unknown-linux-gnu",
"phoxite-lsp-aarch64-pc-windows-msvc",
"phoxite-lsp-x86_64-pc-windows-msvc",
],
},
fallback: None,
version: ver("phoxite-lsp"),
homepage: "https://github.com/samehelhawary/phoxite",
needs: &[],
},
ToolSpec {
name: "gopls",
display: "gopls",
+145
Переглянути файл
@@ -0,0 +1,145 @@
//! Show Diff in External Tool: starts the user's diff program on the two sides of a diff.
use ide_core::{IdeError, IdeResult, settings::ExternalDiffSettings};
use serde::Deserialize;
use specta::Type;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
/// One side of the diff: a file on disk, or text written to a temporary file.
#[derive(Clone, Debug, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalDiffSide {
/// A saved file, passed to the tool as it is.
pub path: Option<PathBuf>,
/// Content without a file of its own (a revision, a text), written to a temporary file.
pub text: Option<String>,
/// The temporary file's name; its extension lets the tool pick a syntax.
pub name: String,
}
/// Splits a parameter line like a shell does for plain words: whitespace separates
/// arguments, double or single quotes keep one together, a backslash escapes the next
/// character inside double quotes and outside quotes.
pub fn split_parameters(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut in_arg = false;
let mut quote: Option<char> = None;
let mut chars = line.chars();
while let Some(c) = chars.next() {
match (quote, c) {
(Some('\''), '\'') | (Some('"'), '"') => quote = None,
(Some('"') | None, '\\') => {
if let Some(next) = chars.next() {
cur.push(next);
}
in_arg = true;
}
(None, '"' | '\'') => {
quote = Some(c);
in_arg = true;
}
(None, c) if c.is_whitespace() => {
if in_arg {
out.push(std::mem::take(&mut cur));
in_arg = false;
}
}
(_, c) => {
cur.push(c);
in_arg = true;
}
}
}
if in_arg {
out.push(cur);
}
out
}
/// The tool's arguments: `%1` the left file, `%2` the right file, `%3` the title.
pub fn expand_parameters(parameters: &str, left: &str, right: &str, title: &str) -> Vec<String> {
split_parameters(parameters)
.into_iter()
.map(|arg| arg.replace("%1", left).replace("%2", right).replace("%3", title))
.collect()
}
fn side_file(side: &ExternalDiffSide, dir: &Path, sub: &str) -> IdeResult<PathBuf> {
if let Some(path) = &side.path {
return Ok(path.clone());
}
let name = Path::new(&side.name).file_name().map(|n| n.to_owned()).unwrap_or_else(|| "content".into());
let folder = dir.join(sub);
std::fs::create_dir_all(&folder)?;
let file = folder.join(name);
std::fs::write(&file, side.text.as_deref().unwrap_or_default())?;
Ok(file)
}
/// Starts the configured tool on `left` ↔ `right` and returns once it runs; the tool
/// lives on after the diff closes, as it would started from a shell.
pub fn launch_external_diff(
settings: &ExternalDiffSettings,
left: &ExternalDiffSide,
right: &ExternalDiffSide,
title: &str,
) -> IdeResult<()> {
let program = settings.path.trim();
if program.is_empty() {
return Err(IdeError::invalid("no external diff tool is set (Settings › Tools › External Diff Tools)"));
}
let needs_temp = left.path.is_none() || right.path.is_none();
// Kept after the call: the tool reads the files after it starts.
let dir = if needs_temp { Some(tempfile::Builder::new().prefix("openidea-diff-").tempdir()?.keep()) } else { None };
let temp = dir.as_deref().unwrap_or_else(|| Path::new(""));
let a = side_file(left, temp, "left")?;
let b = side_file(right, temp, "right")?;
let args = expand_parameters(&settings.parameters, &a.to_string_lossy(), &b.to_string_lossy(), title);
let mut cmd = Command::new(program);
ide_core::process::prepare(&mut cmd);
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
let mut child = cmd
.spawn()
.map_err(|e| IdeError::unavailable(format!("cannot start the external diff tool {program}: {e}")))?;
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splits_quoted_parameters() {
assert_eq!(split_parameters("%1 %2 %3"), ["%1", "%2", "%3"]);
assert_eq!(split_parameters(r#"--title "%3" -L 'a b' x\ y"#), ["--title", "%3", "-L", "a b", "x y"]);
assert_eq!(split_parameters(r#"--empty "" end"#), ["--empty", "", "end"]);
}
#[test]
fn expands_placeholders_inside_arguments() {
let args = expand_parameters("--left=%1 %2 --title %3", "/t/a b.rs", "/t/b.rs", "a.rs (HEAD ↔ Your version)");
assert_eq!(args, ["--left=/t/a b.rs", "/t/b.rs", "--title", "a.rs (HEAD ↔ Your version)"]);
}
#[test]
fn writes_text_sides_to_named_temporary_files() {
let dir = tempfile::tempdir().unwrap();
let side = ExternalDiffSide { path: None, text: Some("x\n".into()), name: "../Main.java".into() };
let file = side_file(&side, dir.path(), "left").unwrap();
assert_eq!(file, dir.path().join("left/Main.java"));
assert_eq!(std::fs::read_to_string(file).unwrap(), "x\n");
let saved = ExternalDiffSide { path: Some("/p/a.rs".into()), text: None, name: "a.rs".into() };
assert_eq!(side_file(&saved, dir.path(), "right").unwrap(), PathBuf::from("/p/a.rs"));
}
#[test]
fn needs_a_program() {
let side = ExternalDiffSide { path: Some("/p/a".into()), text: None, name: "a".into() };
assert!(launch_external_diff(&ExternalDiffSettings::default(), &side, &side, "t").is_err());
}
}
+2
Переглянути файл
@@ -627,6 +627,7 @@ pub mod changelists;
mod cli;
mod compare;
mod diff;
mod external_diff;
mod history;
mod ignore;
mod index_writes;
@@ -653,6 +654,7 @@ pub use cli::{
set_git_command_observer, set_git_executable,
};
pub use diff::build_partial_patch;
pub use external_diff::{ExternalDiffSide, launch_external_diff};
pub use ignore::{IgnoreDestination, add_to_ignore};
pub use manage::{MergeOptions, RebaseOptions, RemoteEdit, Worktree};
pub use remotes::Remote;
+10 -16
Переглянути файл
@@ -24,8 +24,8 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
&& let Some((upstream_name, upstream_id)) = upstream_of(&repo, name.as_ref())
{
info.upstream = Some(upstream_name);
if let (Some(local), Some(up)) = (head_commit, upstream_id) {
let (a, b) = ahead_behind(&repo, local, up)?;
if let Some(local) = head_commit {
let (a, b) = ahead_behind(&repo, local, upstream_id)?;
info.ahead = a;
info.behind = b;
}
@@ -51,16 +51,12 @@ pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
Some(op.to_string())
}
/// Short upstream name (`origin/main`) and, if the tracking ref exists, its commit.
fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, Option<gix::ObjectId>)> {
/// Short upstream name (`origin/main`) and its commit. A branch whose tracking ref is gone (the
/// remote branch was deleted and pruned) tracks nothing, as in IDEA.
fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, gix::ObjectId)> {
let tracking = repo.branch_remote_tracking_ref_name(branch, gix::remote::Direction::Fetch)?.ok()?;
let short = to_string(tracking.as_ref().shorten());
let id = repo
.try_find_reference(tracking.as_ref())
.ok()
.flatten()
.and_then(|mut r| r.peel_to_id().ok().map(|id| id.detach()));
Some((short, id))
let id = repo.try_find_reference(tracking.as_ref()).ok()??.peel_to_id().ok()?.detach();
Some((to_string(tracking.as_ref().shorten()), id))
}
/// Commits in `local` not in `upstream`, and vice versa.
@@ -114,11 +110,9 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
};
if let Some((up, up_id)) = upstream_of(&repo, full.as_ref()) {
branch.upstream = Some(up);
if let Some(up_id) = up_id {
let (a, b) = ahead_behind(&repo, id, up_id)?;
branch.ahead = a;
branch.behind = b;
}
let (a, b) = ahead_behind(&repo, id, up_id)?;
branch.ahead = a;
branch.behind = b;
}
out.push(branch);
}
+6
Переглянути файл
@@ -777,12 +777,18 @@ fn fetch_prunes_deleted_remote_branches() {
let (fx, bare) = Fixture::with_origin();
fx.git(&["push", "-q", "origin", "main:gone"]);
fx.git(&["fetch", "-q"]);
fx.git(&["checkout", "-q", "-b", "feature", "--track", "origin/gone"]);
let repo = fx.repo();
let upstream = || repo.branches().unwrap().into_iter().find(|b| b.name == "feature").and_then(|b| b.upstream);
assert!(repo.branches().unwrap().iter().any(|b| b.name == "origin/gone"));
assert_eq!(upstream().as_deref(), Some("origin/gone"));
git_in(&bare, &["branch", "-D", "gone"]);
let (cancel, out) = quiet();
repo.fetch(&cancel, &out).unwrap();
assert!(!repo.branches().unwrap().iter().any(|b| b.name == "origin/gone"));
// The branch that tracked it no longer counts as tracking, as in IDEA.
assert_eq!(upstream(), None);
assert_eq!(repo.branch_info().unwrap().upstream, None);
}
#[test]
+2
Переглянути файл
@@ -20,6 +20,8 @@ trash.workspace = true
tracing.workspace = true
parking_lot.workspace = true
zip.workspace = true
flate2.workspace = true
tar.workspace = true
[dev-dependencies]
tempfile.workspace = true
+163 -44
Переглянути файл
@@ -1,6 +1,7 @@
//! Read-only browsing of zip archives (jar, zip, war…), IDEA's `jar://` file
//! system: `<archive>!` is the archive's root and `<archive>!/<entry>` an entry
//! inside it. Listing and reading go through a small cache of parsed central
//! Read-only browsing of zip archives (jar, zip, war…) and gzip'd tars (Zig
//! keeps its fetched packages as `.tar.gz` blobs), IDEA's `jar://` file system:
//! `<archive>!` is the archive's root and `<archive>!/<entry>` an entry inside
//! it. Listing and reading go through a small cache of parsed central
//! directories, refreshed when the archive changes on disk.
use crate::{EntryKind, FileEntry, mtime_ms, natural_cmp};
@@ -8,7 +9,7 @@ use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::{Read, Seek};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock};
use std::time::SystemTime;
@@ -22,13 +23,21 @@ pub const ARCHIVE_SEPARATOR: char = '!';
/// Parsed archives kept open.
const CACHE_SIZE: usize = 8;
/// Whether `path` names a file browsed as an archive (by extension).
/// Whether `path` names a file browsed as an archive: a zip extension, or a
/// gzip'd tar (`x.tar.gz`).
pub fn is_archive_file(path: &Path) -> bool {
if is_tar_gz(path) {
return true;
}
path.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| ARCHIVE_EXTENSIONS.iter().any(|a| a.eq_ignore_ascii_case(e)))
}
fn is_tar_gz(path: &Path) -> bool {
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.to_ascii_lowercase().ends_with(".tar.gz"))
}
/// `(archive, entry)` for `<archive>!` (entry `""`) or `<archive>!/<entry>`;
/// `None` for ordinary paths. The entry is `/`-separated without leading or trailing `/`.
pub fn split_archive_path(path: &Path) -> Option<(PathBuf, String)> {
@@ -84,7 +93,14 @@ struct Archive {
mtime_ms: f64,
/// Entry path (`""` = root) → node.
nodes: HashMap<String, Node>,
zip: Mutex<zip::ZipArchive<File>>,
contents: Contents,
}
/// Where entry contents come from: a random-access zip, or a gzip'd tar that
/// is re-scanned per read (package tarballs are small).
enum Contents {
Zip(Mutex<zip::ZipArchive<File>>),
Tar(Mutex<File>),
}
/// Most recently used first.
@@ -115,43 +131,83 @@ fn parent_of(name: &str) -> (&str, &str) {
impl Archive {
fn open(path: &Path, stamp: (Option<SystemTime>, u64), mtime_ms: f64) -> IdeResult<Self> {
let mut zip = zip::ZipArchive::new(File::open(path)?).map_err(|e| zip_error(path, e))?;
let mut nodes: HashMap<String, Node> = HashMap::new();
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
for i in 0..zip.len() {
let Ok(file) = zip.by_index_raw(i) else { continue };
let Ok(name) = file.name() else { continue };
let Some(name) = clean_name(&name) else { continue };
let (dir, size) = (file.is_dir(), file.size());
drop(file);
let mut parent = parent_of(&name).0;
while !nodes.contains_key(parent) {
nodes.insert(parent.to_owned(), Node { dir: true, size: 0, index: None, children: Vec::new() });
parent = parent_of(parent).0;
}
let node = nodes.entry(name).or_insert(Node { dir, size: 0, index: None, children: Vec::new() });
node.dir |= dir;
node.index = Some(i);
node.size = if node.dir { 0 } else { size };
}
let links: Vec<(String, String)> = nodes
.keys()
.filter(|k| !k.is_empty())
.map(|k| {
let (parent, base) = parent_of(k);
(parent.to_owned(), base.to_owned())
})
.collect();
for (parent, base) in links {
if let Some(p) = nodes.get_mut(&parent) {
p.dir = true;
p.children.push(base);
}
}
Ok(Self { stamp, mtime_ms, nodes, zip: Mutex::new(zip) })
let file = File::open(path)?;
let (nodes, contents) = if is_tar_gz(path) {
(tar_nodes(&file)?, Contents::Tar(Mutex::new(file)))
} else {
let mut zip = zip::ZipArchive::new(file).map_err(|e| zip_error(path, e))?;
let nodes = zip_nodes(&mut zip)?;
(nodes, Contents::Zip(Mutex::new(zip)))
};
Ok(Self { stamp, mtime_ms, nodes, contents })
}
}
/// The directory tree of a zip, with each entry's central-directory index.
fn zip_nodes(zip: &mut zip::ZipArchive<File>) -> IdeResult<HashMap<String, Node>> {
let mut nodes: HashMap<String, Node> = HashMap::new();
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
for i in 0..zip.len() {
let Ok(file) = zip.by_index_raw(i) else { continue };
let Ok(name) = file.name() else { continue };
let Some(name) = clean_name(&name) else { continue };
let (dir, size) = (file.is_dir(), file.size());
drop(file);
add_entry(&mut nodes, name, i, dir, size);
}
Ok(link_children(nodes))
}
/// The directory tree of a gzip'd tar, with each entry's ordinal position.
/// Entries are re-read by streaming the (decompressed) tar again.
fn tar_nodes(file: &File) -> IdeResult<HashMap<String, Node>> {
let mut nodes: HashMap<String, Node> = HashMap::new();
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
for (i, entry) in tar.entries()?.enumerate() {
let Ok(entry) = entry else { break };
let Ok(name) = entry.path().map(|p| p.to_string_lossy().into_owned()) else { continue };
let Some(name) = clean_name(&name) else { continue };
let (dir, size) = match entry.header().entry_type().is_dir() {
true => (true, 0),
false => (false, entry.header().size().unwrap_or_default()),
};
add_entry(&mut nodes, name, i, dir, size);
}
Ok(link_children(nodes))
}
fn add_entry(nodes: &mut HashMap<String, Node>, name: String, index: usize, dir: bool, size: u64) {
let mut parent = parent_of(&name).0;
while !nodes.contains_key(parent) {
nodes.insert(parent.to_owned(), Node { dir: true, size: 0, index: None, children: Vec::new() });
parent = parent_of(parent).0;
}
let node = nodes.entry(name).or_insert(Node { dir, size: 0, index: None, children: Vec::new() });
node.dir |= dir;
node.index = Some(index);
node.size = if node.dir { 0 } else { size };
}
/// Makes every named entry a child of its parent folder node.
fn link_children(mut nodes: HashMap<String, Node>) -> HashMap<String, Node> {
let links: Vec<(String, String)> = nodes
.keys()
.filter(|k| !k.is_empty())
.map(|k| {
let (parent, base) = parent_of(k);
(parent.to_owned(), base.to_owned())
})
.collect();
for (parent, base) in links {
if let Some(p) = nodes.get_mut(&parent) {
p.dir = true;
p.children.push(base);
}
}
nodes
}
/// The parsed archive at `path`, from the cache unless it changed on disk.
fn archive(path: &Path) -> IdeResult<Arc<Archive>> {
let meta = std::fs::metadata(path)?;
@@ -235,10 +291,31 @@ pub fn read_archive_entry(archive_path: &Path, entry: &str) -> IdeResult<(Vec<u8
Some(_) => return Err(IdeError::invalid(format!("{entry} is a directory"))),
None => return Err(IdeError::not_found(format!("{entry} not found in {}", archive_path.display()))),
};
let mut zip = a.zip.lock();
let mut file = zip.by_index(index).map_err(|e| zip_error(archive_path, e))?;
let mut bytes = Vec::with_capacity(file.size().min(crate::MAX_OPEN_SIZE) as usize);
file.read_to_end(&mut bytes)?;
let bytes = match &a.contents {
Contents::Zip(zip) => {
let mut zip = zip.lock();
let mut file = zip.by_index(index).map_err(|e| zip_error(archive_path, e))?;
let mut bytes = Vec::with_capacity(file.size().min(crate::MAX_OPEN_SIZE) as usize);
file.read_to_end(&mut bytes)?;
bytes
}
Contents::Tar(file) => {
let mut file = file.lock();
file.seek(std::io::SeekFrom::Start(0))?;
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(&mut *file));
for (i, entry) in tar.entries()?.enumerate() {
if i != index {
continue;
}
let mut entry = entry.map_err(|e| IdeError::invalid(format!("{}: {e}", archive_path.display())))?;
let mut bytes =
Vec::with_capacity(entry.header().size().unwrap_or_default().min(crate::MAX_OPEN_SIZE) as usize);
entry.read_to_end(&mut bytes)?;
return Ok((bytes, a.mtime_ms));
}
return Err(IdeError::not_found(format!("{entry} not found in {}", archive_path.display())));
}
};
Ok((bytes, a.mtime_ms))
}
@@ -262,6 +339,20 @@ pub(crate) mod tests {
w.finish().unwrap();
}
/// Writes a gzip'd tar with `files`, the layout of the Zig package cache blobs.
pub(crate) fn write_tar_gz(path: &Path, files: &[(&str, &str)]) {
let enc = flate2::write::GzEncoder::new(File::create(path).unwrap(), flate2::Compression::default());
let mut b = tar::Builder::new(enc);
for (name, text) in files {
let mut header = tar::Header::new_gnu();
header.set_size(text.len() as u64);
header.set_mode(0o644);
header.set_cksum();
b.append_data(&mut header, name, text.as_bytes()).unwrap();
}
b.into_inner().unwrap().finish().unwrap();
}
#[test]
fn splits_archive_paths() {
assert_eq!(split_archive_path(Path::new("/a/b.txt")), None);
@@ -317,6 +408,34 @@ pub(crate) mod tests {
assert_eq!(names(""), vec![("only.txt".into(), EntryKind::File)]);
}
#[test]
fn lists_and_reads_gzipped_tars() {
let tmp = tempfile::tempdir().unwrap();
let hash = "probe_pkg-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8";
let blob = tmp.path().join(format!("{hash}.tar.gz"));
let (zon, lib) = (format!("{hash}/build.zig.zon"), format!("{hash}/src/lib.zig"));
write_tar_gz(&blob, &[(zon.as_str(), ".{ .name = .probe_pkg }"), (lib.as_str(), "pub fn hello() {}\n")]);
let root = |entry: &str| PathBuf::from(format!("{}!/{entry}", blob.display()));
let names = |dir: &str| -> Vec<String> {
crate::read_dir(&root(&format!("{hash}/{dir}")), &[]).unwrap().into_iter().map(|e| e.name).collect()
};
assert_eq!(names(""), vec!["src", "build.zig.zon"]);
assert_eq!(names("src"), vec!["lib.zig"]);
let lib = crate::load_text(&root(&format!("{hash}/src/lib.zig"))).unwrap();
assert_eq!((lib.text.as_str(), lib.binary), ("pub fn hello() {}\n", false));
// A rewritten tar is re-read, and a plain `.gz` stays an ordinary file.
write_tar_gz(&blob, &[("only.zig", "1")]);
let f = File::options().write(true).open(&blob).unwrap();
f.set_modified(SystemTime::now() + std::time::Duration::from_secs(5)).unwrap();
assert_eq!(
crate::read_dir(&root(""), &[]).unwrap().iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
["only.zig"]
);
assert!(!is_archive_file(Path::new("/a/data.gz")));
assert!(is_archive_file(Path::new("/a/pack.TAR.GZ")));
}
#[test]
fn read_dir_and_load_text_go_through_archives() {
let tmp = tempfile::tempdir().unwrap();
+2 -2
Переглянути файл
@@ -197,5 +197,5 @@ You don't write anything special for remote development. In a remote window, `sr
1. Put the logic in the owning crate; convert errors to `IdeError` at its edge; use IPC coordinates.
2. Add the shared implementation to `ide-host::ops::<domain>` if it touches a project; register it with the remote dispatcher if remote windows need it.
3. Add the `#[tauri::command] #[specta::specta]` adapter in `src-tauri/src/commands/<domain>.rs` and list it in `collect_commands!`.
4. If it executes anything, leave it out of the restricted-mode allowlist (it is denied in untrusted projects by default).
5. `pnpm gen:bindings`, then call it with `call(commands.yourCommand(...))`.
4. Decide its trust class: list it by exact name in `restricted_command_allowed` (also in Restricted Mode) or `projectless_command_allowed` (also with no project open), or leave it out to require a trusted project. There are no name prefixes; if it executes anything, leave it out.
5. `pnpm gen:bindings`, then call it with `call(commands.yourCommand(...))`. It also rewrites `src-tauri/tests/commands.snap`; check that the new line shows the trust class and placement you meant.
+2
Переглянути файл
@@ -28,6 +28,8 @@ Style components with CSS Modules: `Thing.module.css` next to `Thing.tsx`, impor
Build from the primitives in `src/ui/` before writing your own: `Button`, `BarButton`, `Input`, `Checkbox`, `Select`, `Dialog`, `Popup`, `Menu`, `Tooltip`, `List`, `Tree`, `Tabs`, `Splitter`, `Scrollbar`, `Spinner`, `Kbd`, and `T` for translated text. They already handle focus, keyboard navigation, theming and translation of their labels. Workbench-level pieces (tool windows, status items, overlays) come from [contributions](/en/contribute/architecture/frontend#contributions), not from custom layout.
Toolbar icon actions use `IconButton`: its full hit target uses `--bg-toolbar-hover` on hover, while pressed and selected states use their corresponding toolbar tokens. Keep semantic icon colours and the keyboard focus ring intact.
## Accessibility
- Use real `<button>` and `<input>` elements (or the primitives that render them), never clickable `<div>`s.
+1 -1
Переглянути файл
@@ -31,7 +31,7 @@ Opening a project folder can run code that the project controls: language server
- When a project that hasn't been decided opens, the **Trust and Open Project?** dialog offers **Trust Project**, **Preview in Restricted Mode** and **Don't Open**. Decisions and trusted locations are managed on Settings' **Project Trust** page (group **Security**), and **Revoke Trust** is an action.
- Trust is user-owned state (`crates/ide-host/src/trust.rs`). **Project settings never grant trust.**
- Enforcement is in the backend, not the UI: every IPC command passes `Host::authorize_command` in the Tauri invoke handler (`src-tauri/src/lib.rs`) before it runs. In an untrusted project only commands on an explicit allowlist (`restricted_command_allowed`) run: reading and editing files and documents, syntax, search, navigation, local history, spelling, analysis, refactoring, settings and similar.
- The allowlist is a default-deny list: **a new command that executes anything is denied in restricted mode until you deliberately classify it there.** Don't add an execution command to the allowlist to make a feature "work" in restricted mode.
- The allowlist is a default-deny list of exact names: **a new command that executes anything is denied in restricted mode until you deliberately classify it there.** Don't add an execution command to the allowlist to make a feature "work" in restricted mode. `src-tauri/tests/commands.snap` lists every command's trust class, so a change shows up in review.
- Below the command layer, language servers don't start (`LspManager` execution switch), and git runs with execution disabled and without the project's `git` executable setting until the project is trusted. Project plugins (`.openidea/plugins/`) load only for trusted projects.
- In a remote window the desktop checks the remote project's trust before forwarding a command, and `openidea-server` authorizes every `invoke` again.
+6 -6
Переглянути файл
@@ -7,12 +7,12 @@ Smoke tests check each language end to end with the real tools the IDE uses: lan
They are not part of `cargo nextest run` or `pnpm test`, because they need the tools installed. CI runs them in the **Language smoke** workflow with pinned versions.
| Suite | What it checks | Languages |
| ----------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------- |
| `crates/ide-host/tests/language_smoke.rs` | Code intelligence through the `ops` the app's commands call | typescript, python, rust, go, java, kotlin, php |
| `crates/ide-host/tests/project_smoke.rs` | Opening a fixture with its build tool and SDK | `maven_sync`, `jdk`, `gradle_sync`, `python_venv` |
| `smoke/run.test.ts` | Run and test configurations through the run store and a real `openidea-server` | typescript, python, rust, go, java, kotlin, php |
| `smoke/debug.test.ts` | Debugging the entry point with the debugger the IDE installs | typescript, python, rust, go, java, kotlin, c, cpp, php |
| Suite | What it checks | Languages |
| ----------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------ |
| `crates/ide-host/tests/language_smoke.rs` | Code intelligence through the `ops` the app's commands call | typescript, python, rust, go, java, kotlin, php |
| `crates/ide-host/tests/project_smoke.rs` | Opening a fixture with its build tool and SDK | `maven_sync`, `jdk`, `gradle_sync`, `python_venv` |
| `smoke/run.test.ts` | Run and test configurations through the run store and a real `openidea-server` | typescript, python, rust, go, java, kotlin, php, zig |
| `smoke/debug.test.ts` | Debugging the entry point with the debugger the IDE installs | typescript, python, rust, go, java, kotlin, c, cpp, zig, php |
## Language smoke
+4
Переглянути файл
@@ -56,6 +56,8 @@ Agents are unavailable in a project you have not marked as trusted.
Available models depend on the installed agent and account. If a selected model is removed, choose another before starting. Refreshing does not change running tasks.
The version below the prompt is reported by a fresh agent initialization when this page is shown or the window regains focus. After updating a CLI, return to this page to refresh it. This does not restart running tasks; an already running agent process keeps its original version until it exits.
</Step>
<Step title="Send">
The task opens as an editor tab and starts.
@@ -119,6 +121,8 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
## Add a custom agent
Any agent that speaks ACP over stdio can be added with an agent file, `agents/<id>.toml` in OpenIDEA's configuration directory:
+2 -1
Переглянути файл
@@ -146,7 +146,8 @@ Closing a selected result activates its left neighbor, or its right neighbor if
**Edit Data** (`F4`) opens a table in an editor tab with server-side paging (100 to 5,000 rows), a `WHERE` filter and an `ORDER BY` field (both with completion). Click a column header to sort; `Shift`-click to add more sort columns.
- Double-click, `Enter` or `F2` edits a cell; `Shift+Enter` opens a larger editor. Pasting tab-separated text fills several cells.
- **Add Row**, **Delete Rows**, **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
- **Add Row** (`⌘N` / `Alt+Insert`), **Delete Rows** (`Ctrl+Y` on Windows and Linux), **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
- **Reload Page** (`⌘R` / `Ctrl+F5`), **Previous Page** and **Next Page** (`⌘⌥↑` / `⌘⌥↓`, `Ctrl+Alt+Up` / `Ctrl+Alt+Down`). These, the copy commands and **Export Data** are actions: find them with **Find Action** and assign shortcuts in **Settings › Keymap**.
- **Submit** (`⌘Enter` / `Ctrl+Enter`) sends all pending changes in one transaction; **Revert** (`⌘⌥Z` / `Ctrl+Alt+Z`) discards them.
Console results are editable the same way when the query is a plain select from one table that includes the primary key. Tables without a primary key, joins, aggregates, `UNION` queries, read-only data sources and ClickHouse results are read-only.
+1 -1
Переглянути файл
@@ -47,7 +47,7 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
| **Move Caret to Code Block Start** / **End** | `⌥⌘[` / `⌥⌘]` | `Ctrl+[` / `Ctrl+]` |
| **Toggle Insert/Overwrite** | `Insert` | `Insert` |
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines; they have no default shortcut.
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
Brackets and quotes are paired as you type, and typing a quote or bracket over a selection surrounds it. These and other typing aids (smart Home, Tab out of a closing bracket, smart indent on Enter, documentation comment stubs, what Backspace does with indentation, reformat on paste) are under **Settings › Editor › General › Smart Keys**.
+1
Переглянути файл
@@ -101,6 +101,7 @@ Each entry starts one LSP server. Servers are listed in order; all regular serve
| `settings` | table | Answers the server's `workspace/configuration` requests. Without it, the requested sections are looked up in `initialization-options`. |
| `install-hint` | string | Shown when the server is missing and the IDE cannot install it. |
| `fallback` | bool | An alternative to the servers listed before it; used only while none of them is installed. |
| `replaces` | string array | Names of servers listed after this one that it makes redundant. They are not used while this server serves the file. Use it for an alternative that covers what an added server does. |
| `features` | string array | Use the server only for these features; empty means everything. Values: `completion`, `inline-completion`, `hover`, `signature-help`, `definition`, `declaration`, `type-definition`, `implementation`, `references`, `document-highlight`, `document-symbol`, `workspace-symbol`, `code-action`, `code-lens`, `rename`, `formatting`, `inlay-hint`, `semantic-tokens`, `document-link`, `call-hierarchy`, `type-hierarchy`, `folding-range`, `selection-range`, `diagnostics`. |
| `code-action-kinds` | string array | Keep only these code action kinds, matched by prefix (`refactor` keeps `refactor.extract`); empty keeps all. |
| `connect` | string | `host:port` of a server that speaks LSP over TCP. See [TCP servers](#tcp-servers). |
+1 -1
Переглянути файл
@@ -148,7 +148,7 @@ The table lists every built-in language definition. Server and debugger names in
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — |
+11 -7
Переглянути файл
@@ -7,11 +7,14 @@ OpenIDEA highlights PHP files (`.php`, `.phtml`, `.phpt` and older `.php3`–`.p
## Language servers
| Server | When it runs |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
| `phpactor` | Fallback: used only while Intelephense is not installed. |
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
| Server | When it runs |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
| `phpactor` | Fallback: used only while Intelephense is not installed. |
| `phoxite` | Alternative with its own Laravel and Blade support: used while neither server above is installed, or when you pick it in **Settings › Languages & Frameworks › Language Servers**. |
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
While Phoxite serves a project, `laravel-lsp` is not started: Phoxite answers the Laravel strings itself.
Intelephense checks code against the project's PHP version (see [Language level](#language-level)) and indexes the stubs and include paths you configure.
@@ -25,6 +28,7 @@ When a `.php` file opens and Intelephense is missing, a notification offers **In
| ------------------ | ---------------------------------------------------------------------- |
| Intelephense | npm (`intelephense`) |
| Laravel LSP | GitHub release (`laravel/lsp`) |
| Phoxite | GitHub release (`samehelhawary/phoxite`) |
| PHP Debug (Xdebug) | Open VSX (`xdebug.php-debug`); needs Node.js to run |
| phpactor | Not installable from the IDE; install it yourself and put it on `PATH` |
@@ -77,12 +81,12 @@ See [Debugging](/en/guide/debugging).
## Framework support
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration.
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration. With Phoxite as the PHP server, routes, views, config, translations and Eloquent models get completion, navigation and rename from it instead.
- **WordPress** and similar platforms: add their stubs under **Additional stubs** and the platform folder under **Include paths**.
## Limitations
- No Blade or Twig template support; only `.php` files get PHP code insight.
- No Blade or Twig template support with Intelephense; only `.php` files get PHP code insight. Phoxite adds code insight in `.blade.php` files, without Blade highlighting.
- phpactor is not installed by the IDE.
- Run with Coverage is not available for PHPUnit.
- Debugging needs the Xdebug extension in your PHP; the IDE does not install it.
+2 -2
Переглянути файл
@@ -197,5 +197,5 @@ onIdeEvent("projectTrustChanged", (e) => {
1. 逻辑放在所属的 crate 里;在其边界把错误转成 `IdeError`;使用 IPC 坐标。
2. 如果涉及项目,把共享实现加到 `ide-host::ops::<domain>`;远程窗口需要的话,注册到远程 dispatcher。
3. 在 `src-tauri/src/commands/<domain>.rs` 添加 `#[tauri::command] #[specta::specta]` 适配函数,并加入 `collect_commands!`。
4. 如果它会执行任何东西,不要把它加进受限模式白名单(未受信任的项目里默认拒绝)。
5. 运行 `pnpm gen:bindings`,然后用 `call(commands.yourCommand(...))` 调用。
4. 决定它的信任级别:在 `restricted_command_allowed`(受限模式下也可运行)或 `projectless_command_allowed`(未打开项目时也可运行)中按完整名称列出它,或者不列出,即需要受信任的项目。没有名称前缀规则;会执行任何东西的命令不要列出。
5. 运行 `pnpm gen:bindings`,然后用 `call(commands.yourCommand(...))` 调用。它也会重写 `src-tauri/tests/commands.snap`;检查新增的那一行是否是你想要的信任级别和运行位置。
+2
Переглянути файл
@@ -28,6 +28,8 @@ description: "前端 UI 代码的规则:设计 token、CSS Modules、图标、
先用 `src/ui/` 里的基础组件,再考虑自己写:`Button`、`BarButton`、`Input`、`Checkbox`、`Select`、`Dialog`、`Popup`、`Menu`、`Tooltip`、`List`、`Tree`、`Tabs`、`Splitter`、`Scrollbar`、`Spinner`、`Kbd`,以及用于翻译文本的 `T`。它们已经处理好焦点、键盘导航、主题和标签翻译。工作台级别的部件(工具窗口、状态栏项、浮层)来自 [contribution](/zh/contribute/architecture/frontend),不要自己写布局。
工具栏图标操作使用 `IconButton`:悬停时整个点击区域使用 `--bg-toolbar-hover`,按下和选中状态使用对应的工具栏 token。保留图标的语义颜色和键盘焦点环。
## 无障碍
- 使用真正的 `<button>` 和 `<input>` 元素(或渲染它们的基础组件),不要用可点击的 `<div>`。
+1 -1
Переглянути файл
@@ -28,7 +28,7 @@ description: "如何报告漏洞,以及贡献者需要维护的安全模型:
- 打开一个尚未做过决定的项目时,会弹出 **信任并打开项目?** 对话框,提供 **信任项目**、**以受限模式预览** 和 **不打开**。已有决定和受信任的位置在设置的 **项目信任** 页面(**安全** 分组)里管理,**撤销信任** 是一个 action。
- 信任是用户自己的状态(`crates/ide-host/src/trust.rs`)。**项目设置永远不能授予信任。**
- 拦截在后端而不是 UI:每个 IPC 命令执行前,都要在 Tauri 的 invoke handler(`src-tauri/src/lib.rs`)里经过 `Host::authorize_command`。未受信任的项目里,只有显式白名单(`restricted_command_allowed`)中的命令能运行:读写文件和文档、语法、搜索、导航、本地历史、拼写、分析、重构、设置等。
- 这份白名单是默认拒绝的:**新增的任何会执行东西的命令,在你有意识地把它归类之前,受限模式下一律拒绝。** 不要为了让某个功能在受限模式下“能用”就把执行类命令加进白名单。
- 这份白名单按完整名称列出,默认拒绝:**新增的任何会执行东西的命令,在你有意识地把它归类之前,受限模式下一律拒绝。** 不要为了让某个功能在受限模式下“能用”就把执行类命令加进白名单。`src-tauri/tests/commands.snap` 列出每个命令的信任级别,改动会出现在审查的 diff 里。
- 在命令层之下,项目受信任之前语言服务器不会启动(`LspManager` 的执行开关),git 以禁止执行的方式运行,也不使用项目里配置的 `git` 可执行文件。项目插件(`.openidea/plugins/`)只在受信任的项目中加载。
- 远程窗口中,桌面端在转发命令前会先确认远程项目是否受信任,`openidea-server` 对每个 `invoke` 还会再校验一次。
+6 -6
Переглянути файл
@@ -7,12 +7,12 @@ description: "在 fixtures 示例项目上,用真实语言服务器跑语言
由于需要安装这些工具,冒烟测试不包含在 `cargo nextest run` 或 `pnpm test` 中。CI 在 **Language smoke** 工作流里用固定版本运行它们。
| 套件 | 检查内容 | 语言 |
| ----------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------- |
| `crates/ide-host/tests/language_smoke.rs` | 经由应用命令所调用的 `ops` 检查代码智能 | typescript、python、rust、go、java、kotlin、php |
| `crates/ide-host/tests/project_smoke.rs` | 用构建工具和 SDK 打开示例项目 | `maven_sync`、`jdk`、`gradle_sync`、`python_venv` |
| `smoke/run.test.ts` | 通过 run store 和真实的 `openidea-server` 执行运行与测试配置 | typescript、python、rust、go、java、kotlin、php |
| `smoke/debug.test.ts` | 用 IDE 安装的调试器调试入口点 | typescript、python、rust、go、java、kotlin、c、cpp、php |
| 套件 | 检查内容 | 语言 |
| ----------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| `crates/ide-host/tests/language_smoke.rs` | 经由应用命令所调用的 `ops` 检查代码智能 | typescript、python、rust、go、java、kotlin、php |
| `crates/ide-host/tests/project_smoke.rs` | 用构建工具和 SDK 打开示例项目 | `maven_sync`、`jdk`、`gradle_sync`、`python_venv` |
| `smoke/run.test.ts` | 通过 run store 和真实的 `openidea-server` 执行运行与测试配置 | typescript、python、rust、go、java、kotlin、php、zig |
| `smoke/debug.test.ts` | 用 IDE 安装的调试器调试入口点 | typescript、python、rust、go、java、kotlin、c、cpp、zig、php |
## 语言冒烟测试
+4
Переглянути файл
@@ -56,6 +56,8 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
可用模型取决于已安装的 agent 和账号。如果已选模型被移除,需要先选择其他模型才能开始任务。刷新不会更改正在运行的任务。
提示词下方的版本来自 agent 的初始化响应;显示此页面或窗口重新获得焦点时会重新查询。更新 CLI 后,返回此页面即可刷新版本。这不会重启正在运行的任务;已运行的 agent 进程在退出前仍使用原来的版本。
</Step>
<Step title="发送">
任务会在编辑器标签页中打开并开始运行。
@@ -119,6 +121,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
## 添加自定义 agent
任何通过 stdio 使用 ACP 的 agent,都可以用一个 agent 文件添加:OpenIDEA 配置目录下的 `agents/<id>.toml`。
+2 -1
Переглянути файл
@@ -145,7 +145,8 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
**编辑数据**(`F4`)在编辑器标签页中打开表,服务器端分页(每页 100 到 5,000 行),并提供 `WHERE` 过滤和 `ORDER BY` 字段(都支持补全)。点击列标题排序,按住 `Shift` 点击可以追加排序列。
- 双击、`Enter` 或 `F2` 编辑单元格;`Shift+Enter` 打开更大的编辑框。粘贴制表符分隔的文本可以一次填写多个单元格。
- **添加行**、**删除行**、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
- **添加行**(`⌘N` / `Alt+Insert`)、**删除行**(Windows 和 Linux 上为 `Ctrl+Y`)、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
- **重新加载页面**(`⌘R` / `Ctrl+F5`)、**上一页** 和 **下一页**(`⌘⌥↑` / `⌘⌥↓`,`Ctrl+Alt+Up` / `Ctrl+Alt+Down`)。这些命令、各种复制命令和 **导出数据** 都是操作:可以在 **查找操作** 中找到,并在 **设置 › 按键映射** 中设置快捷键。
- **提交**(`⌘Enter` / `Ctrl+Enter`)在一个事务中提交所有待定更改;**还原**(`⌘⌥Z` / `Ctrl+Alt+Z`)放弃更改。
如果控制台查询是对单表的简单 select 且包含主键,结果同样可以编辑。没有主键的表、连接查询、聚合、`UNION` 查询、只读数据源和 ClickHouse 的结果都是只读的。
+1 -1
Переглянути файл
@@ -47,7 +47,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
| **将光标移至代码块开头** / **末尾** | `⌥⌘[` / `⌥⌘]` | `Ctrl+[` / `Ctrl+]` |
| **切换插入/改写** | `Insert` | `Insert` |
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行重新排序,默认没有快捷键。
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行(没有选区时为整个文件)重新排序,默认没有快捷键。对行排序按字符编码排序,大写字母排在小写字母之前。
输入时括号和引号会自动成对,选中文本后输入引号或括号会把选区包起来。这些以及其他输入辅助(智能 Home、用 Tab 跳出右括号、回车智能缩进、文档注释骨架、退格键如何处理缩进、粘贴时重新格式化)都在 **设置 › 编辑器 › 常规 › 智能键** 中。
+1
Переглянути файл
@@ -101,6 +101,7 @@ root-markers = ["angular.json", "node_modules/@angular/core"]
| `settings` | 表 | 用于响应服务器的 `workspace/configuration` 请求。不写时,从 `initialization-options` 中查找请求的配置节。 |
| `install-hint` | 字符串 | 服务器缺失且 IDE 无法安装时显示的提示。 |
| `fallback` | 布尔 | 作为前面服务器的备选,只在它们都未安装时使用。 |
| `replaces` | 字符串数组 | 排在它后面、因它而变得多余的服务器名称。它为文件提供服务时,这些服务器不会被使用。用于能覆盖附加服务器功能的备选服务器。 |
| `features` | 字符串数组 | 只把服务器用于这些功能;为空表示全部。可选值:`completion`、`inline-completion`、`hover`、`signature-help`、`definition`、`declaration`、`type-definition`、`implementation`、`references`、`document-highlight`、`document-symbol`、`workspace-symbol`、`code-action`、`code-lens`、`rename`、`formatting`、`inlay-hint`、`semantic-tokens`、`document-link`、`call-hierarchy`、`type-hierarchy`、`folding-range`、`selection-range`、`diagnostics`。 |
| `code-action-kinds` | 字符串数组 | 只保留这些种类的代码操作,按前缀匹配(`refactor` 包含 `refactor.extract`);为空则全部保留。 |
| `connect` | 字符串 | 通过 TCP 提供 LSP 的服务器地址 `host:port`,见 [TCP 服务器](#tcp-服务器)。 |
+1 -1
Переглянути файл
@@ -143,7 +143,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — |
+11 -7
Переглянути файл
@@ -7,11 +7,14 @@ OpenIDEA 开箱即可高亮 PHP 文件(`.php`、`.phtml`、`.phpt` 以及老
## 语言服务器
| 服务器 | 启用条件 |
| -------------- | --------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
| 服务器 | 启用条件 |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
| `phoxite` | 备选,自带 Laravel 和 Blade 支持:仅在以上两个服务器都未安装时使用,或在 **设置 › 语言和框架 › 语言服务器** 中选中它时使用。 |
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
Phoxite 为项目提供服务时不会启动 `laravel-lsp`:Laravel 相关的字符串由 Phoxite 自己处理。
Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别”),并索引你配置的 stub 和包含路径。
@@ -25,6 +28,7 @@ Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别
| ------------------ | -------------------------------------------------- |
| Intelephense | npm(`intelephense`) |
| Laravel LSP | GitHub release(`laravel/lsp`) |
| Phoxite | GitHub release(`samehelhawary/phoxite`) |
| PHP Debug (Xdebug) | Open VSX(`xdebug.php-debug`),运行时需要 Node.js |
| phpactor | IDE 不负责安装,请自行安装并放到 `PATH` 上 |
@@ -77,12 +81,12 @@ PHPUnit 运行配置类型包含 **目标**、**配置文件**、**测试过滤
## 框架支持
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。以 Phoxite 作为 PHP 服务器时,路由、视图、配置、翻译和 Eloquent 模型的补全、跳转和重命名改由它提供。
- **WordPress** 等平台:在 **附加存根** 中加入对应 stub,在 **包含路径** 中加入平台代码目录。
## 已知限制
- 不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。
- 使用 Intelephense 时不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。Phoxite 为 `.blade.php` 文件提供代码智能,但没有 Blade 语法高亮。
- IDE 不会安装 phpactor。
- PHPUnit 不支持使用覆盖率运行。
- 调试需要 PHP 已安装 Xdebug 扩展,IDE 不负责安装。
+2 -2
Переглянути файл
@@ -83,8 +83,8 @@ for (const placement of ["editor", "toolWindow"] as const) {
},
{ id: task.id, placement },
);
// The working indicator ends the conversation, after its rows.
await expect(stream.getByRole("status").getByText("Working…", { exact: true })).toBeVisible();
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
const timer = await page.evaluate(async (id) => {
+75
Переглянути файл
@@ -0,0 +1,75 @@
import { expect, test } from "./fixtures";
test.beforeEach(async ({ workbench: page }) => {
await page.evaluate(async () => {
// Load the IPC module in Vite's browser realm, not Playwright's Node process.
const ipcPath = "/src/platform/ipc.ts";
const { commands } = await import(ipcPath);
const provider = {
id: "omp",
name: "OMP",
command: "omp acp",
program: "omp",
args: ["acp"],
defaultProgram: null,
defaultArgs: [],
loginHint: null,
commandOverridden: false,
commandEditable: true,
commandReadOnlyReason: null,
installed: true,
env: {},
commands: [],
source: { kind: "custom" },
config: [],
thoughtLevels: {},
};
let installed = "18.20.0";
let cached = installed;
window.addEventListener("test:agent-upgraded", () => {
installed = "18.20.2";
});
commands.agentProviders = async () => ({ status: "ok", data: [provider] });
commands.agentProbe = async (id: string, refresh: boolean) => {
if (refresh) cached = installed;
return {
status: "ok",
data: { provider: id, name: "omp", version: cached, protocol: "ACP v1", error: null },
};
};
commands.agentRefreshModels = async () => ({
status: "ok",
data: {
provider: "omp",
config: [],
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
},
});
});
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(page.getByText("omp · 18.20.0 · ACP v1", { exact: true })).toBeVisible();
});
test("refreshes an upgraded agent's version on window focus without losing the draft", async ({ workbench: page }) => {
const message = page.getByRole("textbox", { name: "Message", exact: true });
await message.focus();
await page.keyboard.insertText("Keep this unsent draft");
await page.evaluate(() => {
window.dispatchEvent(new Event("test:agent-upgraded"));
window.dispatchEvent(new Event("focus"));
});
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
await expect(message).toHaveText("Keep this unsent draft");
});
test("refreshes an upgraded agent's version when New Task is reopened", async ({ workbench: page }) => {
await page.getByRole("button", { name: "Close Tab", exact: true }).click();
await page.evaluate(() => window.dispatchEvent(new Event("test:agent-upgraded")));
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
});
+95
Переглянути файл
@@ -98,6 +98,101 @@ test("completion lists the server's items and inserts the chosen one", async ({
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
});
test("documentation shows beside the lookup instead of being clipped by it", async ({ workbench: page }, info) => {
const editor = await openSample(page);
await page.evaluate(async () => {
// Long enough for the pane to reach its max-width: a short doc leaves it at
// `width: max-content`, so the placement assertions would never exercise the room calculation.
const longDocs =
"Computes the order total including tax, discounts and shipping, rounded to the currency's scale. " +
"The result is cached until the order changes, so callers should not hold on to it across edits; " +
"ask for a fresh value after every update.";
const item = (label: string, detail: string) => ({
label,
labelDetail: "()",
detail,
kind: "method",
documentation: { kind: "markdown", value: `Docs for **${label}**. ${longDocs}` },
sortText: null,
filterText: null,
preselect: false,
deprecated: false,
insertText: `${label}()`,
isSnippet: false,
replaceRange: null,
replaceRangeTab: null,
additionalEdits: [],
commitCharacters: [],
command: null,
data: null,
server: 1,
});
window.__ipc.handlers.lsp_completion = () => ({
isIncomplete: false,
items: [item("total", "BigDecimal"), item("toDto", "OrderDto")],
});
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const settings = structuredClone(useProject.getState().settings ?? {});
const editor = settings.editor ?? {};
settings.editor = {
...editor,
completion: { ...editor.completion, showDocumentation: true, documentationDelay: 0 },
};
useProject.setState({ settings });
});
const popup = page.locator(".cm-tooltip-autocomplete");
const openLookup = async () => {
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.type("order.");
await page.keyboard.press("Control+Space");
await expect(popup.getByText("total", { exact: true })).toBeVisible();
await expect(page.locator(".cm-completionInfo")).toContainText("Docs for");
};
const geometry = () =>
page.evaluate(() => {
const info = document.querySelector(".cm-completionInfo") as HTMLElement;
const list = (document.querySelector(".cm-tooltip-autocomplete") as HTMLElement).getBoundingClientRect();
const rect = info.getBoundingClientRect();
const overlapX = Math.max(0, Math.min(rect.right, list.right) - Math.max(rect.left, list.left));
const overlapY = Math.max(0, Math.min(rect.bottom, list.bottom) - Math.max(rect.top, list.top));
const side = info.classList.contains("cm-completionInfo-left")
? "left"
: info.classList.contains("cm-completionInfo-right")
? "right"
: "none";
return {
overlap: overlapX * overlapY,
visible: !!document.elementFromPoint(rect.left + 4, rect.top + 4)?.closest(".cm-completionInfo"),
inside: rect.left >= 0 && rect.right <= document.documentElement.clientWidth,
side,
};
});
await page.setViewportSize({ width: 760, height: 900 });
await openLookup();
await page.screenshot({ path: info.outputPath("completion-documentation.png"), animations: "disabled" });
const narrow = await geometry();
expect(narrow.overlap).toBe(0);
expect(narrow.visible).toBe(true);
expect(narrow.inside).toBe(true);
expect(narrow.side).toBe("left");
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
await page.setViewportSize({ width: 1400, height: 900 });
await openLookup();
const wide = await geometry();
expect(wide.overlap).toBe(0);
expect(wide.visible).toBe(true);
expect(wide.inside).toBe(true);
expect(wide.side).toBe("right");
});
test("typing closes an open documentation tooltip", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(() => {
+64 -2
Переглянути файл
@@ -174,12 +174,36 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
});
test("Markdown preview highlights ⌘F matches and selected word occurrences", async ({ workbench: page }) => {
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const svg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 96" width="320" height="96"><!-- svg-source:excalidraw --><rect width="320" height="96"/></svg>';
const url = `data:image/svg+xml;base64,${btoa(svg)}`;
const routeModule = "/src/platform/tauriCore.ts";
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
setInvokeRoute((cmd: string) => (cmd === "fs_read_image" ? Promise.resolve(url) : null));
});
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("# Order Service\n\nManage **Order** items and `Order` status.\n");
await page.keyboard.insertText(
[
"# Order Service",
"",
"Manage **Order** items and `Order` status.",
"",
"```mermaid",
"flowchart LR",
" A --> B",
"```",
"",
"![Diagram](./arch.excalidraw.svg)",
].join("\n"),
);
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(preview).toContainText("Manage Order items");
@@ -209,6 +233,44 @@ test("Markdown preview highlights ⌘F matches and selected word occurrences", a
})),
)
.toEqual({ current: ["Order"], other: ["Order", "Order"] });
const mermaidSvg = preview.locator(".mermaid-output svg");
const excalidrawImg = preview.locator('img[alt="Diagram"]');
await expect(mermaidSvg).toBeVisible();
await expect(excalidrawImg).toHaveAttribute("src", /^data:image\/svg\+xml/);
const widths = async () => ({
mermaid: (await mermaidSvg.boundingBox())!.width,
excalidraw: (await excalidrawImg.boundingBox())!.width,
});
const base = await widths();
expect(base.mermaid).toBeGreaterThan(50);
expect(base.excalidraw).toBeCloseTo(320, 0);
const runAction = (id: string, times = 1) =>
page.evaluate(
async ({ id, times }) => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
for (let i = 0; i < times; i++) await executeAction(id);
},
{ id, times },
);
await runAction("editor.increaseFontSize", 4);
const zoomedIn = await widths();
expect(zoomedIn.mermaid / base.mermaid).toBeCloseTo(17 / 13, 2);
expect(zoomedIn.excalidraw / base.excalidraw).toBeCloseTo(17 / 13, 2);
await runAction("editor.decreaseFontSize", 6);
const zoomedOut = await widths();
expect(zoomedOut.mermaid / base.mermaid).toBeCloseTo(11 / 13, 2);
expect(zoomedOut.excalidraw / base.excalidraw).toBeCloseTo(11 / 13, 2);
await runAction("editor.resetFontSize");
const reset = await widths();
expect(reset.mermaid).toBeCloseTo(base.mermaid, 1);
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
test("the bookmark gutter takes no width until the file has a bookmark", async ({ workbench: page }) => {
+91
Переглянути файл
@@ -0,0 +1,91 @@
import { expect, openFromTree, test } from "./fixtures";
for (const theme of ["light", "dark"] as const) {
test(`${theme}: toolbar icon buttons provide hover feedback without changing their layout or icons`, async ({
workbench: page,
}) => {
const gear = page.getByRole("button", { name: "IDE and Project Settings", exact: true });
await gear.click();
await page.getByRole("menuitem", { name: "Theme", exact: true }).hover();
await page
.getByRole("menuitemcheckbox", { name: `Islands ${theme === "light" ? "Light" : "Dark"}`, exact: true })
.click();
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
const toolbar = page.locator("header").first();
const disabledRun = toolbar.getByRole("button", { name: "Run", exact: true });
await expect(disabledRun).toBeDisabled();
await disabledRun.hover();
await expect(disabledRun).toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
await openFromTree(page, "App.tsx");
await page.locator("[data-run-chooser]").click();
await page.getByRole("option", { name: "Current File", exact: true }).click();
const project = page.getByRole("region", { name: "Project", exact: true });
const buttons = [
...["Select Opened File", "Expand All", "Collapse All", "Options", "Hide"].map((name) =>
project.getByRole("button", { name, exact: true }),
),
...[
"Run Current File",
"Debug Current File",
"More Actions",
"Search Everywhere",
"IDE and Project Settings",
].map((name) => toolbar.getByRole("button", { name, exact: true })),
];
for (const button of buttons) {
await page.mouse.move(700, 500);
const bounds = await button.boundingBox();
const iconColors = await button.locator("svg [fill], svg [stroke]").evaluateAll((nodes) =>
nodes.map((node) => {
const style = getComputedStyle(node);
return { fill: style.fill, stroke: style.stroke };
}),
);
await expect(button).toBeEnabled();
// Hover inside the hit target but outside its centred icon.
await button.hover({ position: { x: bounds!.width / 2, y: 1 } });
await expect(button).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
expect(await button.boundingBox()).toEqual(bounds);
if (/^(Run|Debug) Current File$/.test((await button.getAttribute("aria-label")) ?? "")) {
expect(
await button.locator("svg [fill], svg [stroke]").evaluateAll((nodes) =>
nodes.map((node) => {
const style = getComputedStyle(node);
return { fill: style.fill, stroke: style.stroke };
}),
),
).toEqual(iconColors);
}
await button.focus();
await page.keyboard.press("Shift+Tab");
await page.keyboard.press("Tab");
await expect(button).toBeFocused();
await expect(button).toHaveCSS("outline-style", "solid");
await expect(button).toHaveCSS("outline-width", "2px");
}
const expand = project.getByRole("button", { name: "Expand All", exact: true });
await expand.hover();
const hover = await expand.evaluate((button) => getComputedStyle(button).backgroundColor);
await page.mouse.down();
await expect(expand).not.toHaveCSS("background-color", hover);
await page.mouse.up();
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "true");
await project.getByRole("button", { name: "Collapse All", exact: true }).click();
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "false");
await project.getByRole("button", { name: "Options", exact: true }).click();
await expect(page.getByRole("menu", { name: "Project options", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await toolbar.getByRole("button", { name: "More Actions", exact: true }).click();
await expect(page.getByRole("menuitem", { name: /^Edit Configurations…/ })).toBeVisible();
await page.keyboard.press("Escape");
await toolbar.getByRole("button", { name: "Search Everywhere", exact: true }).click();
await expect(page.getByRole("dialog", { name: "Search Everywhere", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await project.getByRole("button", { name: "Hide", exact: true }).click();
await expect(project).toBeHidden();
});
}
+7
Переглянути файл
@@ -28,4 +28,11 @@ pub fn build(b: *std.Build) void {
const tests = b.addTest(.{ .root_module = tally });
const test_step = b.step("test", "Run the tests");
test_step.dependOn(&b.addRunArtifact(tests).step);
const failing_tests = b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/failing.zig"),
.target = target,
}) });
const test_failing_step = b.step("test-failing", "Run the tests that fail on purpose");
test_failing_step.dependOn(&b.addRunArtifact(failing_tests).step);
}
+5
Переглянути файл
@@ -0,0 +1,5 @@
//! Fails on purpose: the `test-failing` step, for checking that a run's failure shows up
//! in the test tree and Rerun Failed Tests re-runs it alone.
test "intentionally fails" {
return error.OpenideaFail;
}
+2 -1
Переглянути файл
@@ -3,7 +3,8 @@ const tally = @import("tally");
pub fn main() !void {
const prices = [_]u32{ 4999, 2499, 5999 };
const sum = tally.total(&prices); // Set a breakpoint here
const sum = tally.total(&prices);
var buf: [16]u8 = undefined;
// Set a breakpoint here (QA: debugger) and inspect `sum`.
std.debug.print("Total: {s}\n", .{try tally.format(&buf, sum)});
}
+11
Переглянути файл
@@ -26,6 +26,17 @@ args = ["language-server"]
root-markers = ["composer.json", ".phpactor.json"]
install-hint = "Install phpactor (https://phpactor.readthedocs.io/en/master/usage/standalone.html)"
# Alternative with its own Laravel and Blade support. https://github.com/samehelhawary/phoxite
[[language-servers]]
name = "phoxite"
fallback = true
command = "phoxite-lsp"
args = []
root-markers = ["composer.json", "artisan", "index.php"]
# It answers the Laravel strings itself.
replaces = ["laravel-lsp"]
install-hint = "Install phoxite-lsp from https://github.com/samehelhawary/phoxite/releases and put it on PATH"
# Laravel projects only: hover, definition and completion inside
# config('…'), route('…') and view('…'). Last: Intelephense keeps PHP hover,
# rename and symbols. https://github.com/laravel/lsp
+11
Переглянути файл
@@ -164,6 +164,17 @@ const CASES: Record<string, Case> = {
variable: "line",
evaluate: ["print line", / = /],
},
// Zig ships no debugger of its own: CodeLLDB debugs the binary `zig build` produces.
// The breakpoint lands on the last use of `sum`: zig's debuginfo gives a const local a
// location only within its live range, so `prices` (used earlier) is not in the frame.
zig: {
fixture: "zig-app",
tools: ["codelldb"],
adapter: "codelldb",
file: "src/main.zig",
variable: "sum",
evaluate: ["sum", /13497/],
},
php: {
fixture: "php-app",
setup: (root) =>
+13
Переглянути файл
@@ -135,6 +135,19 @@ const CASES: Record<string, Case> = {
file: "ThresholdCustomsTest.php",
},
},
// The failing run uses the fixture's dedicated `test-failing` step (`zig build` forwards
// no args to the test binary, so a failing test can't be switched on through the config).
zig: {
fixture: "zig-app",
run: { config: "zig:run", prints: "Total: $134.97" },
tests: {
config: "zig:test-failing",
failing: (c) => c,
passed: 0,
failed: "intentionally fails",
file: "src/failing.zig",
},
},
};
let server: Server | null = null;
+17 -9
Переглянути файл
@@ -76,15 +76,26 @@ pub async fn clipboard_set_file_list(app: AppHandle, paths: Vec<PathBuf>) -> Ide
with_clipboard(app, move || Ok(ide_clipboard::set_files(&paths))).await
}
/// The clipboard's image as a PNG data URL, for a paste whose event carried no
/// files: WebKitGTK leaves `clipboardData` empty for a raw image (a screenshot).
/// None when the clipboard holds no image, and always on other platforms.
/// Whether the clipboard holds an image (a screenshot): cheap, for the Paste item's
/// enabled state.
#[tauri::command]
#[specta::specta]
pub fn clipboard_has_image() -> bool {
// Synchronous Tauri commands run on the main thread, as macOS and GTK require.
ide_clipboard::has_image()
}
/// The clipboard's image as a PNG data URL: for a paste whose event carried no files
/// (WebKitGTK leaves `clipboardData` empty for a raw image, a screenshot), and for
/// the project view's Paste, which has no paste event. None when it holds no image.
#[tauri::command]
#[specta::specta]
pub async fn clipboard_image(app: AppHandle) -> IdeResult<Option<String>> {
use base64::Engine;
let data_url =
|bytes: Vec<u8>| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes));
#[cfg(target_os = "linux")]
{
use base64::Engine;
let (tx, rx) = tokio::sync::oneshot::channel();
app.run_on_main_thread(move || {
let sender = std::cell::Cell::new(Some(tx));
@@ -98,14 +109,11 @@ pub async fn clipboard_image(app: AppHandle) -> IdeResult<Option<String>> {
.map_err(|error| {
ide_core::IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}"))
})?;
let png = rx.await.ok().flatten();
Ok(png
.map(|bytes| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))))
Ok(rx.await.ok().flatten().map(data_url))
}
#[cfg(not(target_os = "linux"))]
{
let _ = app;
Ok(None)
Ok(with_clipboard(app, || Ok(ide_clipboard::png())).await?.map(data_url))
}
}
+2
Переглянути файл
@@ -195,6 +195,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
clipboard::clipboard_text,
clipboard::clipboard_file_list,
clipboard::clipboard_has_files,
clipboard::clipboard_has_image,
clipboard::clipboard_image,
clipboard::clipboard_set_file_list,
fonts::system_font_families,
@@ -357,6 +358,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_conflict_versions,
vcs::vcs_diff_text,
vcs::vcs_diff_hunks,
vcs::diff_external_tool,
vcs::vcs_stage_hunks,
vcs::vcs_clone,
vcs::vcs_init,
+15
Переглянути файл
@@ -518,6 +518,21 @@ pub async fn vcs_diff_hunks(app: AppHandle, old_text: String, new_text: String)
.expect("line diff panicked")
}
/// Show Diff in External Tool: starts the tool set in the global settings (never a
/// project's, which a cloned repository could carry) on the two sides, on this machine
/// (a remote window passes the sides as text).
#[tauri::command]
#[specta::specta]
pub async fn diff_external_tool(
state: State<'_, AppState>,
left: ExternalDiffSide,
right: ExternalDiffSide,
title: String,
) -> IdeResult<()> {
let settings = state.global_settings.effective().external_diff;
state.host.blocking(move || launch_external_diff(&settings, &left, &right, &title)).await
}
/// Stages only the selected hunks of a file's working-tree changes.
/// Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
#[tauri::command]
+700
Переглянути файл
@@ -0,0 +1,700 @@
# Generated by `pnpm gen:bindings`; do not edit. One line per command:
# name, trust class, placement in a remote window, in bindings.ts, how Tauri runs it.
agent_accept_changes trusted project_host bindings async
agent_archive always project_host bindings sync
agent_base_text trusted project_host bindings async
agent_cancel always project_host bindings sync
agent_changes trusted project_host bindings async
agent_commands always project_host bindings async
agent_create trusted project_host bindings async
agent_create_ephemeral trusted desktop bindings async
agent_custom_import trusted desktop bindings sync
agent_custom_remove trusted desktop bindings sync
agent_custom_save trusted desktop bindings sync
agent_delete trusted project_host bindings async
agent_entries always project_host bindings sync
agent_external_sessions trusted project_host bindings async
agent_fork trusted project_host bindings async
agent_grouped_changes trusted project_host bindings async
agent_import_session trusted project_host bindings async
agent_mcp_import always project_host bindings sync
agent_mcp_list always project_host bindings sync
agent_mcp_remove always project_host bindings sync
agent_mcp_save always project_host bindings sync
agent_mcp_set_enabled always project_host bindings sync
agent_probe trusted project_host bindings async
agent_prompt trusted project_host bindings async
agent_providers trusted project_host bindings sync
agent_refresh_models trusted project_host bindings sync
agent_registry_install always project_host bindings async
agent_registry_list always project_host bindings async
agent_registry_remove always project_host bindings async
agent_rename trusted project_host bindings sync
agent_respond trusted project_host bindings sync
agent_rollback trusted project_host bindings async
agent_rollback_changes trusted project_host bindings async
agent_send_queued_now trusted project_host bindings sync
agent_set_command trusted project_host bindings sync
agent_set_config trusted project_host bindings async
agent_set_env trusted project_host bindings sync
agent_stop_background always project_host bindings async
agent_subscribe always project_host bindings sync
agent_unarchive always project_host bindings sync
agent_unqueue always project_host bindings sync
analysis_locate_duplicates always project_host bindings async
android_devices trusted desktop bindings async
android_logcat trusted desktop bindings async
app_build_info always desktop bindings sync
app_cancel_quit always desktop bindings sync
app_check_update always desktop bindings async
app_cli_install always desktop bindings async
app_cli_uninstall always desktop bindings async
app_info always desktop bindings sync
app_install_update always desktop bindings async
app_log_location always desktop bindings sync
app_metrics always desktop bindings async
app_quit always desktop bindings sync
app_release_notes trusted desktop bindings async
app_restart always desktop bindings sync
app_update_announcement always desktop bindings sync
app_update_status always desktop bindings sync
app_update_window_ready always desktop bindings sync
apply_workspace_edit always project_host bindings async
build_compile_file trusted project_host bindings async
build_model trusted project_host bindings async
build_run trusted project_host bindings async
build_sync trusted project_host bindings async
caches_local_data_info trusted desktop bindings sync
caches_schedule_invalidation always desktop bindings sync
caches_set_local_data_dir trusted desktop bindings sync
cancel_request always project_host bindings sync
cancel_task always project_host bindings sync
clear_caches always desktop bindings async
clipboard_file_list always desktop bindings async
clipboard_has_files always desktop bindings sync
clipboard_has_image always desktop bindings sync
clipboard_image always desktop bindings async
clipboard_set_file_list always desktop bindings async
clipboard_text trusted desktop bindings async
clipboard_write_text always desktop bindings async
close_project always project_host bindings spawn
coverage_collect trusted project_host bindings async
coverage_import always project_host bindings async
coverage_prepare trusted project_host bindings async
db_apply_edits trusted project_host bindings async
db_completion trusted project_host bindings async
db_connect trusted project_host bindings async
db_connected trusted project_host bindings sync
db_console_path always project_host bindings sync
db_consoles always project_host bindings sync
db_database_catalog trusted project_host bindings async
db_databases trusted project_host bindings async
db_ddl trusted project_host bindings async
db_disconnect trusted project_host bindings async
db_execute trusted project_host bindings async
db_explain trusted project_host bindings async
db_export_file always desktop bindings async
db_finish_transaction trusted project_host bindings async
db_history trusted project_host bindings async
db_object_ddl trusted project_host bindings async
db_remove_history trusted project_host bindings async
db_retain_catalog trusted project_host bindings async
db_save_sources trusted project_host bindings async
db_saved_catalog trusted project_host bindings async
db_schema_objects trusted project_host bindings async
db_schemas trusted project_host bindings async
db_session_context trusted project_host bindings async
db_set_manual_commit trusted project_host bindings async
db_set_password trusted project_host bindings async
db_set_ssh_secret trusted project_host bindings async
db_sources trusted project_host bindings sync
db_statements trusted project_host bindings sync
db_table_details trusted project_host bindings async
db_table_page trusted project_host bindings async
db_tables trusted project_host bindings async
db_test trusted project_host bindings async
db_test_tunnel trusted project_host bindings async
db_trust_ssh_host trusted project_host bindings async
debug_attachable_processes always project_host bindings async
debug_breakpoint_states trusted project_host bindings sync
debug_capabilities trusted project_host bindings sync
debug_completions trusted project_host bindings async
debug_data_breakpoint_info trusted project_host bindings async
debug_evaluate trusted project_host bindings async
debug_evaluate_in trusted project_host bindings async
debug_exception_filters trusted project_host bindings sync
debug_force_step_over trusted project_host bindings async
debug_free_port trusted project_host bindings async
debug_heap_capture trusted project_host bindings async
debug_heap_classes trusted project_host bindings async
debug_heap_close trusted project_host bindings async
debug_heap_compare trusted project_host bindings async
debug_heap_dominators trusted project_host bindings async
debug_heap_open trusted project_host bindings async
debug_heap_path trusted project_host bindings async
debug_heap_save trusted project_host bindings async
debug_hot_reload trusted desktop bindings async
debug_hot_restart trusted desktop bindings async
debug_js_custom_breakpoints trusted project_host bindings async
debug_js_response_body trusted project_host bindings async
debug_js_response_overrides trusted project_host bindings async
debug_js_start_profile trusted project_host bindings async
debug_js_stop_profile trusted project_host bindings async
debug_jvm_memory_classes trusted project_host bindings async
debug_jvm_memory_fields trusted project_host bindings async
debug_jvm_memory_instances trusted project_host bindings async
debug_jvm_memory_referrers trusted project_host bindings async
debug_listen_for_jvm trusted project_host bindings async
debug_pause trusted project_host bindings async
debug_redefine_classes trusted project_host bindings async
debug_restart_frame trusted project_host bindings async
debug_resume trusted project_host bindings async
debug_run_to trusted project_host bindings async
debug_scopes trusted project_host bindings async
debug_send_input trusted project_host bindings async
debug_sessions always project_host bindings sync
debug_set_breakpoints trusted project_host bindings async
debug_set_data_breakpoints trusted project_host bindings async
debug_set_exception_breakpoints trusted project_host bindings async
debug_set_function_breakpoints trusted project_host bindings async
debug_set_variable trusted project_host bindings async
debug_stack_trace trusted project_host bindings async
debug_start trusted project_host bindings async
debug_step trusted project_host bindings async
debug_step_in_target trusted project_host bindings async
debug_step_in_targets trusted project_host bindings async
debug_stop always project_host bindings async
debug_threads trusted project_host bindings async
debug_variables trusted project_host bindings async
dependency_versions trusted project_host bindings async
deploy_compare trusted project_host bindings async
deploy_coverage always project_host bindings async
deploy_delete_remote trusted project_host bindings async
deploy_download trusted project_host bindings async
deploy_info trusted project_host bindings async
deploy_server_root trusted project_host bindings async
deploy_sync trusted project_host bindings async
deploy_test_connection always project_host bindings async
deploy_upload trusted project_host bindings async
diff_external_tool always desktop bindings async
doc_close always project_host bindings async
doc_edit always project_host bindings async
doc_folding always project_host bindings async
doc_highlights always project_host bindings async
doc_open always project_host bindings async
doc_open_untitled always project_host bindings async
doc_open_virtual always project_host bindings async
doc_outline always project_host bindings async
doc_python_facts always project_host bindings async
doc_save always project_host bindings async
doc_save_all always project_host bindings async
doc_save_as always project_host bindings async
doc_selection_ranges always project_host bindings async
doc_set_bom always project_host bindings async
doc_set_encoding always project_host bindings async
doc_set_line_ending always project_host bindings async
doc_snapshot always project_host bindings async
doc_sync_from_disk always project_host bindings async
doc_ui_mode always project_host bindings async
docker_compose_op trusted desktop bindings async
docker_container_op trusted desktop bindings async
docker_container_stats trusted desktop bindings async
docker_container_top trusted desktop bindings async
docker_events trusted desktop bindings async
docker_image_history trusted desktop bindings async
docker_inspect trusted desktop bindings async
docker_logs trusted desktop bindings async
docker_prune trusted desktop bindings async
docker_pull trusted desktop bindings async
docker_registry_login trusted desktop bindings async
docker_remove trusted desktop bindings async
docker_run_env always project_host bindings async
docker_save_settings always desktop bindings async
docker_set_registry_password always desktop bindings async
docker_settings always desktop bindings async
docker_snapshot trusted desktop bindings async
end_process trusted desktop bindings async
env_reload always project_host bindings async
file_dialog_needs_gtk trusted desktop bindings async
find_dirs always project_host bindings sync
find_files always project_host bindings sync
find_files_named always project_host bindings async
find_symbols always project_host bindings sync
fs_compare_directories always project_host bindings async
fs_copy always project_host bindings async
fs_copy_merge always project_host bindings async
fs_create_dir always project_host bindings sync
fs_create_file always project_host bindings sync
fs_create_file_bytes always project_host bindings async
fs_delete always project_host bindings async
fs_entry_kind always project_host bindings async
fs_open_with_system always desktop bindings async
fs_probe always project_host bindings async
fs_read_dir always project_host bindings async
fs_read_image always project_host bindings async
fs_read_range always project_host bindings async
fs_read_text always project_host bindings async
fs_rename always project_host bindings async
fs_resolve_reference always project_host bindings async
fs_set_writable always project_host bindings sync
gh_account_repos trusted desktop bindings async
gh_api trusted desktop bindings async
gh_availability trusted desktop bindings async
gh_pr_checkout trusted desktop bindings async
gh_pr_comment trusted desktop bindings async
gh_pr_create trusted desktop bindings async
gh_pr_list trusted desktop bindings async
gh_pr_prepare_diff trusted desktop bindings async
gh_pr_review trusted desktop bindings async
gh_pr_review_comments trusted desktop bindings async
gh_pr_view trusted desktop bindings async
git_credential_forget always desktop bindings sync
git_credentials always desktop bindings sync
gradle_dependencies trusted project_host bindings async
gradle_link_projects trusted project_host bindings async
gradle_published_catalog trusted project_host bindings async
gradle_unlink_projects trusted project_host bindings async
gtk_pick_paths trusted desktop bindings async
history_content always project_host bindings async
history_list always project_host bindings async
history_list_dir always project_host bindings async
history_put_label always project_host bindings sync
history_restore always project_host bindings async
http_curl trusted desktop bindings async
http_environment_file trusted desktop bindings async
http_environments trusted desktop bindings async
http_execute trusted desktop bindings async
http_from_curl trusted desktop bindings sync
http_history trusted desktop bindings sync
http_history_clear trusted desktop bindings sync
http_history_get trusted desktop bindings sync
http_requests trusted desktop bindings sync
http_variable_definitions trusted desktop bindings async
index_file_extensions always project_host bindings sync
index_status always project_host bindings sync
inspect_code trusted project_host bindings async
java_build_workspace trusted project_host bindings async
java_debug_server trusted project_host bindings async
java_resolve_launch trusted project_host bindings async
jdk_download always project_host bindings async
jdk_download_location always project_host bindings sync
jdk_download_releases always project_host bindings async
jdk_download_vendors always project_host bindings sync
jdtls_required_java always project_host bindings async
jvm_file_presentations always project_host bindings async
languages always desktop bindings sync
light_edit_open always desktop bindings async
light_edit_open_untitled always desktop bindings async
log_frontend always desktop bindings sync
lsp_apply_code_action trusted project_host bindings async
lsp_call_hierarchy trusted project_host bindings async
lsp_can_download_sources trusted project_host bindings async
lsp_code_action_query trusted project_host bindings async
lsp_code_actions trusted project_host bindings async
lsp_code_lens trusted project_host bindings async
lsp_completion trusted project_host bindings async
lsp_document_highlights trusted project_host bindings async
lsp_document_links trusted project_host bindings async
lsp_execute_code_action trusted project_host bindings async
lsp_execute_command trusted project_host bindings async
lsp_format trusted project_host bindings async
lsp_goto trusted project_host bindings async
lsp_goto_implementation trusted project_host bindings async
lsp_hierarchy_members trusted project_host bindings async
lsp_hierarchy_refactor trusted project_host bindings async
lsp_hover trusted project_host bindings async
lsp_implementations trusted project_host bindings async
lsp_inlay_hints trusted project_host bindings async
lsp_inline_completion trusted project_host bindings async
lsp_library_sources trusted project_host bindings async
lsp_prepare_rename trusted project_host bindings async
lsp_prepare_type_hierarchy trusted project_host bindings async
lsp_references trusted project_host bindings async
lsp_rename trusted project_host bindings async
lsp_resend_diagnostics always project_host bindings sync
lsp_resolve_class_file trusted project_host bindings async
lsp_resolve_code_action trusted project_host bindings async
lsp_resolve_command trusted project_host bindings async
lsp_resolve_completion trusted project_host bindings async
lsp_restart trusted project_host bindings async
lsp_restart_named trusted desktop bindings async
lsp_semantic_tokens trusted project_host bindings async
lsp_servers always project_host bindings sync
lsp_signature_help trusted project_host bindings async
lsp_type_hierarchy trusted project_host bindings async
lsp_virtual_document trusted project_host bindings async
lsp_workspace_symbols trusted project_host bindings async
mark_recent always project_host bindings sync
maven_dependency_completion trusted project_host bindings async
maven_dependency_declaration trusted project_host bindings async
maven_exclude_dependency trusted project_host bindings async
maven_goto_declaration trusted project_host bindings async
mcp_agent_run_closed trusted desktop bindings sync
mcp_regenerate_token trusted desktop bindings sync
mcp_report_problems trusted project_host bindings sync
mcp_respond trusted desktop bindings sync
mcp_server_status trusted desktop bindings sync
mcp_set_focused_editor trusted project_host bindings sync
mcp_set_open_editors trusted project_host bindings sync
mcp_ui_ready trusted desktop bindings sync
menu_configure always desktop bindings sync
menu_model always desktop bindings sync
menu_refresh always desktop bindings sync
menu_set_disabled always desktop bindings sync
nav_index_definitions always project_host bindings async
nav_inheritance always project_host bindings async
nav_resolve_module always project_host bindings async
notebook_cell_docs trusted project_host bindings sync
notebook_close always project_host bindings async
notebook_edit always project_host bindings async
notebook_execute trusted project_host bindings async
notebook_get always project_host bindings sync
notebook_interrupt always project_host bindings async
notebook_open always project_host bindings async
notebook_redo always project_host bindings async
notebook_reload always project_host bindings async
notebook_restart trusted project_host bindings async
notebook_save always project_host bindings async
notebook_undo always project_host bindings async
open_project always project_host bindings async
path_completions always project_host bindings async
plugin_activation_event trusted desktop bindings async
plugin_answer_command trusted project_host bindings sync
plugin_answer_commit trusted project_host bindings sync
plugin_answer_prompt trusted project_host bindings sync
plugin_answer_run_target trusted project_host bindings async
plugin_assets always desktop bindings async
plugin_cancel_task trusted project_host bindings sync
plugin_catalog always desktop bindings async
plugin_choose_program outside_restricted project_host bindings async
plugin_color_presentations trusted project_host bindings async
plugin_commit_checks trusted project_host bindings async
plugin_content_tab_action trusted project_host bindings sync
plugin_context_keys trusted project_host bindings sync
plugin_debug_attach_target trusted project_host bindings async
plugin_decoration_sets trusted project_host bindings sync
plugin_endpoints trusted project_host bindings async
plugin_event_kinds trusted project_host bindings async
plugin_finish_operation trusted project_host bindings sync
plugin_formatters trusted project_host bindings sync
plugin_grant outside_restricted desktop bindings async
plugin_install_dir outside_restricted desktop bindings async
plugin_installed_intellij_themes always desktop bindings async
plugin_language_visuals trusted project_host bindings async
plugin_line_markers trusted project_host bindings async
plugin_link trusted desktop bindings async
plugin_list always desktop bindings async
plugin_log_tab_spawn trusted desktop bindings async
plugin_market always desktop bindings async
plugin_market_download always desktop bindings async
plugin_market_url always desktop bindings sync
plugin_navigation_files trusted project_host bindings async
plugin_navigation_goto trusted project_host bindings async
plugin_navigation_index trusted project_host bindings async
plugin_navigation_invalidate trusted project_host bindings sync
plugin_navigation_markers trusted project_host bindings async
plugin_parse_test_results trusted project_host bindings async
plugin_post_events trusted project_host bindings sync
plugin_prepare_debug_run trusted project_host bindings async
plugin_preview_install always desktop bindings async
plugin_program outside_restricted project_host bindings async
plugin_read_intellij_theme always desktop bindings async
plugin_reload outside_restricted desktop bindings async
plugin_revoke_net_host outside_restricted desktop bindings async
plugin_roll_back outside_restricted desktop bindings async
plugin_run_command trusted project_host bindings async
plugin_run_targets trusted project_host bindings async
plugin_secrets trusted desktop bindings sync
plugin_select_tests trusted project_host bindings async
plugin_service_detail trusted project_host bindings async
plugin_service_log trusted project_host bindings async
plugin_set_active_file always project_host bindings sync
plugin_set_capability outside_restricted desktop bindings async
plugin_set_enabled outside_restricted desktop bindings async
plugin_set_market_url always desktop bindings sync
plugin_set_secret trusted desktop bindings sync
plugin_set_theme always desktop bindings sync
plugin_set_theme_frame always desktop bindings sync
plugin_set_ui_locale always project_host bindings async
plugin_stage_package always desktop bindings async
plugin_status_items trusted project_host bindings sync
plugin_subscribe always desktop bindings sync
plugin_sync_languages trusted project_host - -
plugin_sync_packages trusted project_host - -
plugin_terminal_session_close trusted project_host bindings sync
plugin_terminal_session_spawn trusted project_host bindings async
plugin_uninstall outside_restricted desktop bindings async
plugin_unlink trusted desktop bindings async
plugin_unpack_package always desktop bindings async
plugin_view_event trusted project_host bindings async
plugin_view_render trusted project_host bindings async
plugin_web_page trusted desktop bindings sync
plugin_web_pty_spawn trusted desktop bindings async
plugin_web_read_file trusted desktop bindings async
plugin_web_save_file trusted desktop bindings async
prepare_workspace_edit always project_host bindings async
profiler_collect trusted desktop bindings async
profiler_gc_before_stop trusted desktop bindings async
profiler_prepare trusted desktop bindings async
project_current always project_host bindings sync
project_rename always desktop bindings sync
project_roots always project_host bindings sync
project_trust_add_location always desktop bindings async
project_trust_list always project_host bindings sync
project_trust_remove_location always project_host bindings async
project_trust_set always project_host bindings async
project_trust_status always project_host bindings sync
proxy_check_connection always desktop bindings async
recent_files always project_host bindings sync
recent_project_groups always desktop bindings sync
recent_projects always desktop bindings async
redo_workspace_edit always project_host bindings async
refactor_can_undo_file_move always project_host bindings sync
refactor_file_move_edits always project_host bindings async
refactor_file_move_text_edits always project_host bindings async
refactor_move_files always project_host bindings async
refactor_undo_file_move always project_host bindings async
remote_bootstrap_list always desktop bindings async
remote_connect always desktop bindings async
remote_current always desktop bindings sync
remote_delete trusted project_host bindings async
remote_disconnect always desktop bindings sync
remote_download_into trusted project_host bindings async
remote_forward_port trusted desktop bindings async
remote_forwarded_ports trusted desktop bindings sync
remote_import_local trusted desktop bindings async
remote_invoke always desktop bindings async
remote_list always project_host bindings async
remote_mkdir trusted project_host bindings async
remote_of always project_host bindings sync
remote_open always project_host bindings async
remote_rename trusted project_host bindings async
remote_stop_forwarding trusted desktop bindings async
remote_trust_set always desktop bindings sync
remote_trust_status always desktop bindings sync
remove_recent always project_host bindings sync
remove_recent_project always desktop bindings sync
replace_in_files trusted project_host bindings async
replace_preview trusted project_host bindings async
run_application_build trusted project_host bindings async
run_application_publish trusted project_host bindings async
run_apply_settings trusted project_host bindings async
run_close_stdin trusted project_host bindings sync
run_configs trusted project_host bindings async
run_dotnet_resolve trusted project_host bindings async
run_env_files trusted project_host bindings async
run_gradle_init_script trusted project_host bindings async
run_gradle_jvm_args_script always project_host bindings async
run_import_configs trusted project_host bindings async
run_import_sources trusted project_host bindings async
run_list always project_host bindings sync
run_resize trusted project_host bindings sync
run_save_configs trusted project_host bindings async
run_save_templates trusted project_host bindings async
run_start trusted project_host bindings async
run_stdin trusted project_host bindings sync
run_stop always project_host bindings sync
run_system_env always project_host bindings sync
run_templates trusted project_host bindings async
run_test_reports trusted project_host bindings async
run_tomcat_artifacts trusted project_host bindings async
run_tomcat_build trusted project_host bindings async
run_tomcat_home trusted project_host bindings async
run_tomcat_installations trusted project_host bindings async
run_tomcat_sync trusted project_host bindings async
run_tomcat_update trusted project_host bindings async
run_without_derived trusted project_host bindings async
scaffold_catalog always project_host bindings sync
scaffold_create always project_host bindings async
scaffold_options always project_host bindings async
scaffold_requirements always project_host bindings async
sdk_container_python trusted project_host bindings sync
sdk_container_python_refresh trusted project_host bindings async
sdk_detect trusted project_host bindings async
sdk_locate_tools trusted project_host bindings async
sdk_php_composer_install trusted project_host bindings async
sdk_php_effective trusted project_host bindings sync
sdk_php_language_level trusted project_host bindings async
sdk_php_xdebug trusted project_host bindings async
sdk_project_libraries trusted project_host bindings async
sdk_python_create_venv trusted project_host bindings async
sdk_python_effective trusted project_host bindings sync
sdk_python_interpreter trusted project_host bindings async
sdk_python_packages trusted project_host bindings async
sdk_python_pip trusted project_host bindings async
sdk_python_project_interpreters trusted project_host bindings async
search_start always project_host bindings async
search_validate always project_host bindings sync
set_recent_project_groups always desktop bindings sync
settings_export always desktop bindings async
settings_get always project_host bindings sync
settings_get_global always desktop bindings sync
settings_import always desktop bindings async
settings_list_jetbrains_ides always desktop bindings async
settings_read_jetbrains always desktop bindings async
settings_set always project_host bindings sync
spell_check always project_host bindings async
spell_suggest always project_host bindings async
spring_route_sources trusted desktop bindings sync
ssh_askpass_answer always desktop bindings sync
ssh_connected always project_host bindings sync
ssh_disconnect always project_host bindings sync
ssh_needs_secret always project_host bindings sync
ssh_open_terminal always desktop bindings async
ssh_password_saved always project_host bindings sync
ssh_set_secret always project_host bindings sync
ssh_test always project_host bindings async
ssh_trust_host always project_host bindings async
structural_languages always project_host bindings async
structural_search always project_host bindings async
structural_validate always project_host bindings async
syntax_errors always project_host bindings async
syntax_expression_at always project_host bindings async
syntax_identifiers always project_host bindings async
syntax_identifiers_in_files always project_host bindings async
syntax_locals always project_host bindings async
syntax_node_at always project_host bindings async
syntax_structural_ranges always project_host bindings async
syntax_support always project_host bindings sync
system_font_families always desktop bindings async
system_probe_hotkeys trusted desktop bindings sync
term_available_shells always project_host bindings sync
term_default_shell always project_host bindings sync
term_is_busy always project_host bindings async
term_kill always project_host bindings sync
term_resize always project_host bindings sync
term_spawn always project_host bindings async
term_store_image always project_host bindings async
term_write always project_host bindings sync
tools_install trusted project_host bindings async
tools_list trusted project_host bindings async
tools_uninstall trusted project_host bindings async
tools_updates trusted project_host bindings async
undo_workspace_edit always project_host bindings async
user_font_data always desktop - async
vcs_add_to_ignore trusted project_host bindings async
vcs_add_worktree trusted project_host bindings async
vcs_apply_patch trusted project_host bindings async
vcs_blame always project_host bindings async
vcs_block_history always project_host bindings async
vcs_branch_info always project_host bindings async
vcs_branches always project_host bindings async
vcs_changelists_load always project_host bindings async
vcs_changelists_save trusted project_host bindings sync
vcs_checkout trusted project_host bindings async
vcs_clone always project_host bindings async
vcs_commit trusted project_host bindings async
vcs_commit_files always project_host bindings async
vcs_commits_changes always project_host bindings async
vcs_compare_paths always project_host bindings async
vcs_compare_scope always project_host bindings async
vcs_config_get always project_host bindings async
vcs_conflict_versions always project_host bindings async
vcs_create_branch trusted project_host bindings async
vcs_create_patch trusted project_host bindings async
vcs_create_tag trusted project_host bindings async
vcs_delete_branch trusted project_host bindings async
vcs_delete_tag trusted project_host bindings async
vcs_detected_git always project_host bindings sync
vcs_diff_hunks always project_host bindings async
vcs_diff_numstat always project_host bindings async
vcs_diff_revisions always project_host bindings async
vcs_diff_text always project_host bindings async
vcs_diff_with_worktree always project_host bindings async
vcs_discard trusted project_host bindings async
vcs_edit_remote trusted project_host bindings async
vcs_file_at always project_host bindings async
vcs_file_mode trusted project_host bindings async
vcs_git_version trusted project_host bindings async
vcs_has_hook always project_host bindings async
vcs_ignore_blame_revision trusted project_host bindings async
vcs_init always project_host bindings async
vcs_line_hunks always project_host bindings async
vcs_log always project_host bindings async
vcs_log_details always project_host bindings async
vcs_log_details_batch always project_host bindings async
vcs_log_refs always project_host bindings async
vcs_log_users always project_host bindings async
vcs_merge trusted project_host bindings async
vcs_merge_base always project_host bindings async
vcs_merge_with trusted project_host bindings async
vcs_move_worktree trusted project_host bindings async
vcs_open_external_log always project_host bindings async
vcs_operation trusted project_host bindings async
vcs_patch_preview trusted project_host bindings async
vcs_rebase trusted project_host bindings async
vcs_rebase_with trusted project_host bindings async
vcs_remote trusted project_host bindings async
vcs_remotes always project_host bindings async
vcs_remove_worktree trusted project_host bindings async
vcs_rename_branch trusted project_host bindings async
vcs_restore_branch trusted project_host bindings async
vcs_restore_head trusted project_host bindings async
vcs_restore_tag trusted project_host bindings async
vcs_revision_children always project_host bindings async
vcs_revision_files always project_host bindings async
vcs_reword trusted project_host bindings async
vcs_roots always project_host bindings sync
vcs_shelf_delete trusted project_host bindings async
vcs_shelf_diff trusted project_host bindings async
vcs_shelf_import trusted project_host bindings async
vcs_shelf_patch always project_host bindings async
vcs_shelf_rename trusted project_host bindings async
vcs_shelve trusted project_host bindings async
vcs_shelves always project_host bindings async
vcs_stage trusted project_host bindings async
vcs_stage_hunks trusted project_host bindings async
vcs_stage_patch trusted project_host bindings async
vcs_stash_apply trusted project_host bindings async
vcs_stash_drop trusted project_host bindings async
vcs_stash_push trusted project_host bindings async
vcs_stashes always project_host bindings async
vcs_status always project_host bindings async
vcs_status_paths always project_host bindings async
vcs_tags always project_host bindings async
vcs_undo_commit trusted project_host bindings async
vcs_unshelve trusted project_host bindings async
vcs_unstage trusted project_host bindings async
vcs_worktrees always project_host bindings async
vcs_write_patch always project_host bindings async
web_browsers always desktop bindings async
web_goto always project_host bindings async
web_open always desktop bindings async
web_serves_page trusted desktop bindings async
web_unresolved_references always project_host bindings async
web_url always project_host bindings async
window_close_context always desktop bindings sync
window_complete_launch always desktop bindings sync
window_cycle always desktop bindings sync
window_flash_taskbar always desktop bindings sync
window_group_cancel_close always desktop bindings sync
window_group_close always desktop bindings sync
window_group_close_tabs always desktop bindings sync
window_group_current always desktop bindings sync
window_group_detach always desktop bindings async
window_group_merge always desktop bindings async
window_group_reorder always desktop bindings async
window_group_restore always desktop bindings async
window_group_select always desktop bindings async
window_is_fullscreen always desktop bindings sync
window_new always desktop bindings async
window_open_comparison always desktop bindings async
window_open_deployment always desktop bindings async
window_open_diff always desktop bindings async
window_open_file_in_new_window always desktop bindings async
window_open_files always desktop bindings async
window_open_project always desktop bindings async
window_open_projects always desktop bindings sync
window_open_remote always desktop bindings async
window_open_settings always desktop bindings async
window_set_titlebar_height always desktop bindings sync
window_start_drag always desktop bindings sync
window_take_launch always desktop bindings sync
window_toggle_fullscreen always desktop bindings sync
window_toggle_zoom always desktop bindings sync
workspace_attach always desktop bindings async
workspace_create always desktop bindings async
workspace_discover_projects always desktop bindings async
workspace_update always desktop bindings async
wsl_distros always desktop bindings async
wsl_resolve always desktop bindings sync
+93 -2
Переглянути файл
@@ -1,7 +1,98 @@
//! `cargo test -p openidea --test export_bindings` regenerates `src/bindings.ts`
//! without launching the app (used by `pnpm gen:bindings` and CI drift checks).
//! `cargo test -p openidea --test export_bindings` regenerates `src/bindings.ts` and
//! `src-tauri/tests/commands.snap` without launching the app (used by `pnpm gen:bindings`
//! and CI drift checks).
use ide_host::trust::{projectless_command_allowed, restricted_command_allowed};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use tauri_specta::{BuilderConfiguration, LanguageExt};
#[test]
fn export_bindings() {
openidea_lib::export_bindings(&openidea_lib::specta_builder());
}
/// Commands registered outside tauri-specta (`src-tauri/src/lib.rs`), with how Tauri runs them.
const RAW_COMMANDS: &[(&str, &str)] = &[("user_font_data", "async")];
/// Every command, one line each: its trust class, where a remote window runs it, whether it is
/// in `bindings.ts`, and how Tauri runs it. A change to any of these shows up in this file's diff.
#[test]
fn export_command_snapshot() {
let target = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/commands.snap");
let fresh = std::env::temp_dir().join(format!("openidea-commands-{}.snap", std::process::id()));
openidea_lib::specta_builder().export(CommandSnapshot, &fresh).expect("command snapshot");
let text = std::fs::read(&fresh).expect("exported command snapshot");
let _ = std::fs::remove_file(&fresh);
if std::fs::read(&target).ok().as_deref() != Some(text.as_slice()) {
std::fs::write(&target, text).expect("failed to write the command snapshot");
}
}
struct CommandSnapshot;
impl LanguageExt for CommandSnapshot {
type Error = std::io::Error;
fn export(self, cfg: &BuilderConfiguration, path: &Path) -> std::io::Result<()> {
let spawned = spawned_commands();
let mut modes: BTreeMap<&str, &str> = cfg
.commands
.iter()
.map(|f| {
let mode = if spawned.contains(f.name()) {
"spawn"
} else if f.asyncness() {
"async"
} else {
"sync"
};
(f.name(), mode)
})
.collect();
let in_bindings: BTreeSet<&str> = modes.keys().copied().collect();
modes.extend(RAW_COMMANDS.iter().copied());
let routed: BTreeSet<&str> = ide_host::rpc::client_commands().into_iter().collect();
let names: BTreeSet<&str> = modes.keys().chain(&routed).copied().collect();
let mut out = String::from(
"# Generated by `pnpm gen:bindings`; do not edit. One line per command:\n\
# name, trust class, placement in a remote window, in bindings.ts, how Tauri runs it.\n",
);
for name in names {
let trust = if restricted_command_allowed(name) {
"always"
} else if projectless_command_allowed(name) {
"outside_restricted"
} else {
"trusted"
};
let placement = if routed.contains(name) { "project_host" } else { "desktop" };
let bindings = if in_bindings.contains(name) { "bindings" } else { "-" };
let mode = modes.get(name).copied().unwrap_or("-");
out.push_str(&format!("{name:<44} {trust:<18} {placement:<12} {bindings:<8} {mode}\n"));
}
std::fs::write(path, out)
}
}
/// Sync commands declared `#[tauri::command(async)]`, which Tauri runs off the main thread.
fn spawned_commands() -> BTreeSet<String> {
let mut out = BTreeSet::new();
let mut dirs = vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
while let Some(dir) = dirs.pop() {
for entry in std::fs::read_dir(&dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
dirs.push(path);
continue;
}
let source = std::fs::read_to_string(&path).unwrap_or_default();
for (_, rest) in source.match_indices("#[tauri::command(async)]").map(|(i, _)| source.split_at(i)) {
let name = rest.split("fn ").nth(1).and_then(|s| s.split('(').next());
out.insert(name.expect("a function after #[tauri::command(async)]").trim().to_owned());
}
}
}
out
}
+71 -4
Переглянути файл
@@ -310,9 +310,14 @@ export const commands = {
/** Whether the clipboard holds files: cheap, for the Paste item's enabled state. */
clipboardHasFiles: () => __TAURI_INVOKE<boolean>("clipboard_has_files"),
/**
* The clipboard's image as a PNG data URL, for a paste whose event carried no
* files: WebKitGTK leaves `clipboardData` empty for a raw image (a screenshot).
* None when the clipboard holds no image, and always on other platforms.
* Whether the clipboard holds an image (a screenshot): cheap, for the Paste item's
* enabled state.
*/
clipboardHasImage: () => __TAURI_INVOKE<boolean>("clipboard_has_image"),
/**
* The clipboard's image as a PNG data URL: for a paste whose event carried no files
* (WebKitGTK leaves `clipboardData` empty for a raw image, a screenshot), and for
* the project view's Paste, which has no paste event. None when it holds no image.
*/
clipboardImage: () => typedError<string | null, IdeError>(__TAURI_INVOKE("clipboard_image")),
/**
@@ -745,6 +750,12 @@ export const commands = {
vcsDiffText: (path: string, staged: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_diff_text", { path, staged })),
/** Line hunks between two arbitrary texts (diff viewer, commit dialog). */
vcsDiffHunks: (oldText: string, newText: string) => __TAURI_INVOKE<LineHunk[]>("vcs_diff_hunks", { oldText, newText }),
/**
* Show Diff in External Tool: starts the tool set in the global settings (never a
* project's, which a cloned repository could carry) on the two sides, on this machine
* (a remote window passes the sides as text).
*/
diffExternalTool: (left: ExternalDiffSide, right: ExternalDiffSide, title: string) => typedError<null, IdeError>(__TAURI_INVOKE("diff_external_tool", { left, right, title })),
/**
* Stages only the selected hunks of a file's working-tree changes.
* Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
@@ -2259,6 +2270,18 @@ export type AgentSettings_Deserialize = {
smoothText?: boolean,
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
fitWindowWidth?: boolean,
/** While the agent works, playful words fill the pauses in what it reports. */
playfulStatus?: boolean,
/**
* Seconds the agent reports nothing new before the playful words take over; 0 shows them
* from the start.
*/
playfulAfterSeconds?: number,
/**
* The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
* the built-in ones of that activity; an empty list keeps its status factual.
*/
playfulWords?: { [key in string]: string[] },
thinking?: ThinkingDisplay,
toolCalls?: ToolCallDisplay,
/** A tool call's output (a command's, a diff) is shown without opening it. */
@@ -2299,6 +2322,18 @@ export type AgentSettings_Serialize = {
smoothText: boolean,
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
fitWindowWidth: boolean,
/** While the agent works, playful words fill the pauses in what it reports. */
playfulStatus: boolean,
/**
* Seconds the agent reports nothing new before the playful words take over; 0 shows them
* from the start.
*/
playfulAfterSeconds: number,
/**
* The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
* the built-in ones of that activity; an empty list keeps its status factual.
*/
playfulWords: { [key in string]: string[] },
thinking: ThinkingDisplay,
toolCalls: ToolCallDisplay,
/** A tool call's output (a command's, a diff) is shown without opening it. */
@@ -5065,6 +5100,26 @@ export type ExtensionPointInfo = {
contributors: string[],
};
/** Tools › Diff & Merge › External Diff Tools: a program that shows two files' differences. */
export type ExternalDiffSettings = {
/** Offer Show Diff in External Tool in diff viewers. */
enabled?: boolean,
/** The program to start. */
path?: string,
/** Its arguments: `%1` the left file, `%2` the right file, `%3` the diff's title. */
parameters?: string,
};
/** One side of the diff: a file on disk, or text written to a temporary file. */
export type ExternalDiffSide = {
/** A saved file, passed to the tool as it is. */
path: string | null,
/** Content without a file of its own (a revision, a text), written to a temporary file. */
text: string | null,
/** The temporary file's name; its extension lets the tool pick a syntax. */
name: string,
};
/** A formatter that runs outside the language servers, with its own settings group. */
export type ExternalFormatter = "prettier" | "oxfmt" | "ruff";
@@ -6938,6 +6993,7 @@ export type LanguagesSettings = {
ruby?: RubySettings,
markdown?: MarkdownSettings,
arduino?: ArduinoSettings,
zig?: ZigSettings,
};
/** What a freshly opened window should do once its frontend is up. */
@@ -7026,7 +7082,7 @@ export type Launch_Serialize = {
export type LibraryGroup = {
/** Display name, e.g. `Python 3.12 (.venv)`. */
name: string,
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`. */
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath` | `zig` | `zigPackages`. */
kind: string,
roots: LibraryRoot[],
};
@@ -9458,6 +9514,8 @@ export type RunSettings = {
/** Ask before closing a Run tab whose process is still running. */
confirmTerminate?: boolean,
showOnStart?: boolean,
/** New Run/Debug tabs start pinned: a later run doesn't take their place once finished. */
pinTabs?: boolean,
/** Grace period between interrupt and kill when stopping a process. */
terminationTimeoutMs?: number,
};
@@ -9745,6 +9803,8 @@ export type Settings_Deserialize = {
terminal?: TerminalSettings,
actionsOnSave?: ActionsOnSaveSettings,
externalTools?: ExternalTool[],
/** Tools › Diff & Merge › External Diff Tools. */
externalDiff?: ExternalDiffSettings,
/**
* Language servers / debug adapters at a user-chosen location, by the
* command the language definition launches (`elixir-ls`, `codelldb`).
@@ -9809,6 +9869,8 @@ export type Settings_Serialize = {
terminal: TerminalSettings,
actionsOnSave: ActionsOnSaveSettings,
externalTools: ExternalTool[],
/** Tools › Diff & Merge › External Diff Tools. */
externalDiff: ExternalDiffSettings,
/**
* Language servers / debug adapters at a user-chosen location, by the
* command the language definition launches (`elixir-ls`, `codelldb`).
@@ -10950,6 +11012,11 @@ export type Worktree = {
prunable: boolean,
};
export type ZigSettings = {
/** Directory holding the `zig` executable; empty = the one on `PATH`. */
zig?: string,
};
/* Tauri Specta runtime */
async function typedError<T, E>(result: Promise<T>): Promise<{ status: "ok"; data: T } | { status: "error"; error: E }> {
try {
+14
Переглянути файл
@@ -290,6 +290,20 @@ export const documentSynced = Facet.define<() => Promise<void>, (() => Promise<v
combine: (values) => values[0] ?? null,
});
/**
* Undo / Redo of an editor whose history is kept outside CodeMirror (notebook cells share
* the notebook's backend history). Commands that would call CodeMirror's history (Vim's
* `u` / `Ctrl-R`) go through it instead.
*/
export interface ExternalHistory {
undo(): void;
redo(): void;
}
export const externalHistory = Facet.define<ExternalHistory, ExternalHistory | null>({
combine: (values) => values[0] ?? null,
});
export function whenSynced(view: EditorView): Promise<void> {
return view.state.facet(documentSynced)?.() ?? Promise.resolve();
}
+25 -2
Переглянути файл
@@ -75,7 +75,7 @@ import { resetAllEditorsFontZoom, stepAllEditorsFontZoom } from "./cm/prefs";
import { useProject } from "@/platform/project";
import { call, commands } from "@/platform/ipc";
import { editorPrefs } from "@/platform/editorSettings";
import { notifications } from "@/workbench/contributions";
import { menuGroupItems, notifications } from "@/workbench/contributions";
import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import { toggleReadOnly } from "./fileAttributes";
@@ -529,7 +529,29 @@ function copyReference(reference: Promise<string>) {
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
const path = slot.model.path;
const line = view.state.doc.lineAt(view.state.selection.main.head).number;
const { doc, selection } = view.state;
const line = doc.lineAt(selection.main.head).number;
const { from, to } = selection.main;
// The selected lines, leaving out the one a selection ends at the start of.
const first = doc.lineAt(from).number;
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
const contributed = menuGroupItems("copyPath", {
paths: [path],
line: first - 1,
endLine: last > first ? last - 1 : undefined,
}).flatMap((item) =>
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
? [
{
id: item.id,
label: item.verbatim ? item.label : tx(item.label),
preview: item.preview,
shortcut: shortcutLabel(item.id),
run: item.run,
},
]
: [],
);
const flavours = [
{ id: "project.copyAbsolutePath", label: "Absolute Path", value: pathToCopy("absolute", path) },
{ id: "project.copyFileName", label: "File Name", value: pathToCopy("name", path) },
@@ -557,6 +579,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
void executeAction(f.id, f.id === "editor.copyPathWithLineNumber" ? f.value : path);
},
})),
...contributed,
{
id: "editor.copyReference",
label: tx("Reference"),
+37 -12
Переглянути файл
@@ -4,11 +4,13 @@
* (view/FindBar.tsx). Highlighting is ours because CodeMirror only highlights
* while its own panel is open. Match positions found by the bar's counter are
* kept in `findMarks` for the overview lane. The search context (comments /
* string literals) and excluded matches filter matches through the query's
* `test`, so CodeMirror's own commands honour them too.
* string literals), excluded matches and "Search In Changes" (a diff's changed
* ranges) filter matches through the query's `test`, so CodeMirror's own commands
* honour them too.
*/
import {
EditorSelection,
Facet,
Prec,
StateEffect,
StateField,
@@ -93,16 +95,33 @@ export function isExcluded(state: EditorState, from: number, to: number): boolea
return (state.field(findExcluded, false) ?? []).some((x) => x.from === from && x.to === to);
}
type MatchTest = (match: string, state: EditorState, from: number, to: number) => boolean;
const tests = new Map<SearchContext, MatchTest>();
/**
* The changed ranges of a diff pane, for "Search In Changes"; editors outside a diff have none.
* Called per match, so providers read state the diff already keeps.
*/
export const findChangedRanges = Facet.define<
(state: EditorState) => readonly FindScope[],
((state: EditorState) => readonly FindScope[]) | null
>({ combine: (values) => values[0] ?? null });
/** One stable test per context, so equal options give equal queries (`SearchQuery.eq`). */
function testFor(context: SearchContext): MatchTest {
let test = tests.get(context);
function inChangedRange(state: EditorState, from: number, to: number): boolean {
const ranges = state.facet(findChangedRanges)?.(state) ?? [];
return ranges.some((r) => r.from <= from && to <= r.to);
}
type MatchTest = (match: string, state: EditorState, from: number, to: number) => boolean;
const tests = new Map<string, MatchTest>();
/** One stable test per filter, so equal options give equal queries (`SearchQuery.eq`). */
function testFor(context: SearchContext, inChanges: boolean): MatchTest {
const key = `${context}:${inChanges}`;
let test = tests.get(key);
if (!test) {
test = (_match, state, from, to) =>
!isExcluded(state, from, to) && (context === "any" || contextAccepts(context, literalKindAt(state, from)));
tests.set(context, test);
!isExcluded(state, from, to) &&
(!inChanges || inChangedRange(state, from, to)) &&
(context === "any" || contextAccepts(context, literalKindAt(state, from)));
tests.set(key, test);
}
return test;
}
@@ -215,7 +234,13 @@ export interface FindOptions {
preserveCase?: boolean;
}
export function makeQuery(o: FindOptions) {
/** A bar's query: its options, plus filters that belong to what it searches rather than the last search. */
export interface FindQueryOptions extends FindOptions {
/** Only matches inside a diff's changed ranges (`findChangedRanges`). */
inChanges?: boolean;
}
export function makeQuery(o: FindQueryOptions) {
return new SearchQuery({
search: o.search,
// Plain-text search and replace are literal (`\n` is not a newline), as in IDEA.
@@ -224,11 +249,11 @@ export function makeQuery(o: FindOptions) {
wholeWord: o.wholeWord,
regexp: o.regexp,
replace: o.replace,
test: testFor(o.context ?? "any"),
test: testFor(o.context ?? "any", !!o.inChanges),
});
}
export function setQuery(view: EditorView, o: FindOptions) {
export function setQuery(view: EditorView, o: FindQueryOptions) {
const q = makeQuery(o);
if (q.eq(getSearchQuery(view.state))) return;
view.dispatch({ effects: setSearchQuery.of(q) });
+18
Переглянути файл
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { getIndentation, indentUnit } from "@codemirror/language";
import { completedSyntaxTree } from "@/test/syntax";
import { classHighlighter, highlightTree } from "@lezer/highlight";
import { findLanguageDescription, loadSupport, loadedSupport } from "./languages";
@@ -81,6 +82,23 @@ describe("frontend string interpolation", () => {
expect(out.some((t) => t.text.includes("{brace}") && t.style === "tok-string")).toBe(true);
});
it.each(["Kotlin", "Scala", "Dart", "Groovy", "C#"])(
"%s indents brackets opened after a string from the line's indentation",
async (mode) => {
const support = await loadSupport(findLanguageDescription(mode, "")!);
const doc = 'f(\n pair("a", g(\n x\n )),\n)';
const state = EditorState.create({
doc,
extensions: [support!, indentUnit.of(" "), EditorState.tabSize.of(4)],
});
completedSyntaxTree(state);
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
expect(indent(3)).toBe(8);
// C#'s mode leaves a closing bracket's indentation to the editor.
if (mode !== "C#") expect(indent(4)).toBe(4);
},
);
it("keeps Groovy dotted interpolation in code", async () => {
const out = await tokens("Groovy", '"$person.name tail"');
expect(out).toContainEqual(expect.objectContaining({ text: "name", style: "tok-variableName" }));
+5 -1
Переглянути файл
@@ -114,7 +114,11 @@ export function interpolationParser<S>(base: StreamParser<S>, dialect: Interpola
}
if (opening && style !== "comment" && style !== "string.special") {
stream.pos = from + opening.length;
base.token(new StringStream('""', 4, state.indentUnit), frame.code);
// Let the base tokenizer see an empty string at the literal's own column: a stream
// at column 0 would read as a new line and reset the base's line indentation.
const empty = new StringStream(stream.string.slice(0, from) + '""', 4, state.indentUnit);
empty.pos = empty.start = from;
base.token(empty, frame.code);
frame.literal = {
quote,
braces,
+5 -2
Переглянути файл
@@ -1,4 +1,7 @@
import { tags as t, type styleTags } from "@lezer/highlight";
/** @lezer/javascript styles `.` as a deref operator, but not `?.`. */
export const JS_TAGS: Parameters<typeof styleTags>[0] = { "?.": t.derefOperator };
/**
* @lezer/javascript styles `.` as a deref operator, but not `?.`; it tags `this` as `self` (Python's
* `self` colour) and `super` as an atom, which WebStorm colours as keywords.
*/
export const JS_TAGS: Parameters<typeof styleTags>[0] = { "?.": t.derefOperator, "this super": t.keyword };
+25
Переглянути файл
@@ -270,6 +270,31 @@ describe("language modes", () => {
}
});
it("colours `this` and `super` as keywords in Java, JavaScript, TypeScript and C++", async () => {
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
{ tag: t.self, class: "self" },
{ tag: t.atom, class: "atom" },
]);
for (const [mode, path, doc, expected] of [
["Java", "/p/A.java", "class A extends B { A() { super(); this.a = 1; } }", ["super", "this"]],
["JavaScript", "/p/a.js", "class A extends B { m() { super.m(); this.a = 1; } }", ["super", "this"]],
["TypeScript", "/p/a.ts", "class A extends B { m() { super.m(); this.a = 1; } }", ["super", "this"]],
["C++", "/p/a.cpp", "void A::m() { this->a = 1; }", ["this"]],
] as const) {
const support = await loadSupport(findLanguageDescription(mode, path)!);
const found: Array<[string, string]> = [];
highlightTree(support!.language.parser.parse(doc), highlighter, (from, to, style) =>
found.push([doc.slice(from, to), style]),
);
const words = new Set<string>(expected);
expect(
found.filter(([text]) => words.has(text)),
mode,
).toEqual(expected.map((word) => [word, "keyword"]));
}
});
it("recognizes go.mod and go.work files by mode and filename", async () => {
for (const [mode, path] of [
["GoMod", "/project/go.mod"],
+5 -1
Переглянути файл
@@ -293,9 +293,11 @@ const CSS_TAGS: Parameters<typeof styleTags>[0] = {
"ClassName IdName PseudoClassName ColorLiteral CallTag": t.tagName,
};
// @lezer/java tags annotations as plain identifiers.
// @lezer/java tags annotations as plain identifiers, and `this` as `self` (Python's `self` colour);
// IntelliJ colours `this` as a keyword.
export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
"MarkerAnnotation/Identifier Annotation/Identifier MarkerAnnotation Annotation": t.annotation,
this: t.keyword,
};
/** Highlighting the stock grammars lack or colour unlike IntelliJ. */
@@ -306,6 +308,8 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
JSX: JS_TAGS,
TSX: JS_TAGS,
Java: JAVA_TAGS,
// CLion colours `this` as a keyword.
"C++": { this: t.keyword },
PHP: {
"; ,": t.separator,
"ClassDeclaration/Name BaseClause/Name InterfaceClause/Name": t.className,
+8
Переглянути файл
@@ -28,6 +28,14 @@ describe("Sort Lines / Reverse Lines", () => {
expect(apply(doc, sel, sortLinesSpec)).toBe("a\nb\n--\nc\nd");
});
it("sorts by code unit, uppercase before lowercase, as IDEA does", () => {
const doc = '"github:opentofu/tofu-ls" = "0.5"\n"github:PowerShell/PowerShellEditorServices" = "4.7"';
expect(apply(doc, undefined, sortLinesSpec)).toBe(
'"github:PowerShell/PowerShellEditorServices" = "4.7"\n"github:opentofu/tofu-ls" = "0.5"',
);
expect(apply("b\nB\na\nA\n_\n1", undefined, sortLinesSpec)).toBe("1\nA\nB\n_\na\nb");
});
it("does nothing for a single line or an already sorted block", () => {
expect(apply("only", undefined, sortLinesSpec)).toBeNull();
expect(apply("a\nb", undefined, sortLinesSpec)).toBeNull();
+4 -3
Переглянути файл
@@ -7,8 +7,6 @@ import {
type TransactionSpec,
} from "@codemirror/state";
const collator = new Intl.Collator(undefined, { numeric: false, sensitivity: "variant" });
/** Line blocks the command applies to: one per non-empty selection range, or the document. */
function blocks(state: EditorState): Array<{ from: number; to: number }> {
const ranges = state.selection.ranges.filter((r) => !r.empty);
@@ -59,8 +57,11 @@ function rewrite(
};
}
/** Plain UTF-16 code-unit order, as IDEA sorts (`String.compareTo`): every uppercase letter before every lowercase one. */
const byCodeUnit = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
export function sortLinesSpec(state: EditorState): TransactionSpec | null {
return rewrite(state, (lines) => [...lines].sort((a, b) => collator.compare(a, b)), "input.sort");
return rewrite(state, (lines) => [...lines].sort(byCodeUnit), "input.sort");
}
export function reverseLinesSpec(state: EditorState): TransactionSpec | null {
+39 -1
Переглянути файл
@@ -10,7 +10,7 @@ import { LspPopups } from "@/editor/lsp/Popups";
import { registerProjectActions } from "@/features/project-tree/actions";
import { useProjectTree } from "@/features/project-tree/store";
import { useContextMenuStore } from "@/ui";
import { provideNotificationService } from "@/workbench/contributions";
import { provideNotificationService, registerMenuGroup, type MenuGroupContext } from "@/workbench/contributions";
import * as controller from "./controller";
import { createMemoryBackend } from "./backend";
import { registerEditorActions } from "./actions";
@@ -189,6 +189,44 @@ describe("editor Copy Path/Reference chooser", () => {
expect(useLspPopup.getState().popup).toBeNull();
});
it("lists contributed links before Reference, for the selected lines", async () => {
const contexts: MenuGroupContext[] = [];
const run = vi.fn();
disposers.push(
registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: (_menu, ctx) => {
contexts.push(ctx);
return [{ id: "test.copyLink", label: "Host Link", verbatim: true, preview: "https://host/a#L1", run }];
},
}),
);
const view = ctrl.activeSlot!.view!;
await executeAction("editor.copyPathReference");
expect(
popup()
.items.map((item) => item.label)
.slice(-2),
).toEqual(["Host Link", "Reference"]);
expect(popup().items.at(-2)).toMatchObject({
preview: "https://host/a#L1",
shortcut: shortcutLabel("test.copyLink"),
});
await popup().items.at(-2)!.run();
expect(run).toHaveBeenCalledOnce();
// From the first line into the second; then ending at the start of the second line.
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("A {}") } });
await executeAction("editor.copyPathReference");
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("class") } });
await executeAction("editor.copyPathReference");
expect(contexts.map(({ paths, line, endLine }) => [paths, line, endLine])).toEqual([
[[path], 1, undefined],
[[path], 0, 1],
[[path], 0, undefined],
]);
});
it("adds the chooser to Copy / Paste Special", () => {
vi.spyOn(ctrl.activeSlot!.view!, "posAtCoords").mockReturnValue(null);
ctrl.onContextMenu(ctrl.activeSlot!, new MouseEvent("contextmenu"));
+25 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DocModel } from "./model/document";
import { readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
import { offerMakeWritable, readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
function model(readOnly: boolean, extra: Partial<{ virtual: boolean; banner: string | null }> = {}) {
const meta = { readOnly, banner: extra.banner ?? (readOnly ? "readOnly" : null) };
@@ -43,3 +43,27 @@ describe("Toggle Read-only Attribute", () => {
expect(readOnlyQuestion("a.txt", false).confirm).toBe("Make Read-only");
});
});
describe("editing a read-only file", () => {
it("offers to make it writable once, then lets edits through", async () => {
const m = model(true);
answer = true;
expect(offerMakeWritable(m)).toBe(true);
expect(offerMakeWritable(m)).toBe(true);
expect(confirm).toHaveBeenCalledTimes(1);
expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Make File Writable" }));
await vi.waitFor(() => expect(m.setReadOnly).toHaveBeenCalledWith(false));
expect(offerMakeWritable(m)).toBe(false);
});
it("refuses edits without asking for library, binary and too-large documents", () => {
for (const m of [
model(true, { virtual: true }),
model(true, { banner: "binary" }),
model(true, { banner: "tooLarge" }),
])
expect(offerMakeWritable(m)).toBe(true);
expect(confirm).not.toHaveBeenCalled();
expect(offerMakeWritable(model(false))).toBe(false);
});
});
+21 -1
Переглянути файл
@@ -1,7 +1,8 @@
/**
* File › File Properties › Make File Read-only / Writable (IDEA's "Toggle
* Read-only Attribute", also the status bar lock): asks, then flips the
* file's writable bit and the open document's editability.
* file's writable bit and the open document's editability. Typing into a file
* whose read-only attribute is set asks the same (IDEA's Clear Read-Only Status).
*/
import { call, commands, isTauri } from "@/platform/ipc";
import { basename } from "@/platform/project";
@@ -41,3 +42,22 @@ export function toggleReadOnly(model: DocModel) {
(ok) => ok && void setFileWritable(model, meta.readOnly),
);
}
let asking: DocModel | null = null;
/**
* An edit was attempted in `model`. When only the file's read-only attribute is in the
* way (not a binary, too large or library file), offers to make it writable, once at a
* time. Returns whether the edit was refused: the caller drops it either way.
*/
export function offerMakeWritable(model: DocModel): boolean {
const meta = model.getMeta();
if (!meta.readOnly) return false;
if (model.virtual || meta.banner !== "readOnly" || asking) return true;
asking = model;
const q = readOnlyQuestion(basename(model.path), true);
void confirm({ title: q.title, message: q.message, ok: q.confirm })
.then((ok) => ok && model.getMeta().readOnly && setFileWritable(model, true))
.finally(() => (asking = null));
return true;
}
+11
Переглянути файл
@@ -34,6 +34,7 @@ import {
import { showContextMenu } from "@/ui";
import { baseExtensions, compartments, contributionExtensions } from "../cm/setup";
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
import { offerMakeWritable } from "../fileAttributes";
import type { DocModel } from "./document";
import type { WorkspaceHistoryTarget } from "./workspaceHistory";
import { isNavigation } from "./navHistory";
@@ -147,6 +148,12 @@ export class EditorSlot {
return this.state;
}
private refuseReadOnlyEdit(e: Event): boolean {
if (!offerMakeWritable(this.model)) return false;
e.preventDefault();
return true;
}
private slotExtensions() {
return [
this.model.manager.workspaceHistory.extension(this.historyTarget),
@@ -169,6 +176,10 @@ export class EditorSlot {
this.host.onContextMenu(this, e);
return true;
},
// Typing, pasting or dropping into a read-only file offers to make it writable.
beforeinput: (e) => this.refuseReadOnlyEdit(e),
paste: (e) => this.refuseReadOnlyEdit(e),
drop: (e) => this.refuseReadOnlyEdit(e),
}),
ViewPlugin.define((view) => {
// Gutters sit outside the content DOM. Gutter extensions with their own menu (breakpoints,
+8 -8
Переглянути файл
@@ -74,7 +74,7 @@
flex: none;
display: flex;
align-items: center;
gap: 2px;
gap: var(--space-0-5);
padding: 0 6px 0 8px;
}
.pin {
@@ -89,7 +89,7 @@
flex: none;
display: flex;
align-items: center;
gap: 8px;
gap: var(--space-2);
min-height: 36px;
padding: 0 12px;
background: var(--bg-editor-banner, color-mix(in srgb, var(--accent) 7%, var(--bg-editor, var(--bg-elev))));
@@ -133,8 +133,8 @@
display: grid;
grid-template-columns: minmax(220px, 420px) auto 1fr;
align-items: center;
column-gap: 6px;
row-gap: 6px;
column-gap: var(--space-1-5);
row-gap: var(--space-1-5);
padding: 6px 8px 6px 10px;
background: var(--bg-editor-inline, var(--bg-elev));
border-bottom: 1px solid var(--border-editor-tabs, var(--border));
@@ -155,7 +155,7 @@
.findButtons {
display: flex;
align-items: center;
gap: 2px;
gap: var(--space-0-5);
}
.findCount {
font-size: var(--fs-ui);
@@ -173,14 +173,14 @@
.replaceButtons {
display: flex;
align-items: center;
gap: 6px;
gap: var(--space-1-5);
}
/* Go to line */
.gotoBody {
display: flex;
flex-direction: column;
gap: 8px;
gap: var(--space-2);
padding: 8px 16px 0;
}
.gotoHint {
@@ -316,7 +316,7 @@
flex: none;
display: flex;
align-items: center;
gap: 2px;
gap: var(--space-0-5);
height: 26px;
padding: 0 8px;
overflow: hidden;
+1 -1
Переглянути файл
@@ -115,7 +115,7 @@ function EmptyEditorArea() {
return (
<div ref={ref} className={styles.area}>
<EmptyEditor />
{over && <div className={clsx(styles.dropZone, styles["drop-center"])} aria-hidden="true" />}
{over && <div className={styles.dropZone} aria-hidden="true" />}
</div>
);
}
+19 -6
Переглянути файл
@@ -99,6 +99,8 @@ export interface FindTarget {
/** Still open: an unmount that isn't a close (React's dev-mode remount) keeps the highlights. */
isOpen(): boolean;
results?(options: FindOptions): FindResultsSource | null;
/** A diff pane's "Search In Changes" filter, kept by the diff (not the last search). */
inChanges?: { get(): boolean; set(on: boolean): void };
}
const activeTab = (paneId: string) => useTabs.getState().panes[paneId]?.active ?? null;
@@ -373,6 +375,13 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
const [historyMenu, setHistoryMenu] = useState<"find" | "replace" | null>(null);
const [filterMenu, setFilterMenu] = useState(false);
const setOpts = (patch: Partial<FindOptions>) => updateOptions(id, () => patch);
// Search In Changes applies to finding only, as in IDEA: the replace bar searches the whole side.
const [inChangesOn, setInChangesOn] = useState(() => !!target.inChanges?.get());
const inChanges = !!target.inChanges && !replace && inChangesOn;
const toggleInChanges = () => {
target.inChanges?.set(!inChangesOn);
setInChangesOn(!inChangesOn);
};
useLayoutEffect(() => {
panelTargets.set(id, target);
@@ -421,15 +430,16 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
// Push the query into the editor. Like IDEA, only a change of the query (typing, options)
// selects the nearest match: showing the bar again over its editor leaves the caret alone.
const shown = useRef<{ target: FindTarget; version: unknown; opts: FindOptions } | null>(null);
const shown = useRef<{ target: FindTarget; version: unknown; opts: FindOptions; inChanges: boolean } | null>(null);
useEffect(() => {
const view = target.view();
if (!view) return;
const prev = shown.current;
const changed = prev?.target === target && prev.version === version && prev.opts !== opts;
shown.current = { target, version, opts };
const changed =
prev?.target === target && prev.version === version && (prev.opts !== opts || prev.inChanges !== inChanges);
shown.current = { target, version, opts, inChanges };
const valid = !opts.regexp || regexValid(opts.search);
setQuery(view, valid ? opts : { ...opts, search: "" });
setQuery(view, valid ? { ...opts, inChanges } : { ...opts, search: "" });
view.dispatch({ effects: setFindOpen.of(true) });
if (changed && valid && opts.search && useFindPreferences.getState().scrollToResults) {
const from = view.state.selection.main.from;
@@ -437,7 +447,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
findNext(view);
}
recount(target);
}, [opts, target, version]);
}, [opts, target, version, inChanges]);
// Keep the counter current while the document / selection changes.
useEffect(() => {
@@ -564,6 +574,9 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
checked: scoped || undefined,
run: () => toggleScope(target),
},
...(target.inChanges && !replace
? [{ label: "Search In Changes", checked: inChangesOn || undefined, run: toggleInChanges }]
: []),
{ kind: "separator" },
{ kind: "header", label: "Search Scope" },
...SEARCH_CONTEXTS.map((c) => ({
@@ -688,7 +701,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
icon="filter"
title="Filter Search Results"
size="small"
pressed={scoped || opts.context !== "any"}
pressed={scoped || inChanges || opts.context !== "any"}
onClick={() => setFilterMenu(true)}
/>
<IconButton ref={moreRef} icon="more" title="More" size="small" onClick={() => setMoreMenu(true)} />
+2 -2
Переглянути файл
@@ -58,7 +58,7 @@
.row {
display: flex;
align-items: center;
gap: 6px;
gap: var(--space-1-5);
height: var(--h-list-row);
padding: 0 6px;
border-radius: var(--radius-row);
@@ -87,7 +87,7 @@
.childHeader {
display: flex;
align-items: center;
gap: 6px;
gap: var(--space-1-5);
height: var(--h-list-row);
padding: 0 6px;
margin-bottom: 2px;
Loaded 100 of 382 files, more files were not shown because too many files have changed in this diff. Show more