Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion apps/gpui/crates/shell/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

use gpui_kit::Global;
use imgconvert_backend::instance_lock::{self, AcquireOutcome, InstanceInfo, InstanceLock};
use imgconvert_backend::paths;
use imgconvert_backend::settings::Settings;
use imgconvert_backend::{paths, write_journal};
use imgconvert_gpui::{init_app, open_blocked_window, open_main_window, probe_driver};
use imgconvert_gpui_shared::i18n::Locale;
use imgconvert_gpui_shared::{SettingsModel, perf_probe, services};
Expand Down Expand Up @@ -56,6 +56,11 @@ fn main() {
return;
}
};
// Before any conversion and while holding the marker, so every
// journal found belongs to a process that has ended.
if instance_lock.is_some() {
recover_interrupted_writes();
}
cx.set_global(HeldInstanceLock(instance_lock));
init_app(cx);
match open_main_window(cx) {
Expand All @@ -71,6 +76,33 @@ fn main() {
});
}

/// Resolves output writes a previous run left unfinished (a forced quit, a
/// crash) and starts this run's write journal.
fn recover_interrupted_writes() {
let Some(dir) = paths::app_data_dir().map(|dir| dir.join(write_journal::JOURNAL_DIR_NAME))
else {
return;
};
match write_journal::recover_and_install(&dir) {
Ok(report) => {
for path in &report.restored {
eprintln!(
"imgconvert: restored the previous output {}",
path.display()
);
}
if !report.removed.is_empty() || report.retained > 0 {
eprintln!(
"imgconvert: removed {} leftover file(s) of interrupted writes; {} kept for later",
report.removed.len(),
report.retained
);
}
}
Err(error) => eprintln!("imgconvert: cannot start the write journal: {error}"),
}
}

/// Takes the single-instance marker. Without a data directory or on an I/O
/// failure other than contention the shell still starts (and settings then
/// cannot be saved either, which the panel reports).
Expand Down
13 changes: 13 additions & 0 deletions apps/gpui/crates/workflow/src/workflow_panel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ impl WorkflowPanel {
self.notice = None;
}
self.output_session_grant = Some(dir.clone());
retry_interrupted_writes(cx);
let dir = dir.to_string_lossy().into_owned();
self.settings.update(cx, |settings, cx| {
settings.update(cx, |settings| settings.out_dir = Some(dir));
Expand Down Expand Up @@ -255,6 +256,7 @@ impl WorkflowPanel {
if self.planning {
return;
}
retry_interrupted_writes(cx);
let access = imgconvert_backend::access::runtime_file_access();
if let Some(dir) = self.output_dir(cx).filter(|dir| {
output_grant_valid(
Expand Down Expand Up @@ -677,6 +679,17 @@ pub fn build_options(
)
}

/// Retries what startup recovery had to leave unresolved: a folder grant
/// (the Mac App Store sandbox keeps no access across launches) or a volume
/// mounted again may make it reachable. Runs only while no batch can write,
/// on this thread, so it never races an output write. It reads the journal
/// folder and, almost always, finds nothing to do.
fn retry_interrupted_writes(cx: &App) {
if !progress_bridge::is_busy(cx) {
imgconvert_backend::write_journal::retry_retained();
}
}

#[cfg(test)]
mod tests {
#[test]
Expand Down
29 changes: 25 additions & 4 deletions crates/imgconvert-backend/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ use crate::pdf;
pub use crate::pdf::PdfConvertOptions;
use crate::progress::{BatchId, ProgressSink};
use crate::result_cache;
use crate::write_journal;
use imgconvert_platform::{atomic_output, external_codecs};

static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
Expand Down Expand Up @@ -1229,6 +1230,7 @@ fn temp_file(out: &Path) -> Result<(PathBuf, File), ConversionError> {
.map(|duration| duration.as_nanos())
.unwrap_or(0);
let tmp = parent.join(format!(".imgconvert-{pid}-{nanos}-{counter}.tmp"));
write_journal::note_tmp(&tmp);
match OpenOptions::new().write(true).create_new(true).open(&tmp) {
Ok(file) => return Ok((tmp, file)),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Expand All @@ -1248,10 +1250,15 @@ fn write_output(
fs::create_dir_all(parent).map_err(|e| output_io_error("无法创建输出目录", out, &e))?;
}

match mode {
let _op = write_journal::Op::start();
let result = match mode {
WriteMode::Replace => replace_output(out, bytes),
WriteMode::CreateNew => write_new_output(out, bytes),
};
if let Some(parent) = out.parent() {
write_journal::sync_dir(parent);
}
result
}

fn write_temp_output(out: &Path, bytes: &[u8]) -> Result<PathBuf, ConversionError> {
Expand Down Expand Up @@ -1310,6 +1317,12 @@ where
let cleanup = cleanup_partial_note(tmp);
error.append(&cleanup)
})?;
if let Err(error) = write_journal::note_backup(out, &backup) {
// Never stage the previous output where nothing records it.
let cleanup = cleanup_partial_note(tmp);
let detail = output_io_error("无法记录写入日志", out, &error);
return Err(detail.append(&cleanup));
}
if let Err(error) = rename(out, &backup) {
if error.kind() == std::io::ErrorKind::NotFound {
// The destination disappeared after the initial replacement attempt. It is now safe
Expand All @@ -1336,7 +1349,11 @@ where
let detail = output_io_error("无法写入输出文件", out, &rename_error);
match rename(&backup, out) {
Ok(()) => Err(detail.append(&format!("; 原文件已恢复{cleanup}"))),
Err(restore_error) => Err(detail.append(&format!(
Err(restore_error) => Err({
write_journal::retain_current();
detail
}
.append(&format!(
"; 无法恢复原文件,备份位于 {}: {restore_error}{cleanup}",
backup.display()
))),
Expand Down Expand Up @@ -1441,8 +1458,12 @@ fn write_new_output(out: &Path, bytes: &[u8]) -> Result<Option<ConvertWarning>,
Ok(atomic_output::Committed {
leftover_temp: Some(_),
..
}) => Ok(Some(ConvertWarning::TemporaryFileRetained {
path: tmp.to_string_lossy().to_string(),
}) => Ok(Some({
// The next start removes the leftover link.
write_journal::retain_current();
ConvertWarning::TemporaryFileRetained {
path: tmp.to_string_lossy().to_string(),
}
})),
Err(error) => {
let detail = conversion_error_for_commit(out, &error);
Expand Down
1 change: 1 addition & 0 deletions crates/imgconvert-backend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub mod progress;
pub mod result_cache;
pub mod service;
pub mod thumbnail;
pub mod write_journal;

/// Settings persistence, per-channel paths and the single-instance marker
/// live in the platform crate; shells reach them through this facade.
Expand Down
Loading
Loading