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

...
Автор SHA1 Повідомлення Дата
l0ng-ai d3d0fd23c6 fix(agents): keep session header controls inside a narrow conversation column (#1540)
The meters were fixed-width and the header didn't clip, so in a narrow
conversation the stop, terminal and changes buttons spilled over the
Changes pane. The title now shrinks first, meters that don't fit drop
out whole, and the buttons keep their size.
2026-11-05 19:21:09 +08:00
l0ng-ai c3b7e34b22 perf(vcs): filter the Git log with git log instead of a background search index (#1537)
* perf(vcs): filter the Git log with git log instead of a background search index

The log built a persistent inverted index of every commit's message, authors and
changed paths in the background, with a progress bar above the commit list, and
walked trees itself to filter by path. Building it took minutes on large
repositories, and filters were slow until it finished.

- Text: plain text uses `git log --fixed-strings --grep` (with
  `--regexp-ignore-case` unless Match Case is on); text of 4+ hex digits also
  matches hash prefixes. Regex filters still match in-process.
- Paths: `git log -- :(literal)<paths>` replaces the in-process path walk and
  its per-commit tree cache. It uses git's history simplification and, when the
  repository has a changed-path commit-graph, its Bloom filters. Glob characters
  in a path are literal.
- Authors match against the commit metadata cache.
- Removed the search tables, `index_log`, the `vcs_log_index` command and the
  indexing progress bar. The commit metadata cache stays.

* docs(contributing): ask for screenshots only when a change alters what users see

Removing a feature together with its UI, copy-only and non-visual changes now
describe what was checked instead of attaching before/after screenshots.

* fix(vcs): match case-insensitive non-ASCII Git log text in process

git folds case only for ASCII under the C locale it runs with, so a
case-insensitive filter like "ärger" missed "Ärger". Such text is now
matched against commit messages directly. Path and text selection also
ignore log.showSignature and log.follow from the user's config.
2026-11-05 19:20:43 +08:00
l0ng-ai 91d6c7de57 test(plugins): keep one snapshot of the released plugin API and require it at release (#1512)
The snapshot of a released API was a manual step, and v0.1.37 shipped API 1.1.0
without one, so nothing checked the APIs added in 1.1. Each version also added a
full copy of wit/.

- tests/api/released/ holds the latest released WIT (now 1.1.0) and replaces the
  per-version folders: each snapshot passed the check against the one before,
  so the latest covers every release.
- api_frozen.rs: under the released version wit/ must match the snapshot
  exactly; additions need a version bump. Before, a function added to a
  released version passed, and components built from it didn't link in that
  release's IDE.
- release.yml: create-release fails when the wit/ version differs from the
  snapshot's, naming the folder to copy wit/ into.
2026-11-05 17:54:21 +08:00
l0ng-ai abb7b1d962 ci: skip jobs a pull request can't affect and bound every job's run time (#1501)
All workflows share the account's 20 concurrent hosted runners, and each PR push
queued 14 jobs whatever it touched, so releases and other PRs waited behind them.

- CI: a Changes job lists the PR's files. Rust (3 OSes), the musl server, plugins
  and cargo deny skip when only frontend, test or docs files changed (files the
  Rust code embeds from src/ still count as Rust); Frontend and E2E skip on
  docs-only changes. Pushes and manual runs still run everything.
- Language smoke: pushes to main use the same path filter as pull requests.
- Every CI job has a timeout, so a hung job can't hold a runner for 6 hours.
- CI's token is read-only.
2026-11-05 17:52:04 +08:00
l0ng-ai c57156ef4b fix(i18n): translate the Logcat tool window title in Chinese
The zh text equalled the English source, which the catalog test treats as
untranslated in a locale with its own script.
2026-11-05 17:42:37 +08:00
l0ng-ai f55cdcdc31 fix(plugins): hand plugins paths in one form on Windows (#1500)
* fix(plugins): hand plugins paths in one form on Windows

Plugins got the project root, editor path, provider documents, code action edits, vcs-status roots and find-files results as D:\… while event paths from the UI use /, so Checkstyle could not find the project of a saved file. The host now converts every path it hands to plugins with ipc_path::to_ipc.

* fix(checkstyle): match native Windows report paths

* test(plugins): use workbench IPC paths in host fixtures
2026-11-05 17:03:09 +08:00
l0ng-ai 7d267ab50e docs(plugins): describe released plugin API versions as frozen
The README still said the API could change freely while the plugin system is a preview. API 1.0.0 shipped with 0.1.36 and is checked by api_frozen; 1.1.0 ships with 0.1.37.
2026-11-05 16:28:55 +08:00
Jaw 50986088f9 feat(editor): Copy Reference copies path:line unless the caret is on a declaration's name (#1507)
Copy Reference used the outline symbols enclosing the caret, so anywhere inside a method it copied the method's qualified name and the line was lost. It now names a symbol only with the caret on a declaration's name (its selection range) and copies `path:line` everywhere else, for every language. The `package …;` symbol jdtls reports is no longer qualified, so that line copies `path:1`.

Co-authored-by: jaw52 <[email protected]>
2026-11-05 16:25:33 +08:00
l0ng-ai 7a0f60377c fix(tomcat): update web resources from the folders the WAR is built from (#1508)
Updating a Tomcat deployment took web resources only from src/main/webapp, so JSPs under WebContent (maven-war-plugin webResources) never reached it. It now reads warSourceDirectory and webResources from the pom, or webAppDirName / webAppDirectory from the Gradle build.
2026-11-05 16:21:33 +08:00
l0ng-ai 945f09347e feat(vcs): mark the current worktree in the Worktrees list (#1506)
The worktree whose path is the window's repository root gets a check before its branch (Current worktree); drive paths compare case-insensitively. Branch names keep their width and the path is cut short instead.
2026-11-05 16:15:10 +08:00
l0ng-ai 2924824e7b fix(run): import JetBrains Spring Boot and Application configurations (#1504)
The JetBrains importer skipped SpringBootApplicationConfigurationType and Application as unsupported types. Both now map to the spring-boot / application forms' command line with their module, working directory and environment; options without a field are listed as left out.
2026-11-05 16:10:19 +08:00
l0ng-ai 26e3ecc3a0 fix(project): open a window's project once when opens race (#1503)
Two opens of one window could each find no current project and build a full project (index, language servers, watchers); the second replaced the first without closing it, leaving two jdtls on one workspace. open_project and open_light now hold a per-window lock from the check to the insert.
2026-11-05 16:05:54 +08:00
Lee Dong Geon 456b329d73 feat(themes): preview themes from the gear menu and Settings, and import theme plugins from every JetBrains IDE (#1498)
The main toolbar gear's Theme submenu and Settings › Appearance › Theme preview the theme under the pointer after the same delay as Quick Switch Scheme, and closing without a choice brings the selected theme back. Choosing a theme while it was previewed left the preview flag on, so the start-up theme cache kept the previous theme; `setTheme` now ends the preview.

Import Theme from JetBrains IDE… lists one row per theme plugin and installs it without switching the theme, like any theme plugin install. It reads only the newest settings folder of each product, so folders left behind by upgrades don't list their plugins again.

Co-authored-by: ldg030201 <[email protected]>
2026-11-05 15:57:04 +08:00
74 змінених файлів з 1211 додано та 909 видалено

No files matched your search

+2 -1
Переглянути файл
@@ -9,7 +9,8 @@
<!-- Required. Commands you actually ran and their results; what else this could
affect and how you checked it still works.
UI changes: before/after screenshots. Multi-step interactions: a recording.
Visible UI changes: before/after screenshots (not for removed UI or copy-only
changes). Multi-step interactions: a recording.
Backend changes: logs or command output. -->
## Review focus
+60
Переглянути файл
@@ -7,6 +7,9 @@ on:
types: [opened, synchronize, reopened]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
# A newer push supersedes the run in progress, on main too.
@@ -19,8 +22,50 @@ env:
CARGO_PROFILE_DEV_DEBUG: line-tables-only
jobs:
# Which parts a pull request touches, so jobs it can't affect skip and leave the
# shared runners to others. Pushes and manual runs always run everything.
changes:
name: Changes
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: read
outputs:
rust: ${{ steps.classify.outputs.rust }}
frontend: ${{ steps.classify.outputs.frontend }}
steps:
- id: classify
env:
GH_TOKEN: ${{ github.token }}
PR: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
echo "rust=true" >> "$GITHUB_OUTPUT"
echo "frontend=true" >> "$GITHUB_OUTPUT"
exit 0
fi
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat files.txt
docs='^(docs/|\.agents/|\.claude/|\.idea/|\.github/ISSUE_TEMPLATE/|\.github/pull_request_template\.md$|[^/]+\.md$|LICENSE$|NOTICE$)'
# Frontend-only paths. The Rust code embeds a few files under src/; those stay out.
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
embedded='^src/(bindings\.ts|styles/tokens\.css|features/plugins/views/frame-bridge\.js|platform/keymaps/)'
# A job runs when any changed file falls outside the paths that can't affect it.
rust=false
if grep -Ev "$docs|$web" files.txt | grep -q . || grep -Eq "$embedded" files.txt; then rust=true; fi
frontend=false
if grep -Ev "$docs" files.txt | grep -q .; then frontend=true; fi
echo "rust=$rust frontend=$frontend"
echo "rust=$rust" >> "$GITHUB_OUTPUT"
echo "frontend=$frontend" >> "$GITHUB_OUTPUT"
rust:
name: Rust (${{ matrix.os }})
needs: changes
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
@@ -62,6 +107,9 @@ jobs:
# keep that build working.
server:
name: Remote server (linux musl)
needs: changes
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 40
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v5
@@ -77,6 +125,9 @@ jobs:
# own workspaces (the root excludes them), so the jobs above don't see them.
plugins:
name: Plugins (SDK, official, fixtures)
needs: changes
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 30
runs-on: ubuntu-22.04
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/target-plugins
@@ -126,6 +177,9 @@ jobs:
deny:
name: Cargo deny
needs: changes
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
@@ -135,6 +189,9 @@ jobs:
frontend:
name: Frontend
needs: changes
if: needs.changes.outputs.frontend == 'true'
timeout-minutes: 30
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v5
@@ -152,6 +209,9 @@ jobs:
e2e:
name: E2E
needs: changes
if: needs.changes.outputs.frontend == 'true'
timeout-minutes: 30
runs-on: ubuntu-24.04
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
container: mcr.microsoft.com/playwright:v1.64.1-noble
+5 -4
Переглянути файл
@@ -11,10 +11,7 @@ name: Language smoke
on:
push:
branches: [main]
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
paths:
paths: &paths
- "crates/**"
- "languages/**"
- "fixtures/**"
@@ -27,6 +24,10 @@ on:
- "package.json"
- "pnpm-lock.yaml"
- ".github/workflows/language-smoke.yml"
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
paths: *paths
workflow_dispatch:
concurrency:
+10
Переглянути файл
@@ -37,6 +37,16 @@ jobs:
echo "::error::tag $TAG does not match tauri.conf.json version $app"
exit 1
fi
# A shipped plugin API is frozen: its WIT must be the snapshot api_frozen.rs checks later
# versions against (plugins/README.md, "Evolving the plugin API").
- name: Plugin API snapshot matches wit/
run: |
api() { sed -n 's/^package openidea:plugin@\(.*\);$/\1/p' "$1/plugin.wit"; }
snapshot=sdk/rust/openidea-plugin/tests/api/released
if [ "$(api wit)" != "$(api "$snapshot")" ]; then
echo "::error::plugin API $(api wit) ships without a snapshot ($snapshot is $(api "$snapshot")): copy wit/*.wit to $snapshot/"
exit 1
fi
# The official plugins' public key (from PLUGIN_SIGNING_KEY, the seed
# `openidea-plugin keygen` writes), built into the app: their packages
# must carry its signature whatever the marketplace index lists. Without
+2 -1
Переглянути файл
@@ -51,7 +51,8 @@ Visual style: dark, low-contrast greys, one cool accent
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain description, and a
**How it was verified** section with commands run, results and (for UI) before/after screenshots.
**How it was verified** section with commands run, results and, when the change alters what users
see, before/after screenshots (not for UI removed along with a feature, copy-only or non-visual changes).
Unclear product decisions → `needs-decision` and stop.
## Skills
+3 -2
Переглянути файл
@@ -25,8 +25,9 @@ Project layout, coding rules, commands and checks are in [AGENTS.md](AGENTS.md).
- Fill in the template. Keep the description short and in plain words. If it
doesn't fit in a few sentences, the PR is probably too big.
- **How it was verified** is required: the commands you ran and their results,
and what else the change could affect. UI changes need before/after screenshots;
multi-step interactions need a recording.
and what else the change could affect. Changes to what users see need before/after
screenshots; multi-step interactions need a recording. UI that goes away with a removed
feature, copy-only and non-visual changes don't; say what you checked instead.
- If a change needs a product decision you can't make, ask in the issue and stop
rather than guessing.
+10
Переглянути файл
@@ -86,6 +86,8 @@ pub struct Host {
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
/// Shutdowns of projects closed with [`Host::close_project_detached`].
closing: parking_lot::Mutex<Vec<std::thread::JoinHandle<()>>>,
/// One open at a time per window (see [`Host::opening`]).
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
}
/// How long exit waits for project shutdown before giving up.
@@ -135,6 +137,7 @@ impl Host {
requests: Default::default(),
project_requests: RwLock::default(),
closing: Default::default(),
open_locks: Default::default(),
};
host.apply_proxy();
host
@@ -401,6 +404,13 @@ impl Host {
self.requests.cancel(id);
}
/// The lock an open of `window` holds from its check for the current project to its
/// insert: two opens racing (a double click, a launch path and a restore) would each start
/// an index, language servers and watchers, and the second would replace the first unclosed.
pub(crate) fn opening(&self, window: &str) -> Arc<parking_lot::Mutex<()>> {
self.open_locks.lock().entry(window.to_owned()).or_default().clone()
}
pub(crate) fn insert_project(&self, window: &str, project: Arc<Project>) {
self.projects.write().insert(window.to_owned(), project);
}
-26
Переглянути файл
@@ -405,28 +405,6 @@ pub async fn vcs_log_details_batch(
result
}
pub async fn vcs_log_index(
host: &Host,
window: &str,
repo: Option<PathBuf>,
request: Option<RequestId>,
) -> IdeResult<LogIndexProgress> {
let project = LogAccess::new(host, window, repo.as_deref());
let cancel =
request.map_or_else(ide_core::CancellationToken::new, |id| host.begin_project_read_request(window, id));
let result = blocking(move || {
project.with_log_repo_at(repo.as_deref(), |r| {
r.enable_log_index(&project.cache);
if request.is_some() { r.index_log(&cancel) } else { Ok(r.log_index_progress()) }
})
})
.await;
if let Some(request) = request {
host.end_request(request);
}
result
}
pub async fn vcs_revision_children(
host: &Host,
window: &str,
@@ -1222,10 +1200,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_log_details_batch", |c| async move {
vcs_log_details_batch(&c.host, &c.window, c.arg("repo")?, c.arg("revisions")?, c.arg("request")?).await
});
d.add(
"vcs_log_index",
|c| async move { vcs_log_index(&c.host, &c.window, c.arg("repo")?, c.arg("request")?).await },
);
d.add("vcs_revision_children", |c| async move {
vcs_revision_children(&c.host, &c.window, c.arg("repo")?, c.arg("revision")?, c.arg("directory")?).await
});
+16 -2
Переглянути файл
@@ -2,6 +2,7 @@
//! Capabilities were checked by the runtime before any of this runs.
use super::{PluginEvent, PluginEventSink};
use ide_core::ipc_path::to_ipc;
use ide_core::{CancellationToken, TextEdit};
use ide_extension::Package;
use ide_language::ProgramPin;
@@ -419,7 +420,7 @@ impl HostApi for PluginApi {
let info = repo.branch_info().map_err(failed)?;
let changed = repo.status().map_err(failed)?.len();
Ok(Some(RepositoryStatus {
root: repo.root().to_string_lossy().into_owned(),
root: to_ipc(repo.root()),
branch: info.head,
commit: info.head_commit,
upstream: info.upstream,
@@ -467,7 +468,7 @@ impl HostApi for PluginApi {
}
let Ok(rel) = entry.path().strip_prefix(root) else { continue };
if matcher.is_match(rel) {
out.push(entry.path().to_string_lossy().into_owned());
out.push(to_ipc(entry.path()));
}
}
out.sort();
@@ -806,6 +807,19 @@ mod tests {
PluginApi { pkg: Package::new(manifest, dir.to_path_buf()), shared }
}
#[test]
fn repository_and_search_paths_match_ipc_events() {
let tmp = tempfile::tempdir().unwrap();
assert!(std::process::Command::new("git").args(["init", "-q"]).arg(tmp.path()).status().unwrap().success());
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir(root.join("src")).unwrap();
let file = root.join("src/Example.java");
std::fs::write(&file, "class Example {}\n").unwrap();
let api = api(&root, Arc::default());
assert_eq!(api.find_files(&root, "**/*.java", 8).unwrap(), [to_ipc(&file)]);
assert_eq!(api.vcs_status(&root).unwrap().unwrap().root, to_ipc(&root));
}
#[test]
fn programs_run_only_as_approved() {
let tmp = tempfile::tempdir().unwrap();
+11 -1
Переглянути файл
@@ -422,7 +422,8 @@ struct IdeDir {
plugins: PathBuf,
}
/// The settings folders of JetBrains IDEs and Android Studio (2020.1 and later), newest first.
/// The settings folders of JetBrains IDEs and Android Studio (2020.1 and later), newest first, one
/// per product: its newest version's (an upgrade leaves the older ones behind).
fn ide_dirs(layout: Layout, home: &Path, env: impl Fn(&str) -> Option<OsString>) -> Vec<IdeDir> {
let var = |key: &str| env(key).filter(|v| !v.is_empty()).map(PathBuf::from);
let (config_root, data_root) = match layout {
@@ -462,6 +463,8 @@ fn ide_dirs(layout: Layout, home: &Path, env: impl Fn(&str) -> Option<OsString>)
}
}
out.sort_by(|a, b| b.version.cmp(&a.version).then_with(|| a.label.cmp(&b.label)));
let mut products = std::collections::HashSet::new();
out.retain(|ide| products.insert(ide.product.clone()));
out
}
@@ -784,6 +787,13 @@ mod tests {
};
let mac = mk(home.join("Library/Application Support/JetBrains/IntelliJIdea2025.2"));
mk(home.join("Library/Application Support/JetBrains/Toolbox"));
// An upgrade leaves the older version's folder behind: only the newest of a product counts.
mk(home.join("Library/Application Support/JetBrains/IntelliJIdea2024.3"));
mk(home.join("Library/Application Support/JetBrains/IntelliJIdea2025.10"));
let dirs = ide_dirs(Layout::Mac, home, |_| None);
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].label, "IntelliJ IDEA 2025.10");
std::fs::remove_dir(home.join("Library/Application Support/JetBrains/IntelliJIdea2025.10")).unwrap();
let dirs = ide_dirs(Layout::Mac, home, |_| None);
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].label, "IntelliJ IDEA 2025.2");
+4
Переглянути файл
@@ -77,6 +77,8 @@ impl Host {
lap = std::time::Instant::now();
};
let root = dunce::canonicalize(root)?;
let opening = self.opening(window);
let _opening = opening.lock();
// Reject a damaged manifest before replacing the currently open project.
ide_workspace::workspace::Workspace::load(&root)?;
// The window reloaded (or asked again) for the project it already has: keep
@@ -569,6 +571,8 @@ impl Host {
return Err(IdeError::invalid(format!("{} is a folder", file.display())));
}
let dir = file.parent().map(Path::to_path_buf).ok_or_else(|| IdeError::invalid("no parent folder"))?;
let opening = self.opening(window);
let _opening = opening.lock();
if let Ok(current) = self.project(window)
&& current.light
{
-1
Переглянути файл
@@ -316,7 +316,6 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "vcs_log_users"
| "vcs_log_details"
| "vcs_log_details_batch"
| "vcs_log_index"
| "vcs_revision_children"
| "vcs_revision_files"
| "vcs_open_external_log"
+46
Переглянути файл
@@ -0,0 +1,46 @@
//! Opening the project a window is already opening reuses it: racing opens (a double
//! click, a launch path and a restore) must not start a second index and language servers.
use ide_core::NullSink;
use ide_host::{Host, HostConfig};
use std::sync::{Arc, Barrier};
#[test]
fn racing_opens_of_one_window_share_one_project() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("src/Main.java"), "class Main {}\n").unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
let _guard = runtime.enter();
let host = Arc::new(Host::new(HostConfig {
config_dir: tmp.path().join("config"),
data_dir: tmp.path().join("data"),
local_data_dir: tmp.path().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: runtime.handle().clone(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
let start = Arc::new(Barrier::new(4));
let opens: Vec<_> = (0..4)
.map(|_| {
let (host, root, start) = (host.clone(), root.clone(), start.clone());
std::thread::spawn(move || {
start.wait();
host.open_project("main", &root).unwrap()
})
})
.collect();
let projects: Vec<_> = opens.into_iter().map(|t| t.join().unwrap()).collect();
let current = host.project("main").unwrap();
for project in &projects {
assert!(Arc::ptr_eq(project, &current), "every open returns the window's one project");
}
host.close_project("main");
}
+6 -5
Переглянути файл
@@ -6,6 +6,7 @@
//! `plugins/build.sh <dir>` after changing their source or `wit/`.
use ide_core::error::ErrorKind;
use ide_core::ipc_path::to_ipc;
use ide_host::plugins::*;
use ide_plugin::{EditorContext, HostError, Invocation, Limits};
use parking_lot::Mutex;
@@ -214,7 +215,7 @@ fn fixture(limits: Limits) -> Fixture {
std::fs::create_dir_all(project.join("src")).unwrap();
std::fs::write(project.join("src/notes.txt"), "one two three\nfour five\n").unwrap();
std::fs::write(tmp.path().join("secret.txt"), "top secret").unwrap();
let project = project.canonicalize().unwrap();
let project = dunce::canonicalize(project).unwrap();
let events: Events = Arc::default();
let sink = {
let events = events.clone();
@@ -359,7 +360,7 @@ fn read_file_is_confined_to_the_project() {
let inv = Invocation { client: None, workspace_root: None, editor: None };
let err = f.host.run_command("misbehave", "read", Some("src/notes.txt"), inv).unwrap_err().message;
assert!(err.contains("no project is open"), "{err}");
assert_eq!(f.run("misbehave", "root", None).unwrap().unwrap(), f.project.to_string_lossy());
assert_eq!(f.run("misbehave", "root", None).unwrap().unwrap(), to_ipc(&f.project));
assert_eq!(f.status("misbehave"), PluginStatus::Active);
}
@@ -1740,7 +1741,7 @@ fn official_checkstyle_checks_on_save() {
let java = f.project.join("src/A.java");
std::fs::write(&java, "class A {\n\tint x;\n}\n").unwrap();
let saved = |f: &Fixture| {
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(java.to_string_lossy().into_owned())]);
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(to_ipc(&java))]);
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
};
saved(&f);
@@ -1793,7 +1794,7 @@ fn official_license_header_reports_fixes_and_scans() {
f.workspace.diagnostics.lock().get(&("openidea.license-header".into(), path.to_path_buf())).cloned()
};
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileOpened(a.to_string_lossy().into_owned())]);
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileOpened(to_ipc(&a))]);
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
assert!(f.host.wait_events(Duration::from_secs(20)));
let d = diagnostics(&a).expect("published on open");
@@ -1818,7 +1819,7 @@ fn official_license_header_reports_fixes_and_scans() {
f.host.run_command("openidea.license-header", "scan", None, f.inv()).unwrap();
assert_eq!(diagnostics(&b).map(|d| d.len()), Some(1), "found by the scan");
std::fs::write(&a, "// Copyright (c) 2026 X\nfn a() {}\n").unwrap();
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(a.to_string_lossy().into_owned())]);
f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(to_ipc(&a))]);
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
assert!(f.host.wait_events(Duration::from_secs(20)));
assert_eq!(diagnostics(&a).map(|d| d.len()), Some(0), "cleared once the header is there");
+24 -7
Переглянути файл
@@ -13,6 +13,7 @@ use crate::types::{
};
use crate::wit_host::{bindings, providers_bindings, syntax_bindings, views_bindings};
use ide_core::CancellationToken;
use ide_core::ipc_path::to_ipc;
use ide_extension::Capability;
use parking_lot::Mutex;
use std::path::Path;
@@ -935,12 +936,7 @@ fn location_from_wit(l: wit_types::Location) -> Location {
}
fn doc_to_wit(d: &ProviderDocument) -> wit_prov::Document {
wit_prov::Document {
path: d.path.to_string_lossy().into_owned(),
language: d.language.clone(),
version: d.version,
text: d.text.clone(),
}
wit_prov::Document { path: to_ipc(&d.path), language: d.language.clone(), version: d.version, text: d.text.clone() }
}
/// Resets the budgets for the next call: fuel, deadline, cancellation.
@@ -1012,7 +1008,7 @@ fn code_action_to_wit(a: &CodeAction) -> wit_prov::CodeAction {
.edits
.iter()
.map(|(path, edits)| wit_prov::FileEdit {
path: path.to_string_lossy().into_owned(),
path: to_ipc(path),
edits: edits
.iter()
.map(|e| wit_types::TextEdit { range: range_to_wit(e.range), text: e.new_text.clone() })
@@ -1131,6 +1127,27 @@ fn event_to_wit_view(e: ViewEvent) -> wit_vt::ViewEvent {
mod tests {
use super::*;
#[cfg(windows)]
#[test]
fn provider_and_resolved_action_paths_match_ipc_events() {
for (path, expected) in [
(r"C:\project\Example.java", "C:/project/Example.java"),
(r"\\?\C:\project\Example.java", "C:/project/Example.java"),
(r"\\server\share\Example.java", "//server/share/Example.java"),
] {
let doc = ProviderDocument { path: path.into(), ..Default::default() };
assert_eq!(doc_to_wit(&doc).path, expected);
let action = CodeAction {
title: "Fix".into(),
kind: None,
preferred: false,
edits: vec![(path.into(), Vec::new())],
data: None,
};
assert_eq!(code_action_to_wit(&action).edits[0].path, expected);
}
}
fn ext(kind: &str) -> wit_types::Extension {
wit_types::Extension { kind: kind.into(), data: "{}".into() }
}
+4 -2
Переглянути файл
@@ -5,6 +5,7 @@
use crate::runtime::{StoreData, clip};
use crate::sandbox;
use crate::types::{EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, StatusItem, net_host};
use ide_core::ipc_path::to_ipc;
use ide_extension::Capability;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
@@ -310,7 +311,8 @@ impl workspace::HostProject for StoreData {
if let Err(e) = self.require(Capability::ProjectRead) {
return Ok(Err(e));
}
Ok(Ok(self.table.get(&this)?.root.to_string_lossy().into_owned()))
// Paths reach plugins in IPC form (`/` on Windows), as the UI's event paths do, so they compare as text.
Ok(Ok(to_ipc(&self.table.get(&this)?.root)))
}
fn read_file(&mut self, this: Resource<ProjectRes>, path: String) -> Fallible<String> {
@@ -346,7 +348,7 @@ impl editor::Host for StoreData {}
impl editor::HostTextEditor for StoreData {
fn path(&mut self, this: Resource<EditorRes>) -> wasmtime::Result<String> {
Ok(self.table.get(&this)?.ctx.path.to_string_lossy().into_owned())
Ok(to_ipc(&self.table.get(&this)?.ctx.path))
}
fn language(&mut self, this: Resource<EditorRes>) -> wasmtime::Result<String> {
+105 -2
Переглянути файл
@@ -3,8 +3,9 @@
//! its templates (`default="true"`) and temporary configurations. A configuration found in more
//! than one place is taken from the first, in that order.
//!
//! Python, Django server, Django tests, pytest, npm, Jest, Vitest, Node.js, Shell Script and
//! compound configurations become the matching kinds; other types are skipped with their type.
//! Python, Django server, Django tests, pytest, npm, Jest, Vitest, Node.js, Shell Script,
//! Application, Spring Boot and compound configurations become the matching kinds; other types
//! are skipped with their type.
//! `$PROJECT_DIR$` (and `$MODULE_DIR$`, `$MODULE_WORKING_DIR$`, `$ContentRoot$`,
//! `$ProjectFileDir$`, all the project directory here) and `$USER_HOME$` are replaced; another
//! path variable skips the configuration.
@@ -162,6 +163,8 @@ const VITEST: &str = "JavaScriptTestRunnerVitest";
const NODE: &str = "NodeJSConfigurationType";
const SHELL: &str = "ShConfigurationType";
const COMPOUND: &str = "CompoundRunConfigurationType";
const APPLICATION: &str = "Application";
const SPRING_BOOT: &str = "SpringBootApplicationConfigurationType";
type Res<T> = Result<T, SkipReason>;
@@ -329,6 +332,8 @@ impl Cx<'_> {
JEST | VITEST => self.js_tests(name, c, ty == VITEST, &mut ignored)?,
NODE => self.node(name, c, &mut ignored)?,
SHELL => self.shell(name, c)?,
APPLICATION => self.java_app(name, c, false, &mut ignored)?,
SPRING_BOOT => self.java_app(name, c, true, &mut ignored)?,
COMPOUND => {
members = c.children_named("toRun").filter_map(|t| t.attr("name")).map(str::to_owned).collect();
config(name, "compound", String::new(), Vec::new(), None)
@@ -695,6 +700,54 @@ impl Cx<'_> {
Ok(rc)
}
// ------------------------------------------------------------- Java
/// IDEA's Application and Spring Boot types, as the `application` / `spring-boot` forms run
/// them: `java <vm options> -cp ${classpath} <main> [--spring.profiles.active=…] <arguments>`
/// with the module's runtime classpath.
fn java_app(&self, name: &str, c: &El, spring: bool, ignored: &mut Vec<String>) -> Res<RunConfig> {
let main = if spring { "SPRING_BOOT_MAIN_CLASS" } else { "MAIN_CLASS_NAME" };
let Some(main) = self.text(c.option(main))? else { return Err(SkipReason::NothingToRun) };
let (_, cwd) = self.cwd(c.option("WORKING_DIRECTORY"))?;
let mut args = self.words(c.option("VM_PARAMETERS"))?;
args.extend(["-cp".to_owned(), "${classpath}".to_owned(), main]);
if spring && let Some(profiles) = self.text(c.option("ACTIVE_PROFILES"))? {
args.push(format!("--spring.profiles.active={profiles}"));
}
args.extend(self.words(c.option("PROGRAM_PARAMETERS"))?);
let mut rc =
config(name, if spring { "spring-boot" } else { "application" }, "java".into(), args, Some("java-debug"));
rc.cwd = cwd.map(Into::into);
self.envs(c, &mut rc);
if let Some(module) = c.child("module").and_then(|m| m.attr("name")).filter(|m| !m.is_empty()) {
match module_dir(self.root, module) {
Some(dir) => rc.extras.module = Some(dir),
None => ignored.push(format!("module {module}")),
}
}
// Options the forms have no field for.
if c.flag("ALTERNATIVE_JRE_PATH_ENABLED") {
ignored.push("JRE".into());
}
if c.flag("INCLUDE_PROVIDED_SCOPE") {
ignored.push("provided scope".into());
}
if c.child("classpathModifications").is_some_and(|m| !m.children.is_empty()) {
ignored.push("classpath modifications".into());
}
if spring {
for (option, label) in [("HIDE_BANNER", "hide banner"), ("DEBUG_MODE", "debug output")] {
if c.flag(option) {
ignored.push(label.into());
}
}
if c.child("additionalParameters").is_some_and(|p| !p.children.is_empty()) {
ignored.push("override configuration properties".into());
}
}
Ok(rc)
}
// ------------------------------------------------------------- Shell
/// A script file (with its interpreter) or script text, kept as the Shell Script form's fields.
@@ -835,6 +888,56 @@ fn module_count(root: &Path) -> usize {
.sum()
}
/// The folder (relative, `""` for the project's own) of IDEA module `name`: a Maven module is
/// named after its `artifactId` (usually its folder), a Gradle one `<project>.<path>.<source set>`.
fn module_dir(root: &Path, name: &str) -> Option<String> {
let folder = |dir: &Path| dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let exact = |dir: &Path| folder(dir) == name || pom_artifact(dir).is_some_and(|a| a == name);
if let Some(dir) = find_module(root, &exact) {
return Some(dir);
}
let gradle = name.strip_suffix(".main").or_else(|| name.strip_suffix(".test")).unwrap_or(name);
let last = gradle.rsplit('.').next().filter(|last| *last != name)?;
find_module(root, &|dir: &Path| folder(dir) == last)
}
/// The shallowest build folder under `root` (itself included) that `names` accepts.
fn find_module(root: &Path, names: &dyn Fn(&Path) -> bool) -> Option<String> {
const BUILDS: [&str; 3] = ["pom.xml", "build.gradle", "build.gradle.kts"];
let mut level = vec![root.to_path_buf()];
for _ in 0..5 {
if let Some(found) = level.iter().find(|d| BUILDS.iter().any(|b| d.join(b).is_file()) && names(d)) {
let rel = found.strip_prefix(root).ok()?;
return Some(rel.to_string_lossy().replace('\\', "/"));
}
let mut next: Vec<PathBuf> = level
.iter()
.filter_map(|d| std::fs::read_dir(d).ok())
.flat_map(|entries| entries.flatten().map(|e| e.path()))
.filter(|p| p.is_dir())
.filter(|p| {
let n = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
!n.starts_with('.') && !["node_modules", "target", "build", "out", "src"].contains(&n.as_str())
})
.collect();
next.sort();
level = next;
}
None
}
/// The `artifactId` of the module's own `pom.xml` (not its parent's).
fn pom_artifact(dir: &Path) -> Option<String> {
let pom = std::fs::read_to_string(dir.join("pom.xml")).ok()?;
let own = match (pom.find("<parent>"), pom.find("</parent>")) {
(Some(start), Some(end)) if start < end => format!("{}{}", &pom[..start], &pom[end..]),
_ => pom,
};
let start = own.find("<artifactId>")? + "<artifactId>".len();
let end = start + own[start..].find("</artifactId>")?;
Some(own[start..end].trim().to_owned())
}
/// `--settings` from PyCharm's "Settings" field: a file (`mysite/settings/dev.py`, relative to
/// the project) becomes its module relative to the working directory; a module stays as it is.
fn settings_module(value: &str, root: &Path, dir: &Path) -> String {
+135 -4
Переглянути файл
@@ -204,7 +204,7 @@ pub fn explode(war: &Path, destination: &Path, resources_only: bool) -> IdeResul
}
/// Updates the exploded artifact deployment from the module's own class output directories and
/// its web resources (`src/main/webapp`), file by file and only what changed, instead of
/// its web resources ([`web_sources`]), file by file and only what changed, instead of
/// rebuilding and re-exploding the WAR. `module` and `class_paths` are absolute.
/// `Ok(false)`: not possible this way (not deployed from the artifact yet, the module's output
/// isn't on the classpath, or a module it depends on was compiled since the last update, whose
@@ -232,9 +232,10 @@ pub fn sync_outputs(base: &Path, module: &Path, class_paths: &[PathBuf], resourc
for dir in own {
sync_tree(dir, dir, &classes, Path::new("WEB-INF/classes"), resources_only, &mut current)?;
}
let webapp = module.join("src/main/webapp");
if webapp.is_dir() {
sync_tree(&webapp, &webapp, &dest, Path::new(""), resources_only, &mut current)?;
for (dir, target) in web_sources(module) {
if dir.is_dir() {
sync_tree(&dir, &dir, &dest.join(&target), &target, resources_only, &mut current)?;
}
}
for rel in previous.iter().filter(|p| !current.contains(*p)) {
let path = dest.join(rel);
@@ -246,6 +247,59 @@ pub fn sync_outputs(base: &Path, module: &Path, class_paths: &[PathBuf], resourc
Ok(true)
}
/// The folders whose files the WAR puts at its root (or under the second path): the web app
/// folder (`src/main/webapp`, maven-war-plugin's `warSourceDirectory`, Gradle's
/// `webAppDirName` / `webAppDirectory`), then maven-war-plugin's `webResources`.
pub fn web_sources(module: &Path) -> Vec<(PathBuf, PathBuf)> {
let rel = |dir: &str| {
let dir = ["${project.basedir}/", "${basedir}/"].iter().find_map(|p| dir.strip_prefix(p)).unwrap_or(dir);
module.join(dir.trim())
};
if let Ok(pom) = fs::read_to_string(module.join("pom.xml"))
&& let Some(war) = war_plugin(&pom)
{
let mut out = vec![(rel(tag(war, "warSourceDirectory").unwrap_or("src/main/webapp")), PathBuf::new())];
let mut rest = tag_block(war, "webResources").unwrap_or_default();
while let Some(start) = rest.find("<resource>") {
let end = rest[start..].find("</resource>").map_or(rest.len(), |e| start + e);
let resource = &rest[start..end];
if let Some(dir) = tag(resource, "directory") {
out.push((rel(dir), PathBuf::from(tag(resource, "targetPath").unwrap_or_default())));
}
rest = &rest[end..];
}
return out;
}
let gradle = ["build.gradle", "build.gradle.kts"].iter().find_map(|f| fs::read_to_string(module.join(f)).ok());
let web_app_dir = gradle.as_deref().and_then(|text| {
text.lines()
.filter(|l| !l.trim_start().starts_with("//"))
.find(|l| l.contains("webAppDirName") || l.contains("webAppDirectory"))
.and_then(|l| l.split(['"', '\'']).nth(1).map(str::to_owned))
});
vec![(rel(web_app_dir.as_deref().unwrap_or("src/main/webapp")), PathBuf::new())]
}
/// The `<plugin>` element of maven-war-plugin in `pom`, if it is configured there.
fn war_plugin(pom: &str) -> Option<&str> {
let at = pom.find("<artifactId>maven-war-plugin</artifactId>")?;
let start = pom[..at].rfind("<plugin>")?;
let end = pom[at..].find("</plugin>").map_or(pom.len(), |e| at + e);
Some(&pom[start..end])
}
/// The text of the first `<name>` element in `xml`.
fn tag<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
tag_block(xml, name).map(str::trim).filter(|t| !t.is_empty())
}
fn tag_block<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
let open = format!("<{name}>");
let start = xml.find(&open)? + open.len();
let end = start + xml[start..].find(&format!("</{name}>"))?;
Some(&xml[start..end])
}
fn modified_since(dir: &Path, since: std::time::SystemTime) -> bool {
let Ok(entries) = fs::read_dir(dir) else { return false };
entries.flatten().any(|e| match e.file_type() {
@@ -574,6 +628,83 @@ mod tests {
fs::File::create(dep.join("Core.class")).unwrap().set_modified(later).unwrap();
assert!(!sync_outputs(&base, &module, &paths, false).unwrap());
}
#[test]
fn web_sources_follow_the_war_plugin_and_gradle_settings() {
let tmp = tempfile::tempdir().unwrap();
let module = tmp.path();
let rel = |sources: Vec<(PathBuf, PathBuf)>| -> Vec<(String, String)> {
sources
.into_iter()
.map(|(d, t)| {
let d = d.strip_prefix(module).unwrap().to_string_lossy().replace('\\', "/");
(d, t.to_string_lossy().into_owned())
})
.collect()
};
assert_eq!(rel(web_sources(module)), [("src/main/webapp".to_owned(), String::new())]);
// An Eclipse-style layout: the JSPs come in through webResources.
fs::write(
module.join("pom.xml"),
r#"<project><build><plugins>
<plugin><artifactId>maven-compiler-plugin</artifactId></plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warSourceDirectory>${basedir}/web</warSourceDirectory>
<webResources>
<resource><directory>WebContent</directory><includes><include>**/*</include></includes></resource>
<resource><directory>extra</directory><targetPath>static</targetPath></resource>
</webResources>
</configuration>
</plugin>
</plugins></build></project>"#,
)
.unwrap();
assert_eq!(
rel(web_sources(module)),
[
("web".to_owned(), String::new()),
("WebContent".to_owned(), String::new()),
("extra".to_owned(), "static".to_owned())
]
);
fs::remove_file(module.join("pom.xml")).unwrap();
fs::write(
module.join("build.gradle"),
"plugins { id 'war' }\n// webAppDirName = 'old'\nwebAppDirName = 'WebContent'\n",
)
.unwrap();
assert_eq!(rel(web_sources(module)), [("WebContent".to_owned(), String::new())]);
}
#[test]
fn updates_web_resources_outside_src_main_webapp() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let (base, module) = (root.join("base"), root.join("web"));
let (dest, out) = (base.join("deployment"), module.join("target/classes"));
for dir in [dest.join("WEB-INF/classes"), out.clone(), module.join("WebContent/jsp")] {
fs::create_dir_all(dir).unwrap();
}
fs::write(
module.join("pom.xml"),
"<project><plugin><artifactId>maven-war-plugin</artifactId><configuration><webResources>\
<resource><directory>WebContent</directory></resource></webResources></configuration></plugin></project>",
)
.unwrap();
fs::write(dest.join("index.jsp"), "old").unwrap();
fs::write(module.join("WebContent/jsp/list.jsp"), "new").unwrap();
fs::write(base.join("artifact-path.txt"), "web.war").unwrap();
assert!(sync_outputs(&base, &module, std::slice::from_ref(&out), true).unwrap());
assert_eq!(fs::read_to_string(dest.join("jsp/list.jsp")).unwrap(), "new");
// Files the WAR brought that no source here maps to stay.
assert_eq!(fs::read_to_string(dest.join("index.jsp")).unwrap(), "old");
}
#[test]
fn deployment_errors_identify_the_checked_path() {
let tmp = tempfile::tempdir().unwrap();
+93 -8
Переглянути файл
@@ -239,8 +239,8 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
<envs><env name="VITE_API" value="http://localhost:8000" /></envs>
<method v="2" />
</configuration>
<configuration name="Main" type="Application" factoryName="Application">
<option name="MAIN_CLASS_NAME" value="shop.Main" />
<configuration name="Main" type="JUnit" factoryName="JUnit">
<option name="MAIN_CLASS_NAME" value="shop.MainTest" />
<method v="2" />
</configuration>"#
)),
@@ -272,7 +272,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
assert_eq!(get(&r, "Custom").args, s(&["-m", "pytest", "tests/a.py", "--maxfail=2"]));
assert_eq!(reason(&r, "Unittests in tests"), &SkipReason::UnsupportedType { type_: "tests (Unittests)".into() });
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "Application".into() });
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "JUnit".into() });
let dev = get(&r, "dev");
assert_eq!((dev.kind.as_str(), dev.command.as_str()), ("npm", "pnpm"));
@@ -526,14 +526,11 @@ fn sources_are_offered_when_their_files_exist() {
),
);
assert!(available(dir.path()).is_empty());
write(dir.path(), ".idea/workspace.xml", &workspace(r#"<configuration name="App" type="Application" />"#));
write(dir.path(), ".idea/workspace.xml", &workspace(r#"<configuration name="App" type="JUnit" />"#));
assert_eq!(available(dir.path()), [RunImportSource::Jetbrains]);
write(dir.path(), ".vscode/launch.json", "{}");
assert_eq!(available(dir.path()), [RunImportSource::Vscode, RunImportSource::Jetbrains]);
assert_eq!(
reason(&import_from(dir.path(), &[]), "App"),
&SkipReason::UnsupportedType { type_: "Application".into() }
);
assert_eq!(reason(&import_from(dir.path(), &[]), "App"), &SkipReason::UnsupportedType { type_: "JUnit".into() });
}
#[test]
@@ -702,3 +699,91 @@ fn flags_defaults_inherited_variables_and_nested_django_tests() {
assert_eq!((tests.kind.as_str(), tests.is_test), ("python", true));
assert_eq!(tests.args[..3], s(&["backend/manage.py", "test", "orders"]));
}
#[test]
fn java_applications_and_spring_boot_keep_their_module() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(&root, "pom.xml", "<project><artifactId>shop</artifactId><packaging>pom</packaging></project>");
write(
&root,
"example-service/pom.xml",
"<project><parent><artifactId>shop</artifactId></parent><artifactId>example-service</artifactId></project>",
);
// IDEA names a Maven module after its artifactId, which needn't be its folder.
write(
&root,
"services/api/pom.xml",
"<project><parent><artifactId>shop</artifactId></parent><artifactId>api-service</artifactId></project>",
);
write(
&root,
".idea/workspace.xml",
&workspace(
r#" <configuration name="ExampleApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="example-service" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.example.ExampleApplication" />
<option name="ACTIVE_PROFILES" value="dev,local" />
<option name="VM_PARAMETERS" value="-Xmx512m -Dfile.encoding=UTF-8" />
<option name="PROGRAM_PARAMETERS" value="--server.port=8081" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/example-service" />
<option name="HIDE_BANNER" value="true" />
<envs>
<env name="TZ" value="UTC" />
</envs>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="Api" type="Application" factoryName="Application">
<option name="MAIN_CLASS_NAME" value="com.example.api.Main" />
<module name="api-service" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="ALTERNATIVE_JRE_PATH" value="17" />
<method v="2" />
</configuration>
<configuration name="Gone" type="Application" factoryName="Application">
<option name="MAIN_CLASS_NAME" value="Gone" />
<module name="removed-module" />
</configuration>
<configuration name="NoMain" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="example-service" />
</configuration>"#,
),
);
let r = import_from(&root, &[]);
let boot = get(&r, "ExampleApplication");
assert_eq!(boot.kind, "spring-boot");
assert_eq!(boot.command, "java");
assert_eq!(
boot.args,
s(&[
"-Xmx512m",
"-Dfile.encoding=UTF-8",
"-cp",
"${classpath}",
"com.example.ExampleApplication",
"--spring.profiles.active=dev,local",
"--server.port=8081",
])
);
assert_eq!(boot.extras.module.as_deref(), Some("example-service"));
assert_eq!(cwd(boot), Some(PathBuf::from("example-service")));
assert_eq!(boot.env.get("TZ").map(String::as_str), Some("UTC"));
assert_eq!(boot.debug_adapter.as_deref(), Some("java-debug"));
assert_eq!(ignored(&r, "ExampleApplication"), ["before launch", "hide banner"]);
let api = get(&r, "Api");
assert_eq!(api.kind, "application");
assert_eq!(api.args, s(&["-cp", "${classpath}", "com.example.api.Main"]));
assert_eq!(api.extras.module.as_deref(), Some("services/api"));
assert_eq!(ignored(&r, "Api"), ["JRE"]);
// A module that isn't here any more: the form finds it by the main class.
assert_eq!(get(&r, "Gone").extras.module, None);
assert_eq!(ignored(&r, "Gone"), ["module removed-module"]);
assert_eq!(reason(&r, "NoMain"), &SkipReason::NothingToRun);
}
+112 -205
Переглянути файл
@@ -9,44 +9,88 @@ use std::collections::{HashMap, HashSet};
/// Log "Text or hash" filter: the message (substring or regex), or a hash prefix.
enum TextFilter {
Plain { needle: String, match_case: bool },
/// Commits `git log --grep` selected, or whose id starts with `hash`.
Selected {
ids: HashSet<ObjectId>,
hash: Option<String>,
},
/// Case-insensitive non-ASCII text: git folds case only for ASCII under the C locale.
Folded(String),
Regex(regex_lite::Regex),
}
impl TextFilter {
fn new(text: &str, regex: bool, match_case: bool) -> IdeResult<Option<Self>> {
fn new(
r: &Repo,
scopes: &[String],
q: &LogQuery,
text: &str,
cancel: &CancellationToken,
) -> IdeResult<Option<Self>> {
let text = text.trim();
if text.is_empty() {
return Ok(None);
}
if regex {
if q.text_regex {
let re = regex_lite::RegexBuilder::new(text)
.case_insensitive(!match_case)
.case_insensitive(!q.text_match_case)
.multi_line(true)
.build()
.map_err(|e| IdeError::invalid(format!("invalid regular expression: {e}")))?;
return Ok(Some(Self::Regex(re)));
}
let needle = if match_case { text.to_string() } else { text.to_lowercase() };
Ok(Some(Self::Plain { needle, match_case }))
if !q.text_match_case && !text.is_ascii() {
return Ok(Some(Self::Folded(text.to_lowercase())));
}
let mut filter = vec!["--fixed-strings".to_string(), format!("--grep={text}")];
if !q.text_match_case {
filter.push("--regexp-ignore-case".into());
}
let ids = git_select(r, scopes, &filter, &[], q.first_parent, cancel)?;
let hash = (text.len() >= 4 && text.bytes().all(|b| b.is_ascii_hexdigit())).then(|| text.to_ascii_lowercase());
Ok(Some(Self::Selected { ids, hash }))
}
fn matches(&self, message: &str, id: &ObjectId) -> bool {
match self {
Self::Regex(re) => re.is_match(message),
Self::Plain { needle, match_case } => {
let hash = needle.len() >= 4 && needle.bytes().all(|b| b.is_ascii_hexdigit());
if hash && id.to_string().starts_with(&needle.to_ascii_lowercase()) {
return true;
}
if *match_case {
message.contains(needle.as_str())
} else {
message.to_lowercase().contains(needle.as_str())
}
fn matches(&self, repo: &gix::Repository, index: &mut crate::log_index::LogIndex, id: ObjectId) -> IdeResult<bool> {
Ok(match self {
Self::Regex(re) => re.is_match(&index.message(repo, id)?),
Self::Folded(needle) => index.message(repo, id)?.to_lowercase().contains(needle.as_str()),
Self::Selected { ids, hash } => {
ids.contains(&id) || hash.as_ref().is_some_and(|h| id.to_string().starts_with(h.as_str()))
}
})
}
}
/// Commits git selects from each scope with `filter`. Path limiting uses git's history
/// simplification and, when the repository has them, changed-path Bloom filters.
fn git_select(
r: &Repo,
scopes: &[String],
filter: &[String],
paths: &[String],
first_parent: bool,
cancel: &CancellationToken,
) -> IdeResult<HashSet<ObjectId>> {
let mut ids = HashSet::new();
for scope in scopes {
let mut args =
vec!["log".to_string(), "--format=%H".into(), "--no-show-signature".into(), "--no-follow".into()];
if first_parent {
args.push("--first-parent".into());
}
args.extend(filter.iter().cloned());
args.push("--end-of-options".into());
args.extend(scope.split_whitespace().map(str::to_string));
args.push("--".into());
args.extend(paths.iter().map(|p| format!(":(literal){p}")));
let output =
crate::cli::run_cancellable(r.root(), &args.iter().map(String::as_str).collect::<Vec<_>>(), cancel)?;
for line in output.stdout_str().lines() {
ids.insert(ObjectId::from_hex(line.as_bytes()).map_err(gx)?);
}
}
Ok(ids)
}
pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>> {
@@ -173,87 +217,71 @@ fn log_indexed(
} else {
None
};
let scopes = if let Some(range) = range {
vec![range.to_string()]
} else {
let mut scopes = ranges.iter().map(|s| s.to_string()).collect::<Vec<_>>();
if !tips.is_empty() {
scopes.push(tips.iter().map(ToString::to_string).collect::<Vec<_>>().join(" "));
}
scopes
};
let mut history_paths = HashMap::new();
let path_ids = if paths.is_empty() {
None
} else {
} else if q.follow && paths.len() == 1 {
let mut ids = HashSet::new();
if q.follow && paths.len() == 1 {
let rel = &paths[0];
let mut args = vec![
"log".to_string(),
"--format=%x00%H".into(),
"--name-status".into(),
"-z".into(),
"--follow".into(),
"--topo-order".into(),
];
if q.first_parent {
args.push("--first-parent".into());
}
args.push("--end-of-options".into());
let scopes = if let Some(range) = range {
vec![range.to_string()]
} else {
let mut scopes = ranges.iter().map(|s| s.to_string()).collect::<Vec<_>>();
if !tips.is_empty() {
scopes.push(tips.iter().map(ToString::to_string).collect::<Vec<_>>().join(" "));
}
scopes
};
for scope in scopes {
let mut args = args.clone();
args.extend(scope.split_whitespace().map(str::to_string));
args.extend(["--".into(), rel.clone()]);
let output = crate::cli::run_cancellable(
r.root(),
&args.iter().map(String::as_str).collect::<Vec<_>>(),
cancel,
)?;
let text = output.stdout_str();
let mut tokens = text.split('\0').peekable();
let mut current_path = rel.clone();
while let Some(token) = tokens.next() {
let token = token.trim_start_matches('\n');
if let Ok(id) = ObjectId::from_hex(token.as_bytes()) {
ids.insert(id);
history_paths.insert(id, current_path.clone());
} else if token.starts_with('R') && token[1..].bytes().all(|b| b.is_ascii_digit()) {
if let (Some(old), Some(new)) = (tokens.next(), tokens.next())
&& new == current_path
{
current_path = old.to_string();
}
} else if ["A", "D", "M", "T", "U"].contains(&token) {
tokens.next();
let rel = &paths[0];
let mut args = vec![
"log".to_string(),
"--format=%x00%H".into(),
"--name-status".into(),
"-z".into(),
"--follow".into(),
"--topo-order".into(),
];
if q.first_parent {
args.push("--first-parent".into());
}
args.push("--end-of-options".into());
for scope in &scopes {
let mut args = args.clone();
args.extend(scope.split_whitespace().map(str::to_string));
args.extend(["--".into(), rel.clone()]);
let output =
crate::cli::run_cancellable(r.root(), &args.iter().map(String::as_str).collect::<Vec<_>>(), cancel)?;
let text = output.stdout_str();
let mut tokens = text.split('\0').peekable();
let mut current_path = rel.clone();
while let Some(token) = tokens.next() {
let token = token.trim_start_matches('\n');
if let Ok(id) = ObjectId::from_hex(token.as_bytes()) {
ids.insert(id);
history_paths.insert(id, current_path.clone());
} else if token.starts_with('R') && token[1..].bytes().all(|b| b.is_ascii_digit()) {
if let (Some(old), Some(new)) = (tokens.next(), tokens.next())
&& new == current_path
{
current_path = old.to_string();
}
} else if ["A", "D", "M", "T", "U"].contains(&token) {
tokens.next();
}
}
} else {
let starts = range_ids.as_ref().cloned().unwrap_or_else(|| tips.clone());
ids.extend(
PathWalk::new(&repo, starts, paths.clone(), q.first_parent, cancel, index)?
.map(|item| item.map(|(id, _)| id))
.collect::<IdeResult<HashSet<_>>>()?,
);
}
Some(ids)
} else {
Some(git_select(r, &scopes, &[], &paths, q.first_parent, cancel)?)
};
let authors: Vec<_> =
q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect();
let user_candidates = if q.authors_exact && !authors.is_empty() { index.user_candidates(&authors) } else { None };
let path_candidates = if !q.follow && !paths.is_empty() { index.path_candidates(&paths) } else { None };
let text_candidates = q.text.as_deref().filter(|_| !q.text_regex).and_then(|s| index.message_candidates(s));
let mut visibility = Visibility {
speed_refs: &decorations,
text_candidates,
user_candidates,
path_candidates,
query: q,
path_ids,
range_ids: range_ids.as_ref().map(|ids| ids.iter().copied().collect()),
authors,
text: q.text.as_deref().map(|t| TextFilter::new(t, q.text_regex, q.text_match_case)).transpose()?.flatten(),
text: q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten(),
matches: HashMap::new(),
projected: HashMap::new(),
cancel,
@@ -584,9 +612,6 @@ struct Visibility<'a> {
range_ids: Option<HashSet<ObjectId>>,
authors: Vec<String>,
text: Option<TextFilter>,
text_candidates: Option<HashSet<String>>,
user_candidates: Option<HashSet<String>>,
path_candidates: Option<HashSet<String>>,
matches: HashMap<ObjectId, bool>,
projected: HashMap<ObjectId, Vec<ObjectId>>,
cancel: &'a CancellationToken,
@@ -602,10 +627,7 @@ impl Visibility<'_> {
if let Some(shown) = self.matches.get(&id) {
return Ok(*shown);
}
let indexed = self.index.indexed(&id.to_string());
let shown = if (indexed && self.user_candidates.as_ref().is_some_and(|ids| !ids.contains(&id.to_string())))
|| (indexed && self.path_candidates.as_ref().is_some_and(|ids| !ids.contains(&id.to_string())))
|| !repo.has_object(id)
let shown = if !repo.has_object(id)
|| self.path_ids.as_ref().is_some_and(|ids| !ids.contains(&id))
|| self.range_ids.as_ref().is_some_and(|ids| !ids.contains(&id))
{
@@ -648,15 +670,7 @@ impl Visibility<'_> {
}
}))
&& match &self.text {
Some(text) => {
self.text_candidates.as_ref().is_none_or(|ids| {
ids.contains(&id.to_string())
|| !self.index.indexed(&id.to_string())
|| id.to_string().starts_with(
self.query.text.as_deref().unwrap_or("").trim().to_ascii_lowercase().as_str(),
)
}) && text.matches(&self.index.message(repo, id)?, &id)
}
Some(text) => text.matches(repo, self.index, id)?,
None => true,
}
};
@@ -865,113 +879,6 @@ pub(crate) fn decorations(repo: &gix::Repository) -> IdeResult<HashMap<ObjectId,
Ok(map)
}
/// Commits touching a path, newest first, with git's default history simplification:
/// a commit is shown when its entry for the path differs from every parent, and at a
/// merge that kept one parent's version only that parent's line of history is followed.
struct PathWalk<'r> {
repo: &'r gix::Repository,
paths: Vec<String>,
queue: std::collections::BinaryHeap<(i64, u64, ObjectId)>,
seen: HashSet<ObjectId>,
index: &'r mut crate::log_index::LogIndex,
seq: u64,
first_parent: bool,
cancel: &'r CancellationToken,
shallow: HashSet<ObjectId>,
}
impl<'r> PathWalk<'r> {
fn new(
repo: &'r gix::Repository,
tips: Vec<ObjectId>,
paths: Vec<String>,
first_parent: bool,
cancel: &'r CancellationToken,
index: &'r mut crate::log_index::LogIndex,
) -> IdeResult<Self> {
let mut walk = PathWalk {
repo,
paths,
queue: Default::default(),
seen: Default::default(),
index,
seq: 0,
first_parent,
cancel,
shallow: repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect()).unwrap_or_default(),
};
for tip in tips {
walk.push(tip)?;
}
Ok(walk)
}
fn push(&mut self, id: ObjectId) -> IdeResult<()> {
if self.cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if !self.seen.insert(id) || !self.repo.has_object(id) {
return Ok(());
}
let time = self.repo.find_commit(id).map_err(gx)?.time().map(|t| t.seconds).unwrap_or(0);
// Max-heap on time; among equal times, earlier insertion first.
self.seq += 1;
self.queue.push((time, u64::MAX - self.seq, id));
Ok(())
}
fn step(&mut self) -> IdeResult<Option<(ObjectId, Vec<ObjectId>)>> {
while let Some((_, _, id)) = self.queue.pop() {
let commit = self.repo.find_commit(id).map_err(gx)?;
let parents: Vec<ObjectId> = commit.parent_ids().map(|p| p.detach()).collect();
// Parents cut off by a shallow boundary are treated as absent.
let present: Vec<ObjectId> = parents
.iter()
.copied()
.take(if self.shallow.contains(&id) { 0 } else { usize::MAX })
.filter(|p| self.repo.has_object(p))
.take(if self.first_parent { 1 } else { usize::MAX })
.collect();
let mine = self
.paths
.iter()
.map(|path| self.index.path_entry(self.repo, id, path))
.collect::<IdeResult<Vec<_>>>()?;
let mut same_parent = None;
for p in &present {
let theirs = self
.paths
.iter()
.map(|path| self.index.path_entry(self.repo, *p, path))
.collect::<IdeResult<Vec<_>>>()?;
if theirs == mine {
same_parent = Some(*p);
break;
}
}
match same_parent {
Some(p) => self.push(p)?,
None => {
for p in &present {
self.push(*p)?;
}
if !present.is_empty() || mine.iter().any(Option::is_some) {
return Ok(Some((id, parents)));
}
}
}
}
Ok(None)
}
}
impl Iterator for PathWalk<'_> {
type Item = IdeResult<(ObjectId, Vec<ObjectId>)>;
fn next(&mut self) -> Option<Self::Item> {
self.step().transpose()
}
}
pub(crate) fn commit_files(r: &Repo, rev: &str) -> IdeResult<Vec<ChangedFile>> {
let repo = r.gix()?;
Ok(first_parent_changes(&repo, rev)?.files)
-62
Переглянути файл
@@ -162,14 +162,6 @@ pub struct LogDetails {
pub fingerprint: String,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct LogIndexProgress {
pub indexed: u32,
pub total: u32,
pub running: bool,
}
/// Order of the Git Log (Graph Options › Sort).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -672,7 +664,6 @@ pub struct Repo {
inner: std::sync::Mutex<repo::Cache>,
ignored: std::sync::RwLock<IgnoredNames>,
log_index: std::sync::Mutex<log_index::LogIndex>,
index_progress: std::sync::Mutex<LogIndexProgress>,
log_signatures: std::sync::Mutex<std::collections::HashMap<String, LogDetails>>,
}
@@ -844,59 +835,6 @@ impl Repo {
.into_iter()
.collect())
}
pub fn log_index_progress(&self) -> LogIndexProgress {
self.index_progress.lock().unwrap_or_else(|p| p.into_inner()).clone()
}
/// Incremental persistent inverted index; completed objects survive cancellation/restart.
pub fn index_log(&self, cancel: &CancellationToken) -> IdeResult<LogIndexProgress> {
{
let mut progress = self.index_progress.lock().unwrap_or_else(|p| p.into_inner());
if progress.running {
return Ok(progress.clone());
}
progress.running = true;
}
let result = (|| {
let repo = self.gix()?;
let out = cli::run_cancellable(self.root(), &["rev-list", "--all", "--topo-order"], cancel)?;
let ids: Vec<_> = out
.stdout_str()
.lines()
.map(|id| gix::ObjectId::from_hex(id.as_bytes()).map_err(repo::gx))
.collect::<IdeResult<_>>()?;
{
let mut p = self.index_progress.lock().unwrap_or_else(|p| p.into_inner());
p.total = ids.len() as u32;
p.indexed = 0;
}
for (i, id) in ids.iter().enumerate() {
if cancel.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
let indexed = self.log_index.lock().unwrap_or_else(|p| p.into_inner()).indexed(&id.to_string());
if !indexed {
let files = self.commit_files(&id.to_string())?;
let paths =
files.into_iter().flat_map(|f| std::iter::once(f.path).chain(f.old_path)).collect::<Vec<_>>();
let mut index = self.log_index.lock().unwrap_or_else(|p| p.into_inner());
let c = index.get(&repo, *id)?;
let message = index.message(&repo, *id)?;
index.index_commit(&c.id, &message, &c.author, &c.email, &paths);
if i % 100 == 0 {
index.flush();
}
}
self.index_progress.lock().unwrap_or_else(|p| p.into_inner()).indexed = i as u32 + 1;
}
Ok(())
})();
self.log_index.lock().unwrap_or_else(|p| p.into_inner()).flush();
self.index_progress.lock().unwrap_or_else(|p| p.into_inner()).running = false;
result?;
Ok(self.log_index_progress())
}
pub fn log_details(&self, revision: &str) -> IdeResult<LogDetails> {
self.log_details_cancellable(revision, &CancellationToken::new())
}
+2 -159
Переглянути файл
@@ -6,7 +6,7 @@ use crate::repo::{gx, to_string};
use gix::ObjectId;
use gix::bstr::ByteSlice;
use ide_core::IdeResult;
use redb::{Database, MultimapTableDefinition, ReadableDatabase, TableDefinition};
use redb::{Database, ReadableDatabase, TableDefinition};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock, Weak};
@@ -14,9 +14,6 @@ use std::time::SystemTime;
const COMMITS: TableDefinition<&str, &[u8]> = TableDefinition::new("summaries-v2");
const MESSAGES: TableDefinition<&str, &str> = TableDefinition::new("messages-v1");
const PATHS: TableDefinition<&str, &[u8]> = TableDefinition::new("paths-v2");
const POSTINGS: MultimapTableDefinition<&str, &str> = MultimapTableDefinition::new("search-v1");
const INDEXED: TableDefinition<&str, bool> = TableDefinition::new("indexed-v1");
pub(crate) struct IndexedView {
pub commits: Vec<Commit>,
@@ -36,9 +33,6 @@ pub(crate) struct LogIndex {
memory: HashMap<ObjectId, Arc<Commit>>,
dirty: Vec<Arc<Commit>>,
dirty_messages: Vec<(String, String)>,
dirty_search: Vec<(String, Vec<String>)>,
path_memory: HashMap<(ObjectId, String), Option<(ObjectId, u16)>>,
dirty_paths: Vec<(String, Option<(String, u16)>)>,
pub head: Option<(ObjectId, Option<SystemTime>)>,
pub reachable: HashSet<ObjectId>,
pub views: HashMap<String, Arc<IndexedView>>,
@@ -92,91 +86,6 @@ impl LogIndex {
}
Ok(ids)
}
pub fn indexed(&self, id: &str) -> bool {
self.db
.as_ref()
.and_then(|db| {
let txn = db.begin_read().ok()?;
let table = txn.open_table(INDEXED).ok()?;
Some(table.get(id).ok()??.value())
})
.unwrap_or(false)
}
pub fn index_commit(&mut self, id: &str, message: &str, author: &str, email: &str, paths: &[String]) {
let mut keys: HashSet<String> = Self::grams(message).into_iter().map(|s| format!("m:{s}")).collect();
for user in [author, email, email.split('@').next().unwrap_or(email)] {
keys.insert(format!("u:{}", normalize_user(user)));
}
for path in paths {
keys.insert(format!("p:{path}"));
}
self.dirty_search.push((id.into(), keys.into_iter().collect()));
}
fn grams(text: &str) -> Vec<String> {
let chars: Vec<_> = text.to_lowercase().chars().collect();
chars.windows(3).map(|s| s.iter().collect()).collect::<HashSet<_>>().into_iter().collect()
}
/// Missing/unindexed commits are always checked directly by the caller.
pub fn message_candidates(&self, text: &str) -> Option<HashSet<String>> {
let grams = Self::grams(text);
if grams.is_empty() {
return None;
}
let db = self.db.as_ref()?;
let txn = db.begin_read().ok()?;
let table = txn.open_multimap_table(POSTINGS).ok()?;
let mut candidates: Option<HashSet<String>> = None;
for gram in grams {
let values = table.get(format!("m:{gram}").as_str()).ok()?;
let ids: HashSet<_> = values.filter_map(Result::ok).map(|s| s.value().to_string()).collect();
candidates = Some(match candidates {
Some(old) => old.intersection(&ids).cloned().collect(),
None => ids,
});
if candidates.as_ref().is_some_and(HashSet::is_empty) {
break;
}
}
Some(candidates.unwrap_or_default())
}
pub fn user_candidates(&self, authors: &[String]) -> Option<HashSet<String>> {
let txn = self.db.as_ref()?.begin_read().ok()?;
let table = txn.open_multimap_table(POSTINGS).ok()?;
let mut ids = HashSet::new();
for author in authors {
let name = author.split('<').next().unwrap_or(author).trim();
let email = author.split('<').nth(1).map(|s| s.trim_end_matches('>')).unwrap_or(author);
for alias in [name, email, email.split('@').next().unwrap_or(email)] {
for value in table.get(format!("u:{}", normalize_user(alias)).as_str()).ok()?.filter_map(Result::ok) {
ids.insert(value.value().to_string());
}
}
}
Some(ids)
}
pub fn path_candidates(&self, paths: &[String]) -> Option<HashSet<String>> {
let txn = self.db.as_ref()?.begin_read().ok()?;
let table = txn.open_multimap_table(POSTINGS).ok()?;
let mut ids = HashSet::new();
for path in paths {
for value in table.get(format!("p:{path}").as_str()).ok()?.filter_map(Result::ok) {
ids.insert(value.value().to_string());
}
let prefix = format!("p:{path}/");
let end = format!("{prefix}{}", char::MAX);
for row in table.range(prefix.as_str()..end.as_str()).ok()?.filter_map(Result::ok) {
for value in row.1.filter_map(Result::ok) {
ids.insert(value.value().to_string());
}
}
}
Some(ids)
}
pub fn open(&mut self, dir: &Path) {
if self.opened {
return;
@@ -272,11 +181,7 @@ impl LogIndex {
}
pub fn flush(&mut self) {
if self.dirty.is_empty()
&& self.dirty_paths.is_empty()
&& self.dirty_messages.is_empty()
&& self.dirty_search.is_empty()
{
if self.dirty.is_empty() && self.dirty_messages.is_empty() {
return;
}
let result = (|| -> Result<(), Box<dyn std::error::Error>> {
@@ -291,29 +196,12 @@ impl LogIndex {
table.insert(commit.id.as_str(), bytes.as_slice())?;
}
}
{
let mut table = txn.open_table(PATHS)?;
for (key, value) in &self.dirty_paths {
let bytes = serde_json::to_vec(value)?;
table.insert(key.as_str(), bytes.as_slice())?;
}
}
{
let mut table = txn.open_table(MESSAGES)?;
for (id, message) in &self.dirty_messages {
table.insert(id.as_str(), message.as_str())?;
}
}
{
let mut postings = txn.open_multimap_table(POSTINGS)?;
let mut indexed = txn.open_table(INDEXED)?;
for (id, keys) in &self.dirty_search {
for key in keys {
postings.insert(key.as_str(), id.as_str())?;
}
indexed.insert(id.as_str(), true)?;
}
}
txn.commit()?;
Ok(())
})();
@@ -321,52 +209,7 @@ impl LogIndex {
tracing::warn!("Git log cache write failed: {error}");
}
self.dirty_messages.clear();
self.dirty_search.clear();
self.dirty.clear();
self.dirty_paths.clear();
}
pub fn path_entry(
&mut self,
repo: &gix::Repository,
id: ObjectId,
path: &str,
) -> IdeResult<Option<(ObjectId, u16)>> {
let memory_key = (id, path.to_string());
if let Some(value) = self.path_memory.get(&memory_key) {
return Ok(*value);
}
let key = format!("{id}\0{path}");
let cached = self.db.as_ref().and_then(|db| {
let txn = db.begin_read().ok()?;
let table = txn.open_table(PATHS).ok()?;
let value = table.get(key.as_str()).ok()??;
serde_json::from_slice::<Option<(String, u16)>>(value.value()).ok()
});
let cached = match cached {
Some(None) => Some(None),
Some(Some((hex, mode))) => ObjectId::from_hex(hex.as_bytes()).ok().map(|id| Some((id, mode))),
None => None,
};
let value = if let Some(value) = cached {
value
} else {
let tree = repo.find_commit(id).map_err(gx)?.tree().map_err(gx)?;
let value = tree
.lookup_entry_by_path(Path::new(path))
.map_err(gx)?
.map(|entry| (entry.object_id(), entry.mode().value()));
if self.db.is_some() {
self.dirty_paths.push((key, value.map(|(id, mode)| (id.to_string(), mode))));
}
value
};
if self.path_memory.len() >= 4096 {
self.flush();
self.path_memory.clear();
}
self.path_memory.insert(memory_key, value);
Ok(value)
}
}
-1
Переглянути файл
@@ -65,7 +65,6 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
inner: std::sync::Mutex::new(cache),
ignored: Default::default(),
log_index: Default::default(),
index_progress: Default::default(),
log_signatures: Default::default(),
}))
}
+28 -2
Переглянути файл
@@ -99,8 +99,6 @@ fn lazy_summaries_seek_and_index_survive_refresh_and_restart() {
let cancel = ide_core::CancellationToken::new();
cancel.cancel();
assert!(repo.log_cancellable(&query, &cancel).is_err());
let progress = repo.index_log(&ide_core::CancellationToken::new()).unwrap();
assert_eq!((progress.indexed, progress.total, progress.running), (70, 70, false));
assert_eq!(repo.log(&LogQuery { text: Some("needle body 5".into()), ..query.clone() }).unwrap().len(), 5);
let new = commit(dir, "b", "new head");
let refreshed = repo.log(&LogQuery { retain_until: Some(ids[0].clone()), ..query.clone() }).unwrap();
@@ -436,3 +434,31 @@ fn multiple_paths_are_simplified_together_at_merges() {
assert_eq!(log[0].graph_parents.as_ref().unwrap().len(), 2);
}
}
#[test]
fn paths_are_literal_and_text_matches_bodies_or_hash_prefixes() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let star = commit(dir, "[a]", "star\n\nBody Needle");
let plain = commit(dir, "a", "plain");
let repo = Repo::discover(dir).unwrap().unwrap();
let ids = |q: LogQuery| repo.log(&q).unwrap().into_iter().map(|c| c.id).collect::<Vec<_>>();
assert_eq!(ids(LogQuery { path: Some("[a]".into()), ..Default::default() }), vec![star.clone()]);
assert_eq!(ids(LogQuery { text: Some("body needle".into()), ..Default::default() }), vec![star.clone()]);
assert!(ids(LogQuery { text: Some("body needle".into()), text_match_case: true, ..Default::default() }).is_empty());
assert_eq!(ids(LogQuery { text: Some(plain[..7].to_uppercase()), ..Default::default() }), vec![plain]);
}
#[test]
fn case_insensitive_text_folds_non_ascii() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let hit = commit(dir, "a", "Ärger ПРИВЕТ");
commit(dir, "a", "other");
let repo = Repo::discover(dir).unwrap().unwrap();
let ids = |q: LogQuery| repo.log(&q).unwrap().into_iter().map(|c| c.id).collect::<Vec<_>>();
assert_eq!(ids(LogQuery { text: Some("ärger привет".into()), ..Default::default() }), vec![hit.clone()]);
assert!(ids(LogQuery { text: Some("ärger".into()), text_match_case: true, ..Default::default() }).is_empty());
}
+8 -7
Переглянути файл
@@ -130,14 +130,15 @@ install it from disk.
Only port themes whose licence allows redistribution, keep their licence file,
and credit the original authors in `authors` and `description`.
### From IntelliJ IDEA (automatic)
### From JetBrains IDEs (automatic)
To use a theme you already have in IntelliJ, open **Settings › Plugins**, gear
To use a theme you already have in a JetBrains IDE, open **Settings › Plugins**, gear
menu:
- **Import Theme from IntelliJ IDE…** lists the theme plugins installed in the
JetBrains IDEs (and Android Studio) on this computer, the theme each IDE uses
first. It reads their settings folders: `~/Library/Application Support/JetBrains`
- **Import Theme from JetBrains IDE…** lists the theme plugins installed in the
JetBrains IDEs (and Android Studio) on this computer, one row per plugin of
each IDE, the plugins of the themes the IDEs use first. It reads the settings
folder of each IDE's newest version: `~/Library/Application Support/JetBrains`
(macOS), `%APPDATA%\JetBrains` (Windows), `~/.config/JetBrains` and
`~/.local/share/JetBrains` (Linux).
- **Import IntelliJ Theme from File…** takes a theme plugin downloaded from the
@@ -146,8 +147,8 @@ menu:
The whole plugin becomes one OpenIDEA theme plugin, `intellij.<plugin id>`, with
each of its themes and their editor schemes; it is installed through the usual
install page and the chosen theme (otherwise the first) is applied. Importing
the plugin again replaces it. Both are actions too (`plugins.importIntellijTheme`,
install page, and the theme in use stays as it is: choose one of its themes in
**Settings › Appearance › Theme**. Importing the plugin again replaces it. Both are actions too (`plugins.importIntellijTheme`,
`plugins.importInstalledIntellijTheme`). The conversion is the one described
below.
+46
Переглянути файл
@@ -186,3 +186,49 @@ test("quick theme menu offers all four palettes and applies their kind", async (
await expect(page.locator("html")).toHaveAttribute("data-theme", palette.kind);
}
});
test("gear › Theme previews the theme under the pointer and keeps the one chosen", async ({ workbench: page }) => {
const html = page.locator("html");
const gear = page.getByRole("button", { name: "IDE and Project Settings", exact: true });
const theme = (label: string) => page.getByRole("menuitemcheckbox", { name: label, exact: true });
await gear.click();
await page.getByRole("menuitem", { name: "Theme", exact: true }).hover();
await theme("Solarized Dark").hover();
await expect(html).toHaveAttribute("data-color-theme", "solarized-dark");
// A plugin's theme previews too.
await theme("Harbor Night").hover();
await expect(html).toHaveAttribute("data-plugin-theme", /harbor-night$/);
await expect(html).not.toHaveAttribute("data-color-theme");
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
await expect(html).not.toHaveAttribute("data-plugin-theme");
await expect(html).toHaveAttribute("data-theme", "light");
await gear.click();
await page.getByRole("menuitem", { name: "Theme", exact: true }).hover();
await theme("One Dark").hover();
await expect(html).toHaveAttribute("data-color-theme", "one-dark");
await theme("One Dark").click();
await expect(html).toHaveAttribute("data-color-theme", "one-dark");
// Chosen, not previewed: the next start-up opens with it.
await expect
.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem("openidea.theme") ?? "{}").colorTheme))
.toBe("one-dark");
});
test("Settings › Appearance › Theme previews the highlighted theme until Cancel", async ({ workbench: page }) => {
const html = page.locator("html");
const dialog = await settings(page);
await page.getByRole("button", { name: "Theme", exact: true }).click();
await page.getByRole("option", { name: "Solarized Dark", exact: true }).hover();
await expect(html).toHaveAttribute("data-color-theme", "solarized-dark");
await page.keyboard.press("Escape");
await expect(html).toHaveAttribute("data-theme", "light");
await expect(html).not.toHaveAttribute("data-color-theme");
// Picked: it shows until Apply or Cancel.
await choose(page, "Theme", "One Dark");
await expect(html).toHaveAttribute("data-color-theme", "one-dark");
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(html).toHaveAttribute("data-theme", "light");
await expect(html).not.toHaveAttribute("data-color-theme");
});
+15 -9
Переглянути файл
@@ -11,9 +11,10 @@ editors, and contribute menus, shortcuts, settings, themes, file icon themes
and languages. Plugins that only contribute data (themes, icons, languages,
menus, settings) need no code at all.
> **Preview.** The plugin system ships as a preview: until it is declared
> stable the API (`openidea:[email protected]`) may still change, and the official
> plugins are versioned `0.x`. See _Evolving the plugin API_ below.
> **Preview.** The plugin system ships as a preview and the official plugins
> are versioned `0.x`. Released API versions only grow: a plugin built for
> `openidea:[email protected]` keeps loading in later 1.x IDEs. See _Evolving the
> plugin API_ below.
```
plugins/
@@ -769,7 +770,7 @@ granted, and starts the approved program.
the package at its root or in its only folder, or a folder's `plugin.toml`;
a zip without a `plugin.toml` there, such as an IntelliJ plugin, is refused; IntelliJ
theme plugins are imported instead: _Import IntelliJ Theme from File…_ and _Import Theme
from IntelliJ IDE…_, see [`docs/plugins/themes.md`](../docs/plugins/themes.md)). The install
from JetBrains IDE…_, see [`docs/plugins/themes.md`](../docs/plugins/themes.md)). The install
page lists every capability and whether the package is signed by a publisher
the marketplace trusts; nothing is copied until you accept.
- **Versions:** installed plugins live in `<app-data>/plugins/<id>/<version>/`
@@ -919,8 +920,8 @@ the API itself follows _Evolving the plugin API_ below.
## 10. Evolving the plugin API
While the plugin system is a preview the API may still change freely. Once it
is declared stable wasmtime decides what stays compatible: it resolves interface names
Released versions are frozen: 1.0.0 shipped with OpenIDEA 0.1.36 and 1.1.0
with 0.1.37. wasmtime decides what stays compatible: it resolves interface names
by semver (a component importing `openidea:plugin/[email protected]` links against a
host defining `@1.1.0`, and the host finds its exports the same way), but
function types must match exactly — a record with another field count, or a
@@ -957,10 +958,15 @@ only grows:
Checked automatically:
- SDK `tests/api_frozen.rs`: `tests/api/<version>/` holds the WIT of each
- SDK `tests/api_frozen.rs`: `tests/api/released/` holds the WIT of the latest
released version; every interface, type, function and world import or
export in it must still exist unchanged in `wit/` (rules 1–3). Copy `wit/`
there when releasing; there is no snapshot before the first release.
export in it must still exist unchanged in `wit/` (rules 1–3). Under the
released version `wit/` must match it exactly, so additions start with a
version bump. Each snapshot passed this check against the one before, so
one snapshot covers every release.
- Releasing: when the `wit/` version changes, copy `wit/*.wit` over
`tests/api/released/` in the release commit. The release workflow refuses a
tag whose `wit/` version differs from the snapshot's.
- `crates/ide-plugin/tests/api_compat.rs`: the versions agree, the SDK's copy
matches, the version check (rules 4, 5); a simulated next-minor host (every
import stubbed at the newer version, plus extra functions and an extra
+1 -1
Переглянути файл
@@ -103,7 +103,7 @@ dependencies = [
[[package]]
name = "openidea-plugin-openidea-checkstyle"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"openidea-plugin",
]
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "openidea-plugin-openidea-checkstyle"
version = "0.1.0"
version = "0.1.1"
edition = "2024"
publish = false
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2f4608630c5e41453458ecee5bc4e2f1994a680d4307a5f002f9dd5ccc04d457
69273e1ddfd2fff9f49c11d4fbdc60a771f8e3befe440e1623c2ab97469aa250
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
id = "openidea.checkstyle"
name = "Checkstyle"
version = "0.1.0"
version = "0.1.1"
description = "Checks Java files with Checkstyle when you save them: problems in the editor and the Problems view, quick fixes for tabs, trailing spaces and missing final newlines."
authors = ["OpenIDEA contributors"]
license = "Apache-2.0"
+62 -6
Переглянути файл
@@ -110,6 +110,26 @@ fn project_of(path: &str) -> Option<Project> {
.max_by_key(|p| p.root().map(|r| r.len()).unwrap_or(0))
}
fn windows_path(path: &str) -> String {
let path = path.replace('\\', "/");
if let Some(rest) = path.strip_prefix("//?/UNC/") {
format!("//{rest}")
} else {
path.strip_prefix("//?/").unwrap_or(&path).to_owned()
}
}
fn report_matches_file(reported: &str, path: &str) -> bool {
// WASI plugins run on every host, so interpret the host's path rather than cfg(windows).
let drive = path.as_bytes().get(1) == Some(&b':') && path.as_bytes()[0].is_ascii_alphabetic();
if drive || path.starts_with("//") || path.starts_with(r"\\") {
let (reported, path) = (windows_path(reported), windows_path(path));
reported == path || path.ends_with(&reported)
} else {
reported == path || path.ends_with(reported)
}
}
/// The configuration for files of `project`.
fn config_for(project: &Project) -> String {
PROJECT_CONFIGS
@@ -138,11 +158,8 @@ impl Checkstyle {
return Err(Error::Failed(format!("checkstyle: {}", out.stderr.lines().next().unwrap_or("no report"))));
}
let report = parse_report(&out.stdout);
let problems = report
.into_iter()
.find(|(f, _)| f == path || path.ends_with(f.as_str()))
.map(|(_, p)| p)
.unwrap_or_default();
let problems =
report.into_iter().find(|(f, _)| report_matches_file(f, path)).map(|(_, p)| p).unwrap_or_default();
let text = project.read_file(path).unwrap_or_default();
let diagnostics: Vec<Diagnostic> = problems.iter().map(|p| diagnostic(p, &text)).collect();
host::publish_diagnostics(path, &diagnostics)?;
@@ -233,7 +250,7 @@ impl Plugin for Checkstyle {
register_plugin!(Checkstyle, providers);
#[cfg(test)]
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use openidea_plugin::ProcessOutput;
@@ -288,6 +305,45 @@ mod tests {
assert_eq!(actions[1].edits[0].1[0].text, " void f() {}");
}
#[test]
fn unix_report_paths_preserve_backslashes() {
assert!(report_matches_file("/project/A\\B.java", "/project/A\\B.java"));
assert!(!report_matches_file("/project/A\\B.java", "/project/A/B.java"));
}
#[test]
fn windows_reports_match_the_saved_file_and_keep_quick_fixes() {
for (root, reported) in [
("C:/project", r"C:\project\src\A.java"),
("C:/project", r"\\?\C:\project\src\A.java"),
("C:/project", r"src\A.java"),
("//server/share/project", r"\\server\share\project\src\A.java"),
("//server/share/project", r"\\?\UNC\server\share\project\src\A.java"),
] {
let host =
MockHost::install().with_capabilities(&["project.read", "events", "storage", "process:checkstyle"]);
host.set_project_root(Some(root));
host.add_file("src/A.java", "class A {\n\tint x;\n void f() {} \n}");
let xml = REPORT.replace("/project/src/A.java", reported);
host.on_process("checkstyle", move |_, _| {
Ok(ProcessOutput { status: Some(1), stdout: xml.clone(), stderr: String::new() })
});
let path = format!("{root}/src/A.java");
let mut plugin = Checkstyle::default();
plugin.handle_events(&[Event::FileSaved(path.clone())], &host.invocation());
assert_eq!(host.diagnostics()[&path].len(), 2, "{reported}");
let doc = Document {
path: path.clone(),
language: "java".into(),
version: 1,
text: "class A {\n\tint x;\n void f() {} \n}".into(),
};
let actions = plugin.code_actions(&doc, Range::new(Position::new(1, 0), Position::new(2, 0)));
assert_eq!(actions.len(), 2, "{reported}");
assert_eq!(actions[0].edits[0].0, path);
}
}
#[test]
fn the_projects_configuration_wins() {
let host = MockHost::install().with_capabilities(&["project.read", "events", "storage", "process:checkstyle"]);
-5
Переглянути файл
@@ -220,11 +220,6 @@ describe("IntelliJ theme import", () => {
],
});
expect(pkg.id).toBe("intellij.com-example-deepsea");
expect(pkg.themes).toEqual([
{ id: "deep-sea", sourceId: "deep-sea-id", name: "Deep Sea" },
{ id: "deep-sea-2", sourceId: "copy-id", name: "Deep Sea" },
{ id: "shallow", sourceId: "light-id", name: "Shallow" },
]);
expect(pkg.files.map((f) => f.path)).toEqual([
"plugin.toml",
"themes/deep-sea.theme.json",
@@ -1,4 +1,4 @@
package openidea:plugin@1.0.0;
package openidea:plugin@1.1.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
@@ -1,4 +1,4 @@
package openidea:plugin@1.0.0;
package openidea:plugin@1.1.0;
interface lifecycle {
use types.{context, error};
@@ -1,4 +1,4 @@
package openidea:plugin@1.0.0;
package openidea:plugin@1.1.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
@@ -8,7 +8,7 @@ interface log {
}
interface ui {
use types.{notification-level};
use types.{error, notification-level};
record status-item {
text: string,
@@ -23,6 +23,10 @@ interface ui {
/// Shows or updates the plugin's status bar item `id` in every window.
set-status-item: func(id: string, item: status-item);
remove-status-item: func(id: string);
/// Copies `text` to the system clipboard. Requires `clipboard`.
copy-to-clipboard: func(text: string) -> result<_, error>;
/// Opens an `http://` or `https://` URL in the user's default browser.
open-url: func(url: string) -> result<_, error>;
}
/// Persistent key-value storage of the plugin (survives restarts and idle
@@ -1,4 +1,4 @@
package openidea:plugin@1.0.0;
package openidea:plugin@1.1.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
@@ -7,7 +7,7 @@
/// or processes beyond WASI's clocks and randomness; everything else goes
/// through the imports below, gated by the capabilities granted in
/// `plugin.toml` (a missing one returns `error::denied`).
package openidea:plugin@1.0.0;
package openidea:plugin@1.1.0;
world plugin {
import log;
@@ -1,4 +1,4 @@
package openidea:plugin@1.0.0;
package openidea:plugin@1.1.0;
/// Editor features a plugin provides for the languages it declares under
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
@@ -1,4 +1,4 @@
package openidea:plugin@1.0.0;
package openidea:plugin@1.1.0;
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
/// as in the editor and LSP.
@@ -1,4 +1,4 @@
package openidea:plugin@1.0.0;
package openidea:plugin@1.1.0;
/// Declarative views: tool windows declared
/// under `[[contributes.views]]` and custom editors under
@@ -133,6 +133,10 @@ interface views {
/// `program` (pinned by a `process:<program>` grant) with `args` in the
/// project root: long-running output (logs) and interactive sessions.
open-terminal: func(title: string, program: string, args: list<string>) -> result<_, error>;
/// Opens `path` (project-relative or absolute, inside the project) in an
/// editor of the window the call came from, the caret at `line` and
/// `column` (0-based; UTF-16 column): a view's links to code.
open-location: func(path: string, line: u32, column: u32) -> result<_, error>;
}
/// The plugin's own settings (`[contributes.settings]`), as the user set them
@@ -1,4 +1,4 @@
package openidea:plugin@1.0.0;
package openidea:plugin@1.1.0;
interface workspace {
use types.{error};
@@ -84,6 +84,8 @@ interface vcs {
/// `none` when the project is not in a repository. Requires `vcs.read`.
status: func(project: borrow<project>) -> result<option<repository-status>, error>;
/// Configured remotes (`name`, fetch `url`), in order. Requires `vcs.read`.
remotes: func(project: borrow<project>) -> result<list<tuple<string, string>>, error>;
/// Fetches all remotes (pruning deleted branches). Requires `vcs.write`.
/// Long-running: call it inside a task.
fetch: func(project: borrow<project>) -> result<_, error>;
+69 -61
Переглянути файл
@@ -3,11 +3,13 @@
//! a field added to a record or a case added to a variant breaks every
//! component built for the release.
//!
//! `tests/api/<version>/` is the WIT of each release, copied when it was
//! frozen. Every interface, type and function in it must still exist in
//! `wit/` with the same definition; additions are fine. When a version is
//! released, copy `wit/` to `tests/api/<that version>/`. Until the first
//! release there is no snapshot and the API may still change freely.
//! `tests/api/released/` is the WIT of the latest released version. Every
//! interface, type and function in it must still exist in `wit/` with the same
//! definition. Additions need a newer version than the snapshot's: under the
//! released version `wit/` must match it exactly. When a version ships, copy
//! `wit/` over the snapshot (the release workflow refuses a tag whose `wit/`
//! version differs from it). Each snapshot passed this check against the one
//! before, so the latest one covers every earlier release.
use std::collections::BTreeMap;
use std::path::Path;
@@ -110,77 +112,83 @@ fn anonymous(r: &Resolve, id: TypeId) -> String {
}
}
/// The frozen releases (`tests/api/<version>/`), none before the first release.
fn releases(root: &Path) -> Vec<std::path::PathBuf> {
match std::fs::read_dir(root.join("tests/api")) {
Ok(dir) => dir.map(|e| e.unwrap().path()).filter(|p| p.is_dir()).collect(),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
Err(e) => panic!("tests/api: {e}"),
}
fn root() -> &'static Path {
Path::new(env!("CARGO_MANIFEST_DIR"))
}
/// The latest released version's WIT.
fn released() -> std::path::PathBuf {
root().join("tests/api/released")
}
/// The `package openidea:[email protected]` version of a WIT directory.
fn version(dir: &Path) -> Vec<u64> {
let src = std::fs::read_to_string(dir.join("plugin.wit")).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
let v = src.lines().find_map(|l| l.trim().strip_prefix("package openidea:plugin@")).unwrap();
v.trim_end_matches(';').split('.').map(|p| p.parse().unwrap()).collect()
}
#[test]
fn the_surface_covers_the_whole_api() {
// Keeps the check below meaningful while there is no release to compare.
let current = surface(&Path::new(env!("CARGO_MANIFEST_DIR")).join("wit"));
assert!(current.len() > 50, "only {} items: did wit/ load?", current.len());
assert!(current.keys().any(|k| k.starts_with("world ")));
assert!(current.keys().any(|k| k.contains("/func ")));
assert!(current.keys().any(|k| k.contains("/type ")));
for dir in [root().join("wit"), released()] {
let items = surface(&dir);
assert!(items.len() > 50, "{}: only {} items: did it load?", dir.display(), items.len());
assert!(items.keys().any(|k| k.starts_with("world ")));
assert!(items.keys().any(|k| k.contains("/func ")));
assert!(items.keys().any(|k| k.contains("/type ")));
}
}
#[test]
fn released_apis_are_unchanged() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let current = surface(&root.join("wit"));
for dir in releases(root) {
let release = surface(&dir);
let version = dir.file_name().unwrap().to_string_lossy().into_owned();
let mut broken = Vec::new();
for (key, was) in &release {
match current.get(key) {
None => broken.push(format!("{key}: removed (was {was})")),
// A world may gain imports and exports; everything else stays as it was. Items are
// compared without their `@version`: a later minor names them `@1.1.0`, and wasmtime
// resolves the release's `@1.0.0` to it.
Some(now) if key.starts_with("world ") => {
let had = |s: &str, part: &str| -> Vec<String> {
let start = s.find(part).unwrap() + part.len();
let end = s[start..].find(']').unwrap() + start;
s[start..end]
.split(", ")
.filter(|x| !x.is_empty())
.map(|x| x.split('@').next().unwrap_or(x).to_owned())
.collect()
};
for part in ["imports [", "exports ["] {
let now = had(now, part);
for item in had(was, part) {
if !now.contains(&item) {
broken.push(format!("{key}: no longer has {item}"));
}
fn the_released_api_is_unchanged() {
let current = surface(&root().join("wit"));
let release = surface(&released());
let mut broken = Vec::new();
for (key, was) in &release {
match current.get(key) {
None => broken.push(format!("{key}: removed (was {was})")),
// A world may gain imports and exports; everything else stays as it was. Items are
// compared without their `@version`: a later minor names them `@1.2.0`, and wasmtime
// resolves the release's `@1.1.0` to it.
Some(now) if key.starts_with("world ") => {
let had = |s: &str, part: &str| -> Vec<String> {
let start = s.find(part).unwrap() + part.len();
let end = s[start..].find(']').unwrap() + start;
s[start..end]
.split(", ")
.filter(|x| !x.is_empty())
.map(|x| x.split('@').next().unwrap_or(x).to_owned())
.collect()
};
for part in ["imports [", "exports ["] {
let now = had(now, part);
for item in had(was, part) {
if !now.contains(&item) {
broken.push(format!("{key}: no longer has {item}"));
}
}
}
Some(now) if now != was => broken.push(format!("{key}:\n was {was}\n now {now}")),
Some(_) => {}
}
Some(now) if now != was => broken.push(format!("{key}:\n was {was}\n now {now}")),
Some(_) => {}
}
assert!(broken.is_empty(), "plugin API {version} changed incompatibly:\n {}", broken.join("\n "));
assert!(release.len() > 50, "{version}: only {} items: did the snapshot load?", release.len());
}
assert!(broken.is_empty(), "the released plugin API changed incompatibly:\n {}", broken.join("\n "));
}
#[test]
fn the_current_api_is_a_release_or_newer_than_all() {
// `wit/` is either a frozen release or the next one; never older.
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let src = std::fs::read_to_string(root.join("wit/plugin.wit")).unwrap();
let current = src.lines().find_map(|l| l.trim().strip_prefix("package openidea:plugin@")).unwrap();
let current: Vec<u64> = current.trim_end_matches(';').split('.').map(|p| p.parse().unwrap()).collect();
for dir in releases(root) {
let name = dir.file_name().unwrap().to_string_lossy().into_owned();
let release: Vec<u64> = name.split('.').map(|p| p.parse().unwrap()).collect();
assert!(release <= current, "tests/api/{name} is newer than wit/ ({current:?})");
fn additions_need_a_newer_version() {
// A component built from `wit/` imports what `wit/` declares; under a released version an
// IDE of that release would lack the additions and refuse it.
let (current, release) = (version(&root().join("wit")), version(&released()));
assert!(current >= release, "wit/ ({current:?}) is older than the released API ({release:?})");
if current == release {
let (now, was) = (surface(&root().join("wit")), surface(&released()));
let added: Vec<_> = now.keys().filter(|k| now.get(*k) != was.get(*k)).collect();
assert!(
added.is_empty(),
"wit/ adds to the released version {release:?}; bump the package version in wit/ \
(and the SDK's copy, ENGINE_VERSION, API_VERSION) first:\n {added:?}"
);
}
}
-1
Переглянути файл
@@ -262,7 +262,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_open_external_log,
vcs::vcs_log_details,
vcs::vcs_log_details_batch,
vcs::vcs_log_index,
vcs::vcs_revision_children,
vcs::vcs_revision_files,
vcs::vcs_commit_files,
-10
Переглянути файл
@@ -142,16 +142,6 @@ pub async fn vcs_log_details_batch(
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_log_index(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
request: Option<RequestId>,
) -> IdeResult<LogIndexProgress> {
ide_host::ops::vcs::vcs_log_index(&state.host, window.label(), repo, request).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_revision_children(
window: Window,
state: State<'_, AppState>,
-7
Переглянути файл
@@ -496,7 +496,6 @@ export const commands = {
vcsOpenExternalLog: (path: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("vcs_open_external_log", { path })),
vcsLogDetails: (repo: string | null, revision: string) => typedError<LogDetails, IdeError>(__TAURI_INVOKE("vcs_log_details", { repo, revision })),
vcsLogDetailsBatch: (repo: string | null, revisions: string[], request: RequestId) => typedError<LogDetails[], IdeError>(__TAURI_INVOKE("vcs_log_details_batch", { repo, revisions, request })),
vcsLogIndex: (repo: string | null, request: number | null) => typedError<LogIndexProgress, IdeError>(__TAURI_INVOKE("vcs_log_index", { repo, request })),
vcsRevisionChildren: (repo: string | null, revision: string, directory: string) => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_revision_children", { repo, revision, directory })),
vcsRevisionFiles: (repo: string | null, revision: string) => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_revision_files", { repo, revision })),
vcsCommitFiles: (repo: string | null, commit: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_commit_files", { repo, commit })),
@@ -4987,12 +4986,6 @@ export type LogDetails = {
fingerprint: string,
};
export type LogIndexProgress = {
indexed: number,
total: number,
running: boolean,
};
export type LogLevel = "debug" | "info" | "warn" | "error";
export type LogLocation = {
+4 -2
Переглянути файл
@@ -63,7 +63,7 @@ import { cloneCaretAbove, cloneCaretBelow } from "./cm/verticalMotion";
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
import { cyclicExpandWord } from "./wordCompletion";
import { qualifiedReference } from "./copyReference";
import { symbolChain } from "./view/outline";
import { declarationChain } from "./view/outline";
import { recordClipboard } from "./clipboardHistory";
import { useDocMeta, useOutline } from "./model/document";
import { fontZoom, setFontZoom, stepFontZoom } from "./cm/prefs";
@@ -414,12 +414,14 @@ function copyReference(view: EditorView, slot: EditorSlot) {
const line = state.doc.lineAt(head);
const meta = slot.model.getMeta();
const outline = useOutline.getState()[slot.model.path] ?? [];
// A package is not a member to qualify: jdtls lists the whole `package …;` statement as one.
const chain = declarationChain(outline, line.number - 1, head - line.from).filter((i) => i.kind !== "package");
const reference = qualifiedReference({
language: meta.language,
path: slot.model.path,
root: useProject.getState().project?.root ?? null,
text: state.doc.toString(),
chain: symbolChain(outline, line.number - 1, head - line.from).map((i) => i.name),
chain: chain.map((i) => i.name),
line: line.number - 1,
});
recordClipboard(reference);
+11 -16
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Edit › Copy Reference (⌥⇧⌘C): the fully qualified name of the symbol at
* the caret, built from the file's outline (symbols enclosing the caret) and
* the language's module conventions; `path:line` where there is no symbol.
* Edit › Copy Reference (⌥⇧⌘C): with the caret on a declaration's name, its
* fully qualified name, built from the file's outline and the language's module
* conventions; anywhere else `path:line`, as in IDEA.
*/
export interface ReferenceInput {
@@ -11,7 +11,7 @@ export interface ReferenceInput {
/** Project root, for project-relative paths and module names. */
root: string | null;
text: string;
/** Names of the outline symbols enclosing the caret, outermost first. */
/** Names of the outline symbols down to the one named at the caret, outermost first; empty off a name. */
chain: string[];
/** 0-based caret line. */
line: number;
@@ -59,42 +59,37 @@ const declared = (text: string, re: RegExp) => re.exec(text)?.[1] ?? null;
export function qualifiedReference(r: ReferenceInput): string {
const fallback = `${relativePath(r.path, r.root)}:${r.line + 1}`;
const chain = r.chain.filter(Boolean);
if (!chain.length) return fallback;
switch (r.language) {
case "java":
case "groovy": {
if (!chain.length) return fallback;
const pkg = declared(r.text, /^\s*package\s+([\w.]+)\s*;?/m);
const [type, ...rest] = chain;
const typePath = [pkg, type].filter(Boolean).join(".");
// `pkg.Outer.Inner#member`: the last symbol is the member unless the caret is in a type only.
// `pkg.Outer.Inner#member`: the last symbol is the member unless the caret is on a type's name.
return rest.length ? `${[typePath, ...rest.slice(0, -1)].join(".")}#${rest[rest.length - 1]}` : typePath;
}
case "kotlin":
case "scala": {
if (!chain.length) return fallback;
const pkg = declared(r.text, /^\s*package\s+([\w.]+)/m);
return [pkg, ...chain].filter(Boolean).join(".");
}
case "csharp": {
if (!chain.length) return fallback;
case "csharp":
return chain.join(".");
}
case "rust": {
if (!chain.length) return rustModulePath(r.path);
case "rust":
return [rustModulePath(r.path), ...chain.map((n) => (n.startsWith("impl") ? rustImplType(n) : n))].join("::");
}
case "python":
return [pythonModulePath(r.path, r.root), ...chain].join(".");
case "go": {
const pkg = declared(r.text, /^\s*package\s+(\w+)/m) ?? stem(r.path);
return chain.length ? [pkg, ...chain].join(".") : fallback;
return [pkg, ...chain].join(".");
}
case "cpp":
case "c":
case "objective-cpp":
case "php":
return chain.length ? chain.join("::") : fallback;
return chain.join("::");
default:
return chain.length ? `${relativePath(r.path, r.root)}:${chain.join(".")}` : fallback;
return `${relativePath(r.path, r.root)}:${chain.join(".")}`;
}
}
+30
Переглянути файл
@@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { cyclicExpandWord, expandCandidates, prefixStart } from "./wordCompletion";
import type { OutlineItem } from "@/platform/ipc";
import { pythonModulePath, qualifiedReference, rustImplType, rustModulePath } from "./copyReference";
import { declarationChain } from "./view/outline";
describe("cyclic expand word", () => {
const text = "alphaOne x alphaTwo y al| alphaThree alphaOne";
@@ -101,5 +103,33 @@ describe("copy reference", () => {
expect(
qualifiedReference({ ...base, root: null, language: "markdown", path: "/x/a.md", text: "", chain: [] }),
).toBe("/x/a.md:5");
expect(qualifiedReference({ ...base, language: "python", path: "/p/pkg/mod.py", text: "", chain: [] })).toBe(
"pkg/mod.py:5",
);
expect(qualifiedReference({ ...base, language: "rust", path: "/p/src/a.rs", text: "", chain: [] })).toBe(
"src/a.rs:5",
);
});
it("names a symbol only with the caret on its name, like IDEA", () => {
const item = (name: string, range: number[], sel: number[], children: OutlineItem[] = []): OutlineItem => ({
name,
detail: null,
kind: "class",
range: { start: { line: range[0]!, col: range[1]! }, end: { line: range[2]!, col: range[3]! } },
selection_range: { start: { line: sel[0]!, col: sel[1]! }, end: { line: sel[2]!, col: sel[3]! } },
children,
});
// class Book { line 0, name at cols 6-10
// void sum() { line 1, name at cols 7-10
// total += 1; line 2
const outline = [item("Book", [0, 0, 4, 1], [0, 6, 0, 10], [item("sum", [1, 2, 3, 3], [1, 7, 1, 10])])];
const names = (line: number, col: number) => declarationChain(outline, line, col).map((i) => i.name);
expect(names(1, 8)).toEqual(["Book", "sum"]);
expect(names(1, 10)).toEqual(["Book", "sum"]);
expect(names(0, 6)).toEqual(["Book"]);
expect(names(2, 6)).toEqual([]);
expect(names(1, 2)).toEqual([]);
expect(names(5, 0)).toEqual([]);
});
});
+8
Переглянути файл
@@ -14,3 +14,11 @@ export function symbolChain(items: readonly OutlineItem[], line: number, col: nu
level = hit.children;
}
}
/** The chain up to the innermost item whose name (selection range) holds (line, col); empty off every name. */
export function declarationChain(items: readonly OutlineItem[], line: number, col: number): OutlineItem[] {
const pos = { line, col };
const chain = symbolChain(items, line, col);
const named = chain.findLastIndex((i) => before(i.selection_range.start, pos) && before(pos, i.selection_range.end));
return chain.slice(0, named + 1);
}
+15 -3
Переглянути файл
@@ -46,9 +46,14 @@
border-bottom: 1px solid var(--border);
flex: none;
min-width: 0;
overflow: hidden;
}
.header > * {
flex: none;
}
/* Shrinks ahead of the meters. */
.title {
flex: 0 1 auto;
flex: 0 1000 auto;
min-width: 0;
font-weight: 600;
color: var(--fg-strong);
@@ -539,11 +544,17 @@
white-space: nowrap;
}
/* Meters that don't fit wrap onto a hidden second row instead of being cut in half. */
.meters {
flex: none;
flex: 0 1 auto;
min-width: 0;
height: 22px;
overflow: hidden;
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
align-content: flex-start;
gap: 0 10px;
color: var(--fg-subtle);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
@@ -552,6 +563,7 @@
.meter {
display: inline-flex;
align-items: center;
height: 22px;
gap: 5px;
}
.usageBar {
+47 -51
Переглянути файл
@@ -1,12 +1,11 @@
/**
* Import Theme from IntelliJ IDE: the theme plugins installed in the JetBrains
* IDEs on this machine, each under its plugin's heading, the plugin of the
* theme in use first. Importing a theme brings every theme of its plugin, as
* installing the plugin in IntelliJ does, and applies the chosen one
* (`importIntellijTheme`). A file can be chosen instead.
* Import Theme from JetBrains IDE: the theme plugins installed in the JetBrains
* IDEs (and Android Studio) on this machine, one row per plugin of each IDE, the
* plugins of the themes in use first. Importing installs the plugin with all its
* themes, as installing it in the IDE does (`importIntellijTheme`); which theme
* to use stays a choice in Settings › Appearance. A file can be chosen instead.
*/
import { useEffect, useState } from "react";
import clsx from "clsx";
import type { InstalledIntellijTheme } from "@/bindings";
import { tx } from "@/platform/i18n";
import { Badge, Dialog, List, Spinner, T } from "@/ui";
@@ -15,28 +14,30 @@ import { closeInstalledIntellijThemes, importIntellijTheme, useIntellijThemesDia
import { errorText } from "./store";
import styles from "./PluginsPage.module.css";
type Row =
| { kind: "plugin"; key: string; plugin: string; ide: string; count: number; first: boolean }
| { kind: "theme"; key: string; theme: InstalledIntellijTheme };
interface PluginRow {
key: string;
plugin: string;
ide: string;
path: string;
themes: InstalledIntellijTheme[];
}
/** A heading per plugin (of an IDE) with its themes under it, in the order found (the one in use first). */
function themeRows(themes: readonly InstalledIntellijTheme[]): Row[] {
const plugins = new Map<string, InstalledIntellijTheme[]>();
/** A row per plugin (of an IDE), in the order found (the one in use first). */
function pluginRows(themes: readonly InstalledIntellijTheme[]): PluginRow[] {
const plugins = new Map<string, PluginRow>();
for (const t of themes) {
const key = `${t.ide}\n${t.path}`;
plugins.set(key, [...(plugins.get(key) ?? []), t]);
const row = plugins.get(key) ?? { key, plugin: t.plugin, ide: t.ide, path: t.path, themes: [] };
plugins.set(key, row);
row.themes.push(t);
}
return [...plugins].flatMap(([key, list], i): Row[] => [
{ kind: "plugin", key, plugin: list[0]!.plugin, ide: list[0]!.ide, count: list.length, first: i === 0 },
...list.map((theme): Row => ({ kind: "theme", key: `${key}\n${theme.themeId}`, theme })),
]);
return [...plugins.values()];
}
function IntellijThemesDialog() {
const [themes, setThemes] = useState<InstalledIntellijTheme[] | null>(null);
const [error, setError] = useState<string | null>(null);
// The first theme, under the first heading.
const [active, setActive] = useState(1);
const [active, setActive] = useState(0);
useEffect(() => {
let live = true;
pluginsBackend()
@@ -54,50 +55,48 @@ function IntellijThemesDialog() {
};
}, []);
const run = (theme?: InstalledIntellijTheme) => {
const run = (path?: string) => {
const { onImported } = useIntellijThemesDialog.getState();
closeInstalledIntellijThemes();
void importIntellijTheme(theme?.path, theme?.themeId).then((id) => id && onImported?.(id));
void importIntellijTheme(path).then((id) => id && onImported?.(id));
};
const rows = themeRows(themes ?? []);
const row = rows[active];
const chosen = row?.kind === "theme" ? row.theme : undefined;
const rows = pluginRows(themes ?? []);
const chosen = rows[active];
return (
<Dialog
open
title="Import Theme from IntelliJ IDE"
title="Import Theme from JetBrains IDE"
width={640}
onClose={closeInstalledIntellijThemes}
buttons={[
{ label: "Choose File…", role: "extra", onClick: () => run() },
{ label: "Cancel", role: "cancel" },
{ label: "Import", role: "default", disabled: !chosen, onClick: () => chosen && run(chosen) },
{ label: "Import", role: "default", disabled: !chosen, onClick: () => chosen && run(chosen.path) },
]}
>
<div className={styles.intellijThemes}>
<p className={styles.muted}>
<T>
Theme plugins installed in the JetBrains IDEs on this computer. Importing a theme brings every theme of its
plugin and applies the chosen one. Colours without an OpenIDEA counterpart keep the default theme colours.
Theme plugins installed in the JetBrains IDEs on this computer. Importing one installs it with all its
themes; choose the theme to use in Settings › Appearance. Colours without an OpenIDEA counterpart keep the
default theme colours.
</T>
</p>
{themes === null ? (
<div className={styles.intellijThemesStatus}>
<Spinner size={14} label="Looking for IntelliJ themes" />
<T>Looking for IntelliJ themes…</T>
<Spinner size={14} label="Looking for JetBrains themes" />
<T>Looking for JetBrains themes…</T>
</div>
) : (
<List
items={rows}
getKey={(r) => r.key}
isSection={(r) => r.kind === "plugin"}
activeIndex={chosen ? active : -1}
onActiveChange={setActive}
rowHeight={28}
sectionHeight={30}
rowHeight={44}
className={styles.intellijThemesList}
aria-label={tx("IntelliJ themes")}
aria-label={tx("JetBrains theme plugins")}
empty={
<div className={styles.intellijThemesStatus} role="note">
{error ?? (
@@ -108,24 +107,21 @@ function IntellijThemesDialog() {
)}
</div>
}
renderSection={(r) =>
r.kind === "plugin" && (
<div className={clsx(styles.intellijPlugin, !r.first && styles.intellijPluginNext)}>
<span className={styles.intellijPluginName}>{r.plugin}</span>
<span>{r.count === 1 ? tx("1 theme") : tx`${r.count} themes`}</span>
<span className={styles.intellijPluginIde}>{r.ide}</span>
renderItem={(r) => {
const count = r.themes.length;
return (
<div className={styles.intellijPlugin}>
<div className={styles.intellijPluginHead}>
<span className={styles.itemMain}>{r.plugin}</span>
{r.themes.some((t) => t.active) && <Badge tone="accent">{tx("In use")}</Badge>}
<span className={styles.intellijPluginIde}>
{count === 1 ? tx("1 theme") : tx`${count} themes`} · {r.ide}
</span>
</div>
<span className={styles.intellijPluginThemes}>{r.themes.map((t) => t.themeName).join(", ")}</span>
</div>
)
}
renderItem={(r) =>
r.kind === "theme" && (
<div className={styles.intellijTheme}>
<span className={styles.itemMain}>{r.theme.themeName}</span>
{r.theme.active && <Badge tone="accent">{tx("In use")}</Badge>}
<span className={styles.muted}>{r.theme.dark ? tx("Dark") : tx("Light")}</span>
</div>
)
}
);
}}
/>
)}
</div>
+13 -20
Переглянути файл
@@ -407,37 +407,30 @@
padding: 8px 10px;
color: var(--fg-muted);
}
.intellijTheme {
display: flex;
flex: 1;
align-items: center;
gap: 8px;
min-width: 0;
}
.intellijTheme > .muted {
flex-shrink: 0;
font-size: var(--fs-small);
}
.intellijPlugin {
display: flex;
flex: 1;
align-items: center;
gap: 8px;
align-self: stretch;
flex-direction: column;
justify-content: center;
gap: 2px;
min-width: 0;
}
/* A line above each plugin but the first, as in IDEA's Theme list. */
.intellijPluginNext {
border-top: 1px solid var(--border);
.intellijPluginHead {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.intellijPluginName {
.intellijPluginThemes {
overflow: hidden;
color: var(--fg-secondary);
font-weight: 600;
color: var(--fg-muted);
font-size: var(--fs-small);
text-overflow: ellipsis;
white-space: nowrap;
}
.intellijPluginIde {
flex-shrink: 0;
margin-left: auto;
color: var(--fg-muted);
font-size: var(--fs-small);
}
+1 -1
Переглянути файл
@@ -569,7 +569,7 @@ function gearMenu(plugins: readonly PluginInfo[], updates: number, actions: Gear
...(actions.canImport
? [
{ kind: "separator" as const },
{ label: "Import Theme from IntelliJ IDE…", run: actions.importInstalledIntellij },
{ label: "Import Theme from JetBrains IDE…", run: actions.importInstalledIntellij },
{ label: "Import IntelliJ Theme from File…", run: actions.importIntellijFile },
]
: []),
+27 -21
Переглянути файл
@@ -41,6 +41,15 @@ const INSTALLED: InstalledIntellijTheme[] = [
dark: true,
active: false,
},
{
ide: "DataGrip 2026.2",
plugin: "Night Owl",
path: "/dg/plugins/NightOwl",
themeId: "owl-id",
themeName: "Night Owl",
dark: true,
active: false,
},
];
let notes: Note[];
@@ -100,8 +109,8 @@ afterEach(() => {
});
describe("IntelliJ theme import", () => {
it("installs the converted plugin through the install page and applies the chosen theme", async () => {
expect(await importIntellijTheme("/downloads/DeepSea.zip", "shallow-id")).toBe(ID);
it("installs the converted plugin through the install page and leaves the theme in use as it is", async () => {
expect(await importIntellijTheme("/downloads/DeepSea.zip")).toBe(ID);
expect(read).toHaveBeenCalledWith("/downloads/DeepSea.zip");
const [name, files] = stage.mock.calls[0]!;
expect(name).toBe(ID);
@@ -111,14 +120,11 @@ describe("IntelliJ theme import", () => {
"themes/shallow.theme.json",
]);
expect(installed).toEqual(["/app/plugins/.downloads/generated"]);
expect(useThemeOverride.getState().theme).toBe(`plugin:${ID}/shallow`);
// Which of its themes to use is the user's choice.
expect(useThemeOverride.getState().theme).toBeNull();
});
it("applies the first theme without a choice, and nothing when the install is declined", async () => {
expect(await importIntellijTheme("/downloads/DeepSea.jar")).toBe(ID);
expect(useThemeOverride.getState().theme).toBe(`plugin:${ID}/deep-sea`);
useThemeOverride.setState({ theme: null });
it("returns nothing when the install is declined", async () => {
setConsentPrompt(async () => null);
expect(await importIntellijTheme("/downloads/DeepSea.jar")).toBeNull();
expect(useThemeOverride.getState().theme).toBeNull();
@@ -152,33 +158,33 @@ describe("IntelliJ theme import", () => {
});
});
describe("Import Theme from IntelliJ IDE", () => {
it("lists the installed themes by plugin, the one in use first, and imports the chosen one", async () => {
describe("Import Theme from JetBrains IDE", () => {
it("lists one row per theme plugin, the one in use first, and imports the chosen plugin", async () => {
const user = userEvent.setup();
const onImported = vi.fn();
render(<IntellijThemesDialogHost />);
act(() => showInstalledIntellijThemes(onImported));
const list = await screen.findByRole("listbox", { name: "IntelliJ themes" });
const list = await screen.findByRole("listbox", { name: "JetBrains theme plugins" });
const options = await waitFor(() => {
const found = Array.from(list.querySelectorAll('[role="option"]'));
expect(found).toHaveLength(2);
return found;
});
// Both under their plugin's heading: importing one brings the plugin's every theme.
expect(within(list).getByText("Deep Sea Themes")).toBeInTheDocument();
expect(within(list).getByText("2 themes")).toBeInTheDocument();
expect(within(list).getByText("IntelliJ IDEA 2025.2")).toBeInTheDocument();
expect(options[0]).toHaveTextContent("Shallow");
// A plugin brings all its themes: they are listed in its row, not offered one by one.
expect(options[0]).toHaveTextContent("Deep Sea Themes");
expect(options[0]).toHaveTextContent("In use");
expect(options[1]).toHaveTextContent("Deep Sea");
expect(options[0]).toHaveTextContent("2 themes · IntelliJ IDEA 2025.2");
expect(options[0]).toHaveTextContent("Shallow, Deep Sea");
expect(options[1]).toHaveTextContent("Night Owl");
expect(options[1]).toHaveTextContent("1 theme · DataGrip 2026.2");
expect(options[1]).not.toHaveTextContent("In use");
await user.click(screen.getByText("Deep Sea"));
await user.click(within(list).getByText("1 theme · DataGrip 2026.2"));
await user.click(screen.getByRole("button", { name: "Import" }));
await waitFor(() => expect(onImported).toHaveBeenCalledWith(ID));
expect(read).toHaveBeenCalledWith("/ij/plugins/DeepSea");
expect(useThemeOverride.getState().theme).toBe(`plugin:${ID}/deep-sea`);
expect(screen.queryByRole("listbox", { name: "IntelliJ themes" })).toBeNull();
expect(read).toHaveBeenCalledWith("/dg/plugins/NightOwl");
expect(useThemeOverride.getState().theme).toBeNull();
expect(screen.queryByRole("listbox", { name: "JetBrains theme plugins" })).toBeNull();
});
it("offers a file when no IDE has theme plugins", async () => {
+1 -1
Переглянути файл
@@ -517,7 +517,7 @@ describe("PluginsPage", () => {
);
const imports = async () => {
await user.click(screen.getByRole("button", { name: "Manage Plugins" }));
const found = ["Import Theme from IntelliJ IDE…", "Import IntelliJ Theme from File…"].filter((name) =>
const found = ["Import Theme from JetBrains IDE…", "Import IntelliJ Theme from File…"].filter((name) =>
screen.queryByRole("menuitem", { name }),
);
act(() => hideContextMenu());
+11 -2
Переглянути файл
@@ -113,10 +113,19 @@ export function activate(): () => void {
},
{
id: "plugins.importInstalledIntellijTheme",
title: "Import Theme from IntelliJ IDE…",
title: "Import Theme from JetBrains IDE…",
category: "Plugins",
icon: "plugin",
keywords: ["intellij", "jetbrains", "theme", "color scheme", "migrate"],
keywords: [
"intellij",
"jetbrains",
"pycharm",
"webstorm",
"android studio",
"theme",
"color scheme",
"migrate",
],
when: "projectOpen",
run: () => showInstalledIntellijThemes(),
},
+8 -16
Переглянути файл
@@ -2,30 +2,26 @@
* Settings › Plugins › Import IntelliJ Theme: an IntelliJ theme plugin (a
* Marketplace `.jar` / `.zip`, a plugin folder of an installed IDE) or a
* `.theme.json` becomes an OpenIDEA theme plugin — read by the host, converted
* here (`intellijTheme.ts`), installed through the usual install page — and
* its theme is applied.
* here (`intellijTheme.ts`), installed through the usual install page. Its
* themes join the others; which one to use is chosen in Settings › Appearance.
*/
import { create } from "zustand";
import { pluginThemeRef } from "@/platform/themes";
import { notifications } from "@/workbench/contributions";
import { setTheme } from "@/workbench/theme";
import { pluginsBackend } from "./backend";
import { intellijThemePackage, type ThemePackage } from "./intellijTheme";
import { intellijThemePackage } from "./intellijTheme";
import { errorText, installFromDisk } from "./store";
/**
* Imports the IntelliJ theme plugin at `path` (asks for a file without one)
* and applies its theme `themeId` (an IntelliJ theme id), or its first.
* Returns the installed plugin's id.
* Imports the IntelliJ theme plugin at `path` (asks for a file without one).
* Returns the installed plugin's id; the theme in use stays as it is.
*/
export async function importIntellijTheme(path?: string, themeId?: string): Promise<string | null> {
export async function importIntellijTheme(path?: string): Promise<string | null> {
const backend = pluginsBackend();
let pkg: ThemePackage;
let dir: string;
try {
const picked = path ?? (await backend.pickIntellijTheme());
if (!picked) return null;
pkg = intellijThemePackage(await backend.readIntellijTheme(picked));
const pkg = intellijThemePackage(await backend.readIntellijTheme(picked));
dir = await backend.stagePackage(pkg.id, pkg.files);
} catch (e) {
notifications().notify({
@@ -36,11 +32,7 @@ export async function importIntellijTheme(path?: string, themeId?: string): Prom
});
return null;
}
const id = await installFromDisk(dir);
if (!id) return null;
const theme = pkg.themes.find((t) => t.sourceId === themeId) ?? pkg.themes[0];
if (theme) await setTheme(pluginThemeRef(id, theme.id));
return id;
return installFromDisk(dir);
}
interface DialogState {
+3 -7
Переглянути файл
@@ -384,8 +384,6 @@ export interface ThemePackage {
id: string;
name: string;
files: { path: string; text: string }[];
/** The package's themes: their id here and in the IntelliJ plugin (`sourceId`). */
themes: { id: string; sourceId: string; name: string }[];
}
/** `2.3` → `2.3.0`; IntelliJ plugin versions are not always semver. */
@@ -397,16 +395,15 @@ function semver(version: string | null): string {
/** An OpenIDEA theme plugin (`intellij.<plugin>`) with every theme of an IntelliJ theme plugin. */
export function intellijThemePackage(source: IntellijThemeSource): ThemePackage {
const ids = new Set<string>();
const converted = source.themes.map((t) => {
const themes = source.themes.map((t) => {
const c = convertIntellijTheme(t.theme, t.editorScheme ?? undefined);
let id = c.theme.id;
for (let n = 2; ids.has(id); n++) id = `${c.theme.id.slice(0, 44)}-${n}`;
ids.add(id);
c.theme.id = id;
return { sourceId: t.id, converted: c };
return c;
});
if (converted.length === 0) throw new Error("The plugin has no themes");
const themes = converted.map((c) => c.converted);
if (themes.length === 0) throw new Error("The plugin has no themes");
// Package metadata, not UI text: the plugin list shows it as written.
const description = `${source.name}, imported from an IntelliJ theme plugin.`;
const info: ThemePackageInfo = {
@@ -427,6 +424,5 @@ export function intellijThemePackage(source: IntellijThemeSource): ThemePackage
...(c.scheme ? [{ path: `themes/${c.theme.id}.scheme.json`, text: json(c.scheme) }] : []),
]),
],
themes: converted.map(({ sourceId, converted: c }) => ({ id: c.theme.id, sourceId, name: c.theme.name })),
};
}
+3 -1
Переглянути файл
@@ -171,16 +171,18 @@ export interface SelectProps<V extends string> {
options: readonly SelectOption<V>[];
onChange: (value: V) => void;
disabled?: boolean;
onPreview?: (value: V | null) => void;
"aria-label"?: string;
}
export function Select<V extends string>({ value, options, onChange, disabled, ...aria }: SelectProps<V>) {
export function Select<V extends string>({ value, options, onChange, disabled, onPreview, ...aria }: SelectProps<V>) {
return (
<UiSelect<V>
value={value}
options={options}
onChange={onChange}
disabled={disabled}
onPreview={onPreview}
className={styles.select}
aria-label={aria["aria-label"]}
/>
+19 -2
Переглянути файл
@@ -6,7 +6,7 @@
*/
import { FontPicker } from "../components/FontPicker";
import { useId, useRef, useState, type ReactNode } from "react";
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
import clsx from "clsx";
import { shortcutLabel } from "@/platform/keymap";
import { usePlatform } from "@/platform/platformInfo";
@@ -33,7 +33,8 @@ import { HTTP_PROXY_PAGE } from "./httpProxy";
import styles from "./Behavior.module.css";
import { LOCALES, SUPPORTED_LOCALES, tx, useT } from "@/platform/i18n";
import { BUILTIN_THEMES, useContributedIconThemes } from "@/platform/themes";
import { originDetail, themeSelectOptions, useThemeChoices } from "@/workbench/theme";
import { currentThemeChoice, originDetail, previewTheme, themeSelectOptions, useThemeChoices } from "@/workbench/theme";
import { themePreview } from "@/workbench/quickSwitch";
const BUILTIN_THEME_LABELS = BUILTIN_THEMES.map((t) => t.label);
@@ -62,12 +63,28 @@ function ThemeRow() {
const matched = useLabelMatch("Sync with OS");
const choices = useThemeChoices();
const shown: ConcreteTheme = theme === "system" ? "light" : theme;
// The theme under the pointer shows as in Quick Switch; the one picked here shows until Apply or Cancel.
const picker = useMemo(() => themePreview(), []);
const previewed = useRef(false);
useEffect(
() => () => {
if (previewed.current) previewTheme(null);
},
[],
);
const preview = (id: ConcreteTheme | null) => {
previewed.current = true;
if (id !== null) return picker.preview(id);
picker.restore();
if (shown !== currentThemeChoice()) previewTheme(shown);
};
return (
<Row label="Theme">
<Select<ConcreteTheme>
value={shown}
options={themeSelectOptions(choices, shown)}
onChange={setTheme}
onPreview={preview}
aria-label="Theme"
disabled={sync}
/>
-2
Переглянути файл
@@ -49,7 +49,6 @@ import {
import { hasPrimaryModifier } from "@/platform/keymap";
import { laneColor, reachableFrom, type GraphRow, type GraphSegment } from "./graph";
import { nextSpeedMatch } from "./logSearch";
import { LogIndexStatus } from "./logIndex";
import { presentLogGraph } from "./logPresentation";
import {
closeLogTab,
@@ -328,7 +327,6 @@ export function LogView() {
<SplitPanel id="commits" defaultSize="54%" minSize="25%">
<div className={styles.log}>
<FilterBar />
<LogIndexStatus repositories={repo} />
<CommitList />
</div>
</SplitPanel>
-1
Переглянути файл
@@ -23,7 +23,6 @@ vi.mock("@/platform/ipc", async (original) => {
status: "ok",
data: await Promise.all(ids.map(async () => (await api.details()).data)),
}),
vcsLogIndex: () => ok({ indexed: 0, total: 0, running: false }),
vcsDiffRevisions: (...args: unknown[]) => api.diff(...args),
},
};
+12
Переглянути файл
@@ -305,6 +305,18 @@
.manageRowSelected:hover {
background: var(--bg-list-selected);
}
/* A fixed slot, so the names line up whether or not a row is marked. */
.worktreeMark {
display: flex;
flex: none;
width: 14px;
margin-right: -4px;
}
/* The branch keeps its width; the path is what gets cut short. */
.worktreeName {
flex: none;
max-width: 40%;
}
.comparisonDialog > [data-dialog-body] {
display: flex;
+9 -2
Переглянути файл
@@ -5,12 +5,13 @@ import type { Branch, MergeOptions, Remote, Worktree } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { Checkbox, Dialog, IconButton, Input, Select, T, type SelectOption } from "@/ui";
import { Checkbox, Dialog, Icon, IconButton, Input, Select, T, type SelectOption } from "@/ui";
import { sortLocal, sortRemote } from "./branches";
import { conflictActions, openConflictsInstead, validateBranchName } from "./branchOps";
import { confirmDialog, openDialog } from "./dialogs";
import { errorMessage, runOp, runRemote, saveAll } from "./ops";
import { currentRepo, loadBranches, refreshNow, repoName, selectRepo, useVcs } from "./store";
import { isCurrentWorktree } from "./worktrees";
import styles from "./common.module.css";
import { tx } from "@/platform/i18n";
@@ -660,7 +661,13 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
onClick={() => setSelected(w.path)}
onDoubleClick={() => void executeAction("file.openProjectPath", w.path)}
>
<span className={styles.fileName}>{w.branch ?? (w.head ? w.head.slice(0, 8) : <T>(bare)</T>)}</span>
{/* The worktree this window works in, as IDEA marks it. */}
<span className={styles.worktreeMark}>
{isCurrentWorktree(w.path, repo) && <Icon name="check" size={14} label={tx("Current worktree")} />}
</span>
<span className={clsx(styles.fileName, styles.worktreeName)}>
{w.branch ?? (w.head ? w.head.slice(0, 8) : <T>(bare)</T>)}
</span>
<span className={clsx(styles.fileDir, styles.mono)}>{w.path}</span>
{(w.main || w.locked || w.prunable) && (
<span className={styles.fileDir}>{w.main ? "main" : w.locked ? tx("locked") : tx("prunable")}</span>
-110
Переглянути файл
@@ -1,110 +0,0 @@
import { useEffect } from "react";
import { create } from "zustand";
import type { LogIndexProgress } from "@/bindings";
import { call, commands, nextRequestId, type RequestId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { useVcs } from "./store";
import { IconButton } from "@/ui";
interface Job {
version?: number;
restart?: boolean;
users: number;
request: RequestId | null;
paused: boolean;
progress: LogIndexProgress;
timer?: ReturnType<typeof setInterval>;
}
const jobs = new Map<string, Job>();
const revision = create<{ value: number }>(() => ({ value: 0 }));
const notify = () => revision.setState((s) => ({ value: s.value + 1 }));
function start(repo: string, job: Job) {
if (job.paused) return;
if (job.request != null) {
job.restart = true;
return;
}
const request = nextRequestId();
job.request = request;
job.progress = { ...job.progress, running: true };
job.timer = setInterval(() => {
void call(commands.vcsLogIndex(repo, null))
.then((progress) => {
if (job.request === request) {
job.progress = progress;
notify();
}
})
.catch(() => undefined);
}, 750);
void call(commands.vcsLogIndex(repo, request))
.then(
(progress) => {
job.progress = progress;
},
() => {
job.progress = { ...job.progress, running: false };
},
)
.finally(() => {
if (job.request !== request) return;
job.request = null;
clearInterval(job.timer);
if (job.restart && job.users && !job.paused) {
job.restart = false;
start(repo, job);
}
notify();
});
notify();
}
/** Visible log scopes share one background job per repository. */
export function LogIndexStatus({ repositories }: { repositories: readonly string[] }) {
revision((s) => s.value);
const version = useVcs((s) => s.version);
useEffect(() => {
for (const repo of repositories) {
const job: Job = jobs.get(repo) ?? {
users: 0,
request: null,
paused: false,
progress: { indexed: 0, total: 0, running: false },
};
jobs.set(repo, job);
const first = job.users++ === 0;
if (first || job.version !== version) {
job.version = version;
start(repo, job);
}
}
return () => {
for (const repo of repositories) {
const job = jobs.get(repo)!;
if (--job.users === 0) {
clearInterval(job.timer);
if (job.request != null) void commands.cancelRequest(job.request).catch(() => undefined);
}
}
};
}, [repositories, version]);
return repositories.map((repo) => {
const job = jobs.get(repo);
if (!job || (!job.paused && !job.progress.running)) return null;
return (
<div key={repo} role="status" style={{ display: "flex", alignItems: "center", gap: 6 }}>
{tx`Indexing Git log: ${job.progress.indexed} / ${job.progress.total}`}
<IconButton
icon={job.paused ? "play" : "pause"}
title={job.paused ? "Resume Indexing" : "Pause Indexing"}
onClick={() => {
job.paused = !job.paused;
if (job.paused && job.request != null) void commands.cancelRequest(job.request).catch(() => undefined);
else start(repo, job);
notify();
}}
/>
</div>
);
});
}
+18
Переглянути файл
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { isCurrentWorktree } from "./worktrees";
describe("isCurrentWorktree", () => {
it("matches the repository root this window works in", () => {
expect(isCurrentWorktree("/work/app", "/work/app")).toBe(true);
expect(isCurrentWorktree("/work/app-wt", "/work/app")).toBe(false);
expect(isCurrentWorktree("/work/app/", "/work/app")).toBe(true);
expect(isCurrentWorktree("/work/app", null)).toBe(false);
});
it("ignores the drive letter's case and separators on Windows", () => {
expect(isCurrentWorktree("c:/Work/app", "C:/Work/app")).toBe(true);
expect(isCurrentWorktree("C:\\Work\\app", "C:/Work/app")).toBe(true);
// Only drive paths: elsewhere the case is part of the name.
expect(isCurrentWorktree("/Work/App", "/work/app")).toBe(false);
});
});
+13
Переглянути файл
@@ -0,0 +1,13 @@
/**
* Whether worktree `path` (as `git worktree list` prints it) is the repository root `root`
* this window works in. Git prints `C:/…` with the drive in either case, so drive paths
* compare case-insensitively; a trailing slash doesn't count.
*/
export function isCurrentWorktree(path: string, root: string | null | undefined): boolean {
if (!root) return false;
const norm = (p: string) => {
const s = p.replace(/\\/g, "/").replace(/(.)\/+$/, "$1");
return /^[A-Za-z]:\//.test(s) ? s.toLowerCase() : s;
};
return norm(path) === norm(root);
}
+6 -9
Переглянути файл
@@ -5807,18 +5807,18 @@
"Unsigned": "Sin firmar",
"Roll Back to {previousVersion}": "Revertir a {previousVersion}",
"Install Plugin from Package File…": "Instalar plugin desde archivo de paquete…",
"Import Theme from IntelliJ IDE…": "Importar tema desde IntelliJ IDE…",
"Import Theme from JetBrains IDE…": "Importar tema desde un IDE de JetBrains…",
"Import IntelliJ Theme from File…": "Importar tema de IntelliJ desde archivo…",
"Import Theme from IntelliJ IDE": "Importar tema desde IntelliJ IDE",
"Import Theme from JetBrains IDE": "Importar tema desde un IDE de JetBrains",
"Import IntelliJ Theme": "Importar tema de IntelliJ",
"IntelliJ theme plugin or theme file": "Plugin de tema o archivo de tema de IntelliJ",
"Could not import the IntelliJ theme": "No se pudo importar el tema de IntelliJ",
"Import": "Importar",
"In use": "En uso",
"IntelliJ themes": "Temas de IntelliJ",
"Looking for IntelliJ themes": "Buscando temas de IntelliJ",
"Looking for IntelliJ themes…": "Buscando temas de IntelliJ…",
"Theme plugins installed in the JetBrains IDEs on this computer. Importing a theme brings every theme of its plugin and applies the chosen one. Colours without an OpenIDEA counterpart keep the default theme colours.": "Plugins de temas instalados en los IDE de JetBrains en este equipo. Al importar un tema se incluyen todos los temas de su plugin y se aplica el elegido. Los colores sin equivalente en OpenIDEA conservan los colores del tema predeterminado.",
"JetBrains theme plugins": "Plugins de temas de JetBrains",
"Looking for JetBrains themes": "Buscando temas de JetBrains",
"Looking for JetBrains themes…": "Buscando temas de JetBrains…",
"Theme plugins installed in the JetBrains IDEs on this computer. Importing one installs it with all its themes; choose the theme to use in Settings › Appearance. Colours without an OpenIDEA counterpart keep the default theme colours.": "Plugins de temas instalados en los IDE de JetBrains en este equipo. Al importar uno se instala con todos sus temas; elija el tema que desea usar en Configuración › Apariencia. Los colores sin equivalente en OpenIDEA conservan los colores del tema predeterminado.",
"1 theme": "1 tema",
"{count} themes": "{count} temas",
"No theme plugins found in JetBrains IDEs on this computer. Choose a theme plugin downloaded from the JetBrains Marketplace (.jar or .zip) or a .theme.json file instead.": "No se encontraron plugins de temas en los IDE de JetBrains en este equipo. En su lugar, elija un plugin de tema descargado de JetBrains Marketplace (.jar o .zip) o un archivo .theme.json.",
@@ -6164,9 +6164,6 @@
"Shallow history boundary": "Límite de historial superficial (shallow)",
"All Parents": "Todos los padres",
"Show Commit Bookmark": "Mostrar marcador de confirmación",
"Indexing Git log: {indexed} / {total}": "Indexando registro de Git: {indexed} / {total}",
"Resume Indexing": "Reanudar indexación",
"Pause Indexing": "Pausar indexación",
"Incompatible": "Incompatible",
"Needs plugin API {engine}. Update OpenIDEA to install it.": "Requiere la API de plugins {engine}. Actualice OpenIDEA para instalarlo.",
"Icon Themes": "Temas de iconos",
+8 -10
Переглянути файл
@@ -2707,6 +2707,7 @@
"New Worktree…": "新建工作树…",
"Worktrees…": "工作树…",
"Worktrees": "工作树",
"Current worktree": "当前工作树",
"New Worktree": "新建工作树",
"Git Remotes": "Git 远程",
"Define Remote": "定义远程",
@@ -5842,18 +5843,18 @@
"Unsigned": "未签名",
"Roll Back to {previousVersion}": "回滚到 {previousVersion}",
"Install Plugin from Package File…": "从插件包文件安装…",
"Import Theme from IntelliJ IDE…": "从 IntelliJ IDE 导入主题…",
"Import Theme from JetBrains IDE…": "从 JetBrains IDE 导入主题…",
"Import IntelliJ Theme from File…": "从文件导入 IntelliJ 主题…",
"Import Theme from IntelliJ IDE": "从 IntelliJ IDE 导入主题",
"Import Theme from JetBrains IDE": "从 JetBrains IDE 导入主题",
"Import IntelliJ Theme": "导入 IntelliJ 主题",
"IntelliJ theme plugin or theme file": "IntelliJ 主题插件或主题文件",
"Could not import the IntelliJ theme": "无法导入 IntelliJ 主题",
"Import": "导入",
"In use": "使用中",
"IntelliJ themes": "IntelliJ 主题",
"Looking for IntelliJ themes": "正在查找 IntelliJ 主题",
"Looking for IntelliJ themes…": "正在查找 IntelliJ 主题…",
"Theme plugins installed in the JetBrains IDEs on this computer. Importing a theme brings every theme of its plugin and applies the chosen one. Colours without an OpenIDEA counterpart keep the default theme colours.": "此计算机上 JetBrains IDE 中安装的主题插件。导入某个主题会一并导入其插件的全部主题,并应用所选主题。没有对应 OpenIDEA 颜色的项保留默认主题的颜色。",
"JetBrains theme plugins": "JetBrains 主题插件",
"Looking for JetBrains themes": "正在查找 JetBrains 主题",
"Looking for JetBrains themes…": "正在查找 JetBrains 主题…",
"Theme plugins installed in the JetBrains IDEs on this computer. Importing one installs it with all its themes; choose the theme to use in Settings › Appearance. Colours without an OpenIDEA counterpart keep the default theme colours.": "此计算机上 JetBrains IDE 中安装的主题插件。导入后会安装该插件及其全部主题;要使用的主题请在“设置 › 外观”中选择。没有对应 OpenIDEA 颜色的项保留默认主题的颜色。",
"1 theme": "1 个主题",
"{count} themes": "{count} 个主题",
"No theme plugins found in JetBrains IDEs on this computer. Choose a theme plugin downloaded from the JetBrains Marketplace (.jar or .zip) or a .theme.json file instead.": "在此计算机上的 JetBrains IDE 中未找到主题插件。请改为选择从 JetBrains Marketplace 下载的主题插件(.jar 或 .zip)或 .theme.json 文件。",
@@ -6199,9 +6200,6 @@
"Shallow history boundary": "浅克隆历史边界",
"All Parents": "所有父提交",
"Show Commit Bookmark": "显示提交书签",
"Indexing Git log: {indexed} / {total}": "正在索引 Git 日志:{indexed} / {total}",
"Resume Indexing": "继续索引",
"Pause Indexing": "暂停索引",
"Incompatible": "不兼容",
"Needs plugin API {engine}. Update OpenIDEA to install it.": "需要插件 API {engine}。请更新 OpenIDEA 后再安装。",
"Icon Themes": "图标主题",
@@ -6227,7 +6225,7 @@
"Last Page": "最后一页",
"{first}-{last} of {total}": "{first}-{last},共 {total}",
"Model & effort settings": "模型与推理强度",
"Logcat": "Logcat",
"Logcat": "Logcat 日志",
"Device": "设备",
"No devices": "没有设备",
"Minimum level": "最低级别",
+12 -1
Переглянути файл
@@ -1,4 +1,4 @@
import { useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import clsx from "clsx";
import { Icon, type IconName } from "./icons";
import { Popup } from "./Popup";
@@ -33,6 +33,8 @@ export interface SelectProps<V extends string = string> {
renderValue?: (option: SelectOption<V> | undefined) => ReactNode;
/** Show a search box in the popup (useful for long option lists). */
searchable?: boolean;
/** The option under the pointer or keyboard while the list is open; `null` once it closes. */
onPreview?: (value: V | null) => void;
}
const TYPE_AHEAD_MS = 800;
@@ -59,6 +61,7 @@ export function Select<V extends string = string>({
className,
renderValue,
searchable = false,
onPreview,
...aria
}: SelectProps<V>) {
const tx = useTx();
@@ -112,6 +115,14 @@ export function Select<V extends string = string>({
const activeIndex =
filtered[active] && !unavailable(filtered[active]!) ? active : filtered.findIndex((o) => !unavailable(o));
const previewed = open ? (filtered[activeIndex]?.value ?? null) : null;
const lastPreview = useRef<V | null>(null);
useEffect(() => {
if (previewed === lastPreview.current) return;
lastPreview.current = previewed;
onPreview?.(previewed);
}, [previewed, onPreview]);
const openPopup = () => {
setQuery("");
setActive(
+25 -13
Переглянути файл
@@ -23,7 +23,7 @@ import {
import { WindowControls } from "./WindowControls";
import { usePlatform } from "@/platform/platformInfo";
import { projectInitials } from "./projectColor";
import { keymapItems, themeItems, VIEW_MODE_ITEMS } from "./quickSwitch";
import { keymapItems, themeItems, themePreview, type ThemePreview, VIEW_MODE_ITEMS } from "./quickSwitch";
import { useContributedThemes } from "@/platform/themes";
import { currentThemeChoice, useThemeOverride } from "./theme";
import styles from "./TitleBar.module.css";
@@ -147,13 +147,18 @@ export function customizeToolbarItems(
];
}
/** IDEA's main toolbar gear: Run Anything, Settings, Plugins, quick switches, toolbar customization, updates. */
/**
* IDEA's main toolbar gear: Run Anything, Settings, Plugins, quick switches, toolbar customization, updates.
* With `preview`, a theme under the pointer shows as in Quick Switch.
*/
export function gearMenuItems(
themeId: string,
keymapId: string,
customKeymaps: string[],
customize: MenuItem[] = [{ kind: "action", action: "toolbar.customize", label: "Customize Toolbar…" }],
preview?: ThemePreview,
): MenuItem[] {
const restore = preview && (() => preview.restore());
return [
{ kind: "action", action: "runAnything.show" },
{ kind: "separator" },
@@ -163,20 +168,25 @@ export function gearMenuItems(
{
id: "gear.theme",
label: "Theme",
submenu: [...themeItems(themeId), { kind: "separator" }, { kind: "action", action: "settings.appearance" }],
submenu: [
...themeItems(themeId, preview),
{ kind: "separator" },
{ kind: "action", action: "settings.appearance" },
],
},
{
id: "gear.keymap",
label: "Keymap",
onActive: restore,
submenu: [
...keymapItems(keymapId, customKeymaps),
{ kind: "separator" },
{ kind: "action", action: "settings.keymap", label: "Configure Keymap…" },
],
},
{ id: "gear.viewMode", label: "View Mode", submenu: VIEW_MODE_ITEMS },
{ id: "gear.viewMode", label: "View Mode", onActive: restore, submenu: VIEW_MODE_ITEMS },
{ kind: "separator" },
{ id: "gear.customizeToolbar", label: "Customize Main Toolbar", submenu: customize },
{ id: "gear.customizeToolbar", label: "Customize Main Toolbar", onActive: restore, submenu: customize },
{ kind: "separator" },
{ kind: "action", action: "app.checkForUpdates" },
];
@@ -205,12 +215,20 @@ function GearButton({ customize }: { customize: MenuItem[] }) {
const preset = useKeymap((s) => s.preset);
const customs = settings?.customKeymaps;
useContributedThemes((s) => s.themes);
// One preview per opening: a theme shown from it goes away with the menu unless chosen.
const preview = useMemo(() => (open ? themePreview() : undefined), [open]);
const items = gearMenuItems(
currentThemeChoice(),
typeof settings?.keymap === "string" ? settings.keymap : preset,
customs && typeof customs === "object" ? Object.keys(customs) : [],
customize,
preview,
);
const close = () => {
setOpen(false);
// A chosen theme runs right after the menu closes: let it choose first.
queueMicrotask(() => preview?.end());
};
return (
<>
<IconButton
@@ -221,15 +239,9 @@ function GearButton({ customize }: { customize: MenuItem[] }) {
className={styles.tool}
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
/>
<Menu
open={open}
onClose={() => setOpen(false)}
anchor={ref}
items={items}
aria-label="IDE and Project Settings"
onClick={() => (open ? close() : setOpen(true))}
/>
<Menu open={open} onClose={close} anchor={ref} items={items} aria-label="IDE and Project Settings" />
</>
);
}
+5 -3
Переглянути файл
@@ -218,7 +218,12 @@ export function currentThemeChoice(): ThemeChoiceId {
: resolveThemeChoice(useProject.getState().settings?.appearance as AppearanceLike | undefined, prefersLight());
}
/** A previewed theme is not the next start-up's (`rememberStartupTheme`). */
let previewing = false;
export async function setTheme(next: ThemeSetting) {
// A theme chosen while previewed is the next start-up's.
previewing = false;
useThemeOverride.setState({ theme: next });
if (!isTauri()) return;
try {
@@ -233,9 +238,6 @@ export async function setTheme(next: ThemeSetting) {
}
}
/** A previewed theme is not the next start-up's (`rememberStartupTheme`). */
let previewing = false;
/**
* Shows `id` in this window without selecting it (Quick Switch's instant
* theme switch); `null` shows the selected theme again. Nothing is saved and