Windows and Linux build environments; check clean on both (E-01)
MuPDF builds with MSBuild on Windows (/MT, OpenSSL from vcpkg); Git for Windows' MinGit stands in for the source build there. CEF loads from where libcef lives and sets its API version first on every platform. File identity on Windows compares volume and index. The checkout and reference/ keep LF on Windows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d59159cea2
commit
68b5af76e0
40 files changed
+380
-82
No files matched your search
@@ -203,12 +203,9 @@ pub fn same_file(a: &Path, b: &Path) -> io::Result<bool> {
|
||||
if resolved(a)? == resolved(b)? {
|
||||
return Ok(true);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if let (Ok(ma), Ok(mb)) = (std::fs::metadata(a), std::fs::metadata(b)) {
|
||||
return Ok((ma.dev(), ma.ino()) == (mb.dev(), mb.ino()));
|
||||
}
|
||||
// A missing side is another file.
|
||||
if let (Ok(Some(ia)), Ok(Some(ib))) = (crate::session::file_id(a), crate::session::file_id(b)) {
|
||||
return Ok(ia == ib);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
@@ -462,8 +462,8 @@ fn save_as_onto_its_own_file_checks_for_outside_changes() {
|
||||
let alias = dir.path().join("alias.docx");
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&own, &alias).expect("the alias");
|
||||
#[cfg(not(unix))]
|
||||
let alias = own.clone();
|
||||
#[cfg(windows)]
|
||||
std::fs::hard_link(&own, &alias).expect("the alias");
|
||||
assert!(matches!(
|
||||
save_as(&mut session, &alias, b"local"),
|
||||
Err(SaveError::Conflict)
|
||||
|
||||
@@ -386,6 +386,7 @@ impl Session {
|
||||
}
|
||||
|
||||
mod registry;
|
||||
pub(crate) use registry::file_id;
|
||||
pub use registry::{Open, Sessions};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -33,14 +33,14 @@ struct Key {
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn file_id(path: &Path) -> io::Result<Option<(u64, u64)>> {
|
||||
pub(crate) fn file_id(path: &Path) -> io::Result<Option<(u64, u64)>> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let meta = std::fs::metadata(path)?;
|
||||
Ok(Some((meta.dev(), meta.ino())))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn file_id(path: &Path) -> io::Result<Option<(u64, u64)>> {
|
||||
pub(crate) fn file_id(path: &Path) -> io::Result<Option<(u64, u64)>> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
@@ -75,7 +75,7 @@ fn file_id(path: &Path) -> io::Result<Option<(u64, u64)>> {
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn file_id(_: &Path) -> io::Result<Option<(u64, u64)>> {
|
||||
pub(crate) fn file_id(_: &Path) -> io::Result<Option<(u64, u64)>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
|
||||
@@ -448,7 +448,7 @@ fn an_empty_sheet_scrolls_on_without_waiting() {
|
||||
eprintln!("SKIP: no pinned LOK build");
|
||||
return;
|
||||
};
|
||||
let mut cx = gpui::TestAppContext::single();
|
||||
let cx = gpui::TestAppContext::single();
|
||||
let (view, worker) = cx.update(|app| live_view_of(app, &install, "short.fods", SHORT_ROWS));
|
||||
let json = cx.update(|app| worker.lock().expect("the worker lock").values(&view.read(app).doc, crate::sheet::GEOMETRY).expect("geometry"));
|
||||
let geometry = crate::sheet::geometry(&json).expect("parsed");
|
||||
|
||||
@@ -57,7 +57,11 @@ fn main() {
|
||||
}
|
||||
println!("cargo:rustc-env=ELY_PDF_BUILD={stamp:016x}");
|
||||
println!("cargo:rerun-if-env-changed=ELY_MUPDF_DIR");
|
||||
for lib in ["libmupdf.a", "libmupdf-third.a", "libmupdf-pkcs7.a"] {
|
||||
let windows = std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows");
|
||||
// MSVC's libmupdf.lib holds its third parties and PKCS#7.
|
||||
let libs: &[&str] =
|
||||
if windows { &["libmupdf.lib"] } else { &["libmupdf-pkcs7.a", "libmupdf.a", "libmupdf-third.a"] };
|
||||
for lib in libs {
|
||||
println!("cargo:rerun-if-changed={}", mupdf.join(lib).display());
|
||||
if !mupdf.join(lib).is_file() {
|
||||
panic!("no {lib} in {} (run scripts/build-mupdf.sh or set ELY_MUPDF_DIR)", mupdf.display());
|
||||
@@ -83,26 +87,49 @@ fn main() {
|
||||
.file("shim/ely_sign.c")
|
||||
.file("shim/ely_output.c")
|
||||
.include(root.join("reference/mupdf/include"))
|
||||
.include(openssl("includedir"))
|
||||
.include(openssl(&root, "includedir"))
|
||||
.warnings(true)
|
||||
.cargo_metadata(false)
|
||||
.compile("ely_mupdf");
|
||||
let out = PathBuf::from(std::env::var("OUT_DIR").expect("set by cargo"));
|
||||
let bin = "ely-pdf-worker";
|
||||
println!("cargo:rustc-link-arg-bin={bin}={}", out.join("libely_mupdf.a").display());
|
||||
println!("cargo:rustc-link-arg-bin={bin}={}", mupdf.join("libmupdf-pkcs7.a").display());
|
||||
println!("cargo:rustc-link-arg-bin={bin}={}", mupdf.join("libmupdf.a").display());
|
||||
println!("cargo:rustc-link-arg-bin={bin}={}", mupdf.join("libmupdf-third.a").display());
|
||||
let shim = if windows { "ely_mupdf.lib" } else { "libely_mupdf.a" };
|
||||
println!("cargo:rustc-link-arg-bin={bin}={}", out.join(shim).display());
|
||||
for lib in libs {
|
||||
println!("cargo:rustc-link-arg-bin={bin}={}", mupdf.join(lib).display());
|
||||
}
|
||||
// Signing and checking need OpenSSL, linked in whole.
|
||||
println!("cargo:rustc-link-arg-bin={bin}={}", PathBuf::from(openssl("libdir")).join("libcrypto.a").display());
|
||||
let crypto = if windows { "libcrypto.lib" } else { "libcrypto.a" };
|
||||
println!("cargo:rustc-link-arg-bin={bin}={}", PathBuf::from(openssl(&root, "libdir")).join(crypto).display());
|
||||
if windows {
|
||||
for lib in ["crypt32.lib", "ws2_32.lib", "advapi32.lib", "user32.lib"] {
|
||||
println!("cargo:rustc-link-arg-bin={bin}={lib}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
// What a static libcrypto needs, as its pkg-config says.
|
||||
let needs = std::process::Command::new("pkg-config")
|
||||
.args(["--static", "--libs-only-l", "libcrypto"])
|
||||
.output()
|
||||
.expect("pkg-config, to find OpenSSL");
|
||||
assert!(needs.status.success(), "pkg-config knows no static libcrypto");
|
||||
for lib in String::from_utf8(needs.stdout).expect("UTF-8 flags").split_whitespace().filter(|lib| *lib != "-lcrypto") {
|
||||
println!("cargo:rustc-link-arg-bin={bin}={lib}");
|
||||
}
|
||||
println!("cargo:rustc-link-arg-bin={bin}=-lm");
|
||||
// Tesseract inside MuPDF is C++.
|
||||
let cxx = if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { "-lc++" } else { "-lstdc++" };
|
||||
println!("cargo:rustc-link-arg-bin={bin}={cxx}");
|
||||
}
|
||||
|
||||
/// An OpenSSL directory, from pkg-config.
|
||||
fn openssl(variable: &str) -> String {
|
||||
/// An OpenSSL directory: vcpkg's static build on Windows, else pkg-config's.
|
||||
fn openssl(root: &std::path::Path, variable: &str) -> String {
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||
let dir = root.join("engines/vcpkg/installed/x64-windows-static");
|
||||
let sub = if variable == "includedir" { "include" } else { "lib" };
|
||||
assert!(dir.join("lib/libcrypto.lib").is_file(), "no static OpenSSL in {}", dir.display());
|
||||
return dir.join(sub).display().to_string();
|
||||
}
|
||||
let out = std::process::Command::new("pkg-config")
|
||||
.args([&format!("--variable={variable}"), "libcrypto"])
|
||||
.output()
|
||||
|
||||
@@ -146,7 +146,7 @@ static void write_file(fz_context *ctx, fz_output *out, const char *key, const c
|
||||
fz_write_string(ctx, out, ",\"name\":");
|
||||
ely_json_string(ctx, out, name);
|
||||
fz_write_printf(ctx, out, ",\"page\":%d,\"size\":%ld,\"created\":%ld,\"modified\":%ld,\"type\":", page,
|
||||
(long)file_size(ctx, fs), (long)params.created, (long)params.modified);
|
||||
file_size(ctx, fs), (int64_t)params.created, (int64_t)params.modified);
|
||||
ely_json_string(ctx, out, params.mimetype ? params.mimetype : "");
|
||||
fz_write_string(ctx, out, ",\"note\":");
|
||||
ely_json_string(ctx, out, pdf_dict_get_text_string(ctx, fs, PDF_NAME(Desc)));
|
||||
|
||||
@@ -255,7 +255,7 @@ int ely_text_layer(fz_context *ctx, fz_document *doc, const char *json, int repl
|
||||
{
|
||||
if (!font)
|
||||
font = glyphless(ctx, pdf);
|
||||
ely_add_resource(ctx, pdf, page->obj, PDF_NAME(Font), "ElyOCR", font, name, sizeof name);
|
||||
ely_add_resource(ctx, page->obj, PDF_NAME(Font), "ElyOCR", font, name, sizeof name);
|
||||
buf = fz_new_buffer(ctx, 1024);
|
||||
/* Its own state, so later text stays seen. */
|
||||
fz_append_string(ctx, buf, "q\n");
|
||||
|
||||
@@ -132,7 +132,7 @@ const char *ely_pen_resource(fz_context *ctx, pdf_document *pdf, pdf_page *page,
|
||||
p->ref = pdf_add_cjk_font(ctx, pdf, p->font, p->ordering, 0, 0);
|
||||
break;
|
||||
}
|
||||
return ely_add_resource(ctx, pdf, page->obj, PDF_NAME(Font), "ElyF", p->ref, name, room);
|
||||
return ely_add_resource(ctx, page->obj, PDF_NAME(Font), "ElyF", p->ref, name, room);
|
||||
}
|
||||
|
||||
/* The own font's code for `u`, or -1. */
|
||||
|
||||
@@ -38,6 +38,7 @@ static void inv_q(fz_context *ctx, pdf_processor *proc)
|
||||
static void inv_Q(fz_context *ctx, pdf_processor *proc)
|
||||
{
|
||||
inventory *inv = (inventory *)proc;
|
||||
(void)ctx;
|
||||
if (inv->depth > 0)
|
||||
inv->ctm = inv->stack[--inv->depth];
|
||||
}
|
||||
@@ -45,6 +46,7 @@ static void inv_Q(fz_context *ctx, pdf_processor *proc)
|
||||
static void inv_cm(fz_context *ctx, pdf_processor *proc, float a, float b, float c, float d, float e, float f)
|
||||
{
|
||||
inventory *inv = (inventory *)proc;
|
||||
(void)ctx;
|
||||
inv->ctm = fz_concat(fz_make_matrix(a, b, c, d, e, f), inv->ctm);
|
||||
}
|
||||
|
||||
@@ -62,12 +64,15 @@ static void found(fz_context *ctx, inventory *inv, int form, fz_rect box)
|
||||
|
||||
static void inv_image(fz_context *ctx, pdf_processor *proc, const char *name, fz_image *image)
|
||||
{
|
||||
(void)name;
|
||||
(void)image;
|
||||
found(ctx, (inventory *)proc, 0, fz_unit_rect);
|
||||
}
|
||||
|
||||
static void inv_form(fz_context *ctx, pdf_processor *proc, const char *name, pdf_obj *form)
|
||||
{
|
||||
fz_rect box = fz_transform_rect(pdf_xobject_bbox(ctx, form), pdf_xobject_matrix(ctx, form));
|
||||
(void)name;
|
||||
found(ctx, (inventory *)proc, 1, box);
|
||||
}
|
||||
|
||||
@@ -269,7 +274,7 @@ int ely_place(fz_context *ctx, fz_document *doc, int number, int index, const fl
|
||||
own = (float)image->w / image->h;
|
||||
change = fz_concat(fz_concat(fz_translate(-cx, -cy), fz_scale(fminf(1, own / box), fminf(1, box / own))), fz_translate(cx, cy));
|
||||
ref = pdf_add_image(ctx, pdf, image);
|
||||
h.rename = ely_add_resource(ctx, pdf, page->obj, PDF_NAME(XObject), "ElyIm", ref, name, sizeof name);
|
||||
h.rename = ely_add_resource(ctx, page->obj, PDF_NAME(XObject), "ElyIm", ref, name, sizeof name);
|
||||
}
|
||||
if (fz_matrix_expansion(change) < 0.001f)
|
||||
fz_throw(ctx, FZ_ERROR_ARGUMENT, "a change that leaves nothing");
|
||||
@@ -315,7 +320,7 @@ int ely_add_image(fz_context *ctx, fz_document *doc, int number, const char *pat
|
||||
pdf_begin_operation(ctx, pdf, "Add an image");
|
||||
begun = 1;
|
||||
ref = pdf_add_image(ctx, pdf, image);
|
||||
ely_add_resource(ctx, pdf, page->obj, PDF_NAME(XObject), "ElyIm", ref, name, sizeof name);
|
||||
ely_add_resource(ctx, page->obj, PDF_NAME(XObject), "ElyIm", ref, name, sizeof name);
|
||||
/* The unit square, bottom left first, onto the box. */
|
||||
m = fz_concat(fz_make_matrix(rect[2] - rect[0], 0, 0, rect[1] - rect[3], rect[0], rect[3]), ely_to_user(ctx, page));
|
||||
buf = fz_new_buffer(ctx, 128);
|
||||
|
||||
@@ -38,7 +38,7 @@ void ely_read_block(fz_context *ctx, fz_document *doc, pdf_page *page, int numbe
|
||||
void ely_remove_block(fz_context *ctx, pdf_document *pdf, pdf_page *page, ely_shape *shape);
|
||||
void ely_drop_shape(fz_context *ctx, ely_shape *shape);
|
||||
pdf_obj *ely_append_content(fz_context *ctx, pdf_document *pdf, pdf_obj *page, fz_buffer *buf);
|
||||
const char *ely_add_resource(fz_context *ctx, pdf_document *pdf, pdf_obj *page, pdf_obj *type, const char *stem,
|
||||
const char *ely_add_resource(fz_context *ctx, pdf_obj *page, pdf_obj *type, const char *stem,
|
||||
pdf_obj *ref, char *name, size_t room);
|
||||
void ely_json_string(fz_context *ctx, fz_output *out, const char *s);
|
||||
fz_json *ely_member(fz_context *ctx, fz_json *obj, const char *key, int type);
|
||||
|
||||
@@ -97,6 +97,10 @@ static int take_glyph(fz_context *ctx, void *opaque, int *ucs, int ucslen, fz_ma
|
||||
fz_rect bbox, int tr, float ca, float CA)
|
||||
{
|
||||
targets *t = opaque;
|
||||
(void)bbox;
|
||||
(void)tr;
|
||||
(void)ca;
|
||||
(void)CA;
|
||||
fz_point at = fz_transform_point(fz_transform_point(fz_make_point(0, 0), trm), ctm);
|
||||
/* MuPDF gives at most PDF_MRANGE_CAP; each spells to 18. */
|
||||
int i, k, found = 0, spelt[18 * PDF_MRANGE_CAP], n = 0;
|
||||
|
||||
@@ -68,7 +68,7 @@ static int lay_out(fz_context *ctx, ely_pen *p, const int *u, int n, float size,
|
||||
}
|
||||
|
||||
/* A resource name in `type` that is free, given `ref`. */
|
||||
const char *ely_add_resource(fz_context *ctx, pdf_document *pdf, pdf_obj *page, pdf_obj *type, const char *stem,
|
||||
const char *ely_add_resource(fz_context *ctx, pdf_obj *page, pdf_obj *type, const char *stem,
|
||||
pdf_obj *ref, char *name, size_t room)
|
||||
{
|
||||
pdf_obj *res = pdf_dict_get_inheritable(ctx, page, PDF_NAME(Resources));
|
||||
|
||||
@@ -186,6 +186,7 @@ fn a_reply_to_another_request_is_refused() {
|
||||
}
|
||||
|
||||
/// A noisy RGB PNG, stored uncompressed: large on disk.
|
||||
#[cfg(unix)]
|
||||
fn big_png(path: &Path, side: u32) {
|
||||
let crc = |bytes: &[u8]| {
|
||||
let mut crc = 0xffff_ffffu32;
|
||||
|
||||
@@ -56,6 +56,28 @@ fn an_unreadable_log_is_an_error_not_nothing() {
|
||||
assert!(log_part(log).is_err(), "a log that cannot be read shows");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn an_unreadable_log_is_an_error_not_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let logs = dir.path().join("logs");
|
||||
std::fs::create_dir(&logs).unwrap();
|
||||
let log = logs.join("ely.log");
|
||||
assert_eq!(log_part(log.clone()).unwrap(), None, "no log yet is nothing");
|
||||
std::fs::write(&log, "a line\n").unwrap();
|
||||
let icacls = |path: &std::path::Path, args: [&str; 2]| {
|
||||
let done = std::process::Command::new("icacls").arg(path).args(args).output().unwrap();
|
||||
assert!(done.status.success(), "icacls: {}", String::from_utf8_lossy(&done.stdout));
|
||||
};
|
||||
// Everyone loses its attributes and its folder's listing.
|
||||
icacls(&log, ["/deny", "*S-1-1-0:(RA)"]);
|
||||
icacls(&logs, ["/deny", "*S-1-1-0:(RD)"]);
|
||||
let read = log_part(log.clone());
|
||||
icacls(&logs, ["/remove:d", "*S-1-1-0"]);
|
||||
icacls(&log, ["/remove:d", "*S-1-1-0"]);
|
||||
assert!(read.is_err(), "a log that cannot be read shows: {read:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_log_starts_at_a_whole_line() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -14,6 +14,12 @@ pub const PROGRAM: &str = "git";
|
||||
/// The oldest system Git counted as verified (user decision).
|
||||
pub const LEAST: (u32, u32) = (2, 40);
|
||||
|
||||
/// Git inside a Git install: MinGit's on Windows.
|
||||
#[cfg(windows)]
|
||||
const GIT: &str = "cmd/git.exe";
|
||||
#[cfg(not(windows))]
|
||||
const GIT: &str = "bin/git";
|
||||
|
||||
/// `ELY_GIT`, ElyTree's setting, else Ely's own Git.
|
||||
pub fn locate() -> io::Result<(PathBuf, bool)> {
|
||||
if let Some(path) = std::env::var_os("ELY_GIT") {
|
||||
@@ -62,12 +68,12 @@ pub fn system_version(path: &Path) -> io::Result<String> {
|
||||
/// Beside `dir`, in its bundle, in ElyTree's, or built.
|
||||
fn own(dir: &Path) -> PathBuf {
|
||||
// ElyTree carries Git; the other apps use its copy.
|
||||
let tree = format!("../../../{}.app/Contents/Resources/git/bin/git", AppId::Tree.name());
|
||||
let built = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../engines/git/bin/git");
|
||||
let tree = format!("../../../{}.app/Contents/Resources/git", AppId::Tree.name());
|
||||
let built = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../engines/git").join(GIT);
|
||||
[
|
||||
dir.join("git/bin/git"),
|
||||
dir.join("../Resources/git/bin/git"),
|
||||
dir.join(tree),
|
||||
dir.join("git").join(GIT),
|
||||
dir.join("../Resources/git").join(GIT),
|
||||
dir.join(tree).join(GIT),
|
||||
]
|
||||
.into_iter()
|
||||
.find(|path| path.is_file())
|
||||
@@ -113,17 +119,17 @@ mod tests {
|
||||
assert_eq!(super::parse_version("hello"), None);
|
||||
}
|
||||
|
||||
use super::own;
|
||||
use super::{GIT, own};
|
||||
|
||||
#[test]
|
||||
fn apps_beside_elytree_use_its_git() {
|
||||
let apps = tempfile::tempdir().expect("a temp dir");
|
||||
let mark = apps.path().join("ElyMark.app/Contents/MacOS");
|
||||
let git = apps.path().join("ElyTree.app/Contents/Resources/git/bin");
|
||||
let git = apps.path().join("ElyTree.app/Contents/Resources/git").join(GIT);
|
||||
std::fs::create_dir_all(&mark).expect("ElyMark");
|
||||
assert!(own(&mark).ends_with("engines/git/bin/git"));
|
||||
std::fs::create_dir_all(&git).expect("ElyTree's Git");
|
||||
std::fs::write(git.join("git"), "").expect("git");
|
||||
assert_eq!(own(&mark), mark.join("../../../ElyTree.app/Contents/Resources/git/bin/git"));
|
||||
assert!(own(&mark).ends_with(std::path::Path::new("engines/git").join(GIT)));
|
||||
std::fs::create_dir_all(git.parent().expect("a folder")).expect("ElyTree's Git");
|
||||
std::fs::write(&git, "").expect("git");
|
||||
assert_eq!(own(&mark), mark.join("../../../ElyTree.app/Contents/Resources/git").join(GIT));
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,9 @@
|
||||
use std::{
|
||||
io,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// The `.app` running this process; none in dev builds.
|
||||
pub fn running_bundle() -> io::Result<Option<PathBuf>> {
|
||||
@@ -50,6 +51,7 @@ fn stage(from: &Path, parent: &Path, name: &std::ffi::OsStr) -> io::Result<PathB
|
||||
}
|
||||
|
||||
/// Puts `staged` at `bundle`; on failure the old returns.
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn swap(staged: &Path, bundle: &Path) -> io::Result<()> {
|
||||
let name = bundle.file_name().ok_or_else(|| io::Error::other("the app has no name"))?;
|
||||
let old = bundle.with_file_name(format!(".{}.old", name.to_string_lossy()));
|
||||
|
||||
@@ -73,6 +73,7 @@ pub fn print_pdf(pdf: &Path) -> anyhow::Result<bool> {
|
||||
}
|
||||
|
||||
/// One paper holding every page, turned as needed.
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn paper_for(sizes: &[(f64, f64)]) -> Option<(f64, f64)> {
|
||||
let long = sizes.iter().map(|(w, h)| w.max(*h)).fold(None, |most: Option<f64>, side| Some(most.map_or(side, |m| m.max(side))))?;
|
||||
let short = sizes.iter().map(|(w, h)| w.min(*h)).fold(0.0, f64::max);
|
||||
|
||||
@@ -51,7 +51,7 @@ fn full_name() -> io::Result<String> {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let mut buffer = vec![0u16; size as usize];
|
||||
if unsafe { GetUserNameExW(NameDisplay, buffer.as_mut_ptr(), &mut size) } == 0 {
|
||||
if !unsafe { GetUserNameExW(NameDisplay, buffer.as_mut_ptr(), &mut size) } {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(String::from_utf16_lossy(&buffer[..size as usize]))
|
||||
|
||||
@@ -21,6 +21,9 @@ serde_json.workspace = true
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use anyhow::Result;
|
||||
use cef::{args::Args, *};
|
||||
use futures::{FutureExt as _, StreamExt as _, channel::mpsc};
|
||||
use gpui::{App, AsyncApp, Global, WeakEntity};
|
||||
@@ -14,7 +14,9 @@ use gpui::{App, AsyncApp, Global, WeakEntity};
|
||||
use crate::{handlers, surface::Shared, view::WebView};
|
||||
|
||||
/// The framework beside the app, else the fetched one.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn framework_dir() -> Result<PathBuf> {
|
||||
use anyhow::Context as _;
|
||||
const NAME: &str = "Chromium Embedded Framework.framework";
|
||||
let exe = std::env::current_exe()?;
|
||||
let mut places: Vec<PathBuf> = Vec::new();
|
||||
@@ -39,17 +41,12 @@ fn framework_dir() -> Result<PathBuf> {
|
||||
|
||||
static LOADED: OnceLock<std::result::Result<PathBuf, String>> = OnceLock::new();
|
||||
|
||||
/// Loads the framework once; every process needs it first.
|
||||
/// Loads CEF once and sets its API version.
|
||||
fn load() -> Result<PathBuf> {
|
||||
LOADED
|
||||
.get_or_init(|| {
|
||||
let dir = framework_dir().map_err(|error| format!("{error:#}"))?;
|
||||
let library = dir.join("Chromium Embedded Framework");
|
||||
let name = std::ffi::CString::new(library.as_os_str().as_encoded_bytes())
|
||||
.map_err(|error| error.to_string())?;
|
||||
if unsafe { load_library(Some(&*name.as_ptr().cast())) } != 1 {
|
||||
return Err(format!("CEF did not load from {}", library.display()));
|
||||
}
|
||||
let dir = open()?;
|
||||
// Versioned calls exit the process until this runs.
|
||||
let _ = api_hash(sys::CEF_API_VERSION_LAST, 0);
|
||||
log::info!("web: CEF loaded from {}", dir.display());
|
||||
Ok(dir)
|
||||
@@ -58,6 +55,51 @@ fn load() -> Result<PathBuf> {
|
||||
.map_err(anyhow::Error::msg)
|
||||
}
|
||||
|
||||
/// Loads the framework; its folder.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn open() -> std::result::Result<PathBuf, String> {
|
||||
let dir = framework_dir().map_err(|error| format!("{error:#}"))?;
|
||||
let library = dir.join("Chromium Embedded Framework");
|
||||
let name = std::ffi::CString::new(library.as_os_str().as_encoded_bytes()).map_err(|error| error.to_string())?;
|
||||
if unsafe { load_library(Some(&*name.as_ptr().cast())) } != 1 {
|
||||
return Err(format!("CEF did not load from {}", library.display()));
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// The folder of the libcef.dll this process linked.
|
||||
#[cfg(windows)]
|
||||
fn open() -> std::result::Result<PathBuf, String> {
|
||||
use std::os::windows::ffi::OsStringExt as _;
|
||||
use windows_sys::Win32::System::LibraryLoader::{GetModuleFileNameW, GetModuleHandleW};
|
||||
let name: Vec<u16> = "libcef.dll".encode_utf16().chain([0]).collect();
|
||||
let module = unsafe { GetModuleHandleW(name.as_ptr()) };
|
||||
if module.is_null() {
|
||||
return Err(format!("libcef.dll is not loaded: {}", std::io::Error::last_os_error()));
|
||||
}
|
||||
let mut path = vec![0u16; 32_768];
|
||||
let len = unsafe { GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) } as usize;
|
||||
if len == 0 || len == path.len() {
|
||||
return Err(format!("libcef.dll has no path: {}", std::io::Error::last_os_error()));
|
||||
}
|
||||
let file = PathBuf::from(std::ffi::OsString::from_wide(&path[..len]));
|
||||
file.parent().map(Path::to_path_buf).ok_or_else(|| format!("{} has no folder", file.display()))
|
||||
}
|
||||
|
||||
/// The folder of the libcef.so this process linked.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn open() -> std::result::Result<PathBuf, String> {
|
||||
use std::os::unix::ffi::OsStrExt as _;
|
||||
let mut info: libc::Dl_info = unsafe { std::mem::zeroed() };
|
||||
let entry = sys::cef_api_hash as *const libc::c_void;
|
||||
if unsafe { libc::dladdr(entry, &mut info) } == 0 || info.dli_fname.is_null() {
|
||||
return Err("libcef.so is not loaded".into());
|
||||
}
|
||||
let name = unsafe { std::ffi::CStr::from_ptr(info.dli_fname) };
|
||||
let file = PathBuf::from(std::ffi::OsStr::from_bytes(name.to_bytes()));
|
||||
file.parent().map(Path::to_path_buf).ok_or_else(|| format!("{} has no folder", file.display()))
|
||||
}
|
||||
|
||||
/// In a CEF helper process, runs it to its end.
|
||||
pub fn subprocess() -> Option<i32> {
|
||||
// CEF's own parser needs the framework; plain args do not.
|
||||
@@ -185,10 +227,11 @@ pub fn start(data: &Path, cx: &mut App) -> Result<()> {
|
||||
crate::mac::adopt_app_protocol()?;
|
||||
let exe = std::env::current_exe()?;
|
||||
// Bundled, CEF finds its helper apps; else this binary helps.
|
||||
let bundled = framework.parent().is_some_and(|dir| {
|
||||
let name = exe.file_name().unwrap_or_default().to_string_lossy();
|
||||
dir.join(format!("{name} Helper.app")).is_dir()
|
||||
});
|
||||
let bundled = cfg!(target_os = "macos")
|
||||
&& framework.parent().is_some_and(|dir| {
|
||||
let name = exe.file_name().unwrap_or_default().to_string_lossy();
|
||||
dir.join(format!("{name} Helper.app")).is_dir()
|
||||
});
|
||||
let helper = if bundled {
|
||||
String::new()
|
||||
} else {
|
||||
@@ -201,7 +244,12 @@ pub fn start(data: &Path, cx: &mut App) -> Result<()> {
|
||||
external_message_pump: true as _,
|
||||
no_sandbox: true as _,
|
||||
browser_subprocess_path: helper.as_str().into(),
|
||||
#[cfg(target_os = "macos")]
|
||||
framework_dir_path: framework.to_string_lossy().as_ref().into(),
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
resources_dir_path: framework.to_string_lossy().as_ref().into(),
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
locales_dir_path: framework.join("locales").to_string_lossy().as_ref().into(),
|
||||
root_cache_path: cache.to_string_lossy().as_ref().into(),
|
||||
persist_session_cookies: false as _,
|
||||
log_severity: LogSeverity::WARNING,
|
||||
@@ -267,6 +315,7 @@ fn stop() {
|
||||
}
|
||||
|
||||
/// Why CEF would refuse this cache: another app holds it.
|
||||
#[cfg(unix)]
|
||||
fn held(cache: &Path) -> Option<String> {
|
||||
let lock = std::fs::read_link(cache.join("SingletonLock")).ok()?;
|
||||
let lock = lock.to_string_lossy();
|
||||
@@ -275,3 +324,21 @@ fn held(cache: &Path) -> Option<String> {
|
||||
let alive = unsafe { libc::kill(pid, 0) } == 0;
|
||||
alive.then(|| format!("another copy (process {pid}) is using {}", cache.display()))
|
||||
}
|
||||
|
||||
/// Chromium's Windows lock names no process.
|
||||
#[cfg(windows)]
|
||||
fn held(_cache: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn cef_loads_with_its_api_version() {
|
||||
let dir = super::load().expect("CEF loads");
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
assert!(dir.join("locales").is_dir(), "{} holds CEF's files", dir.display());
|
||||
// Without the version this call exits the process.
|
||||
assert!(cef::command_line_create().is_some());
|
||||
}
|
||||
}
|
||||
@@ -280,7 +280,7 @@ wrap_display_handler! {
|
||||
fn on_cursor_change(
|
||||
&self,
|
||||
_browser: Option<&mut Browser>,
|
||||
_cursor: *mut u8,
|
||||
_cursor: CursorHandle,
|
||||
type_: CursorType,
|
||||
_custom_cursor_info: Option<&CursorInfo>,
|
||||
) -> ::std::os::raw::c_int {
|
||||
|
||||
Reference in new issue
Block a user