дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-25 10:54:44 +02:00
Порівняти коміти
3
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
3d6f648de3 | ||
|
|
ad7fc70df5 | ||
|
|
ffe14e22cd |
No files matched your search
@@ -9,8 +9,7 @@
|
||||
|
||||
<!-- Required. Commands you actually ran and their results; what else this could
|
||||
affect and how you checked it still works.
|
||||
Visible UI changes: before/after screenshots (not for removed UI or copy-only
|
||||
changes). Multi-step interactions: a recording.
|
||||
UI changes: before/after screenshots. Multi-step interactions: a recording.
|
||||
Backend changes: logs or command output. -->
|
||||
|
||||
## Review focus
|
||||
|
||||
@@ -7,9 +7,6 @@ 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.
|
||||
@@ -22,50 +19,8 @@ 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:
|
||||
@@ -107,9 +62,6 @@ 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
|
||||
@@ -125,9 +77,6 @@ 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
|
||||
@@ -177,9 +126,6 @@ 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
|
||||
@@ -189,9 +135,6 @@ 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
|
||||
@@ -209,9 +152,6 @@ 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
|
||||
|
||||
@@ -11,7 +11,10 @@ name: Language smoke
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: &paths
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened]
|
||||
paths:
|
||||
- "crates/**"
|
||||
- "languages/**"
|
||||
- "fixtures/**"
|
||||
@@ -24,10 +27,6 @@ on:
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- ".github/workflows/language-smoke.yml"
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened]
|
||||
paths: *paths
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
|
||||
@@ -37,16 +37,6 @@ 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
|
||||
|
||||
+1
-2
@@ -51,8 +51,7 @@ 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, when the change alters what users
|
||||
see, before/after screenshots (not for UI removed along with a feature, copy-only or non-visual changes).
|
||||
**How it was verified** section with commands run, results and (for UI) before/after screenshots.
|
||||
Unclear product decisions → `needs-decision` and stop.
|
||||
|
||||
## Skills
|
||||
|
||||
@@ -25,9 +25,8 @@ 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. 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.
|
||||
and what else the change could affect. UI changes need before/after screenshots;
|
||||
multi-step interactions need a recording.
|
||||
- If a change needs a product decision you can't make, ask in the issue and stop
|
||||
rather than guessing.
|
||||
|
||||
|
||||
Створено
@@ -6379,7 +6379,6 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"windows",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
|
||||
+1
-8
@@ -16,7 +16,7 @@
|
||||
·
|
||||
<a href="#plugins">Plugins</a>
|
||||
·
|
||||
<a href="#community">Community</a>
|
||||
<a href="https://discord.gg/2Zy4yn7gP">Discord</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
@@ -57,13 +57,6 @@ Install them from Settings › Plugins, or start your own with
|
||||
`openidea-plugin new` — see [Writing OpenIDEA plugins](plugins/README.md) and
|
||||
the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
## Community
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src="docs/assets/wechat-group.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE). Bundled third-party assets are listed in [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
@@ -440,9 +440,7 @@ pub fn load(root: &Path) -> Option<GradleModel> {
|
||||
|
||||
/// Loads exactly this build, without searching its child folders.
|
||||
pub fn load_build(root: &Path, dir: &Path) -> Option<GradleModel> {
|
||||
// Linked builds are saved with forward slashes; rebuild the path so the launcher
|
||||
// and module folders use the platform's separators.
|
||||
let dir: PathBuf = root.join(dir).components().collect();
|
||||
let dir = root.join(dir);
|
||||
if !SETTINGS_FILES.iter().chain(BUILD_FILES).any(|name| dir.join(name).is_file()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -86,8 +86,6 @@ 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.
|
||||
@@ -137,7 +135,6 @@ impl Host {
|
||||
requests: Default::default(),
|
||||
project_requests: RwLock::default(),
|
||||
closing: Default::default(),
|
||||
open_locks: Default::default(),
|
||||
};
|
||||
host.apply_proxy();
|
||||
host
|
||||
@@ -404,13 +401,6 @@ 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);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Project-incarnation notebook ownership and whole-batch execution admission.
|
||||
use crate::ops::Channel;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, IpcPath, SharedSink};
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, SharedSink};
|
||||
use ide_notebook::kernel::{KernelManager, KernelOutput};
|
||||
use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot};
|
||||
use parking_lot::Mutex;
|
||||
@@ -17,7 +17,7 @@ use tokio::sync::{Mutex as AsyncMutex, watch};
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NotebookOutputEvent {
|
||||
pub id: String,
|
||||
pub path: IpcPath,
|
||||
pub path: String,
|
||||
pub cell: String,
|
||||
pub msg_id: String,
|
||||
pub kind: String,
|
||||
@@ -536,7 +536,7 @@ fn commit_output(
|
||||
};
|
||||
Ok(Some(NotebookOutputEvent {
|
||||
id: document.id.clone(),
|
||||
path: document.path.clone().into(),
|
||||
path: document.path.to_string_lossy().into_owned(),
|
||||
cell: cell.to_owned(),
|
||||
msg_id: output.msg_id,
|
||||
kind: output.kind,
|
||||
@@ -592,16 +592,6 @@ mod tests {
|
||||
other.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_notebook_path_reaches_the_ui_as_the_project_tree_names_it() {
|
||||
let (dir, service, _) = fixture();
|
||||
let ui_path =
|
||||
format!("{}/session.ipynb", ide_core::ipc_path::to_ipc(&dunce::canonicalize(dir.path()).unwrap()));
|
||||
let snapshot = service.open(Path::new(&ui_path)).unwrap();
|
||||
assert_eq!(serde_json::to_value(&snapshot).unwrap()["path"], ui_path);
|
||||
service.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn failed_close_keeps_the_incarnation_recoverable_until_a_retry_succeeds() {
|
||||
let (dir, service, initial) = fixture();
|
||||
|
||||
@@ -405,6 +405,28 @@ 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,
|
||||
@@ -1200,6 +1222,10 @@ 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
|
||||
});
|
||||
|
||||
@@ -422,8 +422,7 @@ struct IdeDir {
|
||||
plugins: PathBuf,
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// The settings folders of JetBrains IDEs and Android Studio (2020.1 and later), newest first.
|
||||
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 {
|
||||
@@ -463,8 +462,6 @@ 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
|
||||
}
|
||||
|
||||
@@ -787,13 +784,6 @@ 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");
|
||||
|
||||
@@ -77,8 +77,6 @@ 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
|
||||
@@ -571,8 +569,6 @@ 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
|
||||
{
|
||||
|
||||
@@ -316,6 +316,7 @@ 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"
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
//! 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, ¤t), "every open returns the window's one project");
|
||||
}
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -162,8 +162,7 @@ pub fn client_capabilities() -> Value {
|
||||
"callHierarchy": { "dynamicRegistration": false },
|
||||
"typeHierarchy": { "dynamicRegistration": false }
|
||||
},
|
||||
// rust-analyzer: report when the project has loaded (`quiescent`).
|
||||
"experimental": { "serverStatusNotification": true }
|
||||
"experimental": {}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -234,11 +234,6 @@ impl Handler for ClientHandler {
|
||||
let Some(mgr) = self.mgr.upgrade() else { return };
|
||||
match method {
|
||||
"$/progress" => self.progress(&mgr, params),
|
||||
"experimental/serverStatus" => {
|
||||
if let Some(quiescent) = params.get("quiescent").and_then(Value::as_bool) {
|
||||
self.server.set_loading(mgr.sink(), !quiescent);
|
||||
}
|
||||
}
|
||||
"textDocument/publishDiagnostics" => self.publish_diagnostics(&mgr, params),
|
||||
"window/showMessage" => self.show_message(&mgr, ¶ms),
|
||||
"window/logMessage" => {
|
||||
|
||||
@@ -18,7 +18,6 @@ mod inspect;
|
||||
pub mod jdtls;
|
||||
mod launch;
|
||||
mod library_source;
|
||||
mod loading;
|
||||
mod pull;
|
||||
mod scope;
|
||||
mod server;
|
||||
@@ -217,15 +216,6 @@ fn runtime_handle() -> tokio::runtime::Handle {
|
||||
})
|
||||
}
|
||||
|
||||
fn goto_is_empty(r: &Option<lsp::GotoDefinitionResponse>) -> bool {
|
||||
match r {
|
||||
None => true,
|
||||
Some(lsp::GotoDefinitionResponse::Scalar(_)) => false,
|
||||
Some(lsp::GotoDefinitionResponse::Array(v)) => v.is_empty(),
|
||||
Some(lsp::GotoDefinitionResponse::Link(v)) => v.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
|
||||
match e {
|
||||
RpcError::Cancelled => IdeError::cancelled(),
|
||||
@@ -1173,13 +1163,8 @@ impl LspManager {
|
||||
let mut out = Outcome::new();
|
||||
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
|
||||
let r: IdeResult<Option<lsp::Hover>> =
|
||||
loading::while_loading(&t.server, Some(&cancel), loading::LOADING_WAIT, Option::is_none, || {
|
||||
self.call(t, "textDocument/hover", snap.pos_params(t, pos), Some(&cancel), DEFAULT_TIMEOUT)
|
||||
})
|
||||
.await;
|
||||
self.call(t, "textDocument/hover", snap.pos_params(t, pos), Some(&cancel), DEFAULT_TIMEOUT).await;
|
||||
match r {
|
||||
// Still loading: no documentation yet, not an error.
|
||||
Err(e) if e.kind == ErrorKind::TimedOut && t.server.is_loading() => out.value = Some(None),
|
||||
Ok(Some(h)) => {
|
||||
if let Some(h) = convert::hover(&self.conv(t.enc()), &snap.path, h) {
|
||||
return Ok(Some(h));
|
||||
@@ -1269,17 +1254,16 @@ impl LspManager {
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let mut out = Outcome::new();
|
||||
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
|
||||
let r = loading::while_loading(&t.server, cancel, loading::LOADING_WAIT, goto_is_empty, || {
|
||||
self.call::<_, Option<lsp::GotoDefinitionResponse>>(
|
||||
match self
|
||||
.call::<_, Option<lsp::GotoDefinitionResponse>>(
|
||||
t,
|
||||
method,
|
||||
snap.pos_params(t, pos),
|
||||
cancel,
|
||||
DEFAULT_TIMEOUT,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
match r {
|
||||
.await
|
||||
{
|
||||
Ok(Some(r)) => {
|
||||
let locs = convert::goto_response(&self.conv(t.enc()), r);
|
||||
let locs = library_sources(snap, pos, locs).await;
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
//! Requests answered while a server is still loading the project.
|
||||
//!
|
||||
//! rust-analyzer answers navigation with nothing until it has read the project's
|
||||
//! files, misses macro-generated items until build scripts and proc macros are
|
||||
//! built, and withdraws answers (`ContentModified`) when loading changes its
|
||||
//! data. Such an answer is not final: the request runs again as loading
|
||||
//! progresses, so ⌘B right after opening a project lands once the server can
|
||||
//! answer instead of reporting "not found". Only servers that report loading
|
||||
//! through `experimental/serverStatus` wait; for others nothing changes.
|
||||
|
||||
use crate::server::Server;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::future::Future;
|
||||
use std::time::Duration;
|
||||
|
||||
/// How long an explicit request waits for a server that is still loading.
|
||||
pub(crate) const LOADING_WAIT: Duration = Duration::from_secs(30);
|
||||
/// Retry interval while it loads, for phases that end without a notification.
|
||||
const POLL: Duration = Duration::from_secs(3);
|
||||
|
||||
/// Runs `query` on `server`. While the server is loading, an empty answer or a
|
||||
/// withdrawn one (`ContentModified`; not a cancellation of `cancel`) runs again
|
||||
/// whenever a loading phase ends, until it answers, loading ends, or `wait`
|
||||
/// passes; then a still-loading server yields a `TimedOut` error saying so.
|
||||
pub(crate) async fn while_loading<R, F, Fut>(
|
||||
server: &Server,
|
||||
cancel: Option<&CancellationToken>,
|
||||
wait: Duration,
|
||||
is_empty: impl Fn(&R) -> bool,
|
||||
query: F,
|
||||
) -> IdeResult<R>
|
||||
where
|
||||
F: Fn() -> Fut,
|
||||
Fut: Future<Output = IdeResult<R>>,
|
||||
{
|
||||
let cancelled = || cancel.is_some_and(CancellationToken::is_cancelled);
|
||||
let deadline = tokio::time::Instant::now() + wait;
|
||||
loop {
|
||||
let phase = server.phase_notified();
|
||||
tokio::pin!(phase);
|
||||
phase.as_mut().enable();
|
||||
let asked_while_loading = server.is_loading();
|
||||
let result = query().await;
|
||||
let retry = match &result {
|
||||
Ok(r) => is_empty(r),
|
||||
Err(e) => e.kind == ErrorKind::Cancelled && !cancelled(),
|
||||
};
|
||||
if !retry || cancelled() || server.running().is_none() {
|
||||
return result;
|
||||
}
|
||||
if !server.is_loading() {
|
||||
// Loading ended while the server answered from its old state: ask once more.
|
||||
if asked_while_loading {
|
||||
continue;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
let now = tokio::time::Instant::now();
|
||||
if now >= deadline {
|
||||
return Err(IdeError::new(ErrorKind::TimedOut, format!("{} is still loading the project", server.name)));
|
||||
}
|
||||
let until = deadline.min(now + POLL);
|
||||
let stop = async {
|
||||
match cancel {
|
||||
Some(c) => c.cancelled().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
() = phase => {}
|
||||
() = tokio::time::sleep_until(until) => {}
|
||||
() = stop => return Err(IdeError::cancelled()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,11 +110,6 @@ pub struct Server {
|
||||
pub published_notify: Notify,
|
||||
/// Woken when the last `$/progress` task ends.
|
||||
idle_notify: Notify,
|
||||
/// `experimental/serverStatus` (rust-analyzer): `None` until the server sends
|
||||
/// one, then whether it is still loading the project.
|
||||
loading: Mutex<Option<bool>>,
|
||||
/// Woken whenever a `$/progress` task ends or the server's loading state changes.
|
||||
phase_notify: Notify,
|
||||
transient: Mutex<HashMap<PathBuf, Transient>>,
|
||||
pub java_build_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
pub java_autobuild_suspended: std::sync::atomic::AtomicBool,
|
||||
@@ -149,8 +144,6 @@ impl Server {
|
||||
published: Mutex::new(HashMap::new()),
|
||||
published_notify: Notify::new(),
|
||||
idle_notify: Notify::new(),
|
||||
loading: Mutex::new(None),
|
||||
phase_notify: Notify::new(),
|
||||
transient: Mutex::new(HashMap::new()),
|
||||
java_build_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
java_autobuild_suspended: std::sync::atomic::AtomicBool::new(false),
|
||||
@@ -396,48 +389,22 @@ impl Server {
|
||||
if self.running().is_none() {
|
||||
return;
|
||||
}
|
||||
let busy = self.is_busy();
|
||||
let busy = !self.progress.lock().is_empty();
|
||||
self.set_status(sink, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, None);
|
||||
}
|
||||
|
||||
/// Whether the server reports work in progress (indexing, analysis).
|
||||
pub fn is_busy(&self) -> bool {
|
||||
!self.progress.lock().is_empty() || *self.loading.lock() == Some(true)
|
||||
}
|
||||
|
||||
/// Whether the server says it is still loading the project, so an empty
|
||||
/// answer may not be final. Only `serverStatus` tells: `$/progress` also
|
||||
/// covers background work (indexing, builds) during which answers are final.
|
||||
pub fn is_loading(&self) -> bool {
|
||||
*self.loading.lock() == Some(true)
|
||||
}
|
||||
|
||||
/// Records `experimental/serverStatus`: `quiescent` false while the project loads.
|
||||
pub fn set_loading(&self, sink: &SharedSink, loading: bool) {
|
||||
if self.loading.lock().replace(loading) == Some(loading) {
|
||||
return;
|
||||
}
|
||||
self.refresh_busy_status(sink);
|
||||
self.phase_ended();
|
||||
!self.progress.lock().is_empty()
|
||||
}
|
||||
|
||||
/// Called after a `$/progress` task ended.
|
||||
pub fn progress_ended(&self) {
|
||||
self.phase_ended();
|
||||
}
|
||||
|
||||
fn phase_ended(&self) {
|
||||
self.phase_notify.notify_waiters();
|
||||
if !self.is_busy() {
|
||||
self.idle_notify.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
/// Woken when the next loading phase ends.
|
||||
pub fn phase_notified(&self) -> tokio::sync::futures::Notified<'_> {
|
||||
self.phase_notify.notified()
|
||||
}
|
||||
|
||||
/// Waits until no `$/progress` task is active; false on timeout or cancellation.
|
||||
pub async fn wait_idle(&self, timeout: Duration, cancel: &CancellationToken) -> bool {
|
||||
let deadline = tokio::time::Instant::now() + timeout;
|
||||
@@ -532,7 +499,6 @@ impl Server {
|
||||
}
|
||||
|
||||
pub fn take_progress(&self) -> Vec<(TaskId, String)> {
|
||||
*self.loading.lock() = None;
|
||||
self.progress.lock().drain().map(|(_, p)| (p.task, p.title)).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -1009,78 +1009,6 @@ async fn progress_tasks_and_busy_status() {
|
||||
assert!(tasks[2].3);
|
||||
}
|
||||
|
||||
/// While a server says it is loading the project (rust-analyzer: `serverStatus`
|
||||
/// not quiescent) an empty or withdrawn answer is asked again once loading moves
|
||||
/// on. `$/progress` alone (background indexing, `cargo check`) doesn't wait.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn navigation_waits_for_a_server_that_is_still_loading() {
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Answer {
|
||||
Empty,
|
||||
ContentModified,
|
||||
}
|
||||
for answer in [Answer::Empty, Answer::ContentModified] {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (doc, path) = h.open("a.mk", "fn foo() {}\nfoo();\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
let peer = s.peer();
|
||||
peer.notify("experimental/serverStatus", json!({ "health": "ok", "quiescent": false })).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
if let Answer::ContentModified = answer {
|
||||
s.errors.lock().insert("textDocument/definition".into(), (-32801, "content modified".into()));
|
||||
}
|
||||
let mgr = h.mgr.clone();
|
||||
let goto = tokio::spawn(async move { mgr.goto(doc, Pos::new(1, 1), GotoKind::Definition).await });
|
||||
eventually(|| !s.requested("textDocument/definition").is_empty()).await;
|
||||
assert!(!goto.is_finished(), "{answer:?}: an answer while loading is not final");
|
||||
|
||||
s.errors.lock().clear();
|
||||
let r = json!({"start":{"line":0,"character":3},"end":{"line":0,"character":6}});
|
||||
s.respond("textDocument/definition", json!({ "uri": uri_of(&path), "range": r }));
|
||||
peer.notify("experimental/serverStatus", json!({ "health": "ok", "quiescent": true })).unwrap();
|
||||
let defs = tokio::time::timeout(Duration::from_secs(10), goto).await.unwrap().unwrap().unwrap();
|
||||
assert_eq!(defs, vec![ide_core::Location::file(path.clone(), rng(0, 3, 0, 6))], "{answer:?}");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
// Hover documentation the same way.
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (doc, _) = h.open("a.mk", "x");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
s.peer().notify("experimental/serverStatus", json!({ "health": "ok", "quiescent": false })).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
let mgr = h.mgr.clone();
|
||||
let hover = tokio::spawn(async move { mgr.hover(doc, Pos::new(0, 0), Default::default()).await });
|
||||
eventually(|| !s.requested("textDocument/hover").is_empty()).await;
|
||||
s.respond("textDocument/hover", json!({ "contents": "docs" }));
|
||||
s.peer().notify("experimental/serverStatus", json!({ "health": "ok", "quiescent": true })).unwrap();
|
||||
let hover = tokio::time::timeout(Duration::from_secs(10), hover).await.unwrap().unwrap().unwrap();
|
||||
assert!(hover.is_some());
|
||||
|
||||
// "Nothing here" is the answer at once: rust-analyzer loaded with `cargo check`
|
||||
// running, and a server without `serverStatus` indexing in the background.
|
||||
for quiescent in [Some(true), None] {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (doc, _) = h.open("a.mk", "x");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
let peer = s.peer();
|
||||
if let Some(q) = quiescent {
|
||||
peer.notify("experimental/serverStatus", json!({ "health": "ok", "quiescent": q })).unwrap();
|
||||
}
|
||||
peer.notify("$/progress", json!({ "token": "bg", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
let defs = tokio::time::timeout(Duration::from_secs(2), h.mgr.goto(doc, Pos::new(0, 0), GotoKind::Definition))
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("{quiescent:?}: no wait for background work"))
|
||||
.unwrap();
|
||||
assert!(defs.is_empty());
|
||||
assert_eq!(s.requested("textDocument/definition").len(), 1, "{quiescent:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn progress_titled_with_an_executable_path_shows_the_program_name() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
@@ -3405,8 +3333,7 @@ async fn interactive_capability_is_scoped_to_gopls() {
|
||||
let (doc, _) = h.open("probe.mk", "x\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
let experimental = &s.requested("initialize")[0]["capabilities"]["experimental"];
|
||||
assert!(experimental.get("interactiveResolve").is_none(), "{experimental}");
|
||||
assert_eq!(s.requested("initialize")[0]["capabilities"]["experimental"], json!({}));
|
||||
let form = h
|
||||
.mgr
|
||||
.resolve_command(
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::{
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, error::ErrorKind};
|
||||
use ide_core::{IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use specta::Type;
|
||||
@@ -22,7 +22,7 @@ use crate::kernel::KernelOutput;
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NotebookSnapshot {
|
||||
pub id: String,
|
||||
pub path: IpcPath,
|
||||
pub path: String,
|
||||
pub version: u32,
|
||||
pub dirty: bool,
|
||||
pub can_undo: bool,
|
||||
@@ -188,7 +188,7 @@ impl NotebookDocument {
|
||||
pub fn snapshot(&self) -> NotebookSnapshot {
|
||||
NotebookSnapshot {
|
||||
id: self.id.clone(),
|
||||
path: self.path.clone().into(),
|
||||
path: self.path.to_string_lossy().into_owned(),
|
||||
version: self.version,
|
||||
dirty: self.is_dirty(),
|
||||
can_undo: !self.execution_active && !self.undo.is_empty(),
|
||||
|
||||
@@ -3,9 +3,8 @@
|
||||
//! 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,
|
||||
//! Application, Spring Boot 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 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.
|
||||
@@ -163,8 +162,6 @@ 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>;
|
||||
|
||||
@@ -332,8 +329,6 @@ 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)
|
||||
@@ -700,54 +695,6 @@ 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.
|
||||
@@ -888,56 +835,6 @@ 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 {
|
||||
|
||||
@@ -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 ([`web_sources`]), file by file and only what changed, instead of
|
||||
/// its web resources (`src/main/webapp`), 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,10 +232,9 @@ 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)?;
|
||||
}
|
||||
for (dir, target) in web_sources(module) {
|
||||
if dir.is_dir() {
|
||||
sync_tree(&dir, &dir, &dest.join(&target), &target, 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 rel in previous.iter().filter(|p| !current.contains(*p)) {
|
||||
let path = dest.join(rel);
|
||||
@@ -247,59 +246,6 @@ 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() {
|
||||
@@ -628,83 +574,6 @@ 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();
|
||||
|
||||
@@ -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="JUnit" factoryName="JUnit">
|
||||
<option name="MAIN_CLASS_NAME" value="shop.MainTest" />
|
||||
<configuration name="Main" type="Application" factoryName="Application">
|
||||
<option name="MAIN_CLASS_NAME" value="shop.Main" />
|
||||
<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_: "JUnit".into() });
|
||||
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "Application".into() });
|
||||
|
||||
let dev = get(&r, "dev");
|
||||
assert_eq!((dev.kind.as_str(), dev.command.as_str()), ("npm", "pnpm"));
|
||||
@@ -526,11 +526,14 @@ 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="JUnit" />"#));
|
||||
write(dir.path(), ".idea/workspace.xml", &workspace(r#"<configuration name="App" type="Application" />"#));
|
||||
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_: "JUnit".into() });
|
||||
assert_eq!(
|
||||
reason(&import_from(dir.path(), &[]), "App"),
|
||||
&SkipReason::UnsupportedType { type_: "Application".into() }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -699,91 +702,3 @@ 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);
|
||||
}
|
||||
@@ -9,88 +9,44 @@ use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Log "Text or hash" filter: the message (substring or regex), or a hash prefix.
|
||||
enum TextFilter {
|
||||
/// 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),
|
||||
Plain { needle: String, match_case: bool },
|
||||
Regex(regex_lite::Regex),
|
||||
}
|
||||
|
||||
impl TextFilter {
|
||||
fn new(
|
||||
r: &Repo,
|
||||
scopes: &[String],
|
||||
q: &LogQuery,
|
||||
text: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<Self>> {
|
||||
fn new(text: &str, regex: bool, match_case: bool) -> IdeResult<Option<Self>> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if q.text_regex {
|
||||
if regex {
|
||||
let re = regex_lite::RegexBuilder::new(text)
|
||||
.case_insensitive(!q.text_match_case)
|
||||
.case_insensitive(!match_case)
|
||||
.multi_line(true)
|
||||
.build()
|
||||
.map_err(|e| IdeError::invalid(format!("invalid regular expression: {e}")))?;
|
||||
return Ok(Some(Self::Regex(re)));
|
||||
}
|
||||
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 }))
|
||||
let needle = if match_case { text.to_string() } else { text.to_lowercase() };
|
||||
Ok(Some(Self::Plain { needle, match_case }))
|
||||
}
|
||||
|
||||
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()))
|
||||
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())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>> {
|
||||
@@ -217,71 +173,87 @@ 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 if q.follow && paths.len() == 1 {
|
||||
} else {
|
||||
let mut ids = HashSet::new();
|
||||
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();
|
||||
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();
|
||||
}
|
||||
} 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(r, &scopes, q, t, cancel)).transpose()?.flatten(),
|
||||
text: q.text.as_deref().map(|t| TextFilter::new(t, q.text_regex, q.text_match_case)).transpose()?.flatten(),
|
||||
matches: HashMap::new(),
|
||||
projected: HashMap::new(),
|
||||
cancel,
|
||||
@@ -612,6 +584,9 @@ 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,
|
||||
@@ -627,7 +602,10 @@ impl Visibility<'_> {
|
||||
if let Some(shown) = self.matches.get(&id) {
|
||||
return Ok(*shown);
|
||||
}
|
||||
let shown = if !repo.has_object(id)
|
||||
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)
|
||||
|| self.path_ids.as_ref().is_some_and(|ids| !ids.contains(&id))
|
||||
|| self.range_ids.as_ref().is_some_and(|ids| !ids.contains(&id))
|
||||
{
|
||||
@@ -670,7 +648,15 @@ impl Visibility<'_> {
|
||||
}
|
||||
}))
|
||||
&& match &self.text {
|
||||
Some(text) => text.matches(repo, self.index, id)?,
|
||||
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)
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
};
|
||||
@@ -879,6 +865,113 @@ 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)
|
||||
|
||||
@@ -162,6 +162,14 @@ 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")]
|
||||
@@ -664,6 +672,7 @@ 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>>,
|
||||
}
|
||||
|
||||
@@ -835,6 +844,59 @@ 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())
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::repo::{gx, to_string};
|
||||
use gix::ObjectId;
|
||||
use gix::bstr::ByteSlice;
|
||||
use ide_core::IdeResult;
|
||||
use redb::{Database, ReadableDatabase, TableDefinition};
|
||||
use redb::{Database, MultimapTableDefinition, ReadableDatabase, TableDefinition};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, OnceLock, Weak};
|
||||
@@ -14,6 +14,9 @@ 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>,
|
||||
@@ -33,6 +36,9 @@ 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>>,
|
||||
@@ -86,6 +92,91 @@ 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;
|
||||
@@ -181,7 +272,11 @@ impl LogIndex {
|
||||
}
|
||||
|
||||
pub fn flush(&mut self) {
|
||||
if self.dirty.is_empty() && self.dirty_messages.is_empty() {
|
||||
if self.dirty.is_empty()
|
||||
&& self.dirty_paths.is_empty()
|
||||
&& self.dirty_messages.is_empty()
|
||||
&& self.dirty_search.is_empty()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let result = (|| -> Result<(), Box<dyn std::error::Error>> {
|
||||
@@ -196,12 +291,29 @@ 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(())
|
||||
})();
|
||||
@@ -209,7 +321,52 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,7 @@ 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(),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -99,6 +99,8 @@ 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();
|
||||
@@ -434,31 +436,3 @@ 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());
|
||||
}
|
||||
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 377 KiB |
@@ -130,15 +130,14 @@ 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 JetBrains IDEs (automatic)
|
||||
### From IntelliJ IDEA (automatic)
|
||||
|
||||
To use a theme you already have in a JetBrains IDE, open **Settings › Plugins**, gear
|
||||
To use a theme you already have in IntelliJ, open **Settings › Plugins**, gear
|
||||
menu:
|
||||
|
||||
- **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`
|
||||
- **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`
|
||||
(macOS), `%APPDATA%\JetBrains` (Windows), `~/.config/JetBrains` and
|
||||
`~/.local/share/JetBrains` (Linux).
|
||||
- **Import IntelliJ Theme from File…** takes a theme plugin downloaded from the
|
||||
@@ -147,8 +146,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 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`,
|
||||
install page and the chosen theme (otherwise the first) is applied. Importing
|
||||
the plugin again replaces it. Both are actions too (`plugins.importIntellijTheme`,
|
||||
`plugins.importInstalledIntellijTheme`). The conversion is the one described
|
||||
below.
|
||||
|
||||
|
||||
@@ -186,49 +186,3 @@ 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");
|
||||
});
|
||||
@@ -11,10 +11,9 @@ 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 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.
|
||||
> **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.
|
||||
|
||||
```
|
||||
plugins/
|
||||
@@ -770,7 +769,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 JetBrains IDE…_, see [`docs/plugins/themes.md`](../docs/plugins/themes.md)). The install
|
||||
from IntelliJ 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>/`
|
||||
@@ -920,8 +919,8 @@ the API itself follows _Evolving the plugin API_ below.
|
||||
|
||||
## 10. Evolving the plugin API
|
||||
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -958,15 +957,10 @@ only grows:
|
||||
|
||||
Checked automatically:
|
||||
|
||||
- SDK `tests/api_frozen.rs`: `tests/api/released/` holds the WIT of the latest
|
||||
- SDK `tests/api_frozen.rs`: `tests/api/<version>/` holds the WIT of each
|
||||
released version; every interface, type, function and world import or
|
||||
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.
|
||||
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.
|
||||
- `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
|
||||
|
||||
@@ -220,6 +220,11 @@ 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
-1
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.1.0;
|
||||
package openidea:plugin@1.0.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.1.0;
|
||||
package openidea:plugin@1.0.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
+2
-6
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.1.0;
|
||||
package openidea:plugin@1.0.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
@@ -8,7 +8,7 @@ interface log {
|
||||
}
|
||||
|
||||
interface ui {
|
||||
use types.{error, notification-level};
|
||||
use types.{notification-level};
|
||||
|
||||
record status-item {
|
||||
text: string,
|
||||
@@ -23,10 +23,6 @@ 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
-1
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.1.0;
|
||||
package openidea:plugin@1.0.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
+1
-1
@@ -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.1.0;
|
||||
package openidea:plugin@1.0.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.1.0;
|
||||
package openidea:plugin@1.0.0;
|
||||
|
||||
/// Editor features a plugin provides for the languages it declares under
|
||||
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.1.0;
|
||||
package openidea:plugin@1.0.0;
|
||||
|
||||
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
|
||||
/// as in the editor and LSP.
|
||||
+1
-5
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.1.0;
|
||||
package openidea:plugin@1.0.0;
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
@@ -133,10 +133,6 @@ 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
-3
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.1.0;
|
||||
package openidea:plugin@1.0.0;
|
||||
|
||||
interface workspace {
|
||||
use types.{error};
|
||||
@@ -84,8 +84,6 @@ 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>;
|
||||
@@ -3,13 +3,11 @@
|
||||
//! a field added to a record or a case added to a variant breaks every
|
||||
//! component built for the release.
|
||||
//!
|
||||
//! `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.
|
||||
//! `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.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
@@ -112,83 +110,77 @@ fn anonymous(r: &Resolve, id: TypeId) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
/// 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}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_surface_covers_the_whole_api() {
|
||||
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 ")));
|
||||
}
|
||||
// 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 ")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
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}"));
|
||||
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}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 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:?}"
|
||||
);
|
||||
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:?})");
|
||||
}
|
||||
}
|
||||
@@ -93,16 +93,6 @@ objc2-web-kit = { version = "0.3", default-features = false, features = ["std",
|
||||
gtk = "0.18"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Storage_EnhancedStorage",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Win32_System_Variant",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_Shell_Common",
|
||||
"Win32_UI_Shell_PropertiesSystem",
|
||||
] }
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Gdi",
|
||||
|
||||
@@ -46,9 +46,7 @@ pub fn recent_projects(state: State<'_, AppState>) -> Vec<RecentProject> {
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn remove_recent_project(state: State<'_, AppState>, path: PathBuf) -> IdeResult<()> {
|
||||
state.recent.remove(&path)?;
|
||||
crate::jump_list::refresh(&state.app, state.recent.list());
|
||||
Ok(())
|
||||
state.recent.remove(&path)
|
||||
}
|
||||
|
||||
/// The welcome screen's project groups.
|
||||
@@ -127,7 +125,6 @@ pub fn project_rename(window: Window, state: State<'_, AppState>, name: String)
|
||||
let value = if name.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(name.to_owned()) };
|
||||
project.settings.set(SettingsScope::Project, "general.projectName", value)?;
|
||||
state.recent.rename(&project.root, (!name.is_empty()).then_some(name))?;
|
||||
crate::jump_list::refresh(&state.app, state.recent.list());
|
||||
Ok(project_info(&project))
|
||||
}
|
||||
|
||||
|
||||
@@ -262,6 +262,7 @@ 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,
|
||||
|
||||
@@ -142,6 +142,16 @@ 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>,
|
||||
|
||||
@@ -1,170 +0,0 @@
|
||||
//! Windows taskbar Jump List: the recent projects of the running window.
|
||||
//!
|
||||
//! The list is built while OpenIDEA runs, so its taskbar button offers the same
|
||||
//! recent projects as Welcome / File › Open Recent. `set_app_id` must run before
|
||||
//! the first window is created so the taskbar groups every launch under one
|
||||
//! AppUserModelID.
|
||||
|
||||
use ide_workspace::RecentProject;
|
||||
|
||||
/// Windows shows only a handful of custom destinations; keep the taskbar menu short.
|
||||
#[cfg(any(windows, test))]
|
||||
const MAX_ITEMS: usize = 10;
|
||||
#[cfg(windows)]
|
||||
const CATEGORY: &str = "Recent Projects";
|
||||
/// Marks a second-instance launch from a Jump List item, so it opens in the existing window.
|
||||
pub const OPEN_RECENT_ARG: &str = "--open-recent";
|
||||
|
||||
pub fn set_app_id(app_id: &str) {
|
||||
#[cfg(windows)]
|
||||
imp::set_app_id(app_id);
|
||||
#[cfg(not(windows))]
|
||||
let _ = app_id;
|
||||
}
|
||||
|
||||
/// Rebuilds the taskbar Jump List in the background; `items` is newest first.
|
||||
pub fn refresh(app: &tauri::AppHandle, items: Vec<RecentProject>) {
|
||||
#[cfg(windows)]
|
||||
imp::refresh(app, items);
|
||||
#[cfg(not(windows))]
|
||||
let _ = (app, items);
|
||||
}
|
||||
|
||||
/// The entries a Jump List shows: newest first, capped at [`MAX_ITEMS`].
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) fn visible_items(items: &[RecentProject]) -> Vec<(&str, &std::path::Path)> {
|
||||
items.iter().take(MAX_ITEMS).map(|item| (item.name.as_str(), item.path.0.as_path())).collect()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
use windows::Win32::Storage::EnhancedStorage::{PKEY_AppUserModel_ID, PKEY_Title};
|
||||
use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};
|
||||
use windows::Win32::System::Com::{
|
||||
CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize,
|
||||
};
|
||||
use windows::Win32::UI::Shell::Common::{IObjectArray, IObjectCollection};
|
||||
use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore;
|
||||
use windows::Win32::UI::Shell::{
|
||||
DestinationList, EnumerableObjectCollection, ICustomDestinationList, IShellLinkW,
|
||||
SetCurrentProcessExplicitAppUserModelID, ShellLink,
|
||||
};
|
||||
use windows::core::{HSTRING, Interface};
|
||||
|
||||
/// Shell COM is not thread-safe here; serialize updates from simultaneous project opens.
|
||||
static UPDATE_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
pub fn set_app_id(app_id: &str) {
|
||||
if let Err(error) = unsafe { SetCurrentProcessExplicitAppUserModelID(&HSTRING::from(app_id)) } {
|
||||
tracing::warn!(%error, "cannot set the taskbar AppUserModelID");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn refresh(app: &tauri::AppHandle, items: Vec<RecentProject>) {
|
||||
let app_id = app.config().identifier.clone();
|
||||
let worker = std::thread::Builder::new().name("openidea-jump-list".into()).spawn(move || {
|
||||
let _guard = UPDATE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let com = ComGuard::new();
|
||||
if let Err(error) = update(&app_id, &items) {
|
||||
tracing::warn!(%error, "cannot update the taskbar Jump List");
|
||||
}
|
||||
drop(com);
|
||||
});
|
||||
if let Err(error) = worker {
|
||||
tracing::warn!(%error, "cannot start the taskbar Jump List worker");
|
||||
}
|
||||
}
|
||||
|
||||
struct ComGuard {
|
||||
uninitialize: bool,
|
||||
}
|
||||
|
||||
impl ComGuard {
|
||||
fn new() -> Self {
|
||||
let result = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
|
||||
let uninitialize = result.0 >= 0;
|
||||
if !uninitialize {
|
||||
tracing::debug!(%result, "COM already initialized for the taskbar Jump List");
|
||||
}
|
||||
Self { uninitialize }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ComGuard {
|
||||
fn drop(&mut self) {
|
||||
if self.uninitialize {
|
||||
unsafe { CoUninitialize() };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update(app_id: &str, items: &[RecentProject]) -> windows::core::Result<()> {
|
||||
let app_id_hstring = HSTRING::from(app_id);
|
||||
let visible = visible_items(items);
|
||||
unsafe {
|
||||
let list: ICustomDestinationList = CoCreateInstance(&DestinationList, None, CLSCTX_INPROC_SERVER)?;
|
||||
list.SetAppID(&app_id_hstring)?;
|
||||
if visible.is_empty() {
|
||||
let _ = list.DeleteList(&app_id_hstring);
|
||||
return Ok(());
|
||||
}
|
||||
let mut min_slots = 0u32;
|
||||
let _removed: IObjectArray = list.BeginList(&mut min_slots)?;
|
||||
let collection: IObjectCollection =
|
||||
CoCreateInstance(&EnumerableObjectCollection, None, CLSCTX_INPROC_SERVER)?;
|
||||
let exe = HSTRING::from(std::env::current_exe()?.to_string_lossy().as_ref());
|
||||
for (name, path) in visible {
|
||||
let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?;
|
||||
link.SetPath(&exe)?;
|
||||
let mut arguments = String::with_capacity(path.as_os_str().len() + OPEN_RECENT_ARG.len() + 3);
|
||||
arguments.push_str(OPEN_RECENT_ARG);
|
||||
arguments.push(' ');
|
||||
arguments.push('"');
|
||||
arguments.push_str(&path.to_string_lossy());
|
||||
arguments.push('"');
|
||||
link.SetArguments(&HSTRING::from(arguments.as_str()))?;
|
||||
link.SetDescription(&HSTRING::from(path.to_string_lossy().as_ref()))?;
|
||||
if let Some(parent) = path.parent() {
|
||||
link.SetWorkingDirectory(&HSTRING::from(parent.to_string_lossy().as_ref()))?;
|
||||
}
|
||||
link.SetIconLocation(&exe, 0)?;
|
||||
let properties: IPropertyStore = link.cast()?;
|
||||
let mut title = PROPVARIANT::from(name);
|
||||
let mut app_id_value = PROPVARIANT::from(app_id);
|
||||
let title_result = properties.SetValue(&PKEY_Title, &title);
|
||||
let app_id_result = properties.SetValue(&PKEY_AppUserModel_ID, &app_id_value);
|
||||
let _ = PropVariantClear(&mut title);
|
||||
let _ = PropVariantClear(&mut app_id_value);
|
||||
title_result?;
|
||||
app_id_result?;
|
||||
properties.Commit()?;
|
||||
collection.AddObject(&link)?;
|
||||
}
|
||||
let destinations: IObjectArray = collection.cast()?;
|
||||
list.AppendCategory(&HSTRING::from(CATEGORY), &destinations)?;
|
||||
list.CommitList()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::IpcPath;
|
||||
|
||||
fn item(name: &str, path: &str) -> RecentProject {
|
||||
RecentProject { path: IpcPath::from(path), name: name.into(), opened_at_ms: 0.0, branch: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shows_the_newest_items_capped() {
|
||||
let items: Vec<_> = (0..15).map(|i| item(&format!("p{i}"), &format!("/p/{i}"))).collect();
|
||||
let visible = visible_items(&items);
|
||||
assert_eq!(visible.len(), 10);
|
||||
assert_eq!(visible[0].0, "p0");
|
||||
assert_eq!(visible[9].0, "p9");
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ mod commands;
|
||||
#[cfg(debug_assertions)]
|
||||
mod dev;
|
||||
mod events;
|
||||
mod jump_list;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod linux_window_state;
|
||||
mod logging;
|
||||
@@ -65,8 +64,6 @@ pub fn run() {
|
||||
let context = tauri::generate_context!();
|
||||
#[cfg(debug_assertions)]
|
||||
let context = dev::configure(context);
|
||||
// Before the first window: one taskbar identity for every launch path.
|
||||
jump_list::set_app_id(&context.config().identifier);
|
||||
logging::init(&context.config().identifier);
|
||||
|
||||
let refresh_shell_path = ide_host::shell_env::inherit_login_shell_path(&context.config().identifier);
|
||||
@@ -177,7 +174,6 @@ pub fn run() {
|
||||
}
|
||||
app.on_menu_event(on_menu_event);
|
||||
windows::create_main_window(app.handle())?;
|
||||
jump_list::refresh(app.handle(), app.state::<AppState>().recent.list());
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|window, event| match event {
|
||||
|
||||
@@ -145,7 +145,6 @@ impl AppState {
|
||||
if !display_name.trim().is_empty() {
|
||||
self.recent.rename(&project.root, Some(display_name.trim()))?;
|
||||
}
|
||||
crate::jump_list::refresh(&self.app, self.recent.list());
|
||||
Ok(project)
|
||||
}
|
||||
|
||||
|
||||
@@ -923,17 +923,8 @@ pub fn open_path(app: &AppHandle, path: &Path) {
|
||||
/// Opens paths from outside the app (a second instance, Finder's Open With, the Dock):
|
||||
/// see [`plan_open`]; the focused window is the preferred free one.
|
||||
pub fn open_paths(app: &AppHandle, paths: Vec<PathBuf>) {
|
||||
let (existing, missing): (Vec<_>, Vec<_>) = paths.into_iter().partition(|path| path.exists());
|
||||
if !missing.is_empty() {
|
||||
let paths = missing.iter().map(|path| path.display().to_string()).collect::<Vec<_>>().join("\n");
|
||||
app.state::<AppState>().sink.emit(ide_core::IdeEvent::Notify {
|
||||
level: ide_core::event::NotifyLevel::Warning,
|
||||
title: "Cannot open path".into(),
|
||||
body: Some(format!("The path does not exist:\n{paths}")),
|
||||
});
|
||||
}
|
||||
let preferred = target_window(app).map(|w| w.label().to_owned());
|
||||
run_open(app, plan_open(resolve(existing), &window_holds(app, preferred.as_deref())));
|
||||
run_open(app, plan_open(resolve(paths), &window_holds(app, preferred.as_deref())));
|
||||
}
|
||||
|
||||
/// What each window holds, `preferred` first.
|
||||
@@ -1014,25 +1005,6 @@ fn launch_for(path: PathBuf, is_dir: bool) -> Launch {
|
||||
|
||||
/// Second instance launched: focus this one and open its path argument.
|
||||
pub fn on_second_instance(app: &AppHandle, args: Vec<String>, cwd: String) {
|
||||
if args.iter().any(|arg| arg == crate::jump_list::OPEN_RECENT_ARG)
|
||||
&& let Some(path) = cli_path(&args, Path::new(&cwd)).filter(|path| path.exists())
|
||||
{
|
||||
let target = target_window(app)
|
||||
.filter(|window| auxiliary_parent(window.label()).is_none())
|
||||
.or_else(|| project_window_labels(app).into_iter().find_map(|label| app.get_webview_window(&label)));
|
||||
if let Some(window) = target {
|
||||
let _ = app.emit_to(
|
||||
window.label(),
|
||||
crate::menu::MENU_EVENT,
|
||||
crate::menu::MenuRoute {
|
||||
action: crate::menu::OPEN_RECENT_ACTION.into(),
|
||||
arg: Some(ide_core::ipc_path::to_ipc(&path)),
|
||||
},
|
||||
);
|
||||
focus(&window);
|
||||
return;
|
||||
}
|
||||
}
|
||||
match cli_path(&args, Path::new(&cwd)) {
|
||||
Some(path) => {
|
||||
remember_cli_position(&app.state::<WindowsState>(), &args, &path);
|
||||
|
||||
@@ -496,6 +496,7 @@ 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 })),
|
||||
@@ -4986,6 +4987,12 @@ export type LogDetails = {
|
||||
fingerprint: string,
|
||||
};
|
||||
|
||||
export type LogIndexProgress = {
|
||||
indexed: number,
|
||||
total: number,
|
||||
running: boolean,
|
||||
};
|
||||
|
||||
export type LogLevel = "debug" | "info" | "warn" | "error";
|
||||
|
||||
export type LogLocation = {
|
||||
@@ -5342,7 +5349,7 @@ export type NotebookEdit = { type: "setSource"; cell: string; source: string } |
|
||||
|
||||
export type NotebookOutputEvent = {
|
||||
id: string,
|
||||
path: IpcPath,
|
||||
path: string,
|
||||
cell: string,
|
||||
msgId: string,
|
||||
kind: string,
|
||||
@@ -5354,7 +5361,7 @@ export type NotebookOutputEvent = {
|
||||
|
||||
export type NotebookSnapshot = {
|
||||
id: string,
|
||||
path: IpcPath,
|
||||
path: string,
|
||||
version: number,
|
||||
dirty: boolean,
|
||||
canUndo: boolean,
|
||||
|
||||
@@ -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 { declarationChain } from "./view/outline";
|
||||
import { symbolChain } from "./view/outline";
|
||||
import { recordClipboard } from "./clipboardHistory";
|
||||
import { useDocMeta, useOutline } from "./model/document";
|
||||
import { fontZoom, setFontZoom, stepFontZoom } from "./cm/prefs";
|
||||
@@ -414,14 +414,12 @@ 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: chain.map((i) => i.name),
|
||||
chain: symbolChain(outline, line.number - 1, head - line.from).map((i) => i.name),
|
||||
line: line.number - 1,
|
||||
});
|
||||
recordClipboard(reference);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
|
||||
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 down to the one named at the caret, outermost first; empty off a name. */
|
||||
/** Names of the outline symbols enclosing the caret, outermost first. */
|
||||
chain: string[];
|
||||
/** 0-based caret line. */
|
||||
line: number;
|
||||
@@ -59,37 +59,42 @@ 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 on a type's name.
|
||||
// `pkg.Outer.Inner#member`: the last symbol is the member unless the caret is in a type only.
|
||||
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":
|
||||
case "csharp": {
|
||||
if (!chain.length) return fallback;
|
||||
return chain.join(".");
|
||||
case "rust":
|
||||
}
|
||||
case "rust": {
|
||||
if (!chain.length) return rustModulePath(r.path);
|
||||
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 [pkg, ...chain].join(".");
|
||||
return chain.length ? [pkg, ...chain].join(".") : fallback;
|
||||
}
|
||||
case "cpp":
|
||||
case "c":
|
||||
case "objective-cpp":
|
||||
case "php":
|
||||
return chain.join("::");
|
||||
return chain.length ? chain.join("::") : fallback;
|
||||
default:
|
||||
return `${relativePath(r.path, r.root)}:${chain.join(".")}`;
|
||||
return chain.length ? `${relativePath(r.path, r.root)}:${chain.join(".")}` : fallback;
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,7 @@ 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";
|
||||
@@ -103,33 +101,5 @@ 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([]);
|
||||
});
|
||||
});
|
||||
@@ -14,11 +14,3 @@ 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);
|
||||
}
|
||||
@@ -46,14 +46,9 @@
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex: none;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.header > * {
|
||||
flex: none;
|
||||
}
|
||||
/* Shrinks ahead of the meters. */
|
||||
.title {
|
||||
flex: 0 1000 auto;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
font-weight: 600;
|
||||
color: var(--fg-strong);
|
||||
@@ -544,17 +539,11 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Meters that don't fit wrap onto a hidden second row instead of being cut in half. */
|
||||
.meters {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
height: 22px;
|
||||
overflow: hidden;
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
align-content: flex-start;
|
||||
gap: 0 10px;
|
||||
gap: 10px;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
@@ -563,7 +552,6 @@
|
||||
.meter {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 22px;
|
||||
gap: 5px;
|
||||
}
|
||||
.usageBar {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* 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 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 { 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";
|
||||
@@ -14,30 +15,28 @@ import { closeInstalledIntellijThemes, importIntellijTheme, useIntellijThemesDia
|
||||
import { errorText } from "./store";
|
||||
import styles from "./PluginsPage.module.css";
|
||||
|
||||
interface PluginRow {
|
||||
key: string;
|
||||
plugin: string;
|
||||
ide: string;
|
||||
path: string;
|
||||
themes: InstalledIntellijTheme[];
|
||||
}
|
||||
type Row =
|
||||
| { kind: "plugin"; key: string; plugin: string; ide: string; count: number; first: boolean }
|
||||
| { kind: "theme"; key: string; theme: 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>();
|
||||
/** 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[]>();
|
||||
for (const t of themes) {
|
||||
const key = `${t.ide}\n${t.path}`;
|
||||
const row = plugins.get(key) ?? { key, plugin: t.plugin, ide: t.ide, path: t.path, themes: [] };
|
||||
plugins.set(key, row);
|
||||
row.themes.push(t);
|
||||
plugins.set(key, [...(plugins.get(key) ?? []), t]);
|
||||
}
|
||||
return [...plugins.values()];
|
||||
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 })),
|
||||
]);
|
||||
}
|
||||
|
||||
function IntellijThemesDialog() {
|
||||
const [themes, setThemes] = useState<InstalledIntellijTheme[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
// The first theme, under the first heading.
|
||||
const [active, setActive] = useState(1);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
pluginsBackend()
|
||||
@@ -55,48 +54,50 @@ function IntellijThemesDialog() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const run = (path?: string) => {
|
||||
const run = (theme?: InstalledIntellijTheme) => {
|
||||
const { onImported } = useIntellijThemesDialog.getState();
|
||||
closeInstalledIntellijThemes();
|
||||
void importIntellijTheme(path).then((id) => id && onImported?.(id));
|
||||
void importIntellijTheme(theme?.path, theme?.themeId).then((id) => id && onImported?.(id));
|
||||
};
|
||||
const rows = pluginRows(themes ?? []);
|
||||
const chosen = rows[active];
|
||||
const rows = themeRows(themes ?? []);
|
||||
const row = rows[active];
|
||||
const chosen = row?.kind === "theme" ? row.theme : undefined;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title="Import Theme from JetBrains IDE"
|
||||
title="Import Theme from IntelliJ 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.path) },
|
||||
{ label: "Import", role: "default", disabled: !chosen, onClick: () => chosen && run(chosen) },
|
||||
]}
|
||||
>
|
||||
<div className={styles.intellijThemes}>
|
||||
<p className={styles.muted}>
|
||||
<T>
|
||||
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.
|
||||
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.
|
||||
</T>
|
||||
</p>
|
||||
{themes === null ? (
|
||||
<div className={styles.intellijThemesStatus}>
|
||||
<Spinner size={14} label="Looking for JetBrains themes" />
|
||||
<T>Looking for JetBrains themes…</T>
|
||||
<Spinner size={14} label="Looking for IntelliJ themes" />
|
||||
<T>Looking for IntelliJ themes…</T>
|
||||
</div>
|
||||
) : (
|
||||
<List
|
||||
items={rows}
|
||||
getKey={(r) => r.key}
|
||||
isSection={(r) => r.kind === "plugin"}
|
||||
activeIndex={chosen ? active : -1}
|
||||
onActiveChange={setActive}
|
||||
rowHeight={44}
|
||||
rowHeight={28}
|
||||
sectionHeight={30}
|
||||
className={styles.intellijThemesList}
|
||||
aria-label={tx("JetBrains theme plugins")}
|
||||
aria-label={tx("IntelliJ themes")}
|
||||
empty={
|
||||
<div className={styles.intellijThemesStatus} role="note">
|
||||
{error ?? (
|
||||
@@ -107,21 +108,24 @@ function IntellijThemesDialog() {
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
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>
|
||||
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>
|
||||
</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>
|
||||
|
||||
@@ -407,30 +407,37 @@
|
||||
padding: 8px 10px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.intellijPlugin {
|
||||
.intellijTheme {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
.intellijPluginHead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.intellijPluginThemes {
|
||||
overflow: hidden;
|
||||
color: var(--fg-muted);
|
||||
.intellijTheme > .muted {
|
||||
flex-shrink: 0;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.intellijPlugin {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
align-self: stretch;
|
||||
min-width: 0;
|
||||
}
|
||||
/* A line above each plugin but the first, as in IDEA's Theme list. */
|
||||
.intellijPluginNext {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.intellijPluginName {
|
||||
overflow: hidden;
|
||||
color: var(--fg-secondary);
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.intellijPluginIde {
|
||||
flex-shrink: 0;
|
||||
margin-left: auto;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
@@ -569,7 +569,7 @@ function gearMenu(plugins: readonly PluginInfo[], updates: number, actions: Gear
|
||||
...(actions.canImport
|
||||
? [
|
||||
{ kind: "separator" as const },
|
||||
{ label: "Import Theme from JetBrains IDE…", run: actions.importInstalledIntellij },
|
||||
{ label: "Import Theme from IntelliJ IDE…", run: actions.importInstalledIntellij },
|
||||
{ label: "Import IntelliJ Theme from File…", run: actions.importIntellijFile },
|
||||
]
|
||||
: []),
|
||||
|
||||
@@ -41,15 +41,6 @@ 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[];
|
||||
@@ -109,8 +100,8 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("IntelliJ theme import", () => {
|
||||
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);
|
||||
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);
|
||||
expect(read).toHaveBeenCalledWith("/downloads/DeepSea.zip");
|
||||
const [name, files] = stage.mock.calls[0]!;
|
||||
expect(name).toBe(ID);
|
||||
@@ -120,11 +111,14 @@ describe("IntelliJ theme import", () => {
|
||||
"themes/shallow.theme.json",
|
||||
]);
|
||||
expect(installed).toEqual(["/app/plugins/.downloads/generated"]);
|
||||
// Which of its themes to use is the user's choice.
|
||||
expect(useThemeOverride.getState().theme).toBeNull();
|
||||
expect(useThemeOverride.getState().theme).toBe(`plugin:${ID}/shallow`);
|
||||
});
|
||||
|
||||
it("returns nothing when the install is declined", async () => {
|
||||
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 });
|
||||
setConsentPrompt(async () => null);
|
||||
expect(await importIntellijTheme("/downloads/DeepSea.jar")).toBeNull();
|
||||
expect(useThemeOverride.getState().theme).toBeNull();
|
||||
@@ -158,33 +152,33 @@ describe("IntelliJ theme import", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Import Theme from JetBrains IDE", () => {
|
||||
it("lists one row per theme plugin, the one in use first, and imports the chosen plugin", async () => {
|
||||
describe("Import Theme from IntelliJ IDE", () => {
|
||||
it("lists the installed themes by plugin, the one in use first, and imports the chosen one", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onImported = vi.fn();
|
||||
render(<IntellijThemesDialogHost />);
|
||||
act(() => showInstalledIntellijThemes(onImported));
|
||||
const list = await screen.findByRole("listbox", { name: "JetBrains theme plugins" });
|
||||
const list = await screen.findByRole("listbox", { name: "IntelliJ themes" });
|
||||
const options = await waitFor(() => {
|
||||
const found = Array.from(list.querySelectorAll('[role="option"]'));
|
||||
expect(found).toHaveLength(2);
|
||||
return found;
|
||||
});
|
||||
// A plugin brings all its themes: they are listed in its row, not offered one by one.
|
||||
expect(options[0]).toHaveTextContent("Deep Sea Themes");
|
||||
// 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");
|
||||
expect(options[0]).toHaveTextContent("In use");
|
||||
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]).toHaveTextContent("Deep Sea");
|
||||
expect(options[1]).not.toHaveTextContent("In use");
|
||||
|
||||
await user.click(within(list).getByText("1 theme · DataGrip 2026.2"));
|
||||
await user.click(screen.getByText("Deep Sea"));
|
||||
await user.click(screen.getByRole("button", { name: "Import" }));
|
||||
await waitFor(() => expect(onImported).toHaveBeenCalledWith(ID));
|
||||
expect(read).toHaveBeenCalledWith("/dg/plugins/NightOwl");
|
||||
expect(useThemeOverride.getState().theme).toBeNull();
|
||||
expect(screen.queryByRole("listbox", { name: "JetBrains theme plugins" })).toBeNull();
|
||||
expect(read).toHaveBeenCalledWith("/ij/plugins/DeepSea");
|
||||
expect(useThemeOverride.getState().theme).toBe(`plugin:${ID}/deep-sea`);
|
||||
expect(screen.queryByRole("listbox", { name: "IntelliJ themes" })).toBeNull();
|
||||
});
|
||||
|
||||
it("offers a file when no IDE has theme plugins", async () => {
|
||||
|
||||
@@ -517,7 +517,7 @@ describe("PluginsPage", () => {
|
||||
);
|
||||
const imports = async () => {
|
||||
await user.click(screen.getByRole("button", { name: "Manage Plugins" }));
|
||||
const found = ["Import Theme from JetBrains IDE…", "Import IntelliJ Theme from File…"].filter((name) =>
|
||||
const found = ["Import Theme from IntelliJ IDE…", "Import IntelliJ Theme from File…"].filter((name) =>
|
||||
screen.queryByRole("menuitem", { name }),
|
||||
);
|
||||
act(() => hideContextMenu());
|
||||
|
||||
@@ -113,19 +113,10 @@ export function activate(): () => void {
|
||||
},
|
||||
{
|
||||
id: "plugins.importInstalledIntellijTheme",
|
||||
title: "Import Theme from JetBrains IDE…",
|
||||
title: "Import Theme from IntelliJ IDE…",
|
||||
category: "Plugins",
|
||||
icon: "plugin",
|
||||
keywords: [
|
||||
"intellij",
|
||||
"jetbrains",
|
||||
"pycharm",
|
||||
"webstorm",
|
||||
"android studio",
|
||||
"theme",
|
||||
"color scheme",
|
||||
"migrate",
|
||||
],
|
||||
keywords: ["intellij", "jetbrains", "theme", "color scheme", "migrate"],
|
||||
when: "projectOpen",
|
||||
run: () => showInstalledIntellijThemes(),
|
||||
},
|
||||
|
||||
@@ -2,26 +2,30 @@
|
||||
* 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. Its
|
||||
* themes join the others; which one to use is chosen in Settings › Appearance.
|
||||
* here (`intellijTheme.ts`), installed through the usual install page — and
|
||||
* its theme is applied.
|
||||
*/
|
||||
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 } from "./intellijTheme";
|
||||
import { intellijThemePackage, type ThemePackage } from "./intellijTheme";
|
||||
import { errorText, installFromDisk } from "./store";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
export async function importIntellijTheme(path?: string): Promise<string | null> {
|
||||
export async function importIntellijTheme(path?: string, themeId?: string): Promise<string | null> {
|
||||
const backend = pluginsBackend();
|
||||
let pkg: ThemePackage;
|
||||
let dir: string;
|
||||
try {
|
||||
const picked = path ?? (await backend.pickIntellijTheme());
|
||||
if (!picked) return null;
|
||||
const pkg = intellijThemePackage(await backend.readIntellijTheme(picked));
|
||||
pkg = intellijThemePackage(await backend.readIntellijTheme(picked));
|
||||
dir = await backend.stagePackage(pkg.id, pkg.files);
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
@@ -32,7 +36,11 @@ export async function importIntellijTheme(path?: string): Promise<string | null>
|
||||
});
|
||||
return null;
|
||||
}
|
||||
return installFromDisk(dir);
|
||||
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;
|
||||
}
|
||||
|
||||
interface DialogState {
|
||||
|
||||
@@ -384,6 +384,8 @@ 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. */
|
||||
@@ -395,15 +397,16 @@ 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 themes = source.themes.map((t) => {
|
||||
const converted = 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 c;
|
||||
return { sourceId: t.id, converted: c };
|
||||
});
|
||||
if (themes.length === 0) throw new Error("The plugin has no themes");
|
||||
if (converted.length === 0) throw new Error("The plugin has no themes");
|
||||
const themes = converted.map((c) => c.converted);
|
||||
// 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 = {
|
||||
@@ -424,5 +427,6 @@ 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 })),
|
||||
};
|
||||
}
|
||||
@@ -171,18 +171,16 @@ 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, onPreview, ...aria }: SelectProps<V>) {
|
||||
export function Select<V extends string>({ value, options, onChange, disabled, ...aria }: SelectProps<V>) {
|
||||
return (
|
||||
<UiSelect<V>
|
||||
value={value}
|
||||
options={options}
|
||||
onChange={onChange}
|
||||
disabled={disabled}
|
||||
onPreview={onPreview}
|
||||
className={styles.select}
|
||||
aria-label={aria["aria-label"]}
|
||||
/>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
import { FontPicker } from "../components/FontPicker";
|
||||
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useId, useRef, useState, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
@@ -33,8 +33,7 @@ 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 { currentThemeChoice, originDetail, previewTheme, themeSelectOptions, useThemeChoices } from "@/workbench/theme";
|
||||
import { themePreview } from "@/workbench/quickSwitch";
|
||||
import { originDetail, themeSelectOptions, useThemeChoices } from "@/workbench/theme";
|
||||
|
||||
const BUILTIN_THEME_LABELS = BUILTIN_THEMES.map((t) => t.label);
|
||||
|
||||
@@ -63,28 +62,12 @@ 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}
|
||||
/>
|
||||
|
||||
@@ -49,6 +49,7 @@ 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,
|
||||
@@ -327,6 +328,7 @@ export function LogView() {
|
||||
<SplitPanel id="commits" defaultSize="54%" minSize="25%">
|
||||
<div className={styles.log}>
|
||||
<FilterBar />
|
||||
<LogIndexStatus repositories={repo} />
|
||||
<CommitList />
|
||||
</div>
|
||||
</SplitPanel>
|
||||
|
||||
@@ -23,6 +23,7 @@ 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),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -305,18 +305,6 @@
|
||||
.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;
|
||||
|
||||
@@ -5,13 +5,12 @@ 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, Icon, IconButton, Input, Select, T, type SelectOption } from "@/ui";
|
||||
import { Checkbox, Dialog, 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";
|
||||
|
||||
@@ -661,13 +660,7 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
|
||||
onClick={() => setSelected(w.path)}
|
||||
onDoubleClick={() => void executeAction("file.openProjectPath", w.path)}
|
||||
>
|
||||
{/* 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={styles.fileName}>{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>
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
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>
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
@@ -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 JetBrains IDE…": "Importar tema desde un IDE de JetBrains…",
|
||||
"Import Theme from IntelliJ IDE…": "Importar tema desde IntelliJ IDE…",
|
||||
"Import IntelliJ Theme from File…": "Importar tema de IntelliJ desde archivo…",
|
||||
"Import Theme from JetBrains IDE": "Importar tema desde un IDE de JetBrains",
|
||||
"Import Theme from IntelliJ IDE": "Importar tema desde IntelliJ IDE",
|
||||
"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",
|
||||
"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.",
|
||||
"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.",
|
||||
"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,6 +6164,9 @@
|
||||
"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",
|
||||
|
||||
@@ -2707,7 +2707,6 @@
|
||||
"New Worktree…": "新建工作树…",
|
||||
"Worktrees…": "工作树…",
|
||||
"Worktrees": "工作树",
|
||||
"Current worktree": "当前工作树",
|
||||
"New Worktree": "新建工作树",
|
||||
"Git Remotes": "Git 远程",
|
||||
"Define Remote": "定义远程",
|
||||
@@ -5843,18 +5842,18 @@
|
||||
"Unsigned": "未签名",
|
||||
"Roll Back to {previousVersion}": "回滚到 {previousVersion}",
|
||||
"Install Plugin from Package File…": "从插件包文件安装…",
|
||||
"Import Theme from JetBrains IDE…": "从 JetBrains IDE 导入主题…",
|
||||
"Import Theme from IntelliJ IDE…": "从 IntelliJ IDE 导入主题…",
|
||||
"Import IntelliJ Theme from File…": "从文件导入 IntelliJ 主题…",
|
||||
"Import Theme from JetBrains IDE": "从 JetBrains IDE 导入主题",
|
||||
"Import Theme from IntelliJ IDE": "从 IntelliJ IDE 导入主题",
|
||||
"Import IntelliJ Theme": "导入 IntelliJ 主题",
|
||||
"IntelliJ theme plugin or theme file": "IntelliJ 主题插件或主题文件",
|
||||
"Could not import the IntelliJ theme": "无法导入 IntelliJ 主题",
|
||||
"Import": "导入",
|
||||
"In use": "使用中",
|
||||
"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 颜色的项保留默认主题的颜色。",
|
||||
"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 颜色的项保留默认主题的颜色。",
|
||||
"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 文件。",
|
||||
@@ -6200,6 +6199,9 @@
|
||||
"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": "图标主题",
|
||||
@@ -6225,7 +6227,7 @@
|
||||
"Last Page": "最后一页",
|
||||
"{first}-{last} of {total}": "{first}-{last},共 {total}",
|
||||
"Model & effort settings": "模型与推理强度",
|
||||
"Logcat": "Logcat 日志",
|
||||
"Logcat": "Logcat",
|
||||
"Device": "设备",
|
||||
"No devices": "没有设备",
|
||||
"Minimum level": "最低级别",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import { useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Icon, type IconName } from "./icons";
|
||||
import { Popup } from "./Popup";
|
||||
@@ -33,8 +33,6 @@ 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;
|
||||
@@ -61,7 +59,6 @@ export function Select<V extends string = string>({
|
||||
className,
|
||||
renderValue,
|
||||
searchable = false,
|
||||
onPreview,
|
||||
...aria
|
||||
}: SelectProps<V>) {
|
||||
const tx = useTx();
|
||||
@@ -115,14 +112,6 @@ 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(
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
import { WindowControls } from "./WindowControls";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { projectInitials } from "./projectColor";
|
||||
import { keymapItems, themeItems, themePreview, type ThemePreview, VIEW_MODE_ITEMS } from "./quickSwitch";
|
||||
import { keymapItems, themeItems, VIEW_MODE_ITEMS } from "./quickSwitch";
|
||||
import { useContributedThemes } from "@/platform/themes";
|
||||
import { currentThemeChoice, useThemeOverride } from "./theme";
|
||||
import styles from "./TitleBar.module.css";
|
||||
@@ -147,18 +147,13 @@ export function customizeToolbarItems(
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** IDEA's main toolbar gear: Run Anything, Settings, Plugins, quick switches, toolbar customization, updates. */
|
||||
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" },
|
||||
@@ -168,25 +163,20 @@ export function gearMenuItems(
|
||||
{
|
||||
id: "gear.theme",
|
||||
label: "Theme",
|
||||
submenu: [
|
||||
...themeItems(themeId, preview),
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "settings.appearance" },
|
||||
],
|
||||
submenu: [...themeItems(themeId), { 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", onActive: restore, submenu: VIEW_MODE_ITEMS },
|
||||
{ id: "gear.viewMode", label: "View Mode", submenu: VIEW_MODE_ITEMS },
|
||||
{ kind: "separator" },
|
||||
{ id: "gear.customizeToolbar", label: "Customize Main Toolbar", onActive: restore, submenu: customize },
|
||||
{ id: "gear.customizeToolbar", label: "Customize Main Toolbar", submenu: customize },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "app.checkForUpdates" },
|
||||
];
|
||||
@@ -215,20 +205,12 @@ 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
|
||||
@@ -239,9 +221,15 @@ function GearButton({ customize }: { customize: MenuItem[] }) {
|
||||
className={styles.tool}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => (open ? close() : setOpen(true))}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
/>
|
||||
<Menu
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
anchor={ref}
|
||||
items={items}
|
||||
aria-label="IDE and Project Settings"
|
||||
/>
|
||||
<Menu open={open} onClose={close} anchor={ref} items={items} aria-label="IDE and Project Settings" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -218,12 +218,7 @@ 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 {
|
||||
@@ -238,6 +233,9 @@ 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
|
||||
|
||||
Reference in new issue
Заблокувати користувача