дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-25 02:44:37 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
bc390f48b5 |
No files matched your search
Створено
@@ -4121,7 +4121,6 @@ dependencies = [
|
||||
name = "ide-build"
|
||||
version = "0.1.37"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"ide-core",
|
||||
|
||||
@@ -6,7 +6,6 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
blake3.workspace = true
|
||||
dunce.workspace = true
|
||||
ide-core.workspace = true
|
||||
zip.workspace = true
|
||||
|
||||
@@ -2,49 +2,18 @@
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::io::Read;
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only.
|
||||
type Stamp = (u64, SystemTime, Option<String>);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LaunchFingerprint {
|
||||
version: u32,
|
||||
parameters: String,
|
||||
/// Per input: a [`Stamp`] for regular files, `None` for
|
||||
/// directories and inputs that cannot be resolved. The content hash catches external
|
||||
/// edits that preserve both length and mtime (timestamp-preserving tools, coarse
|
||||
/// timestamp granularity), which `(length, mtime)` alone would miss. Only files inside
|
||||
/// the project are hashed; toolchain inputs such as the JDK's `lib/modules` keep the stamp.
|
||||
files: BTreeMap<PathBuf, Option<Stamp>>,
|
||||
}
|
||||
|
||||
/// `blake3` hex of a file's bytes, streamed in chunks so memory stays bounded. An
|
||||
/// unreadable file records a sentinel so one permission problem does not drop the whole
|
||||
/// fingerprint (that would just force a normal rebuild).
|
||||
fn content_hash(path: &Path) -> IdeResult<String> {
|
||||
let mut file = match fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok("missing".into()),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
let mut buffer = [0; 64 * 1024];
|
||||
loop {
|
||||
let count = file.read(&mut buffer)?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..count]);
|
||||
}
|
||||
Ok(hasher.finalize().to_hex().to_string())
|
||||
files: BTreeMap<PathBuf, Option<(u64, SystemTime)>>,
|
||||
}
|
||||
|
||||
fn scan(
|
||||
root: &Path,
|
||||
path: &Path,
|
||||
files: &mut BTreeMap<PathBuf, Option<Stamp>>,
|
||||
files: &mut BTreeMap<PathBuf, Option<(u64, SystemTime)>>,
|
||||
ancestors: &mut HashSet<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<()> {
|
||||
@@ -67,12 +36,11 @@ fn scan(
|
||||
// Directory mtimes change on irrelevant JDT writes. File paths detect additions/deletions.
|
||||
files.insert(path.to_path_buf(), None);
|
||||
for entry in fs::read_dir(path)? {
|
||||
scan(root, &entry?.path(), files, ancestors, cancel)?;
|
||||
scan(&entry?.path(), files, ancestors, cancel)?;
|
||||
}
|
||||
ancestors.remove(&canonical);
|
||||
} else if meta.is_file() {
|
||||
let hash = if path.starts_with(root) { Some(content_hash(path)?) } else { None };
|
||||
files.insert(path.to_path_buf(), Some((meta.len(), meta.modified()?, hash)));
|
||||
files.insert(path.to_path_buf(), Some((meta.len(), meta.modified()?)));
|
||||
} else {
|
||||
return Err(IdeError::internal("unsupported launch input file"));
|
||||
}
|
||||
@@ -177,11 +145,11 @@ pub fn launch_fingerprint(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let mut files = BTreeMap::new();
|
||||
for path in inputs {
|
||||
scan(root, &path, &mut files, &mut HashSet::new(), cancel)?;
|
||||
scan(&path, &mut files, &mut HashSet::new(), cancel)?;
|
||||
}
|
||||
// Store project inputs relative to the project, including each file's relative path.
|
||||
let files = files.into_iter().map(|(p, stamp)| (p.strip_prefix(root).unwrap_or(&p).to_path_buf(), stamp)).collect();
|
||||
Ok(Some(LaunchFingerprint { version: 2, parameters, files }))
|
||||
Ok(Some(LaunchFingerprint { version: 1, parameters, files }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -263,25 +231,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// An external tool that keeps the byte length and the mtime (timestamp-preserving
|
||||
/// writes, coarse-granularity filesystems) still changes the content: the fingerprint
|
||||
/// must differ via the content hash, not via `(length, mtime)`.
|
||||
#[test]
|
||||
fn external_edit_preserving_length_and_mtime_still_invalidates() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let source = root.join("lib/src/main/kotlin/Channel.kt");
|
||||
let before = fingerprint(root, &model);
|
||||
assert!(before.is_some());
|
||||
let mtime = fs::metadata(&source).unwrap().modified().unwrap();
|
||||
// Same 5-byte length, different content.
|
||||
write(root, "lib/src/main/kotlin/Channel.kt", "valve");
|
||||
fs::File::options().write(true).open(&source).unwrap().set_modified(mtime).unwrap();
|
||||
let after = fingerprint(root, &model);
|
||||
assert_ne!(before, after, "a same-length, same-mtime content change must invalidate the fingerprint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_options_jdk_goal_and_wrapper_invalidate_without_using_class_outputs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -143,7 +143,7 @@ fn nvm_bins(dir: &Path) -> Vec<PathBuf> {
|
||||
}
|
||||
|
||||
/// `v22.10.1` as `[22, 10, 1]`: v22 is newer than v9, v20.10 newer than v20.9.
|
||||
pub fn version_key(name: &str) -> Vec<u64> {
|
||||
fn version_key(name: &str) -> Vec<u64> {
|
||||
name.trim_start_matches('v').split('.').map(|n| n.parse().unwrap_or(0)).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -242,29 +242,6 @@ mod tests {
|
||||
assert!(build().is_err());
|
||||
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 5);
|
||||
}
|
||||
/// An external tool (e.g. an AI code editor) rewrites a source file with the same byte
|
||||
/// length and preserves its mtime. The `(length, mtime)` fingerprint reads that as
|
||||
/// "unchanged" and would reuse the stale snapshot; the content hash must catch it.
|
||||
#[test]
|
||||
fn external_edit_preserving_length_and_mtime_rebuilds_the_snapshot() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(cache.clone());
|
||||
let first = session.build(root, &model, root, false, None, &cancel).unwrap();
|
||||
assert_eq!(fs::read_to_string(first.snapshot.join("0/Main.class")).unwrap(), "first");
|
||||
|
||||
let source = root.join("src/main/kotlin/Main.kt");
|
||||
let mtime = fs::metadata(&source).unwrap().modified().unwrap();
|
||||
fs::write(&source, "other").unwrap(); // 5 bytes, same length as "first"
|
||||
fs::File::options().write(true).open(&source).unwrap().set_modified(mtime).unwrap();
|
||||
let rebuilt = session.build(root, &model, root, false, None, &cancel).unwrap();
|
||||
assert_ne!(rebuilt.snapshot, first.snapshot, "a same-length, same-mtime content change must rebuild");
|
||||
assert_eq!(fs::read_to_string(rebuilt.snapshot.join("0/Main.class")).unwrap(), "other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_drop_removes_superseded_snapshots_and_preserves_records_across_reopen() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -52,14 +52,6 @@ pub fn sdk_python_effective(host: &Host, window: &str) -> IdeResult<Option<ide_c
|
||||
Ok(ide_sdk::apply::python_interpreter(&project.root, &project.settings.effective()).map(Into::into))
|
||||
}
|
||||
|
||||
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
|
||||
pub fn sdk_php_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let settings = project.settings.effective();
|
||||
Ok(ide_sdk::apply::setting_path(&project.root, &settings.languages.php.interpreter).map(Into::into))
|
||||
}
|
||||
|
||||
/// The PHP language level of the project `path` belongs to (a workspace member, by path, as
|
||||
/// the language server configuration picks it).
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
@@ -206,7 +198,6 @@ pub async fn sdk_python_pip(
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("sdk_detect", |c| async move { sdk_detect(&c.host, &c.window, c.arg("kind")?).await });
|
||||
d.add("sdk_python_effective", |c| async move { sdk_python_effective(&c.host, &c.window) });
|
||||
d.add("sdk_php_effective", |c| async move { sdk_php_effective(&c.host, &c.window) });
|
||||
d.add(
|
||||
"sdk_php_language_level",
|
||||
|c| async move { sdk_php_language_level(&c.host, &c.window, c.arg("path")?).await },
|
||||
|
||||
@@ -306,9 +306,8 @@ impl PluginApi {
|
||||
// allowed, and installing it later approves nothing by itself.
|
||||
let pin = self.shared.pins.read().get(&(self.id().to_owned(), cap.clone())).cloned().ok_or_else(|| {
|
||||
HostError::Failed(format!(
|
||||
"{cap}: `{program}` was not found on PATH when this permission was allowed. \
|
||||
Restarting doesn't approve a program installed later: once `{program}` is on PATH, \
|
||||
clear {cap} in Settings › Plugins and select it again"
|
||||
"{cap}: `{program}` was not found when this permission was allowed; \
|
||||
install it, then allow {cap} again in Settings › Plugins"
|
||||
))
|
||||
})?;
|
||||
pin.verify().map(Path::to_path_buf).map_err(|e| HostError::Denied(format!("{cap}: {e}")))
|
||||
@@ -832,8 +831,7 @@ mod tests {
|
||||
// Allowed while the program was missing: say how to fix it rather than "not granted".
|
||||
let err = api.approved_program("lint").unwrap_err().to_string();
|
||||
assert!(
|
||||
err.contains("was not found on PATH when this permission was allowed")
|
||||
&& err.contains("clear process:lint in Settings › Plugins and select it again"),
|
||||
err.contains("was not found when this permission was allowed") && err.contains("allow process:lint again"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
|
||||
@@ -367,7 +367,7 @@ fn php() -> Vec<Sdk> {
|
||||
}
|
||||
}
|
||||
let found = dedupe_by_real_path(found);
|
||||
let mut sdks = par_map(&found, |(path, source)| {
|
||||
par_map(&found, |(path, source)| {
|
||||
let version = query(path, &["-r", "echo PHP_VERSION;"], VERSION_TIMEOUT)?;
|
||||
let version = version.trim().to_owned();
|
||||
if version.is_empty() {
|
||||
@@ -381,16 +381,7 @@ fn php() -> Vec<Sdk> {
|
||||
home: path.parent().and_then(Path::parent).map(Into::into),
|
||||
extra: None,
|
||||
})
|
||||
});
|
||||
newest_first(&mut sdks);
|
||||
sdks
|
||||
}
|
||||
|
||||
/// Newest version first, number by number (8.3.12 before 8.3.9); stable, so on equal
|
||||
/// versions the `PATH` install stays first.
|
||||
pub(crate) fn newest_first(sdks: &mut [Sdk]) {
|
||||
let key = |s: &Sdk| ide_core::tool_path::version_key(s.version.as_deref().unwrap_or(""));
|
||||
sdks.sort_by_key(|s| std::cmp::Reverse(key(s)));
|
||||
})
|
||||
}
|
||||
|
||||
fn node() -> Vec<Sdk> {
|
||||
|
||||
@@ -1322,29 +1322,7 @@ fn php_sources_and_selected_interpreter() {
|
||||
assert_eq!(source("/opt/homebrew/opt/[email protected]/bin/php"), "homebrew");
|
||||
assert_eq!(source("/home/me/bin/php"), "path");
|
||||
|
||||
use crate::discover::{is_versioned_php_name, newest_first, versioned_php_in};
|
||||
let sdk = |path: &str, version: &str| crate::Sdk {
|
||||
path: std::path::PathBuf::from(path).into(),
|
||||
name: format!("PHP {version}"),
|
||||
version: Some(version.into()),
|
||||
source: "path".into(),
|
||||
home: None,
|
||||
extra: None,
|
||||
};
|
||||
let mut sdks = vec![
|
||||
sdk("/opt/homebrew/bin/php", "8.4.1"),
|
||||
sdk("/opt/homebrew/opt/[email protected]/bin/php", "8.1.31"),
|
||||
sdk("/opt/homebrew/opt/[email protected]/bin/php", "8.2.20"),
|
||||
sdk("/home/me/.phpbrew/php/php-8.3.9/bin/php", "8.3.9"),
|
||||
sdk("/home/me/.phpbrew/php/php-8.3.12/bin/php", "8.3.12"),
|
||||
sdk("/home/me/.phpbrew/php/php-7.4.33/bin/php", "7.4.33"),
|
||||
sdk("/usr/bin/php", "8.4.1"),
|
||||
];
|
||||
newest_first(&mut sdks);
|
||||
let order: Vec<_> = sdks.iter().map(|s| s.version.clone().unwrap()).collect();
|
||||
assert_eq!(order, ["8.4.1", "8.4.1", "8.3.12", "8.3.9", "8.2.20", "8.1.31", "7.4.33"]);
|
||||
// Stable: on equal versions the PATH install stays first.
|
||||
assert_eq!(sdks[0].path.0, std::path::PathBuf::from("/opt/homebrew/bin/php"));
|
||||
use crate::discover::{is_versioned_php_name, versioned_php_in};
|
||||
for name in ["php8.1", "php81", "php8", "php8.3.exe"] {
|
||||
assert!(is_versioned_php_name(name), "{name}");
|
||||
}
|
||||
|
||||
@@ -120,7 +120,6 @@ impl TerminalManager {
|
||||
for (k, v) in env {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
apply_powershell_env(&shell, &mut cmd);
|
||||
|
||||
let child = pair
|
||||
.slave
|
||||
@@ -634,18 +633,6 @@ fn terminal_env(user: &BTreeMap<String, String>) -> BTreeMap<String, String> {
|
||||
env
|
||||
}
|
||||
|
||||
/// Older pwsh versions can crash while formatting a localized update banner
|
||||
/// (PowerShell/PowerShell#28131). Keep explicit preferences in the final environment.
|
||||
fn apply_powershell_env(shell: &str, cmd: &mut CommandBuilder) {
|
||||
let name = shell.rsplit(['/', '\\']).next().unwrap_or(shell);
|
||||
if cfg!(windows)
|
||||
&& (name.eq_ignore_ascii_case("pwsh") || name.eq_ignore_ascii_case("pwsh.exe"))
|
||||
&& cmd.get_env("POWERSHELL_UPDATECHECK").is_none_or(|v| v.is_empty())
|
||||
{
|
||||
cmd.env("POWERSHELL_UPDATECHECK", "Off");
|
||||
}
|
||||
}
|
||||
|
||||
/// Git Bash's MSYSTEM profile on Windows, when nobody chose one. A bare
|
||||
/// `bash.exe` would run with the `MSYS` default, whose PATH leaves `git` and
|
||||
/// the mingw64 tools out unless `<Git>\cmd` happens to be inherited — the Git
|
||||
@@ -951,56 +938,6 @@ mod tests {
|
||||
mod shell_start_on_every_platform {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn powershell_update_notifications_default_to_off_on_windows() {
|
||||
for shell in ["pwsh", "pwsh.exe", "PWSH.EXE", "C:\\Program Files\\PowerShell\\7\\PwSh.ExE", "C:/pwsh/pwsh.exe"]
|
||||
{
|
||||
for value in [None, Some("")] {
|
||||
let mut cmd = CommandBuilder::new(shell);
|
||||
cmd.env_clear();
|
||||
if let Some(value) = value {
|
||||
cmd.env("POWERSHELL_UPDATECHECK", value);
|
||||
}
|
||||
apply_powershell_env(shell, &mut cmd);
|
||||
let want = if cfg!(windows) { Some("Off") } else { value };
|
||||
assert_eq!(cmd.get_env("POWERSHELL_UPDATECHECK"), want.map(std::ffi::OsStr::new), "{shell}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_update_notification_preferences_are_preserved() {
|
||||
for value in ["Default", "LTS", "Off"] {
|
||||
let mut cmd = CommandBuilder::new("pwsh.exe");
|
||||
cmd.env_clear();
|
||||
cmd.env("POWERSHELL_UPDATECHECK", value);
|
||||
apply_powershell_env("pwsh.exe", &mut cmd);
|
||||
assert_eq!(cmd.get_env("POWERSHELL_UPDATECHECK"), Some(std::ffi::OsStr::new(value)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn powershell_update_notification_preferences_ignore_key_case() {
|
||||
let mut cmd = CommandBuilder::new("pwsh.exe");
|
||||
cmd.env_clear();
|
||||
cmd.env("POWERSHELL_UPDATECHECK", "Off");
|
||||
cmd.env("powershell_updatecheck", "Default");
|
||||
apply_powershell_env("pwsh.exe", &mut cmd);
|
||||
assert_eq!(cmd.get_env("POWERSHELL_UPDATECHECK"), Some(std::ffi::OsStr::new("Default")));
|
||||
assert_eq!(cmd.iter_full_env_as_str().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_shells_keep_their_update_notification_environment() {
|
||||
for shell in ["powershell.exe", "cmd.exe", "wsl.exe", "bash.exe", "C:\\pwsh.exe\\other.exe", "other-pwsh.exe"] {
|
||||
let mut cmd = CommandBuilder::new(shell);
|
||||
cmd.env_clear();
|
||||
apply_powershell_env(shell, &mut cmd);
|
||||
assert_eq!(cmd.get_env("POWERSHELL_UPDATECHECK"), None, "{shell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn posix_shells_start_as_login_shells_everywhere() {
|
||||
let (shell, args) = resolve_shell(Some("C:\\Program Files\\Git\\bin\\bash.exe"), &[]);
|
||||
|
||||
@@ -868,18 +868,17 @@ impl Documents {
|
||||
.then(|| st.path.clone())
|
||||
})
|
||||
.collect();
|
||||
self.reload_from_disk(&paths, force_clean, true);
|
||||
self.reload_from_disk(&paths, force_clean);
|
||||
}
|
||||
|
||||
/// Re-reads from disk after an external change. Clean documents reload
|
||||
/// silently; dirty ones are left alone and reported via `IdeEvent::Notify`.
|
||||
/// Changes matching our own last save are ignored.
|
||||
pub fn on_disk_changed(&self, paths: &[PathBuf]) {
|
||||
self.reload_from_disk(paths, false, false);
|
||||
self.reload_from_disk(paths, false);
|
||||
}
|
||||
|
||||
/// `dedup`: blind scans skip files whose `(mtime, length)` stamp still matches.
|
||||
fn reload_from_disk(&self, paths: &[PathBuf], force_clean: bool, dedup: bool) {
|
||||
fn reload_from_disk(&self, paths: &[PathBuf], force_clean: bool) {
|
||||
for path in paths {
|
||||
let Some(id) = self.by_path(path) else { continue };
|
||||
let result = self.with_doc(id, |st| {
|
||||
@@ -888,23 +887,7 @@ impl Documents {
|
||||
}
|
||||
let Ok(meta) = std::fs::metadata(&st.path) else { return Ok(()) };
|
||||
let mtime = ide_vfs::mtime_ms(&meta);
|
||||
let unchanged = mtime == st.disk_mtime && meta.len() == st.disk_len;
|
||||
// Blind scans trust the stamp. OS events are authoritative, but they also
|
||||
// echo our own saves: a clean document whose stamp matches is re-checked by
|
||||
// bytes — an external write that preserved both length and mtime differs
|
||||
// from what saving this buffer would write, our own save's echo does not.
|
||||
// Native-to-ascii properties documents and dirty documents keep the stamp
|
||||
// dedup: the former's disk bytes legitimately differ from the buffer text,
|
||||
// the latter warn once per disk state.
|
||||
if unchanged
|
||||
&& (!force_clean || st.dirty)
|
||||
&& (dedup
|
||||
|| st.dirty
|
||||
|| st.native_to_ascii
|
||||
|| ide_vfs::encode(&st.doc.text_for_save(), &st.encoding, st.has_bom)
|
||||
.map(|bytes| bytes == std::fs::read(&st.path).unwrap_or_default())
|
||||
.unwrap_or(true))
|
||||
{
|
||||
if mtime == st.disk_mtime && meta.len() == st.disk_len && (!force_clean || st.dirty) {
|
||||
return Ok(());
|
||||
}
|
||||
if st.dirty {
|
||||
|
||||
@@ -403,46 +403,6 @@ fn external_changes() {
|
||||
f.docs.on_disk_changed(&[f.root.join("other.txt")]);
|
||||
}
|
||||
|
||||
/// An IDE operation that rewrites a file with the same length and mtime still refreshes
|
||||
/// the clean buffer.
|
||||
#[test]
|
||||
fn own_disk_change_preserving_length_and_mtime_reloads_a_clean_document() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("stamp.txt");
|
||||
fs::write(&path, "first").unwrap();
|
||||
let id = f.docs.open(&path).unwrap().id;
|
||||
let mtime = fs::metadata(&path).unwrap().modified().unwrap();
|
||||
fs::write(&path, "other").unwrap();
|
||||
fs::File::options().write(true).open(&path).unwrap().set_modified(mtime).unwrap();
|
||||
f.docs.sync_after_disk_change();
|
||||
assert_eq!(f.docs.snapshot(id).unwrap().text, "other");
|
||||
}
|
||||
|
||||
/// An external write that keeps the byte length and the mtime (timestamp-preserving
|
||||
/// tools, coarse-granularity filesystems) leaves the `(mtime, length)` stamp equal:
|
||||
/// the OS event is still authoritative, so a clean document reloads.
|
||||
#[test]
|
||||
fn external_change_preserving_length_and_mtime_reloads_a_clean_document() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("stamp.txt");
|
||||
fs::write(&path, "first").unwrap(); // 5 bytes
|
||||
let id = f.docs.open(&path).unwrap().id;
|
||||
let mtime = fs::metadata(&path).unwrap().modified().unwrap();
|
||||
|
||||
fs::write(&path, "other").unwrap(); // 5 bytes, different content
|
||||
fs::File::options().write(true).open(&path).unwrap().set_modified(mtime).unwrap();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
let snap = f.docs.snapshot(id).unwrap();
|
||||
assert_eq!(snap.text, "other");
|
||||
assert!(!snap.dirty);
|
||||
|
||||
// The reload recorded the new stamp: repeating the same event changes nothing.
|
||||
let before = f.events.lock().len();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert_eq!(f.events.lock().len(), before);
|
||||
assert_eq!(f.docs.snapshot(id).unwrap().text, "other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encodings_and_read_only() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -324,7 +324,7 @@ a token.
|
||||
|
||||
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
|
||||
|
||||
242 themeable tokens: 121 in the UI theme file, 121 in the editor colour scheme file.
|
||||
240 themeable tokens: 121 in the UI theme file, 119 in the editor colour scheme file.
|
||||
|
||||
### Surfaces (UI theme)
|
||||
|
||||
@@ -446,8 +446,6 @@ a token.
|
||||
| `--syn-python-predefined-usage` | `var(--syn-predefined)` | `var(--syn-predefined)` |
|
||||
| `--syn-python-fstring` | `#a5c261` | `var(--syn-string)` |
|
||||
| `--syn-python-bytes` | `#a5c261` | `var(--syn-string)` |
|
||||
| `--syn-php-variable` | `var(--syn-property)` | `var(--syn-property)` |
|
||||
| `--syn-php-function-call` | `var(--syn-function)` | `var(--syn-function)` |
|
||||
| `--syn-builtin` | `#8888c6` | `#000080` |
|
||||
| `--syn-self` | `#94558d` | `#94558d` |
|
||||
| `--syn-keyword-arg` | `#aa4926` | `#660099` |
|
||||
|
||||
@@ -34,8 +34,6 @@
|
||||
"--syn-python-predefined-usage": "#c4a0f2",
|
||||
"--syn-python-fstring": "#9ccc7a",
|
||||
"--syn-python-bytes": "#9ccc7a",
|
||||
"--syn-php-variable": "#b9a3f0",
|
||||
"--syn-php-function-call": "#f2d07a",
|
||||
"--syn-builtin": "#6fc3df",
|
||||
"--syn-self": "#d6849c",
|
||||
"--syn-keyword-arg": "#c4a0f2",
|
||||
|
||||
@@ -398,7 +398,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
tools::jdk_download,
|
||||
sdk::sdk_detect,
|
||||
sdk::sdk_python_effective,
|
||||
sdk::sdk_php_effective,
|
||||
sdk::sdk_php_language_level,
|
||||
sdk::sdk_project_libraries,
|
||||
sdk::sdk_locate_tools,
|
||||
|
||||
@@ -24,13 +24,6 @@ pub fn sdk_python_effective(window: Window, state: State<'_, AppState>) -> IdeRe
|
||||
ide_host::ops::sdk::sdk_python_effective(&state.host, window.label())
|
||||
}
|
||||
|
||||
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn sdk_php_effective(window: Window, state: State<'_, AppState>) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
ide_host::ops::sdk::sdk_php_effective(&state.host, window.label())
|
||||
}
|
||||
|
||||
/// The PHP language level of the project `path` belongs to: the effective one and Auto's.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -772,8 +772,6 @@ export const commands = {
|
||||
sdkDetect: (kind: SdkKind) => typedError<Sdk[], IdeError>(__TAURI_INVOKE("sdk_detect", { kind })),
|
||||
/** The interpreter the project uses: the configured one, else its virtualenv. */
|
||||
sdkPythonEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective")),
|
||||
/** The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`. */
|
||||
sdkPhpEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_php_effective")),
|
||||
/** The PHP language level of the project `path` belongs to: the effective one and Auto's. */
|
||||
sdkPhpLanguageLevel: (path: string) => typedError<PhpLanguageLevels, IdeError>(__TAURI_INVOKE("sdk_php_language_level", { path })),
|
||||
/**
|
||||
|
||||
@@ -262,24 +262,6 @@ describe("EditorController", () => {
|
||||
useProject.setState({ lightEdit: false });
|
||||
});
|
||||
|
||||
it("opens a file requested while the LightEdit session is being restored", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/x/a.txt": "a", "/y/b.md": "b", "/z/launch.lua": "l" }));
|
||||
ctrl.start();
|
||||
useProject.setState({ lightEdit: true });
|
||||
await ctrl.openFile("/x/a.txt", { focus: false });
|
||||
await ctrl.openFile("/y/b.md", { focus: false });
|
||||
useProject.setState({ lightEdit: false });
|
||||
// A launch with a file path: LightEdit starts and the file opens before the old tabs are back.
|
||||
useProject.setState({ lightEdit: true });
|
||||
await ctrl.openFile("/z/launch.lua", { focus: false });
|
||||
expect(openFilePaths(useTabs.getState())).toEqual(["/x/a.txt", "/y/b.md", "/z/launch.lua"]);
|
||||
const s = useTabs.getState();
|
||||
const active = s.panes[s.activePane]!;
|
||||
expect(active.tabs.find((t) => t.id === active.active)?.input.path).toBe("/z/launch.lua");
|
||||
await ctrl.closeEverything();
|
||||
useProject.setState({ lightEdit: false });
|
||||
});
|
||||
|
||||
it("closes a tab by its input key", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend());
|
||||
ctrl.start();
|
||||
|
||||
@@ -237,8 +237,6 @@ export class EditorController implements SlotHost {
|
||||
private selectionRequests = new Map<string, number>();
|
||||
private activationGeneration = 0;
|
||||
private admitting = false;
|
||||
/** Tabs restored from a saved session: not a user's activation, so a pending open still activates its tab. */
|
||||
private restoring = false;
|
||||
private closeRequests = 0;
|
||||
private projectTransition: Promise<void> = Promise.resolve();
|
||||
|
||||
@@ -271,7 +269,6 @@ export class EditorController implements SlotHost {
|
||||
prevTabs = s;
|
||||
if (
|
||||
!this.admitting &&
|
||||
!this.restoring &&
|
||||
(s.activePane !== prev.activePane || s.panes[s.activePane]?.active !== prev.panes[prev.activePane]?.active)
|
||||
)
|
||||
++this.activationGeneration;
|
||||
@@ -489,12 +486,7 @@ export class EditorController implements SlotHost {
|
||||
pane.tabs = pane.tabs.map((tab) => (documentLifecycle(tab.input, kinds) ? { ...tab, preview: false } : tab));
|
||||
this.restoredViews = new Map(Object.entries(session.files));
|
||||
this.restoredTabs = new Set(Object.values(state.panes).flatMap((p) => p.tabs.map((t) => t.id)));
|
||||
this.restoring = true;
|
||||
try {
|
||||
useTabs.setState(state, true);
|
||||
} finally {
|
||||
this.restoring = false;
|
||||
}
|
||||
useTabs.setState(state, true);
|
||||
for (const pane of Object.values(state.panes)) if (pane.active) void this.ensureSlot(pane.active);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { filterColumns } from "./ColumnsPopup";
|
||||
|
||||
const columns = ["id", "user_id", "name", "created_at", "username"].map((name) => ({ name, type: "TEXT" }));
|
||||
|
||||
describe("filterColumns", () => {
|
||||
it("lists every column for an empty query", () => {
|
||||
expect(filterColumns(columns, " ")).toEqual([0, 1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it("puts prefix matches first, then other matches, ignoring case", () => {
|
||||
expect(filterColumns(columns, "US")).toEqual([1, 4]);
|
||||
expect(filterColumns(columns, "name")).toEqual([2, 4]);
|
||||
expect(filterColumns(columns, "_id")).toEqual([1]);
|
||||
});
|
||||
});
|
||||
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
* Go to Column in a table editor (⌘F12 / Ctrl+F12): the grid's columns, filtered as you type;
|
||||
* Enter selects that column's cell in the current row.
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import { Icon, Input, List, Popup, listNavigate } from "@/ui";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import type { GridColumn } from "./Grid";
|
||||
import styles from "./Database.module.css";
|
||||
|
||||
export function filterColumns(columns: readonly GridColumn[], query: string): number[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
const all = columns.map((_, i) => i);
|
||||
if (!q) return all;
|
||||
const starts = all.filter((i) => columns[i]!.name.toLowerCase().startsWith(q));
|
||||
const contains = all.filter((i) => !starts.includes(i) && columns[i]!.name.toLowerCase().includes(q));
|
||||
return [...starts, ...contains];
|
||||
}
|
||||
|
||||
export function ColumnsPopup(props: {
|
||||
anchor: { x: number; y: number };
|
||||
table: string;
|
||||
columns: readonly GridColumn[];
|
||||
onPick: (col: number) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [active, setActive] = useState(0);
|
||||
const shown = filterColumns(props.columns, query);
|
||||
const current = Math.min(active, shown.length - 1);
|
||||
const pick = (i: number) => {
|
||||
const col = shown[i];
|
||||
if (col !== undefined) props.onPick(col);
|
||||
};
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={props.anchor}
|
||||
placement="bottom"
|
||||
onClose={props.onClose}
|
||||
aria-label={tx`Columns of ${props.table}`}
|
||||
className={styles.columnsPopup}
|
||||
trapFocus
|
||||
>
|
||||
<Input
|
||||
autoFocus
|
||||
aria-label={tx("Search columns")}
|
||||
placeholder={tx`Columns of ${props.table}`}
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setActive(0);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
pick(current);
|
||||
return;
|
||||
}
|
||||
const next = listNavigate(e.key, { items: shown, active: current });
|
||||
if (next !== null) {
|
||||
e.preventDefault();
|
||||
setActive(next);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<List
|
||||
items={shown}
|
||||
getKey={(col) => String(col)}
|
||||
activeIndex={current}
|
||||
onActiveChange={setActive}
|
||||
onActivate={(_, i) => pick(i)}
|
||||
focusable={false}
|
||||
hoverSelects
|
||||
rowHeight={22}
|
||||
aria-label={tx("Columns")}
|
||||
className={styles.columnsList}
|
||||
empty={<span>{tx("No matching columns")}</span>}
|
||||
renderItem={(col) => {
|
||||
const c = props.columns[col]!;
|
||||
return (
|
||||
<span className={styles.columnsRow}>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : c.foreignKey ? "db-column-fk" : "db-column"} size={16} />
|
||||
{c.name}
|
||||
{c.type && c.type !== "NULL" && <span className={styles.treeType}>{c.type}</span>}
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
@@ -90,7 +90,6 @@ export interface DataViewProps extends Pick<
|
||||
/** The search bar is shown (the toolbar's search button, ⌘F in the grid). */
|
||||
searchOpen?: boolean;
|
||||
onSearchOpenChange?: (open: boolean) => void;
|
||||
revealColumn?: GridProps["revealColumn"];
|
||||
"aria-label"?: string;
|
||||
}
|
||||
|
||||
@@ -201,7 +200,6 @@ export function DataView(props: DataViewProps) {
|
||||
isMatch={test ? (r, c) => matchSet.has(`${r}:${c}`) : undefined}
|
||||
currentMatch={currentMatch}
|
||||
onFind={onSearchOpenChange && openSearch}
|
||||
revealColumn={props.revealColumn}
|
||||
aria-label={props["aria-label"]}
|
||||
columns={columns}
|
||||
rowCount={shown}
|
||||
|
||||
@@ -823,25 +823,6 @@
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
/* Go to Column (ColumnsPopup.tsx). */
|
||||
.columnsPopup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
width: 320px;
|
||||
padding: 8px;
|
||||
}
|
||||
.columnsList {
|
||||
height: min(320px, 50vh);
|
||||
}
|
||||
.columnsRow {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.filterPopup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -57,8 +57,6 @@ export interface GridProps {
|
||||
currentMatch?: { row: number; col: number } | null;
|
||||
/** ⌘F / Ctrl+F in the grid (opens the search bar). */
|
||||
onFind?: () => void;
|
||||
/** Go to Column: a new object selects that column's cell in the current row, scrolls to it and focuses the grid. */
|
||||
revealColumn?: { col: number } | null;
|
||||
"aria-label"?: string;
|
||||
}
|
||||
|
||||
@@ -162,37 +160,15 @@ export function Grid(props: GridProps) {
|
||||
estimateSize: () => ROW_H,
|
||||
overscan: 12,
|
||||
});
|
||||
/** Scrolls sideways so column `c` is visible (the first one with the row numbers). */
|
||||
const scrollColumnIntoView = (c: number) => {
|
||||
const el = scrollRef.current;
|
||||
if (!el || c < 0 || c >= widths.length) return;
|
||||
const left = c ? NUM_W + widths.slice(0, c).reduce((a, b) => a + b, 0) : 0;
|
||||
const right = NUM_W + widths.slice(0, c + 1).reduce((a, b) => a + b, 0);
|
||||
if (left < el.scrollLeft) el.scrollLeft = left;
|
||||
else if (right > el.scrollLeft + el.clientWidth) el.scrollLeft = Math.min(left, right - el.clientWidth);
|
||||
};
|
||||
const { currentMatch } = props;
|
||||
useEffect(() => {
|
||||
if (!currentMatch) return;
|
||||
const { row, col } = currentMatch;
|
||||
setSel({ r0: row, c0: col, r1: row, c1: col });
|
||||
virtualizer.scrollToIndex(row, { align: "auto" });
|
||||
scrollColumnIntoView(col);
|
||||
// Follows the match only, not the virtualizer's identity.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [currentMatch?.row, currentMatch?.col]);
|
||||
const { revealColumn } = props;
|
||||
useEffect(() => {
|
||||
if (!revealColumn || !rowCount) return;
|
||||
const { col } = revealColumn;
|
||||
const row = sel ? Math.min(sel.r1, rowCount - 1) : 0;
|
||||
setSel({ r0: row, c0: col, r1: row, c1: col });
|
||||
virtualizer.scrollToIndex(row, { align: "auto" });
|
||||
scrollColumnIntoView(col);
|
||||
scrollRef.current?.focus({ preventScroll: true });
|
||||
// Runs once per request.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [revealColumn]);
|
||||
const totalWidth = useMemo(() => NUM_W + widths.reduce((a, b) => a + b, 0), [widths]);
|
||||
const template = `${NUM_W}px ${widths.map((w) => `${w}px`).join(" ")}`;
|
||||
|
||||
@@ -279,7 +255,6 @@ export function Grid(props: GridProps) {
|
||||
const c = Math.max(0, Math.min(columns.length - 1, sel.c1 + m[1]));
|
||||
setSel(e.shiftKey ? { ...sel, r1: r, c1: c } : { r0: r, c0: c, r1: r, c1: c });
|
||||
virtualizer.scrollToIndex(r, { align: "auto" });
|
||||
scrollColumnIntoView(c);
|
||||
};
|
||||
|
||||
const onCellMouseDown = (e: MouseEvent, r: number, c: number) => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* a WHERE filter, and pending cell edits / added / deleted rows submitted
|
||||
* together in one transaction. Tables without a primary key are read-only.
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
import { Button, EmptyState, Icon, IconButton, Select, Spinner, T, showContextMenu } from "@/ui";
|
||||
import { notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import { SqlFilterInput } from "./SqlFilterInput";
|
||||
import { ColumnsPopup } from "./ColumnsPopup";
|
||||
import { DataView, ExtractorSelect, PanelToggle, exportMenu, type DataPanel } from "./DataView";
|
||||
import type { ExportFormat } from "./export";
|
||||
import {
|
||||
@@ -31,7 +30,6 @@ import {
|
||||
import { openDialog, sourceById, withConnection } from "./store";
|
||||
import type { TableRef } from "./tableInput";
|
||||
import styles from "./Database.module.css";
|
||||
import { registerTableEditor, tableEditorChanged, type TableEditorHandle } from "./tableEditorFocus";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
|
||||
@@ -181,30 +179,9 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
});
|
||||
|
||||
const dirty = hasEdits(edits);
|
||||
// Submit / Revert actions (⌘↩ / ⌥⌘Z) reach the latest state through the handle.
|
||||
const viewRef = useRef<HTMLDivElement>(null);
|
||||
const handle = useRef<TableEditorHandle>({
|
||||
dirty: false,
|
||||
submit: () => {},
|
||||
revert: () => {},
|
||||
showColumns: () => {},
|
||||
}).current;
|
||||
handle.dirty = editable && dirty;
|
||||
handle.submit = () => {
|
||||
if (editable && dirty) void submit();
|
||||
};
|
||||
handle.revert = () => setEdits(emptyEdits());
|
||||
const [columnsAt, setColumnsAt] = useState<{ x: number; y: number } | null>(null);
|
||||
const [revealColumn, setRevealColumn] = useState<{ col: number } | null>(null);
|
||||
handle.showColumns = () => {
|
||||
const r = viewRef.current?.getBoundingClientRect();
|
||||
if (page && r) setColumnsAt({ x: r.left + r.width / 2, y: r.top + 48 });
|
||||
};
|
||||
useEffect(() => registerTableEditor(viewRef.current!, handle), [handle]);
|
||||
useEffect(() => tableEditorChanged(handle), [handle, dirty, editable]);
|
||||
const orderInvalid = orderDraft !== null && !parseOrderBy(orderDraft, names);
|
||||
return (
|
||||
<div className={styles.view} ref={viewRef} data-db-table-editor="">
|
||||
<div className={styles.view}>
|
||||
<div className={styles.toolbar}>
|
||||
<IconButton icon="refresh" title="Reload Page" onClick={reload} disabled={loading} />
|
||||
<div className={styles.pager}>
|
||||
@@ -351,7 +328,6 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
columns={gridColumns}
|
||||
rowCount={rowCount}
|
||||
fixedRows={loaded}
|
||||
revealColumn={revealColumn}
|
||||
value={value}
|
||||
panel={panel}
|
||||
onPanelChange={setPanel}
|
||||
@@ -379,18 +355,6 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{columnsAt && (
|
||||
<ColumnsPopup
|
||||
anchor={columnsAt}
|
||||
table={ref.table}
|
||||
columns={gridColumns}
|
||||
onPick={(col) => {
|
||||
setColumnsAt(null);
|
||||
setRevealColumn({ col });
|
||||
}}
|
||||
onClose={() => setColumnsAt(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,6 @@
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { activeEditor, registerEditorContribution } from "@/editor/api";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
registerEditorKind,
|
||||
@@ -95,7 +94,6 @@ export function activate(): () => void {
|
||||
}),
|
||||
() => setFileDecorations("database", new Map()),
|
||||
watchIdleConnections(),
|
||||
installTableEditorFocus(),
|
||||
registerDatabaseTreeActions(),
|
||||
registerActions([
|
||||
{
|
||||
@@ -154,30 +152,6 @@ export function activate(): () => void {
|
||||
await executeInView(e.view, e.ctx.path);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "db.goToColumn",
|
||||
title: "Go to Column",
|
||||
category: "Tools",
|
||||
keywords: ["table editor", "file structure", "columns"],
|
||||
when: "dbTableEditorFocus",
|
||||
run: () => activeTableEditor()?.showColumns(),
|
||||
},
|
||||
{
|
||||
id: "db.submitChanges",
|
||||
title: "Submit",
|
||||
category: "Tools",
|
||||
keywords: ["table editor", "apply changes", "commit"],
|
||||
when: "dbTableEditorFocus && dbTableEditorChanges",
|
||||
run: () => activeTableEditor()?.submit(),
|
||||
},
|
||||
{
|
||||
id: "db.revertChanges",
|
||||
title: "Revert",
|
||||
category: "Tools",
|
||||
keywords: ["table editor", "discard changes", "undo"],
|
||||
when: "dbTableEditorFocus && dbTableEditorChanges",
|
||||
run: () => activeTableEditor()?.revert(),
|
||||
},
|
||||
{
|
||||
id: "db.explainPlan",
|
||||
title: "Explain Plan",
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DbDriver, DbTablePage } from "@/platform/ipc";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { TableEditor } from "./TableEditor";
|
||||
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
|
||||
import { tableInput } from "./tableInput";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
@@ -89,40 +87,4 @@ describe("table editor capabilities", () => {
|
||||
expect(screen.getByRole("button", { name: "Add Row" })).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: "Submit" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("offers Submit and Revert to the keyboard while the grid has focus and edits are pending (#1549)", async () => {
|
||||
backend.driver = "postgres";
|
||||
backend.applyEdits.mockResolvedValue({ status: "ok", data: 1 });
|
||||
const uninstall = installTableEditorFocus();
|
||||
try {
|
||||
await act(async () => {
|
||||
render(<TableEditor input={tableInput("source", "public", "users")} />);
|
||||
});
|
||||
const grid = screen.getByRole("grid");
|
||||
act(() => grid.focus());
|
||||
expect(getContext()).toMatchObject({ dbTableEditorFocus: true, dbTableEditorChanges: false });
|
||||
|
||||
fireEvent.doubleClick(await screen.findByRole("gridcell", { name: "Ann" }));
|
||||
const input = screen.getByRole("textbox", { name: "Edit name" });
|
||||
// A text field keeps ⌘↩ for its own edit.
|
||||
expect(getContext().dbTableEditorFocus).toBe(false);
|
||||
fireEvent.change(input, { target: { value: "Bob" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
act(() => grid.focus());
|
||||
expect(getContext()).toMatchObject({ dbTableEditorFocus: true, dbTableEditorChanges: true });
|
||||
|
||||
act(() => activeTableEditor()!.revert());
|
||||
expect(screen.getByRole("gridcell", { name: "Ann" })).toBeTruthy();
|
||||
expect(getContext().dbTableEditorChanges).toBe(false);
|
||||
|
||||
fireEvent.doubleClick(screen.getByRole("gridcell", { name: "Ann" }));
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Edit name" }), { target: { value: "Bob" } });
|
||||
fireEvent.keyDown(screen.getByRole("textbox", { name: "Edit name" }), { key: "Enter" });
|
||||
act(() => grid.focus());
|
||||
await act(async () => activeTableEditor()!.submit());
|
||||
expect(backend.applyEdits).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
uninstall();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
/**
|
||||
* The table editor that has focus, for Submit / Revert (⌘↩ / ⌥⌘Z) and Go to Column (⌘F12). Not
|
||||
* while a text field has it: ⌘↩ there applies the field's own edit (the Value panel, the cell editor).
|
||||
*/
|
||||
import { setContext } from "@/platform/context";
|
||||
|
||||
export interface TableEditorHandle {
|
||||
dirty: boolean;
|
||||
submit(): void;
|
||||
revert(): void;
|
||||
showColumns(): void;
|
||||
}
|
||||
|
||||
const handles = new WeakMap<Element, TableEditorHandle>();
|
||||
let active: TableEditorHandle | null = null;
|
||||
|
||||
const isTextField = (el: Element) => !!el.closest("input, textarea, select, [contenteditable='true']");
|
||||
|
||||
function update() {
|
||||
setContext("dbTableEditorFocus", !!active);
|
||||
setContext("dbTableEditorChanges", !!active?.dirty);
|
||||
}
|
||||
|
||||
function onFocusIn(event: FocusEvent) {
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
const root = target?.closest("[data-db-table-editor]");
|
||||
active = (root && !isTextField(target!) && handles.get(root)) || null;
|
||||
update();
|
||||
}
|
||||
|
||||
/** Registers the editor rooted at `root`; returns the function that unregisters it. */
|
||||
export function registerTableEditor(root: Element, handle: TableEditorHandle): () => void {
|
||||
handles.set(root, handle);
|
||||
if (root.contains(document.activeElement) && !isTextField(document.activeElement!)) active = handle;
|
||||
update();
|
||||
return () => {
|
||||
handles.delete(root);
|
||||
if (active === handle) active = null;
|
||||
update();
|
||||
};
|
||||
}
|
||||
|
||||
/** The handle's state changed (pending edits). */
|
||||
export function tableEditorChanged(handle: TableEditorHandle) {
|
||||
if (active === handle) update();
|
||||
}
|
||||
|
||||
export function activeTableEditor(): TableEditorHandle | null {
|
||||
return active;
|
||||
}
|
||||
|
||||
export function installTableEditorFocus(): () => void {
|
||||
document.addEventListener("focusin", onFocusIn);
|
||||
return () => {
|
||||
document.removeEventListener("focusin", onFocusIn);
|
||||
active = null;
|
||||
update();
|
||||
};
|
||||
}
|
||||
@@ -365,120 +365,111 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.consoleArea}>
|
||||
<div
|
||||
className={styles.consoleToolbar}
|
||||
role="toolbar"
|
||||
aria-orientation="vertical"
|
||||
aria-label={tx("Console actions")}
|
||||
>
|
||||
<IconButton
|
||||
icon="search"
|
||||
iconSize={14}
|
||||
title="Find…"
|
||||
shortcut={formatBinding(hostBinding("Meta+F"))}
|
||||
pressed={findOpen}
|
||||
onClick={() => (findOpen ? closeFind() : openFind())}
|
||||
<div className={styles.console}>
|
||||
{findOpen && (
|
||||
<ConsoleFindBar
|
||||
query={query}
|
||||
onChange={changeQuery}
|
||||
options={findOptions}
|
||||
onOptionsChange={changeOptions}
|
||||
count={found.matches.length}
|
||||
active={activeIndex}
|
||||
overflow={found.overflow}
|
||||
invalid={found.invalid}
|
||||
inputRef={findInput}
|
||||
onNext={() => goToMatch(1)}
|
||||
onPrevious={() => goToMatch(-1)}
|
||||
onClose={closeFind}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
ref={scroller}
|
||||
className={clsx(styles.consoleOutput, ansi.palette, !softWrap && styles.noWrap)}
|
||||
onScroll={(e) => {
|
||||
if (programmatic.current) return;
|
||||
const el = e.currentTarget;
|
||||
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
||||
if (atEnd !== stick.current) setFollow(atEnd);
|
||||
}}
|
||||
onContextMenu={onContextMenu}
|
||||
role="log"
|
||||
onKeyDown={onOutputKeyDown}
|
||||
aria-label={tx("Debug console")}
|
||||
tabIndex={0}
|
||||
>
|
||||
{!lines?.length && session.launch?.request === "attach" && (
|
||||
<T>The attached process may not provide standard output to the debugger.</T>
|
||||
)}
|
||||
<div ref={inner} className={styles.consoleInner} style={{ height: virtualizer.getTotalSize() }}>
|
||||
{virtualizer.getVirtualItems().map((item) => {
|
||||
const l = lines?.[item.index];
|
||||
if (!l) return null;
|
||||
return (
|
||||
<span
|
||||
key={item.key}
|
||||
data-index={item.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className={clsx(styles.out, styles[`cat-${l.category}`])}
|
||||
style={{ transform: `translateY(${item.start}px)` }}
|
||||
>
|
||||
{findSegments(l.spans, marksByLine.get(item.index) ?? [], current).map(segmentNode)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.repl}>
|
||||
{interactive && (
|
||||
<>
|
||||
<span className={styles.prompt} aria-hidden>
|
||||
›
|
||||
</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
className={styles.evalInput}
|
||||
onFocus={() => setConsoleHistoryBrowser(browseHistory)}
|
||||
onBlur={() => {
|
||||
setConsoleHistoryBrowser(null);
|
||||
completion.close();
|
||||
}}
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
completion.onInput();
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder={isLive(session) ? "Evaluate in the debug console" : "Session finished"}
|
||||
disabled={!isLive(session)}
|
||||
aria-label={tx("Debug console input")}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
/>
|
||||
{completion.popup}
|
||||
</>
|
||||
)}
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
iconSize={14}
|
||||
title="Scroll to End"
|
||||
size="small"
|
||||
iconSize={12}
|
||||
pressed={follow}
|
||||
onClick={() => setFollow((v) => !v)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="soft-wrap"
|
||||
iconSize={14}
|
||||
title="Soft-Wrap"
|
||||
size="small"
|
||||
iconSize={12}
|
||||
pressed={softWrap}
|
||||
onClick={() => setWrapOverride(!softWrap)}
|
||||
/>
|
||||
<IconButton icon="trash" iconSize={14} title="Clear Console" onClick={() => clearConsole(session.id)} />
|
||||
</div>
|
||||
<div className={styles.console}>
|
||||
{findOpen && (
|
||||
<ConsoleFindBar
|
||||
query={query}
|
||||
onChange={changeQuery}
|
||||
options={findOptions}
|
||||
onOptionsChange={changeOptions}
|
||||
count={found.matches.length}
|
||||
active={activeIndex}
|
||||
overflow={found.overflow}
|
||||
invalid={found.invalid}
|
||||
inputRef={findInput}
|
||||
onNext={() => goToMatch(1)}
|
||||
onPrevious={() => goToMatch(-1)}
|
||||
onClose={closeFind}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
ref={scroller}
|
||||
className={clsx(styles.consoleOutput, ansi.palette, !softWrap && styles.noWrap)}
|
||||
onScroll={(e) => {
|
||||
if (programmatic.current) return;
|
||||
const el = e.currentTarget;
|
||||
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
||||
if (atEnd !== stick.current) setFollow(atEnd);
|
||||
}}
|
||||
onContextMenu={onContextMenu}
|
||||
role="log"
|
||||
onKeyDown={onOutputKeyDown}
|
||||
aria-label={tx("Debug console")}
|
||||
tabIndex={0}
|
||||
>
|
||||
{!lines?.length && session.launch?.request === "attach" && (
|
||||
<T>The attached process may not provide standard output to the debugger.</T>
|
||||
)}
|
||||
<div ref={inner} className={styles.consoleInner} style={{ height: virtualizer.getTotalSize() }}>
|
||||
{virtualizer.getVirtualItems().map((item) => {
|
||||
const l = lines?.[item.index];
|
||||
if (!l) return null;
|
||||
return (
|
||||
<span
|
||||
key={item.key}
|
||||
data-index={item.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className={clsx(styles.out, styles[`cat-${l.category}`])}
|
||||
style={{ transform: `translateY(${item.start}px)` }}
|
||||
>
|
||||
{findSegments(l.spans, marksByLine.get(item.index) ?? [], current).map(segmentNode)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.repl}>
|
||||
{interactive && (
|
||||
<>
|
||||
<span className={styles.prompt} aria-hidden>
|
||||
›
|
||||
</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
className={styles.evalInput}
|
||||
onFocus={() => setConsoleHistoryBrowser(browseHistory)}
|
||||
onBlur={() => {
|
||||
setConsoleHistoryBrowser(null);
|
||||
completion.close();
|
||||
}}
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
completion.onInput();
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder={isLive(session) ? "Evaluate in the debug console" : "Session finished"}
|
||||
disabled={!isLive(session)}
|
||||
aria-label={tx("Debug console input")}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
/>
|
||||
{completion.popup}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<IconButton
|
||||
icon="trash"
|
||||
title="Clear Console"
|
||||
size="small"
|
||||
iconSize={12}
|
||||
onClick={() => clearConsole(session.id)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -218,23 +218,6 @@
|
||||
}
|
||||
|
||||
/* console */
|
||||
/* The Console tab: actions in a vertical strip on the left, as in the Run window. */
|
||||
.consoleArea {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
}
|
||||
.consoleToolbar {
|
||||
flex: none;
|
||||
width: 32px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 4px 0;
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.console {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
@@ -664,24 +664,10 @@ describe("Show Members", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("sorts workspace member roots by the folder names shown in the tree", async () => {
|
||||
fs = new MemoryFs({
|
||||
"/a/service10/ten.txt": "",
|
||||
"/z/Service2/two.txt": "",
|
||||
"/m/alpha/first.txt": "",
|
||||
"/workspace/.openidea/workspace.json": "{}",
|
||||
});
|
||||
it("renders workspace member roots with their own paths, without the settings directory", async () => {
|
||||
fs = new MemoryFs({ "/z/first.txt": "", "/a/second.txt": "", "/workspace/.openidea/workspace.json": "{}" });
|
||||
setProjectFsForTests(fs, "/workspace");
|
||||
initProjectTree("/workspace", "Workspace", ["/a/service10", "/z/Service2", "/m/alpha"]);
|
||||
initProjectTree("/workspace", "Workspace", ["/z", "/a"]);
|
||||
const { rows } = setup();
|
||||
await waitFor(() =>
|
||||
expect(rows()).toEqual([
|
||||
"alpha/m/alpha",
|
||||
"first.txt",
|
||||
"Service2/z/Service2",
|
||||
"two.txt",
|
||||
"service10/a/service10",
|
||||
"ten.txt",
|
||||
]),
|
||||
);
|
||||
await waitFor(() => expect(rows()).toEqual(["z/z", "first.txt", "a/a", "second.txt"]));
|
||||
});
|
||||
@@ -100,10 +100,6 @@ export function isVisible(entry: FileEntry, opts: TreeOptions): boolean {
|
||||
|
||||
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
||||
|
||||
export function compareNames(a: string, b: string): number {
|
||||
return collator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0);
|
||||
}
|
||||
|
||||
/** Symlinks report the target's metadata; folders have size 0 (the entry has no target kind). */
|
||||
export const isDirEntry = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.size === 0);
|
||||
|
||||
@@ -129,7 +125,7 @@ export function sortEntries(
|
||||
const m = (b.mtimeMs ?? 0) - (a.mtimeMs ?? 0);
|
||||
if (m) return m;
|
||||
}
|
||||
return compareNames(a.name, b.name);
|
||||
return collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -104,13 +104,12 @@ describe("creating packages", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("shows manifest members in name order in workspace Project and Project Files views", () => {
|
||||
it("uses only manifest members in order in workspace Project and Project Files views", () => {
|
||||
for (const mode of ["project", "projectFiles"] as const) {
|
||||
initProjectTree("/workspace", "Workspace", ["/z", "/a"]);
|
||||
useProjectTree.setState({ mode });
|
||||
const model = selectModel(useProjectTree.getState());
|
||||
expect(model.roots.map((r) => r.path)).toEqual(["/a", "/z"]);
|
||||
expect(useProjectTree.getState().members).toEqual(["/z", "/a"]);
|
||||
expect(model.roots.map((r) => r.path)).toEqual(["/z", "/a"]);
|
||||
expect(model.byKey.has("/workspace")).toBe(false);
|
||||
initProjectTree("/workspace", "Workspace", ["/a"]);
|
||||
expect(selectModel(useProjectTree.getState()).roots.map((r) => r.path)).toEqual(["/a"]);
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
GROUP_PREFIX,
|
||||
buildModel,
|
||||
buildPathsModel,
|
||||
compareNames,
|
||||
extraFolders,
|
||||
isGroupKey,
|
||||
isLibKey,
|
||||
@@ -35,7 +34,7 @@ import {
|
||||
} from "./model";
|
||||
import { projectFs } from "./fs";
|
||||
import { projectViewRoots, useProjectViewRoots, type ProjectViewRootContribution } from "@/workbench/contributions";
|
||||
import { ancestorsWithin, isSameOrInside, nameOf, type PackageKind } from "./paths";
|
||||
import { ancestorsWithin, isSameOrInside, type PackageKind } from "./paths";
|
||||
|
||||
export interface ViewOptions extends TreeOptions {
|
||||
/** Select the active editor's file in the tree. */
|
||||
@@ -219,9 +218,12 @@ export function selectModel(s: ProjectTreeState): TreeModel {
|
||||
const extras = useProjectViewRoots.getState().roots;
|
||||
const options = treeOptions(s);
|
||||
const contributed = projectViewRoots(extras);
|
||||
const memberRoots = s.members
|
||||
?.map((path) => ({ path, label: nameOf(path), icon: "", detail: path }))
|
||||
.sort((a, b) => compareNames(a.label, b.label));
|
||||
const memberRoots = s.members?.map((path) => ({
|
||||
path,
|
||||
label: path.slice(path.lastIndexOf("/") + 1),
|
||||
icon: "",
|
||||
detail: path,
|
||||
}));
|
||||
const project = () =>
|
||||
memberRoots
|
||||
? withExtraRoots(EMPTY_MODEL, memberRoots, s.listings, options, placeholder)
|
||||
|
||||
@@ -98,13 +98,7 @@ export async function produceResolved(input: ContextInput, dir = false): Promise
|
||||
// Project configurations (tests, cargo, gradle…) need no runtime lookup.
|
||||
if (named.config && !named.config.id.startsWith("context:file:")) return named;
|
||||
const lang = scriptLanguage(input.path, input.content);
|
||||
const env = await toolEnv(
|
||||
neededTools(fresh),
|
||||
input.path,
|
||||
fresh.root,
|
||||
lang === "python" || lang === "shebang",
|
||||
lang === "php" || lang === "shebang",
|
||||
);
|
||||
const env = await toolEnv(neededTools(fresh), input.path, fresh.root, lang === "python" || lang === "shebang");
|
||||
return produceContext(fresh, env);
|
||||
}
|
||||
|
||||
|
||||
@@ -226,15 +226,6 @@ describe("single-file producers (scratches)", () => {
|
||||
it("Ruby, PHP, Perl, Lua, R, Swift, Dart, Elixir, Scala CLI, Kotlin script", () => {
|
||||
expect(run(scratch("a.rb"))).toMatchObject({ command: "/bin/ruby", args: ["a.rb"] });
|
||||
expect(run(scratch("a.php"))).toMatchObject({ command: "/bin/php", args: ["a.php"] });
|
||||
// The PHP chosen in Settings wins over the PATH one, also with no PHP on PATH (#1555).
|
||||
const php81 = "/opt/homebrew/opt/[email protected]/bin/php";
|
||||
expect(run(scratch("a.php"), { ...ALL, php: php81 })).toMatchObject({ command: php81, args: ["a.php"] });
|
||||
expect(run(scratch("a.php"), env({}, { php: php81 }))).toMatchObject({ command: php81, args: ["a.php"] });
|
||||
expect(run(scratch("tool", "#!/usr/bin/env php\n<?php echo 1;"), { ...ALL, php: php81 })).toMatchObject({
|
||||
command: php81,
|
||||
args: ["tool"],
|
||||
});
|
||||
expect(produceContext(scratch("a.php"), env({}))!.missing!.body).toMatch(/Settings › Languages & Frameworks › PHP/);
|
||||
expect(run(scratch("a.pl"))).toMatchObject({ command: "/bin/perl" });
|
||||
expect(run(scratch("a.lua"))).toMatchObject({ command: "/bin/lua" });
|
||||
expect(run(scratch("a.R"))).toMatchObject({ command: "/bin/Rscript", args: ["a.R"] });
|
||||
|
||||
@@ -38,8 +38,6 @@ export interface ToolEnv {
|
||||
windows?: boolean;
|
||||
/** The project interpreter from settings (Python). */
|
||||
python?: string | null;
|
||||
/** The PHP interpreter chosen in settings (else the `php` on `PATH`). */
|
||||
php?: string | null;
|
||||
/** The project root has `deno.json(c)` / `bun.lock(b)`. */
|
||||
deno?: boolean;
|
||||
bun?: boolean;
|
||||
@@ -290,7 +288,7 @@ const INSTALL: Record<string, string> = {
|
||||
js: "Install Node.js from https://nodejs.org (or `brew install node`).",
|
||||
python: "Install Python (`brew install python`) or choose an interpreter in Settings › Python Interpreter.",
|
||||
ruby: "Install Ruby (`brew install ruby`).",
|
||||
php: "Install PHP (`brew install php`) or choose an interpreter in Settings › Languages & Frameworks › PHP.",
|
||||
php: "Install PHP (`brew install php`).",
|
||||
perl: "Install Perl (`brew install perl`).",
|
||||
lua: "Install Lua (`brew install lua`).",
|
||||
r: "Install R (`brew install r`) so that `Rscript` is on the PATH.",
|
||||
@@ -764,8 +762,6 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
|
||||
config: fileConfig(s, "python", py.command, [...py.prefix, s.arg], "debugpy"),
|
||||
};
|
||||
}
|
||||
if (interp === "php" && env.php)
|
||||
return { name: s.file, scope: "file", config: fileConfig(s, "php", env.php, [...sb.slice(1), s.arg]) };
|
||||
const t = sb[0]!.startsWith("/") ? { command: sb[0]!, name: interp } : pick(env, [interp]);
|
||||
if (!t) return { name: s.file, scope: "file", missing: missing(lang, s.file, [interp]) };
|
||||
const kind = /^(ba|z|k|da|fi)?sh$/.test(interp) ? "shell" : interp === "node" ? "node" : interp;
|
||||
@@ -809,8 +805,6 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
|
||||
// Sources roots go on the load path (`-Ilib`), as `rake test` does; paths are project-relative.
|
||||
return simple(lang, s, env, lang, () => [...(s.inProject ? rubyLoadPath(currentRoots()) : []), s.arg]);
|
||||
case "php":
|
||||
if (env.php) return { name: s.file, scope: "file", config: fileConfig(s, "php", env.php, [s.arg]) };
|
||||
return simple(lang, s, env, lang, () => [s.arg]);
|
||||
case "perl":
|
||||
case "lua":
|
||||
case "swift":
|
||||
|
||||
@@ -86,14 +86,6 @@ async function projectPython(): Promise<string | null> {
|
||||
}
|
||||
}
|
||||
|
||||
async function projectPhp(): Promise<string | null> {
|
||||
try {
|
||||
return await call(commands.sdkPhpEffective());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function rootMarkers(root: string | null): Promise<{ deno: boolean; bun: boolean }> {
|
||||
if (!root) return { deno: false, bun: false };
|
||||
try {
|
||||
@@ -114,12 +106,10 @@ export async function toolEnv(
|
||||
file: string | null,
|
||||
root: string | null,
|
||||
python: boolean,
|
||||
php = false,
|
||||
): Promise<ToolEnv> {
|
||||
const [tools, py, phpInterpreter, markers] = await Promise.all([
|
||||
const [tools, py, markers] = await Promise.all([
|
||||
locateTools(names, file),
|
||||
python ? projectPython() : Promise.resolve(null),
|
||||
php ? projectPhp() : Promise.resolve(null),
|
||||
names.includes("deno") || names.includes("bun") ? rootMarkers(root) : Promise.resolve({ deno: false, bun: false }),
|
||||
]);
|
||||
return {
|
||||
@@ -127,7 +117,6 @@ export async function toolEnv(
|
||||
compileDir: compileDir ?? "/tmp/openidea-run",
|
||||
windows: isWindows(),
|
||||
python: py,
|
||||
php: phpInterpreter,
|
||||
...markers,
|
||||
};
|
||||
}
|
||||
@@ -78,9 +78,7 @@ describe("languages settings", () => {
|
||||
}
|
||||
expect(PHP_LANGUAGE_LEVELS[0]).toBe("");
|
||||
expect(PHP_LANGUAGE_LEVELS).toContain("5.6");
|
||||
// Newest first after Auto (#1557).
|
||||
expect(PHP_LANGUAGE_LEVELS[1]).toBe("8.5");
|
||||
expect(PHP_LANGUAGE_LEVELS.at(-1)).toBe("5.6");
|
||||
expect(PHP_LANGUAGE_LEVELS.at(-1)).toBe("8.5");
|
||||
});
|
||||
|
||||
it("finds the PHP page by its language level", () => {
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
* Build Tools › Maven: the toolchain each language's server and run configurations
|
||||
* use (applied by `ide-sdk` when language servers start and when run configurations load).
|
||||
*/
|
||||
import { useEffect, useId, useMemo, useState } from "react";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useId, useMemo } from "react";
|
||||
import { IconButton, Input, type SelectOption } from "@/ui";
|
||||
import { PHP_LANGUAGE_LEVELS } from "@/platform/languageSettings";
|
||||
import { GlobListEditor, Row, Section, Select, Toggle } from "../components/Form";
|
||||
@@ -118,31 +117,13 @@ const PHP_LEVEL_OPTIONS: SelectOption[] = PHP_LANGUAGE_LEVELS.map((level) =>
|
||||
level ? { value: level, label: level } : { value: "", label: "Auto", detail: "from composer.json" },
|
||||
);
|
||||
|
||||
/** The `php` on `PATH` (what the Default interpreter runs), looked up while `enabled`. */
|
||||
function usePathPhp(enabled: boolean): string | null {
|
||||
const [path, setPath] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let live = true;
|
||||
call(commands.sdkLocateTools(["php"], null))
|
||||
.then((r) => live && setPath(r.tools[0]?.path ?? null))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [enabled]);
|
||||
return path;
|
||||
}
|
||||
|
||||
export function PhpPage() {
|
||||
const [interpreter] = useSetting<string>("languages.php.interpreter");
|
||||
const [level, setLevel] = useSetting<string>("languages.php.languageLevel");
|
||||
const [includePaths, setIncludePaths] = useSetting<string[]>("languages.php.includePaths");
|
||||
const [stubs, setStubs] = useSetting<string[]>("languages.php.stubs");
|
||||
const { list } = useDetected("php");
|
||||
const pathPhp = usePathPhp(!interpreter);
|
||||
// Default runs the `php` on PATH: the list is newest first, so it isn't necessarily `list[0]`.
|
||||
const selected = list.find((s) => s.path === (interpreter || pathPhp));
|
||||
const selected = list.find((s) => s.path === interpreter) ?? (interpreter ? undefined : list[0]);
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<Section>
|
||||
|
||||
@@ -129,32 +129,15 @@
|
||||
flex-direction: column;
|
||||
padding: 0 14px 14px;
|
||||
}
|
||||
/* Push dialog: commits above their changed files, split by a draggable divider; the pair fills the body. */
|
||||
.pushSplit {
|
||||
flex: 1;
|
||||
min-height: min(540px, 60vh);
|
||||
}
|
||||
/* The panel's own `height: 100%` doesn't resolve against a flex-basis height in WebKit: stretch instead. */
|
||||
.pushSplit .pushSplitPanel {
|
||||
height: auto;
|
||||
align-self: stretch;
|
||||
}
|
||||
.pushSplitPanel > .pushListWrap {
|
||||
min-height: 0;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
/* Push dialogs: the outgoing commits' changed files below the commits, the diff beside them. */
|
||||
.pushChanges {
|
||||
flex: 1;
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
padding-top: 8px;
|
||||
}
|
||||
.pushChanges .comparison {
|
||||
flex: 1;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
height: min(360px, 45vh);
|
||||
padding: 0 14px 14px;
|
||||
}
|
||||
.pushChangesTitle {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { call, commands } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { Checkbox, Dialog, Input, List, Select, Spinner, SplitGroup, SplitHandle, SplitPanel, T, Tree } from "@/ui";
|
||||
import { Checkbox, Dialog, Input, List, Select, Spinner, T, Tree } from "@/ui";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { openDialog } from "./dialogs";
|
||||
import { formatTime } from "./model";
|
||||
@@ -340,11 +340,6 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
|
||||
const [commits, setCommits] = useState<Commit[] | null>(null);
|
||||
// The commit whose changes are shown; -1: all outgoing commits.
|
||||
const [shownCommit, setShownCommit] = useState(-1);
|
||||
const [pushSplit, setPushSplit] = useState(loadPushSplit);
|
||||
const keepPushSplit = (layout: Record<string, number>) => {
|
||||
setPushSplit(layout);
|
||||
savePushSplit(layout);
|
||||
};
|
||||
const shownCommits = useMemo(
|
||||
() => (commits && shownCommit >= 0 && commits[shownCommit] ? [commits[shownCommit]] : (commits ?? [])),
|
||||
[commits, shownCommit],
|
||||
@@ -445,36 +440,6 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
|
||||
);
|
||||
};
|
||||
|
||||
const commitList = (
|
||||
<div className={styles.pushListWrap}>
|
||||
{error ? (
|
||||
<div className={styles.error}>{error}</div>
|
||||
) : !commits ? (
|
||||
<div className={styles.empty}>
|
||||
<Spinner size={14} />
|
||||
</div>
|
||||
) : (
|
||||
<List
|
||||
items={commits}
|
||||
getKey={(c) => c.id}
|
||||
activeIndex={shownCommit}
|
||||
onActiveChange={setShownCommit}
|
||||
rowHeight={22}
|
||||
aria-label="Outgoing commits"
|
||||
className={styles.boxList}
|
||||
empty={<span>{upstream ? tx("Everything is up to date") : tx("No commits")}</span>}
|
||||
renderItem={(c) => (
|
||||
<span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
|
||||
<span className={styles.commitHash}>{c.shortId}</span>
|
||||
<span className={styles.commitSubject}>{c.summary}</span>
|
||||
<span className={styles.commitMeta}>{c.author}</span>
|
||||
<span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
@@ -555,56 +520,44 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
|
||||
)}
|
||||
{retarget && <span className={styles.hint}> {tx("New")}</span>}
|
||||
</div>
|
||||
{commits?.length && !error ? (
|
||||
<SplitGroup
|
||||
orientation="vertical"
|
||||
id="vcs-push-split"
|
||||
className={styles.pushSplit}
|
||||
defaultLayout={pushSplit}
|
||||
onLayoutChanged={keepPushSplit}
|
||||
>
|
||||
<SplitPanel id="commits" minSize="72px" defaultSize="35%" className={styles.pushSplitPanel}>
|
||||
{commitList}
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="changes" minSize="160px" className={styles.pushSplitPanel}>
|
||||
<PushChanges
|
||||
key={pushChangesKey(repo, shownCommits)}
|
||||
repo={repo}
|
||||
commits={shownCommits}
|
||||
onShowAll={shownCommit >= 0 && commits.length > 1 ? () => setShownCommit(-1) : undefined}
|
||||
/>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
) : (
|
||||
commitList
|
||||
)}
|
||||
<div className={styles.pushListWrap}>
|
||||
{error ? (
|
||||
<div className={styles.error}>{error}</div>
|
||||
) : !commits ? (
|
||||
<div className={styles.empty}>
|
||||
<Spinner size={14} />
|
||||
</div>
|
||||
) : (
|
||||
<List
|
||||
items={commits}
|
||||
getKey={(c) => c.id}
|
||||
activeIndex={shownCommit}
|
||||
onActiveChange={setShownCommit}
|
||||
rowHeight={22}
|
||||
aria-label="Outgoing commits"
|
||||
className={styles.boxList}
|
||||
empty={<span>{upstream ? tx("Everything is up to date") : tx("No commits")}</span>}
|
||||
renderItem={(c) => (
|
||||
<span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
|
||||
<span className={styles.commitHash}>{c.shortId}</span>
|
||||
<span className={styles.commitSubject}>{c.summary}</span>
|
||||
<span className={styles.commitMeta}>{c.author}</span>
|
||||
<span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<PushChanges
|
||||
key={pushChangesKey(repo, shownCommits)}
|
||||
repo={repo}
|
||||
commits={shownCommits}
|
||||
onShowAll={shownCommit >= 0 && (commits?.length ?? 0) > 1 ? () => setShownCommit(-1) : undefined}
|
||||
/>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
const PUSH_SPLIT_KEY = "openidea.vcs.pushSplit";
|
||||
|
||||
/** Heights of the Push dialog's commits and changed files, as the splitter left them. */
|
||||
function loadPushSplit(): Record<string, number> | undefined {
|
||||
try {
|
||||
const v: unknown = JSON.parse(localStorage.getItem(PUSH_SPLIT_KEY) ?? "null");
|
||||
return v && typeof v === "object" && Object.values(v).every((n) => typeof n === "number")
|
||||
? (v as Record<string, number>)
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function savePushSplit(layout: Record<string, number>) {
|
||||
try {
|
||||
localStorage.setItem(PUSH_SPLIT_KEY, JSON.stringify(layout));
|
||||
} catch {
|
||||
/* kept for this dialog only */
|
||||
}
|
||||
}
|
||||
|
||||
const SILENT_FORCE_PUSH_KEY = "openidea.vcs.silentForcePushTargets";
|
||||
|
||||
function silentForcePushTargets(): string[] {
|
||||
|
||||
@@ -50,7 +50,6 @@ export const eclipseMacos: Record<string, string[]> = {
|
||||
"code.expandToLevel5": [],
|
||||
"refactor.extractMethod": ["Meta+Alt+M"],
|
||||
"navigate.fileStructure": ["Meta+O"],
|
||||
"db.goToColumn": ["Meta+O"],
|
||||
"find.inFile": [],
|
||||
"find.inPath": ["Ctrl+H"],
|
||||
"find.next": ["Meta+K"],
|
||||
@@ -124,8 +123,6 @@ export const eclipseMacos: Record<string, string[]> = {
|
||||
"debug.stepOver": ["F6"],
|
||||
"debug.forceStepOver": ["Meta+Ctrl+F6"],
|
||||
"code.surroundWith": ["Meta+Alt+Z"],
|
||||
// ⌥⌘Z is Surround With here, not the table editor's Revert.
|
||||
"db.revertChanges": [],
|
||||
"file.reloadFromDisk": [],
|
||||
"project.reloadFromDisk": [],
|
||||
"navigate.toggleBookmark": [],
|
||||
|
||||
@@ -52,7 +52,6 @@ export const eclipseWindows: Record<string, string[]> = {
|
||||
"code.expandToLevel5": [],
|
||||
"refactor.extractMethod": ["Shift+Alt+M"],
|
||||
"navigate.fileStructure": ["Ctrl+F3", "Ctrl+O"],
|
||||
"db.goToColumn": ["Ctrl+F3", "Ctrl+O"],
|
||||
"find.inFile": [],
|
||||
"find.inPath": ["Ctrl+H"],
|
||||
"find.next": ["Ctrl+K"],
|
||||
|
||||
@@ -41,7 +41,6 @@ const shared = [
|
||||
"find.popup.openResult",
|
||||
],
|
||||
["navigate.typeHierarchy", "db.editData"],
|
||||
["navigate.fileStructure", "db.goToColumn"],
|
||||
["find.replaceInFile", "agents.findInConversation", "vcs.log.goToRef"],
|
||||
["find.next", "find.popup.nextResult"],
|
||||
["find.previous", "find.popup.previousResult"],
|
||||
|
||||
@@ -352,10 +352,6 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"graphql.runQuery": ["Meta+Enter"],
|
||||
"http.runAll": [],
|
||||
"db.execute": ["Meta+Enter"],
|
||||
// Table editor with pending changes (after `vcs.rollback`, so ⌥⌘Z reverts the table's edits there).
|
||||
"db.goToColumn": ["Meta+F12"],
|
||||
"db.submitChanges": ["Meta+Enter"],
|
||||
"db.revertChanges": ["Meta+Alt+Z"],
|
||||
"db.showToolWindow": [],
|
||||
"agents.newTask": ["Meta+Shift+I"],
|
||||
"agents.showToolWindow": [],
|
||||
|
||||
@@ -350,10 +350,6 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"graphql.runQuery": ["Ctrl+Enter"],
|
||||
"http.runAll": [],
|
||||
"db.execute": ["Ctrl+Enter"],
|
||||
// Table editor with pending changes (after `vcs.rollback`, so Ctrl+Alt+Z reverts the table's edits there).
|
||||
"db.goToColumn": ["Ctrl+F12"],
|
||||
"db.submitChanges": ["Ctrl+Enter"],
|
||||
"db.revertChanges": ["Ctrl+Alt+Z"],
|
||||
"db.showToolWindow": [],
|
||||
"agents.newTask": ["Ctrl+Alt+Shift+I"],
|
||||
"agents.showToolWindow": [],
|
||||
|
||||
@@ -22,7 +22,6 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"navigate.implementation": ["Meta+F12"],
|
||||
"navigate.typeDeclaration": [],
|
||||
"navigate.fileStructure": ["Meta+Shift+O"],
|
||||
"db.goToColumn": ["Meta+Shift+O"],
|
||||
"navigate.relatedSymbol": [],
|
||||
"navigate.nextError": ["F8"],
|
||||
"navigate.prevError": ["Shift+F8"],
|
||||
|
||||
@@ -62,21 +62,21 @@ const DEFAULT_RUFF_FORMATTER: ExternalFormatterValid = {
|
||||
languages: ["python"],
|
||||
};
|
||||
|
||||
/** `languages.php.languageLevel` values, newest first; `""` = Auto (from `composer.json`). */
|
||||
/** `languages.php.languageLevel` values; `""` = Auto (from `composer.json`). */
|
||||
export const PHP_LANGUAGE_LEVELS = [
|
||||
"",
|
||||
"8.5",
|
||||
"8.4",
|
||||
"8.3",
|
||||
"8.2",
|
||||
"8.1",
|
||||
"8.0",
|
||||
"7.4",
|
||||
"7.3",
|
||||
"7.2",
|
||||
"7.1",
|
||||
"7.0",
|
||||
"5.6",
|
||||
"7.0",
|
||||
"7.1",
|
||||
"7.2",
|
||||
"7.3",
|
||||
"7.4",
|
||||
"8.0",
|
||||
"8.1",
|
||||
"8.2",
|
||||
"8.3",
|
||||
"8.4",
|
||||
"8.5",
|
||||
] as const;
|
||||
|
||||
export interface LanguagesValid {
|
||||
|
||||
@@ -1935,7 +1935,6 @@
|
||||
"Run a configuration with coverage to see which lines its tests execute.": "使用覆盖率运行配置,即可查看其测试执行了哪些行。",
|
||||
"Run a request from an .http file with the gutter ▶ or ⌘↩.": "使用装订区域中的 ▶ 或 ⌘↩ 运行 .http 文件中的请求。",
|
||||
"Run actions": "运行操作",
|
||||
"Console actions": "控制台操作",
|
||||
"Run and Debug": "运行和调试",
|
||||
"Run code cleanup": "运行代码清理",
|
||||
"Run configurations": "运行配置",
|
||||
@@ -3745,10 +3744,6 @@
|
||||
"Clear local filter": "清除本地筛选",
|
||||
"Search values": "搜索值",
|
||||
"No matching values": "没有匹配的值",
|
||||
"Go to Column": "转到列",
|
||||
"Columns of {table}": "{table} 的列",
|
||||
"Search columns": "搜索列",
|
||||
"No matching columns": "没有匹配的列",
|
||||
"Clear Filter": "清除筛选",
|
||||
"Clear Local Filter For All Columns": "清除所有列的本地筛选",
|
||||
"Value panel": "值面板",
|
||||
|
||||
Reference in new issue
Заблокувати користувача