дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 04:56:08 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
e9a5a4c907 |
No files matched your search
@@ -134,10 +134,7 @@ fn codex_meta(line: &serde_json::Value) -> Option<(String, Option<String>)> {
|
||||
let payload =
|
||||
line.get("payload").filter(|p| p.get("type").and_then(serde_json::Value::as_str) == Some("session_meta"));
|
||||
let inner = payload.and_then(|p| p.get("payload")).or_else(|| {
|
||||
line.get("type")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|t| *t == "session_meta")
|
||||
.map(|_| line.get("payload").unwrap_or(line))
|
||||
line.get("type").and_then(serde_json::Value::as_str).filter(|t| *t == "session_meta").and(Some(line))
|
||||
})?;
|
||||
let id = inner.get("id").and_then(serde_json::Value::as_str)?.to_owned();
|
||||
let cwd = inner.get("cwd").and_then(serde_json::Value::as_str).map(str::to_owned);
|
||||
@@ -296,28 +293,16 @@ mod tests {
|
||||
assert_eq!(sessions[0].title, "hello there");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_meta_accepts_current_and_legacy_shapes() {
|
||||
let meta = json!({"id": "thread-1", "cwd": "/work/app"});
|
||||
for line in [
|
||||
json!({"type": "session_meta", "payload": meta}),
|
||||
json!({"payload": {"type": "session_meta", "payload": meta}}),
|
||||
json!({"type": "session_meta", "id": "thread-1", "cwd": "/work/app"}),
|
||||
] {
|
||||
assert_eq!(codex_meta(&line), Some(("thread-1".to_owned(), Some("/work/app".to_owned()))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_codex_rollouts_with_meta() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write(
|
||||
&tmp.path().join("sessions/2026/01/02/rollout-01.jsonl"),
|
||||
&[
|
||||
json!({"timestamp": "t", "type": "session_meta",
|
||||
"payload": {"id": "thread-1", "cwd": "/work/app"}}),
|
||||
json!({"timestamp": "t", "type": "event_msg",
|
||||
"payload": {"type": "user_message", "message": "add tests"}}),
|
||||
json!({"timestamp": "t", "payload": {"type": "session_meta",
|
||||
"payload": {"id": "thread-1", "cwd": "/work/app"}}}),
|
||||
json!({"timestamp": "t", "payload": {"type": "user_message",
|
||||
"payload": {"message": "add tests"}}}),
|
||||
],
|
||||
);
|
||||
write(&tmp.path().join("sessions/notes.jsonl"), &[json!({"nope": true})]);
|
||||
|
||||
@@ -1244,18 +1244,11 @@ impl DebugManager {
|
||||
// rdbg's terminate exits the Ruby process without terminating its children.
|
||||
let graceful =
|
||||
terminate && s.request == "launch" && s.adapter != "rdbg" && s.supports("supportsTerminateRequest");
|
||||
// A program suspended in the debugger cannot act on SIGTERM, and on macOS not even die of
|
||||
// SIGKILL while the debugger holds it: it is killed (with what it started) and the adapter
|
||||
// is told to end it. A killed program has no shutdown output to wait for.
|
||||
let killed = own_terminate && !graceful && s.suspended.get();
|
||||
if killed {
|
||||
crate::session::signal_debuggee(s, true).await;
|
||||
}
|
||||
if !s.conn.is_closed() {
|
||||
if graceful {
|
||||
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
|
||||
}
|
||||
if !graceful && (!own_terminate || killed) {
|
||||
if !graceful && !own_terminate {
|
||||
let _ = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
@@ -1266,7 +1259,7 @@ impl DebugManager {
|
||||
.await;
|
||||
}
|
||||
}
|
||||
if own_terminate && !graceful && !killed {
|
||||
if own_terminate && !graceful {
|
||||
// Signal before anything else: waiting on a request the adapter may not answer
|
||||
// would delay the shutdown the console is supposed to show.
|
||||
crate::session::signal_debuggee(s, false).await;
|
||||
@@ -1285,7 +1278,7 @@ impl DebugManager {
|
||||
// lets Run start again into an occupied port, so wait for the program first — with the
|
||||
// connection still open, so a second Stop can find the session and kill it.
|
||||
crate::session::wait_for_debuggee(s, terminate).await;
|
||||
if terminate && s.request == "launch" && !killed {
|
||||
if terminate && s.request == "launch" {
|
||||
// The adapter reports `terminated` only after it has drained the program's console
|
||||
// (java-debug waits up to 5 s for the pump): closing before that drops the last
|
||||
// shutdown lines from the console.
|
||||
|
||||
@@ -527,14 +527,6 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
}
|
||||
}
|
||||
"disconnect" => {
|
||||
// Like Delve: the adapter ends the program it launched.
|
||||
#[cfg(unix)]
|
||||
if msg["arguments"]["terminateDebuggee"] == true
|
||||
&& let Some(pid) = script.debuggee_pid
|
||||
{
|
||||
// SAFETY: plain syscall on the test's own child process.
|
||||
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
|
||||
}
|
||||
ok!(msg, Value::Null);
|
||||
let _ = w.lock().await.shutdown().await;
|
||||
break;
|
||||
@@ -2327,44 +2319,6 @@ async fn stop_waits_for_the_launched_program_to_exit() {
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Terminated)).await;
|
||||
}
|
||||
|
||||
/// Delve and other adapters without `terminate`: a program stopped at a breakpoint cannot
|
||||
/// handle the SIGTERM Stop sends, so Stop has the adapter end it instead of waiting out the grace period.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn stop_kills_a_program_suspended_at_a_breakpoint_at_once() {
|
||||
let mut child = std::process::Command::new("python3")
|
||||
.args(["-c", "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(30)"])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let pid = child.id();
|
||||
let exited = Arc::new(AtomicBool::new(false));
|
||||
{
|
||||
let exited = exited.clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
exited.store(true, Ordering::Release);
|
||||
});
|
||||
}
|
||||
let h = harness(Script { debuggee_pid: Some(pid), supports_terminate: false, ..Default::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let session = h.manager.session(id).unwrap();
|
||||
while session.debuggee_pid.load(Ordering::Acquire) != i64::from(pid) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await; // let the program install its trap
|
||||
let started = Instant::now();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
assert!(elapsed < Duration::from_secs(3), "stop waited {elapsed:?} for a suspended program");
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while !exited.load(Ordering::Acquire) {
|
||||
assert!(Instant::now() < deadline, "the suspended program was left running");
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_second_stop_kills_the_program_instead_of_waiting() {
|
||||
|
||||
@@ -1159,8 +1159,7 @@ impl Repo {
|
||||
write::stage_patch(self, patch, &|path| encoding(path).map(Into::into))
|
||||
}
|
||||
/// Discards unstaged changes: tracked paths are restored from the index (staged
|
||||
/// changes are kept), untracked files and directories are deleted. A submodule goes back
|
||||
/// to the commit the index records, with its tracked files restored.
|
||||
/// changes are kept), untracked files and directories are deleted.
|
||||
pub fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::discard(self, paths)
|
||||
|
||||
@@ -25,19 +25,16 @@ pub(crate) fn save(r: &Repo, message: &str) -> IdeResult<()> {
|
||||
if run(r.root(), &["status", "--porcelain", "--untracked-files=no"], None)?.stdout_str().trim().is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let before = stash_top(r);
|
||||
let before = run(r.root(), &["rev-parse", "-q", "--verify", "refs/stash"], None).map(|o| o.stdout_str()).ok();
|
||||
run(r.root(), &["stash", "push", "-q", "-m", message], None)?;
|
||||
// A stash that succeeds without a new entry found nothing it saves: the status above also
|
||||
// lists submodules at another commit or with changes inside, which a stash leaves in place.
|
||||
let Some(id) = stash_top(r).filter(|id| Some(id) != before.as_ref()) else { return Ok(()) };
|
||||
std::fs::write(marker, id)?;
|
||||
let id = run(r.root(), &["rev-parse", "refs/stash"], None)?.stdout_str();
|
||||
if before.as_deref().map(str::trim) == Some(id.trim()) {
|
||||
return Err(IdeError::invalid("could not save the local changes"));
|
||||
}
|
||||
std::fs::write(marker, id.trim())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stash_top(r: &Repo) -> Option<String> {
|
||||
run(r.root(), &["rev-parse", "-q", "--verify", "refs/stash"], None).ok().map(|o| o.stdout_str().trim().to_owned())
|
||||
}
|
||||
|
||||
/// Brings the saved changes back once no operation is in progress. Fails when they come
|
||||
/// back with conflicts (they then also stay in the stash).
|
||||
pub(crate) fn restore(r: &Repo) -> IdeResult<()> {
|
||||
|
||||
@@ -391,24 +391,18 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
let rel = r.rel_paths(paths)?;
|
||||
// `git restore --worktree` refuses unmerged paths: roll those back to HEAD first.
|
||||
discard_unmerged(r, &rel)?;
|
||||
let (mut tracked, mut untracked, mut submodules) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (mut tracked, mut untracked) = (Vec::new(), Vec::new());
|
||||
{
|
||||
let repo = r.gix()?;
|
||||
let index = repo.index_or_empty().map_err(gx)?;
|
||||
for p in rel {
|
||||
let exact = index.entry_index_by_path(BStr::new(p.as_bytes())).ok().map(|i| &index.entries()[i]);
|
||||
let exact = index.entry_index_by_path(BStr::new(p.as_bytes())).is_ok();
|
||||
let dir_prefix = if p == "." { String::new() } else { format!("{}/", p.trim_end_matches('/')) };
|
||||
let children = index.prefixed_entries(BStr::new(dir_prefix.as_bytes()));
|
||||
if let Some(entry) = exact {
|
||||
if entry.mode.is_submodule() {
|
||||
submodules.push(p);
|
||||
} else {
|
||||
tracked.push(p);
|
||||
}
|
||||
let has_tracked_children = index.prefixed_entries(BStr::new(dir_prefix.as_bytes())).is_some();
|
||||
if exact {
|
||||
tracked.push(p);
|
||||
} else if r.abs_path(&p).is_dir() {
|
||||
if let Some(children) = children {
|
||||
submodules
|
||||
.extend(children.iter().filter(|e| e.mode.is_submodule()).map(|e| e.path(&index).to_string()));
|
||||
if has_tracked_children {
|
||||
tracked.push(p.clone());
|
||||
}
|
||||
untracked.push(p);
|
||||
@@ -418,11 +412,6 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
}
|
||||
}
|
||||
run_paths(r, &["restore", "--worktree"], &tracked)?;
|
||||
// A plain restore leaves a submodule alone. This one checks out the commit the index
|
||||
// records there and restores its tracked files, keeping its untracked ones.
|
||||
if crate::execution_allowed() {
|
||||
run_paths(r, &["restore", "--recurse-submodules", "--worktree"], &submodules)?;
|
||||
}
|
||||
if !untracked.is_empty() {
|
||||
// `git clean` keeps ignored files and refuses paths outside the worktree.
|
||||
run_paths(r, &["clean", "-f", "-d", "-q"], &untracked)?;
|
||||
|
||||
@@ -69,8 +69,7 @@ impl Fixture {
|
||||
fn push_from_other(&self, bare: &Path, rel: &str, content: &str) {
|
||||
let other = self.tmp.path().join(format!("other-{}", rel.replace('/', "_")));
|
||||
if !other.exists() {
|
||||
let (bare, other_dir) = (bare.to_str().unwrap(), other.to_str().unwrap());
|
||||
git_in(self.tmp.path(), &["clone", "-q", "-c", "core.autocrlf=false", bare, other_dir]);
|
||||
git_in(self.tmp.path(), &["clone", "-q", bare.to_str().unwrap(), other.to_str().unwrap()]);
|
||||
configure(&other);
|
||||
}
|
||||
git_in(&other, &["pull", "-q", "--rebase"]);
|
||||
@@ -637,73 +636,6 @@ fn update_with_rebase_keeps_a_file_added_then_deleted_added_to_the_index() {
|
||||
assert!(fx.git(&["status", "--porcelain", "--", "ad.txt"]).starts_with('A'), "still added");
|
||||
}
|
||||
|
||||
/// Submodules `dirty` and `moved` (each with commits "one" and "two", at "two") committed in
|
||||
/// the clone of [`Fixture::with_origin`] and pushed; then `dirty` gets an uncommitted edit of a
|
||||
/// tracked file plus an untracked file, and `moved` is checked out at "one". Returns the commit
|
||||
/// the superproject records for `moved`.
|
||||
fn with_changed_submodules(fx: &Fixture) -> String {
|
||||
for name in ["dirty", "moved"] {
|
||||
let lib = fx.tmp.path().join(format!("lib-{name}"));
|
||||
std::fs::create_dir(&lib).unwrap();
|
||||
git_in(&lib, &["init", "-q"]);
|
||||
configure(&lib);
|
||||
std::fs::write(lib.join("f.txt"), "one\n").unwrap();
|
||||
git_in(&lib, &["add", "-A"]);
|
||||
git_in(&lib, &["commit", "-q", "-m", "one"]);
|
||||
std::fs::write(lib.join("f.txt"), "two\n").unwrap();
|
||||
git_in(&lib, &["commit", "-q", "-am", "two"]);
|
||||
let url = lib.to_str().unwrap();
|
||||
fx.git(&["-c", "protocol.file.allow=always", "-c", "core.autocrlf=false", "submodule", "add", "-q", url, name]);
|
||||
configure(&fx.path(name));
|
||||
}
|
||||
fx.commit_all("submodules");
|
||||
fx.git(&["push", "-q", "origin", "main"]);
|
||||
let recorded = git_in(&fx.path("moved"), &["rev-parse", "HEAD"]);
|
||||
fx.write("dirty/f.txt", "edited\n");
|
||||
fx.write("dirty/untracked.txt", "u\n");
|
||||
git_in(&fx.path("moved"), &["checkout", "-q", "HEAD~1"]);
|
||||
recorded
|
||||
}
|
||||
|
||||
/// git lists submodules at another commit or with changes inside among the superproject's
|
||||
/// changes, but its stash leaves them in place, so Update Project has nothing to put aside (#3632).
|
||||
#[test]
|
||||
fn update_with_changed_submodules_and_no_other_local_changes() {
|
||||
for (rebase, earlier_stash) in [(false, false), (false, true), (true, false), (true, true)] {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
let recorded = with_changed_submodules(&fx);
|
||||
if earlier_stash {
|
||||
fx.write("a.txt", "stashed\n");
|
||||
fx.git(&["stash", "push", "-q", "-m", "earlier"]);
|
||||
}
|
||||
fx.push_from_other(&bare, "remote.txt", "r\n");
|
||||
let repo = fx.repo();
|
||||
let (cancel, out) = quiet();
|
||||
repo.pull(rebase, &cancel, &out).unwrap_or_else(|e| panic!("rebase={rebase} stash={earlier_stash}: {e}"));
|
||||
assert!(fx.exists("remote.txt"));
|
||||
assert_eq!(fx.read("dirty/f.txt"), "edited\n");
|
||||
assert_ne!(git_in(&fx.path("moved"), &["rev-parse", "HEAD"]), recorded);
|
||||
let stashes = fx.git(&["stash", "list"]);
|
||||
assert_eq!(stashes.lines().count(), usize::from(earlier_stash), "{stashes}");
|
||||
assert!(!fx.dir.join(".git/openidea-saved-changes").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollback_changed_submodules_restores_the_recorded_commit_and_tracked_files() {
|
||||
for whole_root in [false, true] {
|
||||
let (fx, _bare) = Fixture::with_origin();
|
||||
let recorded = with_changed_submodules(&fx);
|
||||
let repo = fx.repo();
|
||||
let paths = if whole_root { vec![fx.dir.clone()] } else { vec![fx.path("dirty"), fx.path("moved")] };
|
||||
repo.discard(&paths).unwrap();
|
||||
assert_eq!(fx.read("dirty/f.txt"), "two\n", "whole_root={whole_root}");
|
||||
assert_eq!(git_in(&fx.path("moved"), &["rev-parse", "HEAD"]), recorded);
|
||||
assert_eq!(fx.read("dirty/untracked.txt"), "u\n", "untracked files of a submodule are kept");
|
||||
assert_eq!(fx.git(&["status", "--porcelain", "--ignore-submodules=untracked"]), "");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_to_the_remote_branch_drops_local_commits_and_keeps_local_changes() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
|
||||
@@ -441,26 +441,13 @@ impl SettingsStore {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JetBrainsSettings {
|
||||
pub entries: Vec<String>,
|
||||
/// Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`,
|
||||
/// `codestyles/*.xml` and some of `options/`.
|
||||
/// Entry name → text, for `colors/*.icls` and the `options/*.xml` files OpenIDEA reads.
|
||||
pub files: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
const JETBRAINS_MARKER: &str = "IntelliJ IDEA Global Settings";
|
||||
const JETBRAINS_OPTIONS: [&str; 9] = [
|
||||
"options/editor-font.xml",
|
||||
"options/terminal-font.xml",
|
||||
"options/colors.scheme.xml",
|
||||
"options/code.style.schemes.xml",
|
||||
"options/editor.xml",
|
||||
"options/ide.general.xml",
|
||||
// The active keymap is stored per operating system.
|
||||
"options/mac/keymap.xml",
|
||||
"options/windows/keymap.xml",
|
||||
"options/linux/keymap.xml",
|
||||
];
|
||||
/// Folders whose files are all read: (folder, extension).
|
||||
const JETBRAINS_READ_DIRS: [(&str, &str); 3] = [("colors/", ".icls"), ("keymaps/", ".xml"), ("codestyles/", ".xml")];
|
||||
const JETBRAINS_OPTIONS: [&str; 4] =
|
||||
["options/editor-font.xml", "options/colors.scheme.xml", "options/editor.xml", "options/ide.general.xml"];
|
||||
const JETBRAINS_MAX_TEXT: u64 = 4 << 20;
|
||||
|
||||
/// The settings of a JetBrains IDE: an exported `settings.zip`, or the IDE's own settings folder
|
||||
@@ -471,23 +458,11 @@ pub fn read_jetbrains_settings(path: &Path) -> IdeResult<JetBrainsSettings> {
|
||||
|
||||
fn is_mapped_jetbrains_file(name: &str) -> bool {
|
||||
JETBRAINS_OPTIONS.contains(&name)
|
||||
|| JETBRAINS_READ_DIRS
|
||||
.iter()
|
||||
.any(|(dir, ext)| name.strip_prefix(dir).is_some_and(|n| !n.contains('/') && n.ends_with(ext)))
|
||||
|| name.strip_prefix("colors/").is_some_and(|n| !n.contains('/') && n.ends_with(".icls"))
|
||||
}
|
||||
|
||||
/// Folders of the settings folder whose files are listed (their names say what the user customised).
|
||||
const JETBRAINS_LISTED_DIRS: [&str; 9] = [
|
||||
"options",
|
||||
"options/mac",
|
||||
"options/windows",
|
||||
"options/linux",
|
||||
"colors",
|
||||
"keymaps",
|
||||
"codestyles",
|
||||
"templates",
|
||||
"inspection",
|
||||
];
|
||||
const JETBRAINS_LISTED_DIRS: [&str; 6] = ["options", "colors", "keymaps", "codestyles", "templates", "inspection"];
|
||||
|
||||
fn read_jetbrains_folder(dir: &Path) -> IdeResult<JetBrainsSettings> {
|
||||
use std::io::Read;
|
||||
@@ -961,25 +936,11 @@ mod tests {
|
||||
("options/editor-font.xml", "<application/>"),
|
||||
("options/vcs.xml", "<application/>"),
|
||||
("keymaps/macOS.xml", "<keymap/>"),
|
||||
("keymaps/nested/ignored.xml", "<keymap/>"),
|
||||
("codestyles/Default.xml", "<code_scheme/>"),
|
||||
("options/mac/keymap.xml", "<application/>"),
|
||||
("options/terminal-font.xml", "<application/>"),
|
||||
],
|
||||
);
|
||||
let read = read_jetbrains_settings(&ok).unwrap();
|
||||
assert_eq!(read.entries.len(), 9);
|
||||
assert_eq!(
|
||||
read.files.keys().collect::<Vec<_>>(),
|
||||
[
|
||||
"codestyles/Default.xml",
|
||||
"colors/_@user_Darcula.icls",
|
||||
"keymaps/macOS.xml",
|
||||
"options/editor-font.xml",
|
||||
"options/mac/keymap.xml",
|
||||
"options/terminal-font.xml"
|
||||
]
|
||||
);
|
||||
assert_eq!(read.entries.len(), 5);
|
||||
assert_eq!(read.files.keys().collect::<Vec<_>>(), ["colors/_@user_Darcula.icls", "options/editor-font.xml"]);
|
||||
assert!(read_jetbrains_settings(&write("other.zip", &[("options/editor.xml", "")])).is_err());
|
||||
std::fs::write(tmp.path().join("plain.zip"), "not a zip").unwrap();
|
||||
assert!(read_jetbrains_settings(&tmp.path().join("plain.zip")).is_err());
|
||||
@@ -998,31 +959,18 @@ mod tests {
|
||||
put("colors/nested/ignored.icls", "<scheme/>");
|
||||
put("options/editor-font.xml", "<application/>");
|
||||
put("options/vcs.xml", "<application/>");
|
||||
put("options/mac/keymap.xml", "<application/>");
|
||||
put("keymaps/macOS.xml", "<keymap/>");
|
||||
put("codestyles/Default.xml", "<code_scheme/>");
|
||||
put("plugins/Tools/lib/tools.jar", "jar");
|
||||
|
||||
let read = read_jetbrains_settings(&config).unwrap();
|
||||
assert_eq!(
|
||||
read.files.keys().collect::<Vec<_>>(),
|
||||
[
|
||||
"codestyles/Default.xml",
|
||||
"colors/_@user_Darcula.icls",
|
||||
"keymaps/macOS.xml",
|
||||
"options/editor-font.xml",
|
||||
"options/mac/keymap.xml"
|
||||
]
|
||||
);
|
||||
assert_eq!(read.files.keys().collect::<Vec<_>>(), ["colors/_@user_Darcula.icls", "options/editor-font.xml"]);
|
||||
assert_eq!(
|
||||
read.entries,
|
||||
[
|
||||
"options/editor-font.xml",
|
||||
"options/vcs.xml",
|
||||
"options/mac/keymap.xml",
|
||||
"colors/_@user_Darcula.icls",
|
||||
"keymaps/macOS.xml",
|
||||
"codestyles/Default.xml",
|
||||
"installed.txt"
|
||||
]
|
||||
);
|
||||
|
||||
@@ -330,13 +330,7 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<
|
||||
/// disabled in place (no rebuild).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn menu_set_disabled(window: WebviewWindow, app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec<String>) {
|
||||
// The window whose menu runs: a project window also while its Settings window is focused.
|
||||
if menu::native_menu_bar()
|
||||
&& windows::target_window(&app).is_some_and(|target| !owns_menu_config(window.label(), target.label()))
|
||||
{
|
||||
return;
|
||||
}
|
||||
pub fn menu_set_disabled(app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec<String>) {
|
||||
let disabled: std::collections::HashSet<String> = ids.into_iter().collect();
|
||||
if *menu_state.disabled.lock() == disabled {
|
||||
return;
|
||||
|
||||
+14
-13
@@ -373,24 +373,25 @@ pub(crate) fn dispatch_menu_action(app: &tauri::AppHandle, id: &str) {
|
||||
let Some(route) = menu::route(&menu::spec(menu::Os::current()), id) else { return };
|
||||
match windows::target_window(app) {
|
||||
Some(w) => {
|
||||
// The window to bring back to the front once what the action shows is closed (Settings).
|
||||
let mut return_to = None;
|
||||
let label = match windows::menu_destination(w.label(), &route.action) {
|
||||
windows::MenuDestination::Own => w.label(),
|
||||
windows::MenuDestination::Parent { label, raise } => {
|
||||
if raise && let Some(parent) = app.get_webview_window(label) {
|
||||
windows::focus(&parent);
|
||||
return_to = Some(w.label());
|
||||
}
|
||||
label
|
||||
// App-level items of an auxiliary window go to its project window. Settings is modal for it:
|
||||
// nothing else gets through. Others handle their own items; Close Tab closes the window.
|
||||
let label = match windows::auxiliary(w.label()) {
|
||||
Some((_, parent))
|
||||
if matches!(
|
||||
route.action.as_str(),
|
||||
"app.quit" | "file.settings" | "file.projectStructure" | "file.newProjectsSettings"
|
||||
) =>
|
||||
{
|
||||
parent
|
||||
}
|
||||
windows::MenuDestination::Close => {
|
||||
Some((kind, _)) if kind.modal() => return,
|
||||
Some(_) if route.action == "editor.closeTab" => {
|
||||
let _ = w.close();
|
||||
return;
|
||||
}
|
||||
_ => w.label(),
|
||||
};
|
||||
let event = menu::MenuEvent { route: &route, return_to };
|
||||
if let Err(e) = app.emit_to(label, menu::MENU_EVENT, &event) {
|
||||
if let Err(e) = app.emit_to(label, menu::MENU_EVENT, &route) {
|
||||
tracing::warn!("failed to deliver menu event {id}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -904,17 +904,6 @@ pub struct MenuRoute {
|
||||
pub arg: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload of [`MENU_EVENT`]: the route, and the window that was in front when the item was
|
||||
/// chosen if the action runs in another one (a Settings window's project window).
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MenuEvent<'a> {
|
||||
#[serde(flatten)]
|
||||
pub route: &'a MenuRoute,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub return_to: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// Maps a clicked item id to the action to run. `None` for ids that are not
|
||||
/// IDE items (native roles, placeholders).
|
||||
pub fn route(spec: &[Entry], id: &str) -> Option<MenuRoute> {
|
||||
|
||||
@@ -360,8 +360,8 @@ impl AuxKind {
|
||||
self != AuxKind::Settings
|
||||
}
|
||||
|
||||
/// Has no actions of its own: menu items run in its project window.
|
||||
fn runs_menu_in_parent(self) -> bool {
|
||||
/// Modal for its parent: menu items other than app-level ones are dropped.
|
||||
pub fn modal(self) -> bool {
|
||||
self == AuxKind::Settings
|
||||
}
|
||||
|
||||
@@ -386,34 +386,6 @@ pub fn auxiliary(label: &str) -> Option<(AuxKind, &str)> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a menu item chosen while window `label` is focused runs.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum MenuDestination<'a> {
|
||||
/// The window's own frontend.
|
||||
Own,
|
||||
/// The project window `label`; `raise` brings it to the front so what the action shows is seen.
|
||||
Parent { label: &'a str, raise: bool },
|
||||
/// The window itself is the tab: Close Tab closes it.
|
||||
Close,
|
||||
}
|
||||
|
||||
/// Actions an auxiliary window always leaves to its project window.
|
||||
const PARENT_ACTIONS: [&str; 4] = ["app.quit", "file.settings", "file.projectStructure", "file.newProjectsSettings"];
|
||||
|
||||
/// Where menu item `action` runs while window `label` is focused. As in IDEA, the menu stays usable
|
||||
/// with Settings open: it runs in the project window, whose enablement (no focused editor) the menu shows.
|
||||
pub fn menu_destination<'a>(label: &'a str, action: &str) -> MenuDestination<'a> {
|
||||
match auxiliary(label) {
|
||||
None => MenuDestination::Own,
|
||||
Some((_, parent)) if PARENT_ACTIONS.contains(&action) => {
|
||||
MenuDestination::Parent { label: parent, raise: false }
|
||||
}
|
||||
Some((kind, parent)) if kind.runs_menu_in_parent() => MenuDestination::Parent { label: parent, raise: true },
|
||||
Some(_) if action == "editor.closeTab" => MenuDestination::Close,
|
||||
Some(_) => MenuDestination::Own,
|
||||
}
|
||||
}
|
||||
|
||||
/// The project window an auxiliary window belongs to (`settings-main` → `main`).
|
||||
pub fn auxiliary_parent(label: &str) -> Option<&str> {
|
||||
auxiliary(label).map(|(_, parent)| parent)
|
||||
@@ -2377,27 +2349,6 @@ mod tests {
|
||||
assert_eq!(sorted_labels(labels.into_iter().filter(|l| auxiliary_parent(l).is_none())), ["main", "project-2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_items_chosen_in_settings_run_in_its_project_window() {
|
||||
use MenuDestination::*;
|
||||
for (label, action, expected) in [
|
||||
("main", "app.about", Own),
|
||||
("main", "editor.closeTab", Own),
|
||||
// #3625: Settings has no actions of its own; the rest of the menu runs in the project window.
|
||||
("settings-main", "app.checkForUpdates", Parent { label: "main", raise: true }),
|
||||
("settings-project-2", "file.newFile", Parent { label: "project-2", raise: true }),
|
||||
("settings-main", "editor.closeTab", Parent { label: "main", raise: true }),
|
||||
("settings-main", "file.settings", Parent { label: "main", raise: false }),
|
||||
("settings-main", "app.quit", Parent { label: "main", raise: false }),
|
||||
("comparison-main-0", "app.quit", Parent { label: "main", raise: false }),
|
||||
("comparison-main-0", "editor.closeTab", Close),
|
||||
("diff-main-1", "vcs.diff.next", Own),
|
||||
("deployment-main", "app.about", Own),
|
||||
] {
|
||||
assert_eq!(menu_destination(label, action), expected, "{label} {action}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_bounds_fit_current_work_area() {
|
||||
for (parent, size, work, expected) in [
|
||||
|
||||
@@ -6773,10 +6773,7 @@ export type JdkVendor = {
|
||||
*/
|
||||
export type JetBrainsSettings = {
|
||||
entries: string[],
|
||||
/**
|
||||
* Entry name → text, for the files OpenIDEA reads: `colors/*.icls`, `keymaps/*.xml`,
|
||||
* `codestyles/*.xml` and some of `options/`.
|
||||
*/
|
||||
/** Entry name → text, for `colors/*.icls` and the `options/*.xml` files OpenIDEA reads. */
|
||||
files: { [key in string]: string },
|
||||
};
|
||||
|
||||
|
||||
@@ -89,13 +89,11 @@ export function cellLspExtensions(ctx: EditorDocContext): Extension[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* A diff pane showing a file's open document: hover / quick docs, ⌘/Ctrl-click
|
||||
* navigation and semantic highlighting, so colours match the editor while
|
||||
* reviewing. Editing features stay with text editors; panes without a document
|
||||
* (revisions) get nothing from the semantic extension (`docOf` is null).
|
||||
* A diff pane showing a file's open document: hover / quick docs and ⌘/Ctrl-click navigation,
|
||||
* so references can be followed while reviewing. Editing features stay with text editors.
|
||||
*/
|
||||
export function diffLspExtensions(ctx: EditorDocContext): Extension[] {
|
||||
return [lspDoc.of(ctx), lspTheme, hintExtension(), hoverExtension(), navigationExtension(), semanticExtension()];
|
||||
return [lspDoc.of(ctx), lspTheme, hintExtension(), hoverExtension(), navigationExtension()];
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
|
||||
@@ -11,10 +11,7 @@ const component = (name: string, options: Record<string, string>) =>
|
||||
.map(([k, v]) => `<option name="${k}" value="${v}" />`)
|
||||
.join("")}</component></application>`;
|
||||
|
||||
const settings = {
|
||||
editor: { fontFamily: "JetBrains Mono", fontSize: 13, customSchemes: {}, colorOverrides: {} },
|
||||
customKeymaps: {},
|
||||
};
|
||||
const editor = { fontFamily: "JetBrains Mono", fontSize: 13, customSchemes: {}, colorOverrides: {} };
|
||||
|
||||
/** JetBrains Maple Mono's metrics (ascent 1.02em, descent 0.3em), for any family. */
|
||||
const fontHeight = (_family: string, size: number) => Math.ceil(size * 1.02) + Math.ceil(size * 0.3);
|
||||
@@ -58,7 +55,7 @@ const webstorm = {
|
||||
|
||||
describe("planJetBrainsImport", () => {
|
||||
it("maps a WebStorm export to the settings it has, and lists what is left out", async () => {
|
||||
const plan = await planJetBrainsImport(webstorm, settings, fontHeight);
|
||||
const plan = await planJetBrainsImport(webstorm, editor, fontHeight);
|
||||
const writes = Object.fromEntries(plan.writes);
|
||||
const schemes = writes["editor.customSchemes"] as Record<string, { name: string; parent: string }>;
|
||||
const [id, scheme] = Object.entries(schemes)[0]!;
|
||||
@@ -76,7 +73,6 @@ describe("planJetBrainsImport", () => {
|
||||
"files.ensureFinalNewline": true,
|
||||
"editor.stickyScroll": false,
|
||||
"editor.softWrap": false,
|
||||
"console.softWrap": true,
|
||||
"general.confirmExit": false,
|
||||
});
|
||||
expect(plan.rows).toContainEqual({
|
||||
@@ -88,7 +84,7 @@ describe("planJetBrainsImport", () => {
|
||||
label: "Remove trailing spaces on:",
|
||||
value: "All lines",
|
||||
});
|
||||
expect(plan.skipped).toEqual(["Code Style options other than Tabs and Indents", "Inspections", "Plugins"]);
|
||||
expect(plan.skipped).toEqual(["Keymap", "Code Style", "Inspections", "Plugins"]);
|
||||
expect(plan.invalid).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -106,7 +102,7 @@ describe("planJetBrainsImport", () => {
|
||||
}),
|
||||
},
|
||||
},
|
||||
settings,
|
||||
editor,
|
||||
fontHeight,
|
||||
);
|
||||
expect(plan.writes).toEqual([
|
||||
@@ -114,24 +110,20 @@ describe("planJetBrainsImport", () => {
|
||||
["editor.lineHeight", 27],
|
||||
["files.trimTrailingWhitespace", false],
|
||||
["editor.softWrap", true],
|
||||
["console.softWrap", true],
|
||||
]);
|
||||
expect(plan.skipped).toEqual([]);
|
||||
});
|
||||
|
||||
it("re-importing replaces the earlier copy of a scheme and drops its edits", async () => {
|
||||
const first = Object.fromEntries((await planJetBrainsImport(webstorm, settings, fontHeight)).writes);
|
||||
const customs = first["editor.customSchemes"] as typeof settings.editor.customSchemes;
|
||||
const first = Object.fromEntries((await planJetBrainsImport(webstorm, editor, fontHeight)).writes);
|
||||
const customs = first["editor.customSchemes"] as typeof editor.customSchemes;
|
||||
const [id] = Object.keys(customs);
|
||||
const again = await planJetBrainsImport(
|
||||
webstorm,
|
||||
{
|
||||
...settings,
|
||||
editor: {
|
||||
...settings.editor,
|
||||
customSchemes: customs,
|
||||
colorOverrides: { [id!]: { keyword: { bold: true } }, other: {} },
|
||||
},
|
||||
...editor,
|
||||
customSchemes: customs,
|
||||
colorOverrides: { [id!]: { keyword: { bold: true } }, other: {} },
|
||||
},
|
||||
fontHeight,
|
||||
);
|
||||
@@ -144,7 +136,7 @@ describe("planJetBrainsImport", () => {
|
||||
it("falls back to the font size when the font cannot be measured", async () => {
|
||||
const plan = await planJetBrainsImport(
|
||||
{ entries: [], files: { "options/editor-font.xml": component("DefaultFont", { FONT_SIZE: "20" }) } },
|
||||
settings,
|
||||
editor,
|
||||
() => undefined,
|
||||
);
|
||||
expect(plan.writes).toEqual([
|
||||
@@ -153,166 +145,8 @@ describe("planJetBrainsImport", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("imports the keymaps and makes the active one current", async () => {
|
||||
const keymap =
|
||||
'<keymap version="1" name="macOS copy" parent="Mac OS X 10.5+">' +
|
||||
'<action id="NextTab"><keyboard-shortcut first-keystroke="ctrl right" /></action>' +
|
||||
'<action id="GotoSuperMethod" /><action id="RunAnything" /></keymap>';
|
||||
const active =
|
||||
'<application><component name="KeymapManager"><active_keymap name="macOS copy" /></component></application>';
|
||||
const bundle = {
|
||||
entries: ["keymaps/macOS copy.xml", "keymaps/broken.xml"],
|
||||
files: {
|
||||
"keymaps/macOS copy.xml": keymap,
|
||||
"keymaps/broken.xml": "<nope",
|
||||
// The active keymap is stored per operating system; the host picks its own.
|
||||
"options/mac/keymap.xml": active,
|
||||
"options/windows/keymap.xml": active,
|
||||
"options/linux/keymap.xml": active,
|
||||
},
|
||||
};
|
||||
const plan = await planJetBrainsImport(bundle, settings);
|
||||
const expected = {
|
||||
name: "macOS copy",
|
||||
parent: "intellij-macos",
|
||||
overrides: { "editor.nextTab": ["Ctrl+Right"], "navigate.superMethod": [] },
|
||||
};
|
||||
expect(plan.writes).toEqual([
|
||||
["customKeymaps", { "custom.macos-copy": expected }],
|
||||
["keymap", "custom.macos-copy"],
|
||||
]);
|
||||
expect(plan.rows).toEqual([
|
||||
{ label: "Keymap", value: "macOS copy" },
|
||||
{ label: "Current keymap", value: "macOS copy" },
|
||||
]);
|
||||
expect(plan.unknownActions).toEqual(["RunAnything"]);
|
||||
expect(plan.invalid).toEqual(["broken.xml"]);
|
||||
|
||||
// Importing again replaces the earlier copy and keeps the user's other keymaps.
|
||||
const mine = { name: "Mine", parent: "vscode-macos", overrides: {} };
|
||||
const again = await planJetBrainsImport(bundle, {
|
||||
...settings,
|
||||
customKeymaps: { "custom.macos-copy": { ...expected, overrides: {} }, "custom.mine": mine },
|
||||
});
|
||||
expect(again.writes[0]).toEqual(["customKeymaps", { "custom.macos-copy": expected, "custom.mine": mine }]);
|
||||
});
|
||||
|
||||
it("imports the terminal font", async () => {
|
||||
const plan = await planJetBrainsImport(
|
||||
{
|
||||
entries: [],
|
||||
files: {
|
||||
"options/terminal-font.xml": component("TerminalFontOptions", {
|
||||
VERSION: "1",
|
||||
FONT_SIZE: "17",
|
||||
FONT_SIZE_2D: "17.0",
|
||||
FONT_FAMILY: "MesloLGS NF",
|
||||
LINE_SPACING: "1.1",
|
||||
}),
|
||||
},
|
||||
},
|
||||
settings,
|
||||
);
|
||||
expect(plan.writes).toEqual([
|
||||
["terminal.useEditorFont", false],
|
||||
["terminal.fontFamily", "MesloLGS NF"],
|
||||
["terminal.fontSize", 17],
|
||||
["terminal.lineHeight", 1.1],
|
||||
]);
|
||||
});
|
||||
|
||||
it("imports tabs and indents of the current code style scheme onto the languages' own styles", async () => {
|
||||
const scheme = (name: string, body: string) => `<code_scheme name="${name}" version="173">${body}</code_scheme>`;
|
||||
const plan = await planJetBrainsImport(
|
||||
{
|
||||
entries: ["codestyles/Default.xml", "codestyles/Team.xml"],
|
||||
files: {
|
||||
"options/code.style.schemes.xml": component("CodeStyleSchemeSettings", { CURRENT_SCHEME_NAME: "Team" }),
|
||||
"codestyles/Default.xml": scheme(
|
||||
"Default",
|
||||
'<codeStyleSettings language="Python"><indentOptions><option name="INDENT_SIZE" value="8" /></indentOptions></codeStyleSettings>',
|
||||
),
|
||||
"codestyles/Team.xml": scheme(
|
||||
"Team",
|
||||
'<option name="RIGHT_MARGIN" value="100" />' +
|
||||
'<option name="OTHER_INDENT_OPTIONS"><value><option name="TAB_SIZE" value="8" />' +
|
||||
'<option name="USE_TAB_CHARACTER" value="true" /></value></option>' +
|
||||
'<JSCodeStyleSettings version="0"><option name="USE_SEMICOLON_AFTER_STATEMENT" value="false" /></JSCodeStyleSettings>' +
|
||||
'<codeStyleSettings language="TypeScript"><option name="SPACE_WITHIN_BRACKETS" value="true" />' +
|
||||
'<indentOptions><option name="INDENT_SIZE" value="2" /><option name="CONTINUATION_INDENT_SIZE" value="2" />' +
|
||||
'<option name="TAB_SIZE" value="2" /></indentOptions></codeStyleSettings>' +
|
||||
'<codeStyleSettings language="HTML"><option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />' +
|
||||
'<indentOptions><option name="USE_TAB_CHARACTER" value="true" /></indentOptions></codeStyleSettings>' +
|
||||
'<codeStyleSettings language="Brainfuck"><indentOptions><option name="INDENT_SIZE" value="3" /></indentOptions></codeStyleSettings>',
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
...settings,
|
||||
editor: {
|
||||
...settings.editor,
|
||||
codeStyle: { languages: { typescript: { hardWrapAt: 90 }, go: { tabSize: 8 } } },
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(plan.writes).toEqual([
|
||||
["editor.codeStyle.hardWrapAt", 100],
|
||||
["editor.tabSize", 8],
|
||||
["editor.insertSpaces", false],
|
||||
[
|
||||
"editor.codeStyle.languages",
|
||||
{
|
||||
typescript: { hardWrapAt: 90, indent: 2, tabSize: 2 },
|
||||
typescriptreact: { indent: 2, tabSize: 2 },
|
||||
html: { useTab: true, lineCommentAtFirstColumn: false },
|
||||
go: { tabSize: 8 },
|
||||
},
|
||||
],
|
||||
]);
|
||||
expect(plan.rows).toContainEqual({ label: "Code Style › TypeScript", value: "Indent 2, Tab size 2" });
|
||||
expect(plan.rows).toContainEqual({ label: "Use tab character", value: "On" });
|
||||
expect(plan.skipped).toEqual(["Code Style options other than Tabs and Indents"]);
|
||||
});
|
||||
|
||||
it("imports the editor options that have a setting here", async () => {
|
||||
const xml =
|
||||
"<application>" +
|
||||
component("EditorSettings", {
|
||||
IS_SMOOTH_CARET_BLINKING: "true",
|
||||
IS_BLOCK_CURSOR: "true",
|
||||
ARE_LINE_NUMBERS_SHOWN: "false",
|
||||
LINE_NUMERATION: "HYBRID",
|
||||
SHOW_BREADCRUMBS_ABOVE: "true",
|
||||
CARET_BLINKING_PERIOD: "700",
|
||||
IS_ANIMATED_SCROLLING: "false",
|
||||
}).replace(/<\/?application>/g, "") +
|
||||
component("CodeInsightSettings", {
|
||||
AUTOINSERT_PAIR_QUOTE: "false",
|
||||
REFORMAT_ON_PASTE: "2",
|
||||
SMART_BACKSPACE: "1",
|
||||
PARAMETER_INFO_DELAY: "500",
|
||||
COMPLETION_CASE_SENSITIVE: "2",
|
||||
}).replace(/<\/?application>/g, "") +
|
||||
"</application>";
|
||||
const plan = await planJetBrainsImport({ entries: [], files: { "options/editor.xml": xml } }, settings);
|
||||
expect(Object.fromEntries(plan.writes)).toEqual({
|
||||
"editor.appearance.lineNumberMode": "hybrid",
|
||||
"editor.breadcrumbs.placement": "top",
|
||||
"editor.appearance.smoothCaretBlinking": true,
|
||||
"editor.appearance.blockCaret": true,
|
||||
"editor.appearance.lineNumbers": false,
|
||||
"editor.appearance.caretBlinkPeriod": 700,
|
||||
"editor.smartKeys.pairQuotes": false,
|
||||
"editor.completion.parameterInfoDelay": 500,
|
||||
"editor.smartKeys.reformatOnPaste": "indentBlock",
|
||||
"editor.smartKeys.backspaceUnindent": "nearest",
|
||||
});
|
||||
expect(plan.rows).toContainEqual({ label: "Unindent", value: "To nearest indent position" });
|
||||
expect(plan.rows).toContainEqual({ label: "Show line numbers", value: "Hybrid" });
|
||||
});
|
||||
|
||||
it("skips colour schemes that cannot be read", async () => {
|
||||
const plan = await planJetBrainsImport({ entries: [], files: { "colors/broken.icls": "<nope" } }, settings);
|
||||
const plan = await planJetBrainsImport({ entries: [], files: { "colors/broken.icls": "<nope" } }, editor);
|
||||
expect(plan.invalid).toEqual(["broken.icls"]);
|
||||
expect(plan.writes).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -58,7 +58,7 @@ it.each(["Cancel", "Import"])("confirms folder settings before applying them: %s
|
||||
expect(screen.getByText("Monaco")).toBeInTheDocument();
|
||||
expect(screen.getByText("17")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("Custom")).toHaveLength(2);
|
||||
expect(screen.getByText(/Not imported:/)).toHaveTextContent("Plugins");
|
||||
expect(screen.getByText(/Not imported:/)).toHaveTextContent("Keymap, Plugins");
|
||||
expect(set).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: button }));
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
installMenuBridge,
|
||||
menuAccelerator,
|
||||
menuActionIds,
|
||||
returnFocusAfterMenu,
|
||||
routeMenuEvent,
|
||||
} from "../menuBridge";
|
||||
|
||||
@@ -55,84 +54,6 @@ describe("menu state from the frontend", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("pushes enablement once when the window loses focus, for its Settings window (#3625)", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
|
||||
const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
vi.spyOn(ipc.commands, "appBuildInfo").mockRejectedValue(new Error("No build info in tests"));
|
||||
vi.spyOn(ipc.commands, "menuConfigure").mockResolvedValue();
|
||||
vi.spyOn(ipc.commands, "menuModel").mockResolvedValue([
|
||||
{ kind: "action", id: "test.menuBlur", label: "Test", hint: null, arg: null, checked: null },
|
||||
]);
|
||||
const pushDisabled = vi.spyOn(ipc.commands, "menuSetDisabled").mockResolvedValue();
|
||||
const offAction = registerAction({ id: "test.menuBlur", title: "Test", when: "testMenuBlurEditor", run: () => {} });
|
||||
setContext("testMenuBlurEditor", true);
|
||||
const dispose = installMenuBridge();
|
||||
try {
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
expect(pushDisabled).toHaveBeenCalledExactlyOnceWith([]);
|
||||
pushDisabled.mockClear();
|
||||
|
||||
// Focus moves to the Settings window: the editor loses focus, then the window blurs.
|
||||
hasFocus.mockReturnValue(false);
|
||||
setContext("testMenuBlurEditor", false);
|
||||
window.dispatchEvent(new Event("blur"));
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
expect(pushDisabled).toHaveBeenCalledExactlyOnceWith(["test.menuBlur"]);
|
||||
pushDisabled.mockClear();
|
||||
|
||||
// Later changes in a background window are not pushed.
|
||||
setContext("testMenuBlurEditor", true);
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
expect(pushDisabled).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
dispose();
|
||||
offAction();
|
||||
clearContext("testMenuBlurEditor");
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
|
||||
it("brings Settings back once the dialog opened from its menu closes (#3625)", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
const focusSettings = vi.fn(async () => {});
|
||||
try {
|
||||
// About opens a dialog: Settings waits under it.
|
||||
const about = returnFocusAfterMenu(
|
||||
Promise.resolve(true)
|
||||
.then(() => setContext("popupOpen", true))
|
||||
.then(() => true),
|
||||
focusSettings,
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(focusSettings).not.toHaveBeenCalled();
|
||||
setContext("popupOpen", false);
|
||||
await about;
|
||||
expect(focusSettings).toHaveBeenCalledOnce();
|
||||
|
||||
// An action that opens nothing: Settings comes back right away.
|
||||
focusSettings.mockClear();
|
||||
const saveAll = returnFocusAfterMenu(Promise.resolve(true), focusSettings);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
await saveAll;
|
||||
expect(focusSettings).toHaveBeenCalledOnce();
|
||||
|
||||
// Focus moved on (a new window or a native dialog): Settings stays where it is.
|
||||
focusSettings.mockClear();
|
||||
vi.mocked(document.hasFocus).mockReturnValue(false);
|
||||
const open = returnFocusAfterMenu(Promise.resolve(true), focusSettings);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
await open;
|
||||
expect(focusSettings).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
clearContext("popupOpen");
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
|
||||
it("lists registered tool windows by title and saved layouts", () => {
|
||||
localStorage.clear();
|
||||
_reloadLayouts();
|
||||
|
||||
@@ -8,8 +8,6 @@ vi.mock("@tauri-apps/api/core", () => ({
|
||||
Channel: class {
|
||||
onmessage: (p: unknown) => void = () => {};
|
||||
},
|
||||
// Balloons are mirrored to a system notification (`showSystemNotification`).
|
||||
invoke: async () => null,
|
||||
}));
|
||||
|
||||
type Channel = { onmessage: (p: UpdateProgress) => void };
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
/**
|
||||
* JetBrains option names (as the IDE writes them to `options/editor.xml` and
|
||||
* `codestyles/*.xml`) and the OpenIDEA settings of the same meaning. Each entry
|
||||
* carries the label the option has in Settings, for the import confirmation.
|
||||
*/
|
||||
|
||||
type Mapped = readonly [key: string, label: string];
|
||||
|
||||
/** `<component name="EditorSettings">`: on/off options. */
|
||||
export const EDITOR_FLAGS: Record<string, Mapped> = {
|
||||
IS_WHEEL_FONTCHANGE_ENABLED: ["editor.general.wheelZoom", "Change font size with Ctrl/Command+Mouse Wheel"],
|
||||
IS_DND_ENABLED: ["editor.general.dragAndDrop", "Enable drag-and-drop functionality in editor"],
|
||||
USE_CUSTOM_SOFT_WRAP_INDENT: ["editor.general.softWrapIndent", "Use original line's indent for wrapped parts"],
|
||||
ADDITIONAL_PAGE_AT_BOTTOM: ["editor.general.scrollPastEnd", "Show virtual space at file bottom"],
|
||||
KEEP_TRAILING_SPACE_ON_CARET_LINE: ["editor.general.keepTrailingOnCaretLine", "Keep trailing spaces on caret line"],
|
||||
REMOVE_TRAILING_BLANK_LINES: [
|
||||
"editor.general.removeTrailingBlankLines",
|
||||
"Remove trailing blank lines at the end of saved files",
|
||||
],
|
||||
IS_CARET_BLINKING: ["editor.appearance.caretBlinking", "Caret blinking (ms):"],
|
||||
IS_SMOOTH_CARET_BLINKING: ["editor.appearance.smoothCaretBlinking", "Use smooth caret blinking"],
|
||||
IS_BLOCK_CURSOR: ["editor.appearance.blockCaret", "Use block caret"],
|
||||
IS_SMOOTH_CARET_MOVEMENT: ["editor.appearance.smoothCaretMovement", "Use smooth caret movement"],
|
||||
IS_RIGHT_MARGIN_SHOWN: [
|
||||
"editor.appearance.hardWrapGuides",
|
||||
"Show hard wrap and visual guides (configured in Code Style options)",
|
||||
],
|
||||
ARE_LINE_NUMBERS_SHOWN: ["editor.appearance.lineNumbers", "Show line numbers"],
|
||||
IS_LEADING_WHITESPACES_SHOWN: ["editor.appearance.whitespaceLeading", "Leading"],
|
||||
IS_INNER_WHITESPACES_SHOWN: ["editor.appearance.whitespaceInner", "Inner"],
|
||||
IS_TRAILING_WHITESPACES_SHOWN: ["editor.appearance.whitespaceTrailing", "Trailing"],
|
||||
IS_INDENT_GUIDES_SHOWN: ["editor.appearance.indentGuides", "Show indent guides"],
|
||||
SHOW_INTENTION_BULB: ["editor.appearance.intentionBulb", "Show intention bulb"],
|
||||
ENABLE_RENDERED_DOC: ["editor.appearance.renderDocComments", "Render documentation comments"],
|
||||
SHOW_BREADCRUMBS: ["editor.breadcrumbs.show", "Show breadcrumbs:"],
|
||||
IS_FOLDING_OUTLINE_SHOWN: ["editor.folding.showOutline", "Show code folding outline"],
|
||||
SMART_HOME: ["editor.smartKeys.smartHome", "Home moves caret to first non-whitespace character"],
|
||||
IS_CAMEL_WORDS: ["editor.smartKeys.camelHumps", 'Use "CamelHumps" words'],
|
||||
IS_HIGHLIGHT_SELECTION_OCCURRENCES: ["editor.codeEditing.highlightSelection", "Occurrences of selected text"],
|
||||
SHOW_QUICK_DOC_ON_MOUSE_OVER_ELEMENT: ["editor.codeEditing.quickDocOnHover", "Show quick documentation on hover"],
|
||||
INSERT_PARENTHESES_AUTOMATICALLY: [
|
||||
"editor.completion.insertParentheses",
|
||||
"Insert parentheses automatically when applicable",
|
||||
],
|
||||
};
|
||||
|
||||
/** `<component name="EditorSettings">`: numbers. */
|
||||
export const EDITOR_NUMBERS: Record<string, Mapped> = {
|
||||
CARET_BLINKING_PERIOD: ["editor.appearance.caretBlinkPeriod", "Caret blinking (ms):"],
|
||||
STICKY_LINES_LIMIT: ["editor.codeEditing.stickyLinesMax", "Maximum number of lines"],
|
||||
TOOLTIPS_DELAY_MS: ["editor.codeEditing.quickDocDelay", "Tooltip delay"],
|
||||
};
|
||||
|
||||
/** `<component name="CodeInsightSettings">`: on/off options. */
|
||||
export const CODE_INSIGHT_FLAGS: Record<string, Mapped> = {
|
||||
AUTOINSERT_PAIR_BRACKET: ["editor.smartKeys.pairBrackets", "Insert paired brackets (), [], {}"],
|
||||
AUTOINSERT_PAIR_QUOTE: ["editor.smartKeys.pairQuotes", "Insert pair quote"],
|
||||
SURROUND_SELECTION_ON_QUOTE_TYPED: [
|
||||
"editor.smartKeys.surroundSelection",
|
||||
"Surround selection on typing quote or brace",
|
||||
],
|
||||
TAB_EXITS_BRACKETS_AND_QUOTES: ["editor.smartKeys.tabOutOfPair", "Jump outside closing bracket/quote with Tab"],
|
||||
SMART_INDENT_ON_ENTER: ["editor.smartKeys.smartIndent", "Smart indent"],
|
||||
JAVADOC_STUB_ON_ENTER: ["editor.smartKeys.insertDocStub", "Insert documentation comment stub"],
|
||||
HIGHLIGHT_IDENTIFIER_UNDER_CARET: ["editor.codeEditing.highlightUsages", "Usages of element at caret"],
|
||||
HIGHLIGHT_BRACES: ["editor.codeEditing.highlightBraces", "Matched brace"],
|
||||
AUTO_POPUP_COMPLETION_LOOKUP: ["editor.completion.autoPopup", "Show suggestions as you type"],
|
||||
AUTOCOMPLETE_ON_CODE_COMPLETION: ["editor.completion.autoInsertSingle", "Automatically insert single suggestions"],
|
||||
AUTO_POPUP_JAVADOC_INFO: ["editor.completion.showDocumentation", "Show the documentation popup in"],
|
||||
AUTO_POPUP_PARAMETER_INFO: ["editor.completion.parameterInfo", "Show the parameter info popup in"],
|
||||
};
|
||||
|
||||
/** `<component name="CodeInsightSettings">`: numbers. */
|
||||
export const CODE_INSIGHT_NUMBERS: Record<string, Mapped> = {
|
||||
JAVADOC_INFO_DELAY: ["editor.completion.documentationDelay", "Show the documentation popup in"],
|
||||
PARAMETER_INFO_DELAY: ["editor.completion.parameterInfoDelay", "Show the parameter info popup in"],
|
||||
};
|
||||
|
||||
/** `REFORMAT_ON_PASTE` (IDEA's `CodeInsightSettings` constants) → `editor.smartKeys.reformatOnPaste`, its label. */
|
||||
export const REFORMAT_ON_PASTE: Record<string, Mapped> = {
|
||||
"1": ["none", "None"],
|
||||
"2": ["indentBlock", "Indent Block"],
|
||||
"3": ["indentEachLine", "Indent Each Line"],
|
||||
};
|
||||
|
||||
/** `SMART_BACKSPACE` (IDEA's `SmartBackspaceMode` ordinals) → `editor.smartKeys.backspaceUnindent`, its label. */
|
||||
export const SMART_BACKSPACE: Record<string, Mapped> = {
|
||||
"0": ["none", "Disabled"],
|
||||
"1": ["nearest", "To nearest indent position"],
|
||||
"2": ["autoindent", "To proper indent position"],
|
||||
};
|
||||
|
||||
/** `<codeStyleSettings language=…>` → the language ids that share that code style here. */
|
||||
export const CODE_STYLE_LANGUAGES: Record<string, readonly string[]> = {
|
||||
JAVA: ["java"],
|
||||
kotlin: ["kotlin"],
|
||||
Groovy: ["groovy"],
|
||||
Scala: ["scala"],
|
||||
JavaScript: ["javascript", "javascriptreact"],
|
||||
TypeScript: ["typescript", "typescriptreact"],
|
||||
Vue: ["vue"],
|
||||
HTML: ["html"],
|
||||
XML: ["xml"],
|
||||
CSS: ["css"],
|
||||
SCSS: ["scss"],
|
||||
SASS: ["sass"],
|
||||
LESS: ["less"],
|
||||
JSON: ["json", "jsonc"],
|
||||
yaml: ["yaml"],
|
||||
TOML: ["toml"],
|
||||
Markdown: ["markdown"],
|
||||
Python: ["python"],
|
||||
go: ["go"],
|
||||
Rust: ["rust"],
|
||||
PHP: ["php"],
|
||||
ruby: ["ruby"],
|
||||
Dart: ["dart"],
|
||||
Swift: ["swift"],
|
||||
"C#": ["csharp"],
|
||||
Lua: ["lua"],
|
||||
SQL: ["sql"],
|
||||
"Shell Script": ["shellscript"],
|
||||
};
|
||||
@@ -1,32 +1,21 @@
|
||||
/**
|
||||
* Import Settings… with a JetBrains `settings.zip`: maps the archive's colour
|
||||
* schemes, keymaps, fonts, tabs and indents, and the editor / general options
|
||||
* OpenIDEA has to settings writes, after a confirmation listing them. Only keys
|
||||
* present in the archive are written (JetBrains leaves defaults out). The rest
|
||||
* is listed as not imported.
|
||||
* schemes and the editor / general options OpenIDEA has to settings writes, after
|
||||
* a confirmation listing them. Only keys present in the archive are written
|
||||
* (JetBrains leaves defaults out). Keymaps, code styles and the rest are listed
|
||||
* as not imported.
|
||||
*/
|
||||
import { Fragment } from "react";
|
||||
import type { CustomKeymap, JetBrainsSettings, LanguageCodeStyle } from "@/bindings";
|
||||
import type { JetBrainsSettings } from "@/bindings";
|
||||
import { customSchemes } from "@/platform/colorScheme";
|
||||
import { createFontProbeCanvas, fontsLoaded, monoFontFamily } from "@/platform/fonts";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { importScheme, parseIcls } from "@/platform/icls";
|
||||
import { addIdeaKeymap, parseIdeaKeymap } from "@/platform/ideaKeymap";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { guessOs } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import styles from "./app.module.css";
|
||||
import {
|
||||
CODE_INSIGHT_FLAGS,
|
||||
CODE_INSIGHT_NUMBERS,
|
||||
CODE_STYLE_LANGUAGES,
|
||||
EDITOR_FLAGS,
|
||||
EDITOR_NUMBERS,
|
||||
REFORMAT_ON_PASTE,
|
||||
SMART_BACKSPACE,
|
||||
} from "./jetbrainsOptions";
|
||||
|
||||
export interface JetBrainsImportPlan {
|
||||
/** Settings writes, in order: `settingsSet("global", key, JSON.stringify(value))`. */
|
||||
@@ -35,22 +24,15 @@ export interface JetBrainsImportPlan {
|
||||
rows: { label: string; value: string }[];
|
||||
/** Categories present in the archive that are not imported (translated). */
|
||||
skipped: string[];
|
||||
/** Colour scheme and keymap files that could not be read. */
|
||||
/** `.icls` files that could not be read. */
|
||||
invalid: string[];
|
||||
/** IDEA action ids the imported keymaps bind that have no counterpart here. */
|
||||
unknownActions: string[];
|
||||
}
|
||||
|
||||
/** The settings the import builds on (`settingsGetGlobal`). */
|
||||
interface CurrentSettings {
|
||||
editor: {
|
||||
fontFamily: string;
|
||||
fontSize: number | null;
|
||||
customSchemes: unknown;
|
||||
colorOverrides: Record<string, unknown>;
|
||||
codeStyle?: { languages?: Record<string, LanguageCodeStyle> };
|
||||
};
|
||||
customKeymaps?: Record<string, CustomKeymap>;
|
||||
interface EditorState {
|
||||
fontFamily: string;
|
||||
fontSize: number | null;
|
||||
customSchemes: unknown;
|
||||
colorOverrides: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const USER_PREFIX = "_@user_";
|
||||
@@ -111,39 +93,12 @@ async function measuredFontHeight(family: string, size: number): Promise<number
|
||||
}
|
||||
}
|
||||
|
||||
/** `<option name value>` children of `parent`. */
|
||||
function optionValues(parent: Element | null | undefined): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const o of Array.from(parent?.children ?? [])) {
|
||||
const name = o.getAttribute("name");
|
||||
const value = o.getAttribute("value");
|
||||
if (o.tagName === "option" && name && value !== null) out.set(name, value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const childOf = (parent: Element, tag: string, name?: string) =>
|
||||
Array.from(parent.children).find((c) => c.tagName === tag && (name === undefined || c.getAttribute("name") === name));
|
||||
|
||||
/** The code style scheme called `name` among `codestyles/*.xml`. */
|
||||
function codeScheme(files: Record<string, string>, name: string): Element | undefined {
|
||||
for (const [file, text] of Object.entries(files)) {
|
||||
if (!file.startsWith("codestyles/")) continue;
|
||||
const doc = new DOMParser().parseFromString(text, "application/xml");
|
||||
const root = doc.documentElement;
|
||||
if (!doc.querySelector("parsererror") && root.tagName === "code_scheme" && root.getAttribute("name") === name)
|
||||
return root;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function planJetBrainsImport(
|
||||
bundle: JetBrainsSettings,
|
||||
current: CurrentSettings,
|
||||
editor: EditorState,
|
||||
fontHeight: FontHeight = measuredFontHeight,
|
||||
): Promise<JetBrainsImportPlan> {
|
||||
const { editor } = current;
|
||||
const plan: JetBrainsImportPlan = { writes: [], rows: [], skipped: [], invalid: [], unknownActions: [] };
|
||||
const plan: JetBrainsImportPlan = { writes: [], rows: [], skipped: [], invalid: [] };
|
||||
const add = (key: string, value: string | number | boolean | undefined, label: string, shown?: string) => {
|
||||
if (value === undefined) return;
|
||||
plan.writes.push([key, value]);
|
||||
@@ -179,33 +134,6 @@ export async function planJetBrainsImport(
|
||||
if (id) add("editor.colorScheme", id, tx("Current color scheme"), customs[id]?.name);
|
||||
}
|
||||
|
||||
let keymaps = current.customKeymaps ?? {};
|
||||
const importedKeymaps = new Map<string, string>(); // name in the keymap file → keymap id
|
||||
for (const [file, text] of Object.entries(bundle.files)) {
|
||||
if (!file.startsWith("keymaps/")) continue;
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parseIdeaKeymap(text);
|
||||
} catch {
|
||||
plan.invalid.push(file.slice("keymaps/".length));
|
||||
continue;
|
||||
}
|
||||
// Overwrites an earlier import of the same keymap, as colour schemes do.
|
||||
const next = addIdeaKeymap(keymaps, parsed);
|
||||
keymaps = next.customs;
|
||||
importedKeymaps.set(parsed.name, next.id);
|
||||
plan.unknownActions.push(...parsed.unknownActions.filter((id) => !plan.unknownActions.includes(id)));
|
||||
plan.rows.push({ label: tx("Keymap"), value: keymaps[next.id]?.name ?? parsed.name });
|
||||
}
|
||||
if (importedKeymaps.size) {
|
||||
plan.writes.push(["customKeymaps", keymaps]);
|
||||
// The active keymap is stored per operating system; a bundled one keeps OpenIDEA's choice.
|
||||
const os = { macos: "mac", windows: "windows", linux: "linux", web: "" }[guessOs()];
|
||||
const active = options(bundle.files[`options/${os}/keymap.xml`], "KeymapManager", "active_keymap").get("");
|
||||
const id = importedKeymaps.get(active ?? "");
|
||||
if (id) add("keymap", id, tx("Current keymap"), keymaps[id]?.name);
|
||||
}
|
||||
|
||||
const font = options(bundle.files["options/editor-font.xml"], "DefaultFont");
|
||||
const family = font.get("FONT_FAMILY")?.trim() || undefined;
|
||||
add("editor.fontFamily", family, tx("Font"));
|
||||
@@ -221,21 +149,6 @@ export async function planJetBrainsImport(
|
||||
}
|
||||
add("editor.ligatures", bool(font.get("USE_LIGATURES")), tx("Enable ligatures"));
|
||||
|
||||
const terminal = options(bundle.files["options/terminal-font.xml"], "TerminalFontOptions");
|
||||
const terminalFamily = terminal.get("FONT_FAMILY")?.trim() || undefined;
|
||||
const terminalSize = num(terminal.get("FONT_SIZE"));
|
||||
// A terminal font of its own: stop following the editor font (the font rows below say so).
|
||||
if (terminalFamily || terminalSize) plan.writes.push(["terminal.useEditorFont", false]);
|
||||
add("terminal.fontFamily", terminalFamily, tx("Terminal font"));
|
||||
add("terminal.fontSize", terminalSize, tx("Terminal font size"));
|
||||
add("terminal.lineHeight", num(terminal.get("LINE_SPACING")), tx("Terminal line height"));
|
||||
add("terminal.columnWidth", num(terminal.get("COLUMN_SPACING")), tx("Terminal column width"));
|
||||
add(
|
||||
"terminal.fallbackFontFamily",
|
||||
terminal.get("SECONDARY_FONT_FAMILY")?.trim() || undefined,
|
||||
tx("Terminal fallback font"),
|
||||
);
|
||||
|
||||
const ed = options(bundle.files["options/editor.xml"], "EditorSettings");
|
||||
const strip = ed.get("STRIP_TRAILING_SPACES"); // None | Changed | Whole
|
||||
if (strip === "Changed" || strip === "Whole") {
|
||||
@@ -262,95 +175,13 @@ export async function planJetBrainsImport(
|
||||
wraps === undefined ? undefined : wraps.split(",").includes("MAIN_EDITOR"),
|
||||
tx("Soft-wrap files"),
|
||||
);
|
||||
add(
|
||||
"console.softWrap",
|
||||
wraps === undefined ? undefined : wraps.split(",").includes("CONSOLE"),
|
||||
tx("Use soft wraps in console"),
|
||||
);
|
||||
add("editor.general.softWrapFiles", ed.get("SOFT_WRAP_FILE_MASKS")?.trim() || undefined, tx("File patterns"));
|
||||
const numeration = { ABSOLUTE: "Absolute", RELATIVE: "Relative", HYBRID: "Hybrid" }[ed.get("LINE_NUMERATION") ?? ""];
|
||||
add("editor.appearance.lineNumberMode", numeration?.toLowerCase(), tx("Show line numbers"), tx(numeration ?? ""));
|
||||
const above = bool(ed.get("SHOW_BREADCRUMBS_ABOVE"));
|
||||
add(
|
||||
"editor.breadcrumbs.placement",
|
||||
above === undefined ? undefined : above ? "top" : "bottom",
|
||||
tx("Show breadcrumbs:"),
|
||||
tx(above ? "Top" : "Bottom"),
|
||||
);
|
||||
const insight = options(bundle.files["options/editor.xml"], "CodeInsightSettings");
|
||||
for (const [source, flags, numbers] of [
|
||||
[ed, EDITOR_FLAGS, EDITOR_NUMBERS],
|
||||
[insight, CODE_INSIGHT_FLAGS, CODE_INSIGHT_NUMBERS],
|
||||
] as const) {
|
||||
for (const [name, [key, label]] of Object.entries(flags)) add(key, bool(source.get(name)), tx(label));
|
||||
for (const [name, [key, label]] of Object.entries(numbers)) add(key, num(source.get(name)), tx(label));
|
||||
}
|
||||
const paste = REFORMAT_ON_PASTE[insight.get("REFORMAT_ON_PASTE") ?? ""];
|
||||
add("editor.smartKeys.reformatOnPaste", paste?.[0], tx("Reformat on paste"), tx(paste?.[1] ?? ""));
|
||||
const backspace = SMART_BACKSPACE[insight.get("SMART_BACKSPACE") ?? ""];
|
||||
add("editor.smartKeys.backspaceUnindent", backspace?.[0], tx("Unindent"), tx(backspace?.[1] ?? ""));
|
||||
|
||||
// Tabs and Indents of the current code style scheme; its other formatting options have no setting here.
|
||||
const schemeName =
|
||||
options(bundle.files["options/code.style.schemes.xml"], "CodeStyleSchemeSettings").get("CURRENT_SCHEME_NAME") ??
|
||||
"Default";
|
||||
const scheme = codeScheme(bundle.files, schemeName);
|
||||
if (scheme) {
|
||||
const root = optionValues(scheme);
|
||||
add("editor.codeStyle.hardWrapAt", num(root.get("RIGHT_MARGIN")), tx("Hard wrap at"));
|
||||
add(
|
||||
"editor.codeStyle.detectIndents",
|
||||
bool(root.get("AUTODETECT_INDENTS")),
|
||||
tx("Detect and use existing file indents for editing"),
|
||||
);
|
||||
// "Other File Types": the indent of languages without a code style of their own.
|
||||
const other = optionValues(childOf(childOf(scheme, "option", "OTHER_INDENT_OPTIONS") ?? scheme, "value"));
|
||||
add("editor.tabSize", num(other.get("TAB_SIZE")), tx("Tab size"));
|
||||
const otherTabs = bool(other.get("USE_TAB_CHARACTER"));
|
||||
add(
|
||||
"editor.insertSpaces",
|
||||
otherTabs === undefined ? undefined : !otherTabs,
|
||||
tx("Use tab character"),
|
||||
otherTabs === undefined ? undefined : onOff(otherTabs),
|
||||
);
|
||||
|
||||
const languages = { ...editor.codeStyle?.languages };
|
||||
let changed = false;
|
||||
for (const block of Array.from(scheme.children)) {
|
||||
const ids = CODE_STYLE_LANGUAGES[block.getAttribute("language") ?? ""];
|
||||
if (block.tagName !== "codeStyleSettings" || !ids) continue;
|
||||
const own = optionValues(block);
|
||||
const indent = optionValues(childOf(block, "indentOptions"));
|
||||
const style: Partial<LanguageCodeStyle> = {};
|
||||
const shown: string[] = [];
|
||||
const set = <K extends keyof LanguageCodeStyle>(
|
||||
key: K,
|
||||
value: LanguageCodeStyle[K] | undefined,
|
||||
label: string,
|
||||
) => {
|
||||
if (value === undefined) return;
|
||||
style[key] = value;
|
||||
shown.push(`${tx(label)} ${typeof value === "boolean" ? onOff(value) : value}`);
|
||||
};
|
||||
set("indent", num(indent.get("INDENT_SIZE")), "Indent");
|
||||
set("tabSize", num(indent.get("TAB_SIZE")), "Tab size");
|
||||
set("useTab", bool(indent.get("USE_TAB_CHARACTER")), "Use tab character");
|
||||
set("hardWrapAt", num(own.get("RIGHT_MARGIN")), "Hard wrap at");
|
||||
set("lineCommentAtFirstColumn", bool(own.get("LINE_COMMENT_AT_FIRST_COLUMN")), "Line comment at first column");
|
||||
set("lineCommentAddSpace", bool(own.get("LINE_COMMENT_ADD_SPACE")), "Add a space at line comment start");
|
||||
if (!shown.length) continue;
|
||||
for (const id of ids) languages[id] = { ...languages[id], ...style } as LanguageCodeStyle;
|
||||
changed = true;
|
||||
plan.rows.push({ label: `${tx("Code Style")} › ${block.getAttribute("language")}`, value: shown.join(", ") });
|
||||
}
|
||||
if (changed) plan.writes.push(["editor.codeStyle.languages", languages]);
|
||||
}
|
||||
|
||||
const general = options(bundle.files["options/ide.general.xml"], "GeneralSettings");
|
||||
add("general.confirmExit", bool(general.get("confirmExit")), tx("Confirm before exiting the IDE"));
|
||||
|
||||
const has = (prefix: string) => bundle.entries.some((e) => e.startsWith(prefix));
|
||||
if (has("codestyles/")) plan.skipped.push(tx("Code Style options other than Tabs and Indents"));
|
||||
if (has("keymaps/")) plan.skipped.push(tx("Keymap"));
|
||||
if (has("codestyles/")) plan.skipped.push(tx("Code Style"));
|
||||
if (has("templates/")) plan.skipped.push(tx("Live templates"));
|
||||
if (has("inspection/")) plan.skipped.push(tx("Inspections"));
|
||||
if (has("installed.txt")) plan.skipped.push(tx("Plugins"));
|
||||
@@ -359,7 +190,6 @@ export async function planJetBrainsImport(
|
||||
|
||||
function Summary({ plan }: { plan: JetBrainsImportPlan }) {
|
||||
const left = [...plan.skipped, ...plan.invalid];
|
||||
const unknown = plan.unknownActions;
|
||||
return (
|
||||
<div className={styles.importSummary}>
|
||||
<div>{tx("These settings will be imported:")}</div>
|
||||
@@ -376,7 +206,6 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
|
||||
{tx("Not imported:")} {left.join(", ")}
|
||||
</div>
|
||||
)}
|
||||
{unknown.length > 0 && <div>{tx`Not available in OpenIDEA (${unknown.length}): ${unknown.join(", ")}.`}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -384,7 +213,8 @@ function Summary({ plan }: { plan: JetBrainsImportPlan }) {
|
||||
/** Reads `path`, asks, then writes the mapped settings to the global layer. */
|
||||
export async function importJetBrainsSettings(path: string) {
|
||||
const bundle = await call(commands.settingsReadJetbrains(path));
|
||||
const plan = await planJetBrainsImport(bundle, await commands.settingsGetGlobal());
|
||||
const { editor } = await commands.settingsGetGlobal();
|
||||
const plan = await planJetBrainsImport(bundle, editor);
|
||||
if (!plan.writes.length) {
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* equivalent while the JS keymap stays the only dispatcher (see src-tauri/src/menu.rs).
|
||||
*/
|
||||
import { executeActionFrom, getAction, isActionEnabled, useActions } from "@/platform/actions";
|
||||
import { getContext, useContextKeys } from "@/platform/context";
|
||||
import { useContextKeys } from "@/platform/context";
|
||||
import { keysWithPrefix, t, tx, useI18n } from "@/platform/i18n";
|
||||
import { commands, isTauri, type DynamicItem, type MenuConfig, type MenuNode } from "@/platform/ipc";
|
||||
import {
|
||||
@@ -32,8 +32,6 @@ export const MENU_EVENT = "openidea://menu";
|
||||
export interface MenuRoute {
|
||||
action: string;
|
||||
arg?: string | null;
|
||||
/** The window in front when the item was chosen, if it is not this one (this window's Settings). */
|
||||
returnTo?: string;
|
||||
}
|
||||
|
||||
export function isMenuRoute(v: unknown): v is MenuRoute {
|
||||
@@ -49,36 +47,6 @@ export function routeMenuEvent(
|
||||
return run(payload.action, payload.arg ?? undefined);
|
||||
}
|
||||
|
||||
/** How long an action chosen from the menu may take to open its dialog or popup. */
|
||||
const OPEN_DELAY_MS = 300;
|
||||
|
||||
const layersClosed = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (!getContext().popupOpen) return resolve();
|
||||
const off = useContextKeys.subscribe((ctx) => {
|
||||
if (ctx.popupOpen) return;
|
||||
off();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* After an item chosen in this window's Settings window ran here (the backend brought this window
|
||||
* forward): once the dialog or popup it opened closes, or right away if it opened none, Settings comes
|
||||
* back to the front, as IDEA's Settings dialog stays under the dialogs opened from the menu. Not when
|
||||
* focus has moved on (a new window, a native dialog).
|
||||
*/
|
||||
export async function returnFocusAfterMenu(
|
||||
ran: Promise<boolean>,
|
||||
focusWindow: () => Promise<void>,
|
||||
delay = OPEN_DELAY_MS,
|
||||
): Promise<void> {
|
||||
await ran;
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
await layersClosed();
|
||||
if (document.hasFocus()) await focusWindow();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keymap key names a macOS key equivalent can show. Mirrors the names muda's accelerator
|
||||
* parser accepts: Tauri drops an accelerator it cannot parse, and the item shows no shortcut.
|
||||
@@ -199,36 +167,22 @@ export function installMenuBridge(): () => void {
|
||||
|
||||
void import("@tauri-apps/api/webviewWindow").then(async ({ getCurrentWebviewWindow }) => {
|
||||
// Window-scoped: a global `listen` would also receive other windows' menu events.
|
||||
const off = await getCurrentWebviewWindow().listen(MENU_EVENT, ({ payload }) => {
|
||||
const ran = routeMenuEvent(payload);
|
||||
const returnTo = isMenuRoute(payload) ? payload.returnTo : undefined;
|
||||
if (returnTo)
|
||||
void returnFocusAfterMenu(ran, async () => {
|
||||
const { Window } = await import("@tauri-apps/api/window");
|
||||
await (await Window.getByLabel(returnTo))?.setFocus();
|
||||
}).catch(() => {});
|
||||
});
|
||||
const off = await getCurrentWebviewWindow().listen(MENU_EVENT, ({ payload }) => void routeMenuEvent(payload));
|
||||
if (disposed) off();
|
||||
else unlisten = off;
|
||||
});
|
||||
|
||||
// Enablement of the native items follows this window's context (IDEA greys out
|
||||
// what cannot run). Recomputed shortly after context changes, sent only when it changed.
|
||||
// Also once on blur: the menu still runs here while this window's Settings window is focused,
|
||||
// with nothing focused here (editor actions disabled). The backend ignores it for other windows.
|
||||
let ids: Set<string> | null = null;
|
||||
let lastDisabled = "";
|
||||
let forceEnablement = false;
|
||||
let afterBlur = false;
|
||||
let enableTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const pushEnablement = (force = false, blurred = false) => {
|
||||
const pushEnablement = (force = false) => {
|
||||
forceEnablement ||= force;
|
||||
afterBlur ||= blurred;
|
||||
clearTimeout(enableTimer);
|
||||
enableTimer = setTimeout(() => {
|
||||
const unfocused = !document.hasFocus();
|
||||
if (!ids || disposed || (unfocused && !afterBlur)) return;
|
||||
afterBlur = false;
|
||||
if (!ids || disposed || !document.hasFocus()) return;
|
||||
const dynamic = Object.values(dynamicMenuItems()).flatMap((items) => items.map((d) => d.action));
|
||||
const disabled = disabledMenuActions(new Set([...ids, ...dynamic]));
|
||||
const key = disabled.join(",");
|
||||
@@ -255,8 +209,6 @@ export function installMenuBridge(): () => void {
|
||||
// The backend edits only submenus whose visible items changed, so switching project
|
||||
// tabs does not redraw the macOS menu bar.
|
||||
window.addEventListener("focus", onFocus);
|
||||
const onBlur = () => pushEnablement(true, true);
|
||||
window.addEventListener("blur", onBlur);
|
||||
const unsubs = [
|
||||
useI18n.subscribe((s, prev) => {
|
||||
if (s.messages !== prev.messages) push();
|
||||
@@ -285,7 +237,6 @@ export function installMenuBridge(): () => void {
|
||||
clearTimeout(timer);
|
||||
clearTimeout(enableTimer);
|
||||
window.removeEventListener("focus", onFocus);
|
||||
window.removeEventListener("blur", onBlur);
|
||||
unlisten?.();
|
||||
unsubs.forEach((u) => u());
|
||||
};
|
||||
|
||||
+1
-5
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { normalizeBinding } from "@/platform/keymap";
|
||||
import { fromSwingStroke, parseIdeaKeymap } from "./ideaKeymap";
|
||||
import { fromSwingStroke, parseIdeaKeymap } from "../keymap/ideaKeymapImport";
|
||||
|
||||
describe("IntelliJ IDEA keymap import", () => {
|
||||
it("converts Swing keystrokes", () => {
|
||||
@@ -8,10 +8,6 @@ describe("IntelliJ IDEA keymap import", () => {
|
||||
expect(fromSwingStroke("ctrl pressed OPEN_BRACKET")).toBe("Ctrl+[");
|
||||
expect(fromSwingStroke("F12")).toBe("F12");
|
||||
expect(fromSwingStroke("alt BACK_SPACE")).toBe("Alt+Backspace");
|
||||
// As IDEA saves a user's keymap.
|
||||
expect(fromSwingStroke("ctrl right")).toBe("Ctrl+Right");
|
||||
expect(fromSwingStroke("shift ctrl alt s")).toBe("Shift+Ctrl+Alt+S");
|
||||
expect(fromSwingStroke("meta back_slash")).toBe("Meta+\\");
|
||||
expect(fromSwingStroke("meta NUMPAD5")).toBeNull();
|
||||
expect(fromSwingStroke("hyper A")).toBeNull();
|
||||
});
|
||||
@@ -53,7 +53,7 @@ import {
|
||||
} from "./model";
|
||||
import { groupIcon, groupPath, groupRank } from "./groups";
|
||||
import { KeymapNameDialog } from "./KeymapDialogs";
|
||||
import { parseIdeaKeymap } from "@/platform/ideaKeymap";
|
||||
import { parseIdeaKeymap } from "./ideaKeymapImport";
|
||||
import { RecordShortcutDialog } from "./RecordShortcutDialog";
|
||||
import { StrokeRecorder } from "./StrokeRecorder";
|
||||
import styles from "./Keymap.module.css";
|
||||
|
||||
+4
-28
@@ -4,16 +4,8 @@
|
||||
* parent; each listed action's shortcuts replace the parent's.
|
||||
*/
|
||||
import { IDEA_ACTIONS } from "@/platform/ideaActions";
|
||||
import type { CustomKeymap } from "@/bindings";
|
||||
import {
|
||||
customKeymapId,
|
||||
defaultPreset,
|
||||
isValidBinding,
|
||||
normalizeBinding,
|
||||
PRESET_TITLES,
|
||||
withBindings,
|
||||
type Keymap,
|
||||
} from "@/platform/keymap";
|
||||
import { defaultPreset, isValidBinding, normalizeBinding, type Keymap } from "@/platform/keymap";
|
||||
import { withBindings } from "./model";
|
||||
|
||||
export interface ImportedIdeaKeymap {
|
||||
name: string;
|
||||
@@ -75,16 +67,13 @@ const SWING_KEYS: Record<string, string> = {
|
||||
|
||||
const SWING_MODS: Record<string, string> = { shift: "Shift", ctrl: "Ctrl", control: "Ctrl", alt: "Alt", meta: "Meta" };
|
||||
|
||||
/**
|
||||
* `"shift meta O"` / `"ctrl pressed OPEN_BRACKET"` → `"Meta+Shift+O"`, or null when not expressible.
|
||||
* Bundled keymaps name keys in upper case; the keymaps IDEA saves for the user are all lower case (`"ctrl right"`).
|
||||
*/
|
||||
/** `"shift meta O"` / `"ctrl pressed OPEN_BRACKET"` → `"Meta+Shift+O"`, or null when not expressible. */
|
||||
export function fromSwingStroke(stroke: string): string | null {
|
||||
const words = stroke
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter((w) => !/^(pressed|released|typed)$/i.test(w));
|
||||
const key = words.pop()?.toUpperCase();
|
||||
const key = words.pop();
|
||||
if (!key || words.some((w) => !SWING_MODS[w.toLowerCase()])) return null;
|
||||
const name = /^([A-Z0-9]|F\d{1,2})$/.test(key) ? key : SWING_KEYS[key];
|
||||
return name ? [...words.map((w) => SWING_MODS[w.toLowerCase()]), name].join("+") : null;
|
||||
@@ -145,16 +134,3 @@ export function parseIdeaKeymap(xml: string): ImportedIdeaKeymap {
|
||||
skippedShortcuts,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a parsed keymap to the user keymaps under its own name, replacing an
|
||||
* earlier import of the same name (a name a bundled keymap has gets a suffix).
|
||||
*/
|
||||
export function addIdeaKeymap(
|
||||
customs: Record<string, CustomKeymap>,
|
||||
parsed: ImportedIdeaKeymap,
|
||||
): { id: string; customs: Record<string, CustomKeymap> } {
|
||||
const name = Object.values(PRESET_TITLES).includes(parsed.name) ? `${parsed.name} (JetBrains)` : parsed.name;
|
||||
const id = Object.keys(customs).find((k) => customs[k]?.name === name) ?? customKeymapId(name, customs);
|
||||
return { id, customs: { ...customs, [id]: { name, parent: parsed.parent, overrides: parsed.overrides } } };
|
||||
}
|
||||
@@ -5,19 +5,23 @@
|
||||
*/
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { evaluateWhen, type ContextKeys } from "@/platform/context";
|
||||
import {
|
||||
customKeymapId,
|
||||
defaultPreset,
|
||||
normalizeBinding,
|
||||
presetBindings,
|
||||
PRESET_TITLES,
|
||||
PRESETS,
|
||||
withBindings,
|
||||
type Keymap,
|
||||
type KeymapDraft,
|
||||
} from "@/platform/keymap";
|
||||
import { defaultPreset, normalizeBinding, PRESET_TITLES, PRESETS, useKeymap, type Keymap } from "@/platform/keymap";
|
||||
|
||||
export { presetBindings, withBindings, type KeymapDraft };
|
||||
export interface KeymapDraft {
|
||||
preset: string;
|
||||
overrides: Keymap;
|
||||
}
|
||||
|
||||
/**
|
||||
* The defaults of `id`: the preset's, or for an action the preset leaves out,
|
||||
* the shortcut its plugin declares (`keymaps`). Removing or changing one is an
|
||||
* override like any other.
|
||||
*/
|
||||
export function presetBindings(preset: string, id: string): string[] {
|
||||
const own = PRESETS[preset];
|
||||
const keys = own && id in own ? own[id] : useKeymap.getState().extensions?.[id];
|
||||
return (keys ?? []).map(normalizeBinding);
|
||||
}
|
||||
|
||||
export function resolveBindings(draft: KeymapDraft, id: string): string[] {
|
||||
return draft.overrides[id]?.map(normalizeBinding) ?? presetBindings(draft.preset, id);
|
||||
@@ -37,6 +41,17 @@ export function isModified(draft: KeymapDraft, id: string): boolean {
|
||||
return id in draft.overrides;
|
||||
}
|
||||
|
||||
const sameList = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
|
||||
|
||||
/** Sets the full binding list of `id`; drops the override when it equals the preset. */
|
||||
export function withBindings(draft: KeymapDraft, id: string, bindings: readonly string[]): Keymap {
|
||||
const list = [...new Set(bindings.map(normalizeBinding))];
|
||||
const overrides = { ...draft.overrides };
|
||||
if (sameList(list, presetBindings(draft.preset, id))) delete overrides[id];
|
||||
else overrides[id] = list;
|
||||
return overrides;
|
||||
}
|
||||
|
||||
export function addBinding(draft: KeymapDraft, id: string, binding: string): Keymap {
|
||||
return withBindings(draft, id, [...resolveBindings(draft, id), binding]);
|
||||
}
|
||||
@@ -220,13 +235,24 @@ export function validateKeymapName(name: string, customs: CustomKeymaps, ownId?:
|
||||
return clash ? `Keymap '${n}' already exists` : null;
|
||||
}
|
||||
|
||||
function newKeymapId(name: string, customs: CustomKeymaps): string {
|
||||
const slug =
|
||||
name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "") || "keymap";
|
||||
let id = `custom.${slug}`;
|
||||
for (let i = 2; customs[id] || PRESETS[id]; i++) id = `custom.${slug}-${i}`;
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Copies the selected keymap (its effective overrides) under `name`; returns the new id. */
|
||||
export function duplicateKeymap(
|
||||
draft: KeymapDraft,
|
||||
customs: CustomKeymaps,
|
||||
name: string,
|
||||
): { id: string; customs: CustomKeymaps } {
|
||||
const id = customKeymapId(name, customs);
|
||||
const id = newKeymapId(name, customs);
|
||||
return {
|
||||
id,
|
||||
customs: { ...customs, [id]: { name: name.trim(), parent: draft.preset, overrides: { ...draft.overrides } } },
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/**
|
||||
* CodeMirror setup for the VCS viewers (diff, merge, local history): token
|
||||
* based theme + syntax colours and lazy language loading through the editor's
|
||||
* language pipeline, so colours match the editor.
|
||||
* based theme + syntax colours and lazy language loading by file name.
|
||||
*/
|
||||
import { syntaxHighlighting, type LanguageSupport } from "@codemirror/language";
|
||||
import { HighlightStyle, LanguageDescription, syntaxHighlighting, type LanguageSupport } from "@codemirror/language";
|
||||
import {
|
||||
Compartment,
|
||||
EditorState,
|
||||
@@ -33,9 +32,8 @@ import {
|
||||
import { getChunks, mergeViewSiblings, type Chunk } from "@codemirror/merge";
|
||||
import { defaultKeymap } from "@codemirror/commands";
|
||||
import { search, searchKeymap } from "@codemirror/search";
|
||||
import { tags as t } from "@lezer/highlight";
|
||||
import { scrollbarMarks, type ScrollbarMark } from "@/editor/api";
|
||||
import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
|
||||
import { findLanguageDescription, loadSupport, uiModeForPath } from "@/editor/core/cm/languages";
|
||||
import { findExtension } from "@/editor/core/cm/find";
|
||||
import { overviewLane, overviewLaneIn } from "@/editor/core/cm/lanes";
|
||||
import { LINE_INSET } from "@/editor/core/cm/lineInset";
|
||||
@@ -296,6 +294,26 @@ export const diffWords: Extension = [
|
||||
EditorView.editorAttributes.of({ class: "cm-diffWords" }),
|
||||
];
|
||||
|
||||
export const viewerHighlight = HighlightStyle.define([
|
||||
{
|
||||
tag: [t.keyword, t.modifier, t.controlKeyword, t.operatorKeyword, t.definitionKeyword],
|
||||
color: "var(--syn-keyword)",
|
||||
},
|
||||
{ tag: [t.string, t.special(t.string), t.regexp, t.character], color: "var(--syn-string)" },
|
||||
{ tag: [t.typeName, t.className, t.namespace, t.tagName], color: "var(--syn-type)" },
|
||||
{ tag: [t.function(t.variableName), t.function(t.propertyName)], color: "var(--syn-function)" },
|
||||
{ tag: [t.comment, t.lineComment, t.blockComment, t.docComment], color: "var(--syn-comment)", fontStyle: "italic" },
|
||||
{ tag: [t.annotation, t.meta, t.attributeName], color: "var(--syn-annotation)" },
|
||||
{ tag: [t.number, t.bool, t.null, t.atom], color: "var(--syn-number)" },
|
||||
{ tag: [t.constant(t.variableName), t.standard(t.variableName)], color: "var(--syn-constant)" },
|
||||
{ tag: [t.punctuation, t.bracket, t.operator], color: "var(--syn-punct)" },
|
||||
{ tag: [t.propertyName], color: "var(--syn-property)" },
|
||||
{ tag: [t.variableName], color: "var(--syn-variable)" },
|
||||
{ tag: t.invalid, color: "var(--syn-invalid)" },
|
||||
{ tag: t.heading, fontWeight: "var(--fw-code-bold, 700)", color: "var(--fg-strong)" },
|
||||
{ tag: t.link, color: "var(--link)", textDecoration: "underline" },
|
||||
]);
|
||||
|
||||
export const viewerTheme = EditorView.theme(
|
||||
{
|
||||
...overviewStyles,
|
||||
@@ -512,7 +530,7 @@ export function viewerBase(opts: {
|
||||
opts.findBar
|
||||
? [findExtension(), keymap.of(defaultKeymap)]
|
||||
: [search({ top: true }), keymap.of([...searchKeymap, ...defaultKeymap])],
|
||||
syntaxHighlighting(openideaHighlightStyle),
|
||||
syntaxHighlighting(viewerHighlight),
|
||||
viewerTheme,
|
||||
changedLines,
|
||||
EditorState.readOnly.of(opts.readOnly),
|
||||
@@ -522,22 +540,18 @@ export function viewerBase(opts: {
|
||||
];
|
||||
}
|
||||
|
||||
let languagesPromise: Promise<readonly LanguageDescription[]> | null = null;
|
||||
const cache = new Map<string, Promise<LanguageSupport | null>>();
|
||||
|
||||
/**
|
||||
* Loads the language for `fileName` through the editor's pipeline
|
||||
* (`findLanguageDescription` + `loadSupport`): the same modes, tag patches and
|
||||
* `data-language` attribute as the editor, so colours match. Unknown
|
||||
* extensions resolve like the editor's (null once the backend languages are
|
||||
* loaded, file-name match before that).
|
||||
*/
|
||||
/** Loads the language for `fileName` (by extension / name), or null. */
|
||||
export function languageFor(fileName: string): Promise<LanguageSupport | null> {
|
||||
const name = fileName.slice(fileName.lastIndexOf("/") + 1);
|
||||
const hit = cache.get(name);
|
||||
if (hit) return hit;
|
||||
const p = Promise.resolve(uiModeForPath(fileName))
|
||||
.then((uiMode) => findLanguageDescription(uiMode ?? null, fileName))
|
||||
.then((desc) => (desc ? loadSupport(desc) : null))
|
||||
languagesPromise ??= import("@codemirror/language-data").then((m) => m.languages);
|
||||
const p = languagesPromise
|
||||
.then((langs) => LanguageDescription.matchFilename(langs, name))
|
||||
.then((desc) => (desc ? desc.load() : null))
|
||||
.catch(() => null);
|
||||
cache.set(name, p);
|
||||
return p;
|
||||
|
||||
@@ -730,43 +730,3 @@ export function installKeyboardDispatcher(
|
||||
target.removeEventListener("blur", onBlur);
|
||||
};
|
||||
}
|
||||
|
||||
/** A keymap being edited: a bundled preset and the overrides on top of it. */
|
||||
export interface KeymapDraft {
|
||||
preset: string;
|
||||
overrides: Keymap;
|
||||
}
|
||||
|
||||
/**
|
||||
* The defaults of `id`: the preset's, or for an action the preset leaves out,
|
||||
* the shortcut its plugin declares (`keymaps`). Removing or changing one is an
|
||||
* override like any other.
|
||||
*/
|
||||
export function presetBindings(preset: string, id: string): string[] {
|
||||
const own = PRESETS[preset];
|
||||
const keys = own && id in own ? own[id] : useKeymap.getState().extensions?.[id];
|
||||
return (keys ?? []).map(normalizeBinding);
|
||||
}
|
||||
|
||||
const sameList = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
|
||||
|
||||
/** Sets the full binding list of `id`; drops the override when it equals the preset. */
|
||||
export function withBindings(draft: KeymapDraft, id: string, bindings: readonly string[]): Keymap {
|
||||
const list = [...new Set(bindings.map(normalizeBinding))];
|
||||
const overrides = { ...draft.overrides };
|
||||
if (sameList(list, presetBindings(draft.preset, id))) delete overrides[id];
|
||||
else overrides[id] = list;
|
||||
return overrides;
|
||||
}
|
||||
|
||||
/** A free id for a user keymap called `name`. */
|
||||
export function customKeymapId(name: string, customs: Record<string, unknown>): string {
|
||||
const slug =
|
||||
name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "") || "keymap";
|
||||
let id = `custom.${slug}`;
|
||||
for (let i = 2; customs[id] || PRESETS[id]; i++) id = `custom.${slug}-${i}`;
|
||||
return id;
|
||||
}
|
||||
@@ -465,8 +465,6 @@
|
||||
"These settings will be imported:": "These settings will be imported:",
|
||||
"Not imported:": "Not imported:",
|
||||
"Current color scheme": "Current color scheme",
|
||||
"Current keymap": "Current keymap",
|
||||
"Code Style options other than Tabs and Indents": "Code Style options other than Tabs and Indents",
|
||||
"No settings OpenIDEA can import were found": "No settings OpenIDEA can import were found",
|
||||
"Overwrite existing branch": "Overwrite existing branch",
|
||||
"Unset upstream branch": "Unset upstream branch",
|
||||
|
||||
@@ -3512,8 +3512,6 @@
|
||||
"These settings will be imported:": "将导入以下设置:",
|
||||
"Not imported:": "不导入:",
|
||||
"Current color scheme": "当前配色方案",
|
||||
"Current keymap": "当前按键映射",
|
||||
"Code Style options other than Tabs and Indents": "制表符和缩进以外的代码样式选项",
|
||||
"No settings OpenIDEA can import were found": "没有找到 OpenIDEA 可以导入的设置",
|
||||
"Rename Project": "重命名项目",
|
||||
"Rename Project…": "重命名项目…",
|
||||
|
||||
Reference in new issue
Заблокувати користувача