-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfalse
More file actions
653 lines (597 loc) · 25.2 KB
/
Copy pathfalse
File metadata and controls
653 lines (597 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
use std::path::{Path, PathBuf};
use std::thread;
use std::time::Instant;
use std::io::Read;
use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use crossbeam_channel::{bounded, Receiver, Sender};
use crate::action::{CollisionPolicy, FileOperation, RefreshTarget};
use crate::fs::{
copy_path_with_progress, count_path_entries, create_directory, create_file, delete_path,
looks_like_binary, rename_path, trash_path, EntryInfo, FileSystemError,
backend::FsBackend, local::LocalBackend,
};
use crate::pane::PaneId;
// ---------------------------------------------------------------------------
// Public request types — one per worker
// ---------------------------------------------------------------------------
#[derive(Clone, Debug)]
pub struct ArchiveListRequest {
pub pane: PaneId,
pub archive_path: PathBuf,
pub inner_path: PathBuf, // for navigating inside nested directories in the archive
}
#[derive(Clone, Debug)]
pub struct ScanRequest {
pub pane: PaneId,
pub path: PathBuf,
}
#[derive(Clone, Debug)]
pub struct FileOpRequest {
pub operation: FileOperation,
pub refresh: Vec<RefreshTarget>,
pub collision: CollisionPolicy,
}
#[derive(Clone, Debug)]
pub struct PreviewRequest {
pub path: PathBuf,
pub syntect_theme: String,
pub archive: Option<PathBuf>,
pub inner_path: Option<PathBuf>,
}
#[derive(Clone, Debug)]
pub struct EditorLoadRequest {
pub path: PathBuf,
}
#[derive(Clone, Debug)]
pub struct GitStatusRequest {
pub pane: PaneId,
pub path: PathBuf,
}
#[derive(Clone, Debug)]
pub struct FindRequest {
pub pane: PaneId,
pub root: PathBuf,
pub max_depth: usize,
}
#[derive(Clone, Debug)]
pub struct WatchRequest {
pub paths: Vec<PathBuf>,
}
// ---------------------------------------------------------------------------
// Result types (unchanged public surface)
// ---------------------------------------------------------------------------
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum JobResult {
DirectoryScanned {
pane: PaneId,
path: PathBuf,
entries: Vec<EntryInfo>,
elapsed_ms: u128,
},
ArchiveListed {
pane: PaneId,
archive_path: PathBuf,
inner_path: PathBuf,
entries: Vec<EntryInfo>,
elapsed_ms: u128,
},
FileOperationCompleted {
message: String,
refreshed: Vec<RefreshedPane>,
elapsed_ms: u128,
},
FileOperationCollision {
operation: FileOperation,
refresh: Vec<RefreshTarget>,
path: PathBuf,
elapsed_ms: u128,
},
FileOperationProgress {
status: FileOperationStatus,
},
JobFailed {
pane: PaneId,
path: PathBuf,
message: String,
elapsed_ms: u128,
},
PreviewLoaded {
path: PathBuf,
view: crate::preview::ViewBuffer,
},
EditorLoaded {
path: PathBuf,
contents: String,
},
EditorLoadFailed {
path: PathBuf,
message: String,
},
/// Git status fetched successfully for a pane's working directory.
GitStatusLoaded {
pane: PaneId,
status: crate::git::RepoStatus,
},
/// The path is not inside a git repository (or git is not available).
GitStatusAbsent {
pane: PaneId,
},
FindResults {
pane: PaneId,
root: PathBuf,
entries: Vec<PathBuf>,
},
DirectoryChanged {
path: PathBuf,
},
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RefreshedPane {
pub pane: PaneId,
pub path: PathBuf,
pub entries: Vec<EntryInfo>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FileOperationStatus {
pub operation: &'static str,
pub completed: u64,
pub total: u64,
pub current_path: PathBuf,
}
// ---------------------------------------------------------------------------
// Worker channels
// ---------------------------------------------------------------------------
/// Three typed senders — one per dedicated worker thread.
pub struct WorkerChannels {
pub scan_tx: Sender<ScanRequest>,
pub file_op_tx: Sender<FileOpRequest>,
pub preview_tx: Sender<PreviewRequest>,
pub editor_tx: Sender<EditorLoadRequest>,
pub git_tx: Sender<GitStatusRequest>,
pub find_tx: Sender<FindRequest>,
pub watch_tx: Sender<WatchRequest>,
pub archive_tx: Sender<ArchiveListRequest>,
}
/// Spawn three dedicated background workers that all fan results into a single
/// `Receiver<JobResult>`. Each worker processes its queue sequentially; because
/// the queues are independent, a slow file operation never delays a scan.
pub fn spawn_workers() -> (WorkerChannels, Receiver<JobResult>) {
let (result_tx, result_rx) = bounded::<JobResult>(64);
// --- Scan worker ---
let (scan_tx, scan_rx) = bounded::<ScanRequest>(16);
{
let result_tx = result_tx.clone();
thread::Builder::new()
.name("zeta-scan".into())
.spawn(move || {
for req in scan_rx {
let started_at = Instant::now();
let backend = LocalBackend;
let job_result = match backend.scan_directory(&req.path) {
Ok(entries) => JobResult::DirectoryScanned {
pane: req.pane,
path: req.path,
entries,
elapsed_ms: started_at.elapsed().as_millis(),
},
Err(err) => JobResult::JobFailed {
pane: req.pane,
path: req.path,
message: err.to_string(),
elapsed_ms: started_at.elapsed().as_millis(),
},
};
if result_tx.send(job_result).is_err() {
break;
}
}
})
.expect("failed to spawn scan worker");
}
// --- File operation worker ---
let (file_op_tx, file_op_rx) = bounded::<FileOpRequest>(8);
{
let result_tx = result_tx.clone();
thread::Builder::new()
.name("zeta-file-op".into())
.spawn(move || {
for req in file_op_rx {
let outcome = run_file_operation(
req.operation,
req.refresh,
req.collision,
&result_tx,
);
let job_result = match outcome {
Ok(r) | Err(r) => r,
};
if result_tx.send(job_result).is_err() {
break;
}
}
})
.expect("failed to spawn file-op worker");
}
// --- Preview worker ---
let (preview_tx, preview_rx) = bounded::<PreviewRequest>(8);
{
let result_tx_preview = result_tx.clone();
thread::Builder::new()
.name("zeta-preview".into())
.spawn(move || {
for req in preview_rx {
let view = if req.archive.is_none() {
load_preview_content(&req.path, &req.syntect_theme)
} else if let (Some(archive_path), Some(inner_path)) = (req.archive.clone(), req.inner_path.clone()) {
// Attempt to extract single file from archive into memory
match std::fs::File::open(&archive_path) {
Ok(f) => {
let name = archive_path.file_name().and_then(|s| s.to_str()).unwrap_or("").to_lowercase();
if name.ends_with(".zip") {
match zip::ZipArchive::new(f) {
Ok(mut za) => {
let inner_name = inner_path.to_string_lossy();
match za.by_name(&inner_name) {
Ok(mut entry) => {
let mut buf = Vec::new();
use std::io::Read;
let _ = entry.read_to_end(&mut buf);
load_preview_from_bytes(&buf, &inner_path, &req.syntect_theme)
}
Err(_) => crate::preview::ViewBuffer::from_plain("[empty file]"),
}
}
Err(_) => crate::preview::ViewBuffer::from_plain("[empty file]"),
}
} else {
// Try tar variants with decompression based on extension
let archive_reader: Box<dyn std::io::Read> = if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
Box::new(flate2::read::GzDecoder::new(f))
} else if name.ends_with(".tar.bz2") || name.ends_with(".tbz2") {
Box::new(bzip2::read::BzDecoder::new(f))
} else if name.ends_with(".tar.xz") || name.ends_with(".txz") {
Box::new(xz2::read::XzDecoder::new(f))
} else {
Box::new(f)
};
let mut ar = tar::Archive::new(archive_reader);
let mut found = None;
if let Ok(entries) = ar.entries() {
for mut e in entries.flatten() {
if let Ok(path) = e.path() {
if path == inner_path {
let mut buf = Vec::new();
let _ = e.read_to_end(&mut buf);
found = Some(buf);
break;
}
}
}
}
if let Some(buf) = found { load_preview_from_bytes(&buf, &inner_path, &req.syntect_theme) } else { crate::preview::ViewBuffer::from_plain("[empty file]") }
}
}
Err(_) => crate::preview::ViewBuffer::from_plain("[empty file]"),
}
} else {
load_preview_content(&req.path, &req.syntect_theme)
};
if result_tx_preview
.send(JobResult::PreviewLoaded { path: req.path, view })
.is_err()
{
break;
}
}
})
.expect("failed to spawn preview worker");
}
// --- Editor load worker ---
let (editor_tx, editor_rx) = bounded::<EditorLoadRequest>(4);
{
let result_tx_editor = result_tx.clone();
thread::Builder::new()
.name("zeta-editor-load".into())
.spawn(move || {
for req in editor_rx {
let result = match std::fs::read(&req.path) {
Ok(bytes) => JobResult::EditorLoaded {
path: req.path,
contents: String::from_utf8_lossy(&bytes).into_owned(),
},
Err(error) => JobResult::EditorLoadFailed {
path: req.path,
message: error.to_string(),
},
};
if result_tx_editor.send(result).is_err() {
break;
}
}
})
.expect("failed to spawn editor load worker");
}
// --- Git status worker ---
let (git_tx, git_rx) = bounded::<GitStatusRequest>(16);
{
let result_tx = result_tx.clone();
thread::Builder::new()
.name("zeta-git".into())
.spawn(move || {
for req in git_rx {
let result = match crate::git::fetch_status(&req.path) {
Some(status) => JobResult::GitStatusLoaded { pane: req.pane, status },
None => JobResult::GitStatusAbsent { pane: req.pane },
};
if result_tx.send(result).is_err() {
break;
}
}
})
.expect("failed to spawn git worker");
}
// --- Finder worker ---
let (find_tx, find_rx) = bounded::<FindRequest>(8);
{
let result_tx = result_tx.clone();
thread::Builder::new()
.name("zeta-find".into())
.spawn(move || {
for req in find_rx {
let entries = walk_for_files(&req.root, req.max_depth);
if result_tx
.send(JobResult::FindResults {
pane: req.pane,
root: req.root,
entries,
})
.is_err()
{
break;
}
}
})
.expect("failed to spawn finder worker");
}
// --- Watcher worker ---
let (watch_tx, watch_rx) = bounded::<WatchRequest>(8);
{
let result_tx = result_tx.clone();
thread::Builder::new()
.name("zeta-watch".into())
.spawn(move || run_watcher_worker(watch_rx, result_tx))
.expect("failed to spawn watcher worker");
}
// --- Archive worker ---
let (archive_tx, archive_rx) = bounded::<ArchiveListRequest>(4);
{
let result_tx = result_tx.clone();
thread::Builder::new()
.name("zeta-archive".into())
.spawn(move || {
for req in archive_rx {
let started_at = std::time::Instant::now();
let archive_path = req.archive_path.clone();
// Try ZIP first (open a fresh file handle by path).
if let Ok(zip_file) = std::fs::File::open(&archive_path) {
if let Ok(mut archive) = zip::ZipArchive::new(zip_file) {
let mut seen = std::collections::BTreeSet::new();
let mut entries: Vec<EntryInfo> = Vec::new();
let inner = req.inner_path.to_string_lossy().replace("\\", "/");
let prefix = if inner.is_empty() { String::new() } else if inner.ends_with('/') { inner.clone() } else { format!("{}/", inner) };
for i in 0..archive.len() {
if let Ok(file) = archive.by_index(i) {
let name = file.name().to_string();
let rest = if prefix.is_empty() { name.as_str() } else if name.starts_with(&prefix) { &name[prefix.len()..] } else { continue };
if rest.is_empty() { continue; }
let first = rest.split('/').next().unwrap().to_string();
if !seen.insert(first.clone()) { continue; }
let is_dir = rest.contains('/') || name.ends_with('/');
let kind = if is_dir { crate::fs::EntryKind::Directory } else { crate::fs::EntryKind::File };
let size_bytes = if kind == crate::fs::EntryKind::File { Some(file.size()) } else { None };
entries.push(EntryInfo { name: first.clone(), path: archive_path.join(first), kind, size_bytes, modified: None });
}
}
entries.sort_by(|l, r| l.kind.cmp(&r.kind).then_with(|| l.name.to_lowercase().cmp(&r.name.to_lowercase())));
let _ = result_tx.send(JobResult::ArchiveListed {
pane: req.pane,
archive_path: archive_path.clone(),
inner_path: req.inner_path,
entries,
elapsed_ms: started_at.elapsed().as_millis(),
});
continue; // done for this request
}
}
// Fall back to tar variants (plain tar, tar.gz, tar.bz2, tar.xz).
let ext_name = archive_path.file_name().and_then(|s| s.to_str()).unwrap_or("").to_lowercase();
let tar_file = match std::fs::File::open(&archive_path) {
Ok(f) => f,
Err(err) => {
let _ = result_tx.send(JobResult::JobFailed {
pane: req.pane,
path: archive_path,
message: format!("failed to open archive: {err}"),
elapsed_ms: started_at.elapsed().as_millis(),
});
continue;
}
};
let reader: Box<dyn std::io::Read> = if ext_name.ends_with(".tar.gz") || ext_name.ends_with(".tgz") {
Box::new(flate2::read::GzDecoder::new(tar_file))
} else if ext_name.ends_with(".tar.bz2") || ext_name.ends_with(".tbz2") {
Box::new(bzip2::read::BzDecoder::new(tar_file))
} else if ext_name.ends_with(".tar.xz") || ext_name.ends_with(".txz") {
Box::new(xz2::read::XzDecoder::new(tar_file))
} else {
Box::new(tar_file)
};
let mut ar = tar::Archive::new(reader);
let mut seen = std::collections::BTreeSet::new();
let mut entries: Vec<EntryInfo> = Vec::new();
let inner = req.inner_path.to_string_lossy().replace("\\", "/");
let prefix = if inner.is_empty() { String::new() } else if inner.ends_with('/') { inner.clone() } else { format!("{}/", inner) };
if let Ok(entries_iter) = ar.entries() {
for entry in entries_iter.flatten() {
if let Ok(path) = entry.path() {
let name = path.to_string_lossy().to_string();
let rest = if prefix.is_empty() { name.as_str() } else if name.starts_with(&prefix) { &name[prefix.len()..] } else { continue };
if rest.is_empty() { continue; }
let first = rest.split('/').next().unwrap().to_string();
if !seen.insert(first.clone()) { continue; }
let is_dir = rest.contains('/');
let kind = if is_dir { crate::fs::EntryKind::Directory } else { crate::fs::EntryKind::File };
let size_bytes = if kind == crate::fs::EntryKind::File { Some(entry.size()) } else { None };
entries.push(EntryInfo { name: first.clone(), path: archive_path.join(first), kind, size_bytes, modified: None });
}
}
}
entries.sort_by(|l, r| l.kind.cmp(&r.kind).then_with(|| l.name.to_lowercase().cmp(&r.name.to_lowercase())));
let _ = result_tx.send(JobResult::ArchiveListed {
pane: req.pane,
archive_path,
inner_path: req.inner_path,
entries,
elapsed_ms: started_at.elapsed().as_millis(),
});
}
})
.expect("failed to spawn archive worker");
}
(
WorkerChannels {
scan_tx,
file_op_tx,
preview_tx,
editor_tx,
git_tx,
find_tx,
watch_tx,
archive_tx,
},
result_rx,
)
}
// ---------------------------------------------------------------------------
// Internal worker logic
// ---------------------------------------------------------------------------
fn run_watcher_worker(watch_rx: Receiver<WatchRequest>, result_tx: Sender<JobResult>) {
use std::sync::mpsc;
let (notify_tx, notify_rx) = mpsc::channel();
let mut watcher = RecommendedWatcher::new(notify_tx, Config::default())
.expect("failed to create filesystem watcher");
let mut watched_paths: Vec<PathBuf> = Vec::new();
loop {
while let Ok(req) = watch_rx.try_recv() {
for path in &watched_paths {
let _ = watcher.unwatch(path);
}
watched_paths.clear();
for path in req.paths {
if watched_paths.iter().all(|p| p != &path)
&& watcher.watch(&path, RecursiveMode::NonRecursive).is_ok()
{
watched_paths.push(path);
}
}
}
while let Ok(event_result) = notify_rx.try_recv() {
let Ok(event) = event_result else {
continue;
};
for path in event.paths {
let changed_dir = if path.is_dir() {
path
} else {
path.parent().map(Path::to_path_buf).unwrap_or(path)
};
if result_tx
.send(JobResult::DirectoryChanged { path: changed_dir })
.is_err()
{
return;
}
}
}
std::thread::sleep(std::time::Duration::from_millis(200));
}
}
fn walk_for_files(root: &Path, max_depth: usize) -> Vec<PathBuf> {
let mut results = Vec::new();
walk_recursive(root, max_depth, &mut results);
results
}
fn walk_recursive(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
if depth == 0 {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if name.starts_with('.') || matches!(name, "target" | "node_modules" | "__pycache__" | ".git") {
continue;
}
if path.is_dir() {
walk_recursive(&path, depth - 1, out);
} else {
out.push(path);
}
}
}
fn load_preview_content(path: &Path, syntect_theme: &str) -> crate::preview::ViewBuffer {
let bytes = match std::fs::read(path) {
Ok(b) => b,
Err(_) => return crate::preview::ViewBuffer::from_plain("[empty file]"),
};
load_preview_from_bytes(&bytes, path, syntect_theme)
}
fn load_preview_from_bytes(bytes: &[u8], path: &Path, syntect_theme: &str) -> crate::preview::ViewBuffer {
if bytes.is_empty() {
return crate::preview::ViewBuffer::from_plain("[empty file]");
}
if looks_like_binary(bytes) {
let size_bytes = std::fs::metadata(path)
.map(|m| m.len())
.unwrap_or(bytes.len() as u64);
let label = format!("[binary file — {size_bytes} bytes]");
return crate::preview::ViewBuffer::from_plain(&label);
}
let text = String::from_utf8_lossy(bytes);
let extension = path.extension().and_then(|e| e.to_str());
// Markdown: store raw text for AST rendering at display time.
if extension == Some("md") {
return crate::preview::ViewBuffer::from_markdown(text.into_owned());
}
if let Some(lines) = crate::highlight::highlight_text(&text, extension, syntect_theme) {
return crate::preview::ViewBuffer::from_highlighted(lines);
}
// Fallback: truncate to 200 lines, capped at 200 × 80 chars.
let truncated: String = text
.lines()
.take(200)
.collect::<Vec<_>>()
.join("\n")
.chars()
.take(200 * 80)
.collect();
crate::preview::ViewBuffer::from_plain(&truncated)
}
#[allow(clippy::result_large_err)]
fn run_file_operation(
operation: FileOperation,
refresh: Vec<RefreshTarget>,
collision: CollisionPolicy,
result_tx: &Sender<JobResult>,
) -> Result<JobResult, JobResult> {
let started_at = Instant::now();
let operation = req.operation;
let refresh = req.refresh;
let collision = req.collision;</parameter
let primary_path = primary_path(&operation);
let failure_pane = refresh
.first()
.map(|target| target.pane)
.unwrap_or(PaneId::Left);