B2: setup finish without hang, Open with for PHP files, 0.1.0-alpha
- Finish page starts Lutra through Explorer (Exec, returns at once) instead of RunAsUser/ShellExecute on the setup's UI thread. The 0.0.0 setup hung there while the new, unsigned exe was checked (Norton 360 active); Windows ended it and left lutra-desktop.exe suspended. The NSIS template is an adapted copy of tauri-bundler 2.10.2's. - installer/hooks.nsh registers Lutra only under OpenWithProgids and Applications\lutra-desktop.exe for .php/.phtml/.phpt/.inc; the default app stays. The uninstaller removes exactly those entries. macOS gets an Alternate-rank CFBundleDocumentTypes entry and handles RunEvent::Opened. - A file path argument opens the file inside its Git/Composer root (or folder); a running instance takes it over, switching projects only when the file lies outside (never over unsaved changes). - Version 0.1.0-alpha in the workspace, tauri.conf.json and ui; a test keeps tauri.conf.json in step with the crate version. - xtask bundle passes CARGO_TARGET_DIR to the Tauri CLI as an absolute path. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
84ff80a89f
commit
b17d26b400
17 changed files with 1430 additions and 58 deletions
|
|
@ -10,7 +10,7 @@ pub struct Args {
|
|||
pub control: Option<u16>,
|
||||
/// Isolated data directory (`--data-dir PATH`), see [`crate::datadir`].
|
||||
pub data_dir: Option<PathBuf>,
|
||||
/// Folder or file to open.
|
||||
/// Folder or file to open (see [`crate::open`]).
|
||||
pub path: Option<PathBuf>,
|
||||
/// `--help` was given.
|
||||
pub help: bool,
|
||||
|
|
@ -21,6 +21,9 @@ pub struct Args {
|
|||
/// Usage text for `--help`.
|
||||
pub const USAGE: &str = "usage: lutra-desktop [--control PORT] [--data-dir DIR] [PATH]
|
||||
|
||||
PATH a folder to open as the project, or a file to open in the
|
||||
project around it (its Git or Composer root, else its
|
||||
folder); a running Lutra takes it over
|
||||
--control PORT serve the JSON control channel on 127.0.0.1:PORT; without
|
||||
--data-dir or LUTRA_DATA_DIR the data lives in
|
||||
<temp>/lutra-control/PORT
|
||||
|
|
@ -143,6 +146,20 @@ mod tests {
|
|||
assert!(p(&["a", "b"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn takes_a_bare_file_path_from_open_with() {
|
||||
let a = p(&[r"C:\Users\me\My Projects\shop\src\Kernel.php"]).unwrap();
|
||||
assert_eq!(
|
||||
a.path,
|
||||
Some(PathBuf::from(
|
||||
r"C:\Users\me\My Projects\shop\src\Kernel.php"
|
||||
))
|
||||
);
|
||||
assert_eq!(a.control, None);
|
||||
let b = parse_os([OsString::from("/home/me/app/index.php")]).unwrap();
|
||||
assert_eq!(b.path, Some(PathBuf::from("/home/me/app/index.php")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_raw_arguments() {
|
||||
let a = parse_os([OsString::from("--control"), OsString::from("7937")]).unwrap();
|
||||
|
|
|
|||
|
|
@ -198,16 +198,27 @@ impl Host {
|
|||
/// # Errors
|
||||
/// The engine's error, e.g. when the folder does not exist.
|
||||
pub fn open_project(&self, path: &Path) -> Result<Value, EngineError> {
|
||||
let path = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map(|dir| dir.join(path))
|
||||
.unwrap_or_else(|_| path.to_path_buf())
|
||||
};
|
||||
let path = crate::open::absolute(path);
|
||||
self.run("project.open", json!({ "path": path }))
|
||||
}
|
||||
|
||||
/// Opens the path given on the command line: a file opens in a tab
|
||||
/// inside the project [`crate::open::project_root`] picks for it,
|
||||
/// anything else as the project (see [`Host::open_project`]).
|
||||
///
|
||||
/// # Errors
|
||||
/// The engine's error, e.g. when the path does not exist.
|
||||
pub fn open_path(&self, path: &Path) -> Result<Value, EngineError> {
|
||||
let path = crate::open::absolute(path);
|
||||
if !path.is_file() {
|
||||
return self.open_project(&path);
|
||||
}
|
||||
let root = crate::open::project_root(&path)
|
||||
.ok_or_else(|| EngineError::Failed(format!("{} has no folder", path.display())))?;
|
||||
self.open_project(&root)?;
|
||||
self.run("file.open", json!({ "path": path }))
|
||||
}
|
||||
|
||||
/// Sends the window the events that describe the current state (the open
|
||||
/// project and its buffers), then the notifications and `watchFailed`
|
||||
/// events published before it was ready, for a frontend that just
|
||||
|
|
|
|||
|
|
@ -45,7 +45,9 @@ pub fn rendezvous_dir(args: &Args, isolated: Option<&Path>) -> Option<PathBuf> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Forwards `path` to a running instance found through `dir`.
|
||||
/// Forwards `path` to a running instance found through `dir` (see
|
||||
/// [`open_in`]) and brings its window to the front, also when opening
|
||||
/// fails. A failed focus is ignored: the path is already open.
|
||||
///
|
||||
/// # Returns
|
||||
/// `Ok(true)` if an instance took the request (this process should exit),
|
||||
|
|
@ -58,17 +60,45 @@ pub fn forward(dir: &Path, path: Option<&Path>) -> Result<bool, String> {
|
|||
Ok((_, client)) => client,
|
||||
Err(Unavailable::Missing | Unavailable::Stale(_)) => return Ok(false),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
let path = std::path::absolute(path).map_err(|e| e.to_string())?;
|
||||
let opened = if path.is_dir() {
|
||||
client.open_folder(&path).map(|_| ())
|
||||
} else {
|
||||
client.open_file(&path).map(|_| ())
|
||||
};
|
||||
opened.map_err(|e| format!("the running Lutra cannot open {}: {e}", path.display()))?;
|
||||
}
|
||||
let opened = match path {
|
||||
Some(path) => {
|
||||
let path = std::path::absolute(path).map_err(|e| e.to_string())?;
|
||||
open_in(&mut client, &path)
|
||||
.map_err(|e| format!("the running Lutra cannot open {}: {e}", path.display()))
|
||||
}
|
||||
None => Ok(()),
|
||||
};
|
||||
let _ = client.focus();
|
||||
Ok(true)
|
||||
opened.map(|()| true)
|
||||
}
|
||||
|
||||
/// Opens `path` in the instance behind `client`: a folder as the project,
|
||||
/// a file in a tab. A file the open project cannot take (it lies outside,
|
||||
/// or no project is open) opens inside the project
|
||||
/// [`crate::open::project_root`] picks for it; the engine refuses to close
|
||||
/// a project with unsaved changes, so nothing is lost.
|
||||
///
|
||||
/// # Errors
|
||||
/// The engine's error for the file, or for switching the project.
|
||||
fn open_in(client: &mut client::Client, path: &Path) -> Result<(), client::ClientError> {
|
||||
if path.is_dir() {
|
||||
return client.open_folder(path).map(|_| ());
|
||||
}
|
||||
let open_file = |client: &mut client::Client| {
|
||||
let text = path.to_string_lossy();
|
||||
client
|
||||
.execute("file.open", serde_json::json!({ "path": text }))
|
||||
.map(|_| ())
|
||||
};
|
||||
let first = match open_file(client) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
let Some(root) = crate::open::project_root(path) else {
|
||||
return Err(first);
|
||||
};
|
||||
client.open_folder(&root)?;
|
||||
open_file(client)
|
||||
}
|
||||
|
||||
/// This process's claim on the rendezvous directory.
|
||||
|
|
@ -160,4 +190,77 @@ mod tests {
|
|||
.unwrap();
|
||||
assert_eq!(forward(dir.path(), None), Ok(false), "stale file");
|
||||
}
|
||||
|
||||
/// A running instance on a bare engine, registered in `dir`.
|
||||
fn running(
|
||||
dir: &Path,
|
||||
) -> (
|
||||
Arc<lutra_testkit::EngineBackend>,
|
||||
lutra_control::ServerHandle,
|
||||
) {
|
||||
let backend = Arc::new(lutra_testkit::EngineBackend::new());
|
||||
let token = rendezvous::new_token().unwrap();
|
||||
let server = lutra_control::start_with_token(0, backend.clone(), &token).unwrap();
|
||||
let instance = Instance {
|
||||
port: server.local_addr().port(),
|
||||
token,
|
||||
pid: std::process::id(),
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
};
|
||||
rendezvous::write(dir, &instance).unwrap();
|
||||
(backend, server)
|
||||
}
|
||||
|
||||
/// The open project's root and the open buffers' paths.
|
||||
fn state(backend: &lutra_testkit::EngineBackend) -> (Option<PathBuf>, Vec<PathBuf>) {
|
||||
use lutra_control::Backend;
|
||||
let root = {
|
||||
let engine = backend.engine.lock().unwrap();
|
||||
engine
|
||||
.state()
|
||||
.project
|
||||
.as_ref()
|
||||
.map(|w| w.project.root().to_path_buf())
|
||||
};
|
||||
let list = backend
|
||||
.execute("buffer.list", serde_json::json!({}))
|
||||
.unwrap();
|
||||
let buffers = list
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|b| PathBuf::from(b["path"].as_str().unwrap()))
|
||||
.collect();
|
||||
(root, buffers)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forwarded_file_opens_in_its_project() {
|
||||
let rv = tempfile::tempdir().unwrap();
|
||||
let work = tempfile::tempdir().unwrap();
|
||||
let app = work.path().join("app");
|
||||
std::fs::create_dir_all(app.join("src")).unwrap();
|
||||
std::fs::write(app.join("composer.json"), "{}").unwrap();
|
||||
let file = app.join("src").join("Kernel.php");
|
||||
std::fs::write(&file, "<?php\n").unwrap();
|
||||
let (backend, _server) = running(rv.path());
|
||||
|
||||
assert_eq!(forward(rv.path(), Some(&file)), Ok(true));
|
||||
let (root, buffers) = state(&backend);
|
||||
let root = root.unwrap();
|
||||
assert!(root.join("composer.json").is_file(), "{root:?}");
|
||||
assert_eq!(buffers, vec![PathBuf::from("src").join("Kernel.php")]);
|
||||
|
||||
let other = work.path().join("other");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let loose = other.join("x.php");
|
||||
std::fs::write(&loose, "<?php\n").unwrap();
|
||||
assert_eq!(forward(rv.path(), Some(&loose)), Ok(true));
|
||||
let (root, buffers) = state(&backend);
|
||||
assert!(
|
||||
root.unwrap().join("x.php").is_file(),
|
||||
"switched to the file's project"
|
||||
);
|
||||
assert_eq!(buffers, vec![PathBuf::from("x.php")]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
//! Builds the main window with the stored theme's tokens injected before
|
||||
//! first paint,
|
||||
//! bridges frontend IPC to engine commands and engine events to the window
|
||||
//! (see [`host`]), opens the project given on the command line, and
|
||||
//! (see [`host`]), opens the folder or file given on the command line or,
|
||||
//! on macOS, handed over by Finder (see [`open`]), and
|
||||
//! optionally serves the JSON control channel (`--control PORT`). A normal
|
||||
//! start is a single instance (see [`instance`]): a second start forwards
|
||||
//! its path to the running app and exits. A start with `--data-dir`,
|
||||
|
|
@ -22,6 +23,7 @@ mod host;
|
|||
mod instance;
|
||||
mod menu;
|
||||
mod migrate;
|
||||
mod open;
|
||||
mod screenshot;
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
|
@ -125,7 +127,7 @@ fn run(args: &args::Args) -> Result<(), String> {
|
|||
follow_system_background(&window);
|
||||
}
|
||||
if let Some(path) = &initial_path
|
||||
&& let Err(e) = setup_host.open_project(path)
|
||||
&& let Err(e) = setup_host.open_path(path)
|
||||
{
|
||||
setup_host.report_open_failure(path, &e);
|
||||
}
|
||||
|
|
@ -174,16 +176,32 @@ fn run(args: &args::Args) -> Result<(), String> {
|
|||
});
|
||||
host.start_pump()
|
||||
.map_err(|e| format!("cannot start watching for changes: {e}"))?;
|
||||
app.run(move |_, event| {
|
||||
if let tauri::RunEvent::Exit = event
|
||||
&& let Some(claim) = &claim
|
||||
{
|
||||
claim.release();
|
||||
app.run(move |_, event| match event {
|
||||
tauri::RunEvent::Exit => {
|
||||
if let Some(claim) = &claim {
|
||||
claim.release();
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
tauri::RunEvent::Opened { urls } => open_urls(&host, &urls),
|
||||
_ => {}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// macOS: opens the files Finder hands over ("Open With → Lutra", a file
|
||||
/// dropped on the Dock icon), which arrive as an Apple event instead of
|
||||
/// arguments. Each opens like a path on the command line; a failure is
|
||||
/// shown as a notification.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn open_urls(host: &Host, urls: &[tauri::Url]) {
|
||||
for path in urls.iter().filter_map(|url| url.to_file_path().ok()) {
|
||||
if let Err(e) = host.open_path(&path) {
|
||||
host.report_open_failure(&path, &e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's engine directories from Tauri's path resolver: the app config
|
||||
/// dir for settings, the app data dir for the recovery journal and the
|
||||
/// managed tools. Resolving creates nothing.
|
||||
|
|
@ -365,4 +383,29 @@ mod tests {
|
|||
);
|
||||
assert_eq!(token_color(&theme::DARK, "missing"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bundle_config_matches_the_crate_and_the_installer() {
|
||||
let conf: Value = serde_json::from_str(include_str!("../tauri.conf.json")).unwrap();
|
||||
assert_eq!(conf["version"], env!("CARGO_PKG_VERSION"));
|
||||
assert!(
|
||||
conf["bundle"].get("fileAssociations").is_none(),
|
||||
"on Windows the bundler's associations take over the default app; installer/hooks.nsh registers Open with instead"
|
||||
);
|
||||
let mac: Value = serde_json::from_str(include_str!("../tauri.macos.conf.json")).unwrap();
|
||||
let assoc = &mac["bundle"]["fileAssociations"][0];
|
||||
assert_eq!(assoc["rank"], "Alternate");
|
||||
let mac_exts: Vec<&str> = assoc["ext"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|e| e.as_str().unwrap())
|
||||
.collect();
|
||||
let windows_exts: Vec<&str> = include_str!("../installer/hooks.nsh")
|
||||
.lines()
|
||||
.filter_map(|line| line.trim().strip_prefix("!insertmacro ${MACRO} \""))
|
||||
.filter_map(|rest| rest.strip_suffix('"'))
|
||||
.collect();
|
||||
assert_eq!(mac_exts, windows_exts);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
96
apps/lutra-desktop/src/open.rs
Normal file
96
apps/lutra-desktop/src/open.rs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
//! What a path on the command line opens.
|
||||
//!
|
||||
//! A folder becomes the project. A file (for example from Explorer's
|
||||
//! "Open with → Lutra" on a `.php` file) opens in a tab, inside a project
|
||||
//! chosen for it by [`project_root`]: the nearest folder above it that is a
|
||||
//! Git work tree, else the nearest one with a `composer.json`, else the
|
||||
//! file's own folder.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Markers of a Git work tree: a `.git` folder, or a `.git` file in a
|
||||
/// linked worktree or submodule.
|
||||
const GIT_MARKER: &str = ".git";
|
||||
|
||||
/// Composer's project file.
|
||||
const COMPOSER_MARKER: &str = "composer.json";
|
||||
|
||||
/// The project folder for `file`: the nearest ancestor holding `.git`,
|
||||
/// else the nearest one holding `composer.json`, else the file's parent.
|
||||
/// `None` only for a path without a parent (a bare root).
|
||||
pub fn project_root(file: &Path) -> Option<PathBuf> {
|
||||
let parent = file.parent()?;
|
||||
let nearest = |marker: &str| {
|
||||
parent
|
||||
.ancestors()
|
||||
.find(|dir| dir.join(marker).exists())
|
||||
.map(Path::to_path_buf)
|
||||
};
|
||||
nearest(GIT_MARKER)
|
||||
.or_else(|| nearest(COMPOSER_MARKER))
|
||||
.or_else(|| Some(parent.to_path_buf()))
|
||||
}
|
||||
|
||||
/// `path` made absolute against the current directory; unchanged if that
|
||||
/// fails, so the engine reports the original path.
|
||||
pub fn absolute(path: &Path) -> PathBuf {
|
||||
std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_git_root_wins_over_a_nested_composer_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repo = dir.path().join("repo");
|
||||
let pkg = repo.join("packages").join("api");
|
||||
std::fs::create_dir_all(repo.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(pkg.join("src")).unwrap();
|
||||
std::fs::write(pkg.join("composer.json"), "{}").unwrap();
|
||||
let file = pkg.join("src").join("Kernel.php");
|
||||
assert_eq!(project_root(&file), Some(repo));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_git_file_marks_a_worktree() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tree = dir.path().join("wt");
|
||||
std::fs::create_dir_all(tree.join("src")).unwrap();
|
||||
std::fs::write(tree.join(".git"), "gitdir: elsewhere").unwrap();
|
||||
assert_eq!(project_root(&tree.join("src").join("a.php")), Some(tree));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_marks_a_project_without_git() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app = dir.path().join("app");
|
||||
std::fs::create_dir_all(app.join("public")).unwrap();
|
||||
std::fs::write(app.join("composer.json"), "{}").unwrap();
|
||||
let file = app.join("public").join("index.php");
|
||||
assert_eq!(project_root(&file), Some(app));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loose_file_opens_in_its_folder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let loose = dir.path().join("scratch");
|
||||
std::fs::create_dir_all(&loose).unwrap();
|
||||
let file = loose.join("test.php");
|
||||
if dir.path().ancestors().any(|d| d.join(".git").exists())
|
||||
|| dir
|
||||
.path()
|
||||
.ancestors()
|
||||
.any(|d| d.join("composer.json").exists())
|
||||
{
|
||||
return;
|
||||
}
|
||||
assert_eq!(project_root(&file), Some(loose));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn makes_relative_paths_absolute() {
|
||||
assert!(absolute(Path::new("foo.php")).is_absolute());
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue