дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
468118df57 | ||
|
|
88a6bbca14 | ||
|
|
b9e555300f | ||
|
|
7ff223001b |
No files matched your search
@@ -464,11 +464,16 @@ fn renamed_from(
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The log index, locked only around reads and writes: Git runs without it, so commit
|
||||
/// details and one-commit queries need not wait for a long history walk.
|
||||
fn lock(index: &std::sync::Mutex<crate::log_index::LogIndex>) -> std::sync::MutexGuard<'_, crate::log_index::LogIndex> {
|
||||
index.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut index = r.log_index.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let result = if q.summary_only {
|
||||
let mut all = q.clone();
|
||||
all.skip = 0;
|
||||
@@ -483,14 +488,19 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
|
||||
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
|
||||
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
|
||||
let cached = index.views.get(&key).cloned();
|
||||
let cached = lock(&r.log_index).views.get(&key).cloned();
|
||||
let view = if let Some(cached) = cached {
|
||||
cached
|
||||
} else {
|
||||
// Immutable metadata is reused across roots, filters, merges and ref changes.
|
||||
all.request = q.request;
|
||||
let rows =
|
||||
std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(r, &all, cancel, &mut index)?));
|
||||
let rows = std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(
|
||||
r,
|
||||
&all,
|
||||
cancel,
|
||||
&r.log_index,
|
||||
)?));
|
||||
let mut index = lock(&r.log_index);
|
||||
if index.views.len() >= 4 {
|
||||
index.views.clear();
|
||||
}
|
||||
@@ -512,6 +522,7 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
let retain = q.retain_until.as_ref().and_then(|id| find_pos(id)).map(|i| i + 1).unwrap_or(0);
|
||||
let limit = if q.limit == 0 { usize::MAX } else { (q.limit as usize).max(retain.saturating_sub(start)) };
|
||||
let total = view.rows.len() as u32;
|
||||
let mut index = lock(&r.log_index);
|
||||
let db = index.db().cloned();
|
||||
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
|
||||
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
|
||||
@@ -538,9 +549,9 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
log_indexed(r, q, cancel, &mut index)
|
||||
log_indexed(r, q, cancel, &r.log_index)
|
||||
};
|
||||
index.flush();
|
||||
lock(&r.log_index).flush();
|
||||
result
|
||||
}
|
||||
|
||||
@@ -640,7 +651,7 @@ fn log_indexed(
|
||||
r: &Repo,
|
||||
q: &LogQuery,
|
||||
cancel: &CancellationToken,
|
||||
index: &mut crate::log_index::LogIndex,
|
||||
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
|
||||
) -> IdeResult<Vec<Commit>> {
|
||||
let repo = r.gix()?;
|
||||
let shallow: HashSet<ObjectId> =
|
||||
@@ -676,6 +687,8 @@ fn log_indexed(
|
||||
&& q.since_ms.is_none()
|
||||
&& q.until_ms.is_none()
|
||||
{
|
||||
let mut guard = lock(shared);
|
||||
let index = &mut *guard;
|
||||
update_head_reachable(&repo, index, cancel)?;
|
||||
let id = tips[0];
|
||||
let record = index.get(&repo, id)?;
|
||||
@@ -706,7 +719,9 @@ fn log_indexed(
|
||||
commit.message_truncated = false;
|
||||
return Ok(vec![commit]);
|
||||
}
|
||||
let rows = log_indexed_rows(r, q, cancel, index)?;
|
||||
let rows = log_indexed_rows(r, q, cancel, shared)?;
|
||||
let mut guard = lock(shared);
|
||||
let index = &mut *guard;
|
||||
let db = index.db().cloned();
|
||||
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
|
||||
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
|
||||
@@ -724,7 +739,7 @@ fn log_indexed_rows(
|
||||
r: &Repo,
|
||||
q: &LogQuery,
|
||||
cancel: &CancellationToken,
|
||||
index: &mut crate::log_index::LogIndex,
|
||||
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
|
||||
) -> IdeResult<Vec<crate::log_index::IndexedRow>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -775,7 +790,7 @@ fn log_indexed_rows(
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?)
|
||||
Some(sort_shared(&repo, ids, q, &shallow, cancel, shared)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -802,14 +817,17 @@ fn log_indexed_rows(
|
||||
};
|
||||
let authors: Vec<_> =
|
||||
q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect();
|
||||
update_head_reachable(&repo, index, cancel)?;
|
||||
let mut range_ids_set = range_ids.as_ref().map(|ids| ids.iter().copied().collect::<HashSet<_>>());
|
||||
type Walk<'a> = Box<dyn Iterator<Item = IdeResult<ObjectId>> + 'a>;
|
||||
let walk: Walk<'_> = if let Some(ids) = range_ids {
|
||||
Box::new(ids.into_iter().map(Ok))
|
||||
} else if q.summary_only {
|
||||
let ids = index.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
|
||||
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
|
||||
// One guard for both: a concurrent query with another shallow set resets `nodes`.
|
||||
let mut guard = lock(shared);
|
||||
let ids = guard.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
|
||||
let sorted = sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &guard.nodes)?;
|
||||
drop(guard);
|
||||
Box::new(sorted.into_iter().map(Ok))
|
||||
} else if repo.is_shallow().unwrap_or(false) || q.request.is_some() {
|
||||
// The process can be interrupted even during indegree preparation. Git also
|
||||
// respects shallow boundaries while retaining a topological order.
|
||||
@@ -866,7 +884,7 @@ fn log_indexed_rows(
|
||||
LogOrder::Topo | LogOrder::Standard => topo::Sorting::TopoOrder,
|
||||
LogOrder::Date => topo::Sorting::DateOrder,
|
||||
};
|
||||
let topo = topo::Builder::from_iters(&repo.objects, tips, None::<Vec<ObjectId>>)
|
||||
let topo = topo::Builder::from_iters(&repo.objects, tips.clone(), None::<Vec<ObjectId>>)
|
||||
.sorting(sorting)
|
||||
.parents(if q.first_parent { Parents::First } else { Parents::All })
|
||||
.with_commit_graph(graph)
|
||||
@@ -876,11 +894,20 @@ fn log_indexed_rows(
|
||||
};
|
||||
let walk: Walk<'_> = if q.order == LogOrder::Standard {
|
||||
let ids = walk.collect::<IdeResult<Vec<_>>>()?;
|
||||
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
|
||||
Box::new(sort_shared(&repo, ids, q, &shallow, cancel, shared)?.into_iter().map(Ok))
|
||||
} else {
|
||||
walk
|
||||
};
|
||||
let text = q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten();
|
||||
let mut guard = lock(shared);
|
||||
let index = &mut *guard;
|
||||
// Under the guard that builds the rows: a query run meanwhile (after a branch switch)
|
||||
// may have moved the shared set to another HEAD.
|
||||
update_head_reachable(&repo, index, cancel)?;
|
||||
// A query started before a shallow change may have reset `nodes` to its older set.
|
||||
if index.shallow != shallow {
|
||||
index.ensure_nodes(&repo, &tips, &shallow, cancel)?;
|
||||
}
|
||||
let db = index.db().cloned();
|
||||
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
|
||||
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
|
||||
@@ -952,6 +979,21 @@ fn log_indexed_rows(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sorts with the shared nodes only when they were built for this query's shallow set.
|
||||
fn sort_shared(
|
||||
repo: &gix::Repository,
|
||||
ids: Vec<ObjectId>,
|
||||
q: &LogQuery,
|
||||
shallow: &HashSet<ObjectId>,
|
||||
cancel: &CancellationToken,
|
||||
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
|
||||
) -> IdeResult<Vec<ObjectId>> {
|
||||
let guard = lock(shared);
|
||||
let empty = HashMap::new();
|
||||
let nodes = if &guard.shallow == shallow { &guard.nodes } else { &empty };
|
||||
sort_subset(repo, ids, q.order, q.first_parent, shallow, cancel, nodes)
|
||||
}
|
||||
|
||||
/// A ready-node stack gives incoming merge parents priority, while child counts
|
||||
/// prevent an ancestor shared with another branch from moving ahead of its children.
|
||||
fn sort_subset(
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! A long file history walk must not hold the log index while Git runs: commit details and
|
||||
//! one-commit queries (inline blame, the blame popup) share that index.
|
||||
#![cfg(unix)]
|
||||
|
||||
use ide_vcs::{LogQuery, Repo};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args([
|
||||
"-c",
|
||||
"init.defaultBranch=main",
|
||||
"-c",
|
||||
"user.name=T",
|
||||
"-c",
|
||||
"user.email=t@e",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn details_and_one_commit_queries_do_not_wait_for_a_file_history_walk() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("repo");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
git(&dir, &["init", "-q"]);
|
||||
for i in 0..3 {
|
||||
std::fs::write(dir.join("file"), format!("{i}")).unwrap();
|
||||
git(&dir, &["add", "-A"]);
|
||||
git(&dir, &["commit", "-qm", &format!("c{i}")]);
|
||||
}
|
||||
// A git whose path-limited history walks take seconds.
|
||||
let real = String::from_utf8(Command::new("sh").args(["-c", "command -v git"]).output().unwrap().stdout).unwrap();
|
||||
let started = tmp.path().join("walk-started");
|
||||
let wrapper = tmp.path().join("slow-git");
|
||||
std::fs::write(
|
||||
&wrapper,
|
||||
format!(
|
||||
"#!/bin/sh\ncase \" $* \" in *\" --full-history \"*) : > '{}'; sleep 3;; esac\nexec '{}' \"$@\"\n",
|
||||
started.display(),
|
||||
real.trim()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let repo = Repo::discover(&dir).unwrap().unwrap();
|
||||
repo.set_execution_allowed(true);
|
||||
repo.set_git_executable(Some(&wrapper));
|
||||
std::thread::scope(|scope| {
|
||||
let walk = scope.spawn(|| {
|
||||
repo.log(&LogQuery { path: Some("file".into()), follow: true, ..Default::default() }).unwrap().len()
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
while !started.exists() {
|
||||
assert!(Instant::now() < deadline, "the history walk never started");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let asked = Instant::now();
|
||||
let details = repo.log_details("HEAD").unwrap();
|
||||
let head = repo.log(&LogQuery { branch: Some("HEAD".into()), limit: 1, ..Default::default() }).unwrap();
|
||||
let waited = asked.elapsed();
|
||||
println!("queries waited {waited:?}");
|
||||
assert_eq!(details.message, "c2");
|
||||
assert_eq!(head.len(), 1);
|
||||
assert!(!walk.is_finished(), "the walk ended before the queries ran; the test proves nothing");
|
||||
assert!(waited < Duration::from_secs(2), "queries waited {waited:?} for the walk");
|
||||
assert_eq!(walk.join().unwrap(), 3);
|
||||
});
|
||||
}
|
||||
@@ -26,6 +26,8 @@ impl ApplicationFocus {
|
||||
pub fn changed(app: &tauri::AppHandle, focused: bool) {
|
||||
let generation = app.state::<ApplicationFocus>().changed(focused);
|
||||
if focused {
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::window_groups::detach_deferred(app);
|
||||
return;
|
||||
}
|
||||
let app = app.clone();
|
||||
|
||||
@@ -114,6 +114,16 @@ pub fn sync_tab_group(
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fullscreen_in_background(window: &WebviewWindow) -> bool {
|
||||
let target = window.clone();
|
||||
on_main(window, move || {
|
||||
let active =
|
||||
MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isActive());
|
||||
!active && native(&target).is_some_and(|w| w.styleMask().contains(objc2_app_kit::NSWindowStyleMask::FullScreen))
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Takes `window` out of its tab group into a window of its own; in full screen, a Space of its own.
|
||||
pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
|
||||
let target = window.clone();
|
||||
|
||||
@@ -201,9 +201,19 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
|
||||
select(app, caller, caller)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
static DEFERRED_DETACH: parking_lot::Mutex<Vec<String>> = parking_lot::Mutex::new(Vec::new());
|
||||
|
||||
pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
|
||||
let err = |e: tauri::Error| IdeError::internal(e.to_string());
|
||||
let state = app.state::<WindowsState>();
|
||||
#[cfg(target_os = "macos")]
|
||||
if state.groups.lock().group(caller).is_some()
|
||||
&& app.get_webview_window(caller).is_some_and(|w| crate::macos::fullscreen_in_background(&w))
|
||||
{
|
||||
DEFERRED_DETACH.lock().push(caller.to_owned());
|
||||
return Ok(());
|
||||
}
|
||||
let Some(next) = state.groups.lock().detach(caller) else {
|
||||
changed(app);
|
||||
return Ok(());
|
||||
@@ -234,6 +244,14 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn detach_deferred(app: &AppHandle) {
|
||||
let labels = std::mem::take(&mut *DEFERRED_DETACH.lock());
|
||||
for label in labels {
|
||||
let _ = detach(app, &label);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn destroyed(app: &AppHandle, caller: &str) {
|
||||
let Some(state) = app.try_state::<WindowsState>() else { return };
|
||||
let next = state.groups.lock().detach(caller);
|
||||
|
||||
@@ -101,6 +101,29 @@ describe("resolveMonoFont", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a chosen family that isn't installed", () => {
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("puts the bundled face before the fallback, so Latin text doesn't take the fallback's proportional letters", async () => {
|
||||
const fonts = await import("./fonts");
|
||||
// Before the native catalog loads nothing is known to be missing.
|
||||
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(`"Fira Code", "PingFang SC", ${BASE}`);
|
||||
fonts.noteInstalledFonts(["PingFang SC", "Menlo"]);
|
||||
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(
|
||||
`"Fira Code", "JetBrains Mono", "JetBrains Mono Variable", "PingFang SC", ${BASE}`,
|
||||
);
|
||||
// Installed, bundled and generic families keep the fallback right after them; so does no fallback.
|
||||
expect(fonts.monoFontFamily("menlo", "PingFang SC", BASE)).toBe(`"menlo", "PingFang SC", ${BASE}`);
|
||||
expect(fonts.monoFontFamily("Inter", "PingFang SC", BASE)).toBe(
|
||||
`"Inter", "Inter Variable", "PingFang SC", ${BASE}`,
|
||||
);
|
||||
expect(fonts.monoFontFamily("monospace", "PingFang SC", BASE)).toBe(`"monospace", "PingFang SC", ${BASE}`);
|
||||
expect(fonts.monoFontFamily("Fira Code", "", BASE)).toBe(`"Fira Code", ${BASE}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("discovered Nerd Font fallbacks (#3723)", () => {
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
|
||||
@@ -98,12 +98,15 @@ async function loadUserFont(name: string, alias: string): Promise<void> {
|
||||
* face is named alone unless the native catalog lists an installed JetBrains Mono.
|
||||
*/
|
||||
let monoInstalled: boolean | null = null;
|
||||
/** Lower-cased installed family names from the native catalog, once it has loaded. */
|
||||
let installedFamilies: ReadonlySet<string> | null = null;
|
||||
const bundledMonoOnly = () => guessOs() === "linux" && monoInstalled !== true;
|
||||
const BUNDLED_MONO_STACK = '"JetBrains Mono Variable", ui-monospace, monospace';
|
||||
|
||||
/** Records whether the system has JetBrains Mono installed (`installed`: the native catalog, not the bundled list). */
|
||||
export function noteInstalledFonts(installed: readonly string[], root?: HTMLElement): void {
|
||||
monoInstalled = installed.some((name) => name.trim().toLowerCase() === BUNDLED_MONO_FAMILY.toLowerCase());
|
||||
installedFamilies = new Set(installed.map((name) => name.trim().toLowerCase()));
|
||||
monoInstalled = installedFamilies.has(BUNDLED_MONO_FAMILY.toLowerCase());
|
||||
installMonoStack(root);
|
||||
}
|
||||
|
||||
@@ -256,7 +259,22 @@ export function monoFontFamily(family: string | undefined, fallback = "", base =
|
||||
const name = familyName(family ?? "");
|
||||
const fb = familyName(fallback);
|
||||
const head = familyFaces(name || BUNDLED_MONO_FAMILY);
|
||||
return [...head, ...(fb ? familyFaces(fb) : []), base].join(", ");
|
||||
// A chosen family that isn't installed leaves every glyph to the fallback, often a CJK face
|
||||
// whose Latin letters are proportional: a grid measures its cells by the widest of them and
|
||||
// the text comes out spread apart. The bundled face stands in for the missing one, and the
|
||||
// fallback still covers what that lacks.
|
||||
const standIn = fb && name && familyMissing(name) ? familyFaces(BUNDLED_MONO_FAMILY) : [];
|
||||
return [...head, ...standIn, ...(fb ? familyFaces(fb) : []), base].join(", ");
|
||||
}
|
||||
|
||||
const GENERIC_FAMILIES =
|
||||
/^(?:monospace|ui-monospace|sans-serif|serif|system-ui|ui-sans-serif|ui-serif|cursive|fantasy)$/i;
|
||||
|
||||
/** Whether the native catalog has loaded and doesn't list `name` (bundled and generic families always count as present). */
|
||||
function familyMissing(name: string): boolean {
|
||||
if (!installedFamilies) return false;
|
||||
const key = name.toLowerCase();
|
||||
return !installedFamilies.has(key) && !BUNDLED_FACES.has(key) && !GENERIC_FAMILIES.test(name);
|
||||
}
|
||||
|
||||
/** Tools › Terminal › Font, shared by the terminal and the Run console. */
|
||||
|
||||
@@ -3740,6 +3740,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.",
|
||||
"Hot reload on save failed: {0}": "Hot reload on save failed: {0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?",
|
||||
"New Tab": "New Tab",
|
||||
"New tab in current window": "New tab in current window",
|
||||
"Show Only Widgets": "Show Only Widgets",
|
||||
|
||||
@@ -9762,6 +9762,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Сохранение файла Dart во время запущенной сессии отладки Flutter перезагружает приложение, если в файле нет ошибок.",
|
||||
"Hot reload on save failed: {0}": "Ошибка горячей перезагрузки при сохранении: {0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта, присоединять к уже открытым проектам или открывать как новую вкладку в этом окне.\nКак открыть «{name}»?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта или как новую вкладку в этом окне.\nКак открыть «{name}»?",
|
||||
"Show Only Widgets": "Показывать только виджеты",
|
||||
"Update failed": "Не удалось выполнить обновление",
|
||||
"Updating branches": "Обновление веток",
|
||||
|
||||
@@ -2668,6 +2668,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Çalışan Flutter hata ayıklama oturumunda Dart dosyası kaydedildiğinde, dosyada hata yoksa uygulama yeniden yüklenir.",
|
||||
"Hot reload on save failed: {0}": "Kaydetmede sıcak yeniden yükleme başarısız: {0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir, açık projelere bağlanabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?",
|
||||
"New Tab": "Yeni sekme",
|
||||
"New tab in current window": "Geçerli pencerede yeni sekme",
|
||||
"Show Only Widgets": "Yalnızca Bileşenleri Göster",
|
||||
|
||||
@@ -9195,6 +9195,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "儲存正在執行的 Flutter 偵錯工作階段裡的 Dart 檔案時重新載入應用,檔案有錯誤時跳過。",
|
||||
"Hot reload on save failed: {0}": "儲存時熱過載失敗:{0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案、附加到已開啟的專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?",
|
||||
"Show Only Widgets": "僅顯示 Widget",
|
||||
"Update failed": "更新失敗",
|
||||
"Updating branches": "正在更新分支",
|
||||
|
||||
@@ -10315,6 +10315,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "保存正在运行的 Flutter 调试会话里的 Dart 文件时重新加载应用,文件有错误时跳过。",
|
||||
"Hot reload on save failed: {0}": "保存时热重载失败:{0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目、附加到已打开的项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?",
|
||||
"Show Only Widgets": "仅显示 Widget",
|
||||
"Update failed": "更新失败",
|
||||
"Updating branches": "正在更新分支",
|
||||
|
||||
@@ -7,9 +7,11 @@ import { ask } from "./messages";
|
||||
import { commands } from "@/platform/ipc";
|
||||
|
||||
const windowOpenRemote = vi.fn();
|
||||
const windowGroupJoin = vi.fn();
|
||||
const remoteWindow = vi.hoisted(() => ({ value: false }));
|
||||
vi.mock("./messages", () => ({ ask: vi.fn() }));
|
||||
vi.mock("@/platform/remote", () => ({
|
||||
isRemoteWindow: () => false,
|
||||
isRemoteWindow: () => remoteWindow.value,
|
||||
connectRemote: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
@@ -18,10 +20,12 @@ vi.mock("@/platform/ipc", () => ({
|
||||
commands: {
|
||||
settingsSet: vi.fn(async () => ({ general: { openProjectIn: "attach" } })),
|
||||
windowOpenRemote: (...a: unknown[]) => windowOpenRemote(...a),
|
||||
windowGroupJoin: (...a: unknown[]) => windowGroupJoin(...a),
|
||||
},
|
||||
}));
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
remoteWindow.value = false;
|
||||
useProject.setState({
|
||||
project: { root: "/a", name: "A", settings: {}, trusted: true, isGit: false },
|
||||
settings: {},
|
||||
@@ -40,14 +44,20 @@ it("offers attach for this open without remembering it", async () => {
|
||||
expect(await chooseProjectWindow("C")).toBe(button);
|
||||
expect(ask).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("does not attach without a project or when opening a remote project", async () => {
|
||||
it("offers a new tab but no attach for a remote project or from a remote window", async () => {
|
||||
useProject.setState({
|
||||
settings: { general: { openProjectIn: "attach" } } as never,
|
||||
});
|
||||
vi.mocked(ask).mockResolvedValue({ button: "cancel", checked: false });
|
||||
expect(await chooseProjectWindow("remote", false)).toBeNull();
|
||||
expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]);
|
||||
useProject.setState({ project: null });
|
||||
expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]);
|
||||
remoteWindow.value = true;
|
||||
expect(await chooseProjectWindow("B")).toBeNull();
|
||||
expect(vi.mocked(ask).mock.calls[1]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]);
|
||||
useProject.setState({ project: null, lightEdit: true });
|
||||
expect(await chooseProjectWindow("B")).toBeNull();
|
||||
expect(vi.mocked(ask).mock.calls[2]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]);
|
||||
useProject.setState({ project: null, lightEdit: false });
|
||||
expect(await chooseProjectWindow("B")).toBe("same");
|
||||
});
|
||||
|
||||
@@ -65,7 +75,7 @@ it("opens a project tab by policy, or a new window when this one can't take one"
|
||||
useProject.setState({ settings: { general: { openProjectIn: "tab" } } } as never);
|
||||
expect(openPolicy()).toBe("tab");
|
||||
expect(await chooseProjectWindow("B")).toBe("tab");
|
||||
expect(await chooseProjectWindow("remote", false)).toBe("new");
|
||||
expect(await chooseProjectWindow("remote", false)).toBe("tab");
|
||||
useProject.setState({ project: null, lightEdit: true });
|
||||
expect(await chooseProjectWindow("B")).toBe("new");
|
||||
expect(ask).not.toHaveBeenCalled();
|
||||
@@ -91,6 +101,16 @@ describe("a recent project opened with a modifier key", () => {
|
||||
usePlatform.setState({ os });
|
||||
});
|
||||
|
||||
it("opens a remote project as a project tab of this window", async () => {
|
||||
windowOpenRemote.mockResolvedValueOnce({ kind: "current" }).mockResolvedValueOnce({ kind: "opened", label: "w2" });
|
||||
const here = vi.fn(async () => {});
|
||||
useProject.setState({ settings: { general: { openProjectIn: "tab" } } as never });
|
||||
expect(await openRemoteProject(target, "/home/me/app", here)).toBe(true);
|
||||
expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", true);
|
||||
expect(windowGroupJoin).toHaveBeenCalledWith("w2");
|
||||
expect(here).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("opens a remote project in that window without asking", async () => {
|
||||
windowOpenRemote.mockResolvedValue({ kind: "opened" });
|
||||
const here = vi.fn(async () => {});
|
||||
|
||||
@@ -40,26 +40,26 @@ export async function chooseProjectWindow(
|
||||
): Promise<"new" | "same" | "attach" | "tab" | null> {
|
||||
const { project, lightEdit } = useProject.getState();
|
||||
if (!project && !lightEdit) return "same";
|
||||
// Both ways of keeping this window's project: a workspace folder, or a project tab of this window.
|
||||
const canAdd = allowAttach && !!project && !isRemoteWindow();
|
||||
// Attach adds a local folder to this local window's workspace; a project tab is a window of its
|
||||
// own joined to this one's group, so it takes remote projects and remote windows too.
|
||||
const canTab = !!project;
|
||||
const canAttach = allowAttach && canTab && !isRemoteWindow();
|
||||
const mode = openPolicy();
|
||||
// A project tab needs this window's project beside it; without one, a new window is the closest.
|
||||
if (mode === "tab") return canAdd ? "tab" : "new";
|
||||
if (mode === "tab") return canTab ? "tab" : "new";
|
||||
if (mode !== "ask") return mode;
|
||||
const r = await ask({
|
||||
title: t("app.window.askTitle"),
|
||||
width: canAdd ? 640 : undefined,
|
||||
body: canAdd
|
||||
width: canAttach ? 640 : undefined,
|
||||
body: canAttach
|
||||
? tx`Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open "${name}"?`
|
||||
: t("app.window.askBody", { name }),
|
||||
: canTab
|
||||
? tx`Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open "${name}"?`
|
||||
: t("app.window.askBody", { name }),
|
||||
buttons: [
|
||||
{ id: "cancel", label: t("common.cancel") },
|
||||
...(canAdd
|
||||
? [
|
||||
{ id: "attach", label: t("app.window.askAttach") },
|
||||
{ id: "tab", label: tx`New Tab` },
|
||||
]
|
||||
: []),
|
||||
...(canAttach ? [{ id: "attach", label: t("app.window.askAttach") }] : []),
|
||||
...(canTab ? [{ id: "tab", label: tx`New Tab` }] : []),
|
||||
{ id: "new", label: t("app.window.askNew") },
|
||||
{ id: "same", label: t("app.window.askThis"), primary: true },
|
||||
],
|
||||
@@ -81,8 +81,8 @@ export async function chooseProjectWindow(
|
||||
|
||||
/**
|
||||
* Opens folder `path` of `target` (an SSH host or a WSL distribution): focuses the
|
||||
* window that has it, else opens it in a new window or (`here`) this one per
|
||||
* "Open project in", or where `override` says. `false`: cancelled.
|
||||
* window that has it, else opens it in a new window, a project tab of this window or
|
||||
* (`here`) this one per "Open project in", or where `override` says. `false`: cancelled.
|
||||
*/
|
||||
export async function openRemoteProject(
|
||||
target: RemoteTarget,
|
||||
@@ -93,8 +93,10 @@ export async function openRemoteProject(
|
||||
if ((await call(commands.windowOpenRemote(target, path, false))).kind === "focused") return true;
|
||||
const mode = override ?? (await chooseProjectWindow(path.replace(/\/+$/, "").split("/").pop() || path, false));
|
||||
if (!mode) return false;
|
||||
if (mode === "new") {
|
||||
await call(commands.windowOpenRemote(target, path, true));
|
||||
if (mode === "new" || mode === "tab") {
|
||||
const outcome = await call(commands.windowOpenRemote(target, path, true));
|
||||
// As a local project tab: the window holding the project, new or focused, joins this one's group.
|
||||
if (mode === "tab" && outcome.kind !== "current") await call(commands.windowGroupJoin(outcome.label));
|
||||
return true;
|
||||
}
|
||||
// The remote host's project doesn't take this window's untitled buffers.
|
||||
|
||||
Reference in new issue
Заблокувати користувача