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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
|
//! `CompState` glue for desktop icons - open/rescan/select/drag/persist,
//! plus the right-click `DesktopMenu`'s own open/close/run-action. Same
//! shape as `state/menu.rs`'s `ContextMenu`/`SnapFlyout` glue.
use super::*;
use crate::desktop_icons::{DesktopIcons, IconKind, CELL_HEIGHT, CELL_WIDTH, GRID_MARGIN};
use crate::desktop_menu::{DesktopMenu, DesktopMenuAction};
/// Common terminal binaries tried, in order, when `general.terminal` is
/// unset - first one actually found on `$PATH` wins. There's no `xdg-
/// open`-equivalent dispatcher for "a shell" the way there is for a file,
/// so unlike `file_manager`'s empty-means-`xdg-open` fallback, this needs
/// a real candidate list.
const TERMINAL_CANDIDATES: &[&str] = &["alacritty", "kitty", "wezterm", "foot", "gnome-terminal", "konsole", "xterm"];
/// The hand-drawn glyphs' base colour - a dedicated, deliberately blue
/// tone, not read from `theme.titlebar_fg_focused` (that field is
/// whatever the user's own titlebar accent happens to be, which could be
/// any colour at all depending on their config; these glyphs want a
/// consistent, recognisable icon palette of their own, matching the
/// "slightly blue, polished look" requested directly, independent of
/// theme). `decoration::render_desktop_icon` derives a lighter top tone
/// and a darker outline/detail tone from this one value via `color::
/// brighten`/`darken`, the same directional-shading helpers the titlebar
/// buttons already use.
const ICON_COLOR: (u8, u8, u8) = (74, 144, 226);
impl CompState {
/// Populates `self.desktop_icons` on first call, then keeps its
/// `origin` continuously re-anchored to the primary monitor's own
/// *current* usable geometry on every later call - cheap enough
/// (one tuple comparison) to run unconditionally at the top of every
/// render pass. Does nothing at all when the config flag is off.
///
/// The re-anchoring is the fix for a real, reported bug: this used to
/// return immediately once `self.desktop_icons` was `Some`, computing
/// `origin` exactly once, on whichever render pass happened to be
/// first. AGS's own top bar registers its exclusive zone (`general.
/// desktop_icons`' fix's own PR: `srd monitors`, `Monitor::geometry`
/// already excludes it) only once that separate client has connected
/// and committed - reliably *after* this compositor's own first
/// render pass, confirmed live via a temporary diagnostic log: origin
/// baked in at `(1936, 16)` (bar not yet registered, `geometry.y` was
/// still `0`) and never moved again even once `srd monitors` reported
/// the bar's real 34-40px reservation moments later - reported live
/// as "Home is still being overlapped by AGS's top bar." Re-deriving
/// `origin` every call (not rebuilding the icon list - render
/// position reads `origin` fresh at push time, never baked into a
/// cached glyph buffer) closes this permanently, for the bar, a dock
/// on any edge, or any later exclusive-zone change alike.
pub(crate) fn ensure_desktop_icons(&mut self) {
if !self.wm.borrow().desktop_icons_enabled {
return;
}
let origins = self.desktop_icon_origins();
if origins.is_empty() {
return;
}
// Rows (for the default-cell-assignment grid) are always derived
// from the *primary* monitor's own height, even when mirroring onto
// every monitor - one shared cell layout for the shared icon list,
// not a different grid shape per monitor.
let rows_source = self.wm.borrow().monitors().iter().find(|m| m.primary).map(|m| m.geometry.height as i32).unwrap_or(600);
if let Some(icons) = &mut self.desktop_icons {
icons.origins = origins;
return;
}
let rows = ((rows_source - 2 * GRID_MARGIN) / CELL_HEIGHT).max(1);
let saved = crate::desktop_icons_state::load();
let icons = crate::desktop_icons::rescan(&saved, rows);
self.desktop_icons = Some(DesktopIcons { origins, icons });
self.desktop_icon_buffers.clear();
}
/// One grid origin per monitor icons should mirror onto: every enabled
/// monitor when `general.desktop_icons_all_monitors` is on (the
/// default - see that field's own doc comment), otherwise just the
/// primary monitor's, matching the original single-monitor behaviour.
/// Sorted by monitor id so the list (and therefore which origin
/// `icon_at` matches first) is stable call to call, not at the mercy of
/// `WindowManager::monitors()`'s own iteration order.
fn desktop_icon_origins(&self) -> Vec<(i32, i32)> {
let wm = self.wm.borrow();
let mut monitors = wm.monitors().to_vec();
monitors.sort_by_key(|m| m.id);
if wm.desktop_icons_all_monitors {
monitors.iter().map(|m| (m.geometry.x + GRID_MARGIN, m.geometry.y + GRID_MARGIN)).collect()
} else {
monitors.iter().find(|m| m.primary).map(|m| vec![(m.geometry.x + GRID_MARGIN, m.geometry.y + GRID_MARGIN)]).unwrap_or_default()
}
}
/// Re-derives the icon list from the real filesystem (a new/removed
/// `~/Desktop` entry) without disturbing any already-persisted cell --
/// `rescan` itself already only assigns a fresh default cell to an
/// icon `saved` has no entry for.
pub(crate) fn refresh_desktop_icons(&mut self) {
let Some(icons) = &self.desktop_icons else { return };
let rows = ((self.primary_monitor_height()) / CELL_HEIGHT).max(1);
let saved = crate::desktop_icons_state::load();
let origins = icons.origins.clone();
let icons = crate::desktop_icons::rescan(&saved, rows);
self.desktop_icons = Some(DesktopIcons { origins, icons });
self.desktop_icon_buffers.clear();
}
fn primary_monitor_height(&self) -> i32 {
self.wm.borrow().monitors().iter().find(|m| m.primary).map(|m| m.geometry.height as i32 - 2 * GRID_MARGIN).unwrap_or(600)
}
/// Rasterises (or re-rasterises) one icon's buffer - called whenever
/// that icon's selection state or drag position changes, never per
/// frame; `render_udev_frame`/`render_frame` just read whatever's
/// already cached here.
fn rebuild_icon_buffer(&mut self, id: &str) {
let Some(icons) = &self.desktop_icons else { return };
let Some(icon) = icons.icons.iter().find(|i| i.id == id) else { return };
let theme = self.wm.borrow().theme;
let label_color = (240, 240, 240);
// While this exact icon is mid-rename, show the live-edited buffer
// (with a trailing caret) instead of its real, on-disk label - so
// typing is visible without touching the filesystem until Enter
// actually commits it (`desktop_icon_rename_key`).
let label: std::borrow::Cow<str> = match &self.renaming_icon {
Some((rid, buf)) if rid == id => format!("{buf}_").into(),
_ => icon.label.as_str().into(),
};
// Real icon-theme artwork (WhiteSur, or whatever the user has
// configured) when it resolves; `None` - no installed theme ships
// this name, or the file it found didn't parse/render - falls
// back to `render_desktop_icon`'s own hand-drawn glyph rather than
// a blank box. Re-looked-up on every rebuild (icon selection
// toggling, a rename) rather than cached separately: rebuilds are
// already infrequent (see this function's own doc comment), and a
// theme change while running should just work on the next one
// without a separate cache-invalidation path to get wrong.
let glyph_box = decoration::desktop_icon_glyph_box(CELL_WIDTH as u32, CELL_HEIGHT as u32);
let (glyph_w, glyph_h) = ((glyph_box.2 - glyph_box.0).max(1) as u32, (glyph_box.3 - glyph_box.1).max(1) as u32);
let real_icon = crate::icon_theme::find_icon(crate::icon_theme::icon_name(icon.kind))
.and_then(|path| crate::icon_theme::rasterize_svg(&path, glyph_w, glyph_h));
let data = decoration::render_desktop_icon(
CELL_WIDTH as u32,
CELL_HEIGHT as u32,
icon.kind,
&label,
icon.selected,
ICON_COLOR,
label_color,
theme.default_border_color,
real_icon.as_deref(),
);
let buffer = MemoryRenderBuffer::from_slice(&data, Fourcc::Argb8888, (CELL_WIDTH, CELL_HEIGHT), 1, Transform::Normal, None);
self.desktop_icon_buffers.insert(id.to_string(), buffer);
}
fn icon_buffer(&mut self, id: &str) -> Option<&MemoryRenderBuffer> {
if !self.desktop_icon_buffers.contains_key(id) {
self.rebuild_icon_buffer(id);
}
self.desktop_icon_buffers.get(id)
}
/// Every `(position, buffer)` pair the render loop needs to push this
/// frame - lazily rebuilds any icon whose buffer isn't cached yet
/// (a fresh icon, or one whose selection/drag state just changed),
/// then returns everything already up to date. Global-space positions;
/// the caller subtracts its own head origin, same as every other
/// `custom_elements` push site.
pub(crate) fn desktop_icon_render_list(&mut self) -> Vec<((i32, i32), MemoryRenderBuffer)> {
let Some(icons) = &self.desktop_icons else { return Vec::new() };
let ids: Vec<String> = icons.icons.iter().map(|i| i.id.clone()).collect();
let origins = icons.origins.clone();
let dragging = self.desktop_icon_drag.clone();
let mut out = Vec::with_capacity(ids.len() * origins.len());
for id in ids {
let buffer = match self.icon_buffer(&id) {
Some(b) => b.clone(),
None => continue,
};
let icons = self.desktop_icons.as_ref().unwrap();
let icon = icons.icons.iter().find(|i| i.id == id).unwrap();
// The dragged copy follows the live pointer on whichever
// monitor it's actually being dragged over; every other
// mirror (if any) stays put at its own origin's cell position
// - dragging on one monitor doesn't yank the icon's other
// mirrors around mid-gesture, only the one actually grabbed.
match &dragging {
Some((drag_id, _, live_pos)) if *drag_id == id => out.push((*live_pos, buffer)),
_ => {
for &origin in &origins {
out.push((icon.top_left(origin), buffer.clone()));
}
}
}
}
out
}
/// Selects `id` (deselecting whatever was selected before, if
/// anything) - both buffers rebuilt only if their selection state
/// actually changed, not unconditionally.
pub(crate) fn select_desktop_icon(&mut self, id: Option<&str>) {
let Some(icons) = &mut self.desktop_icons else { return };
let mut changed = Vec::new();
for icon in &mut icons.icons {
let should = Some(icon.id.as_str()) == id;
if icon.selected != should {
icon.selected = should;
changed.push(icon.id.clone());
}
}
for id in changed {
self.rebuild_icon_buffer(&id);
}
}
/// Starts a rubber-band selection at `pos` (global space) - clears
/// whatever was selected before, matching real desktop convention
/// (Windows/GNOME/macOS all start a fresh marquee selection, not an
/// additive one, unless a modifier like Ctrl/Shift is held - not
/// implemented here, same as this menu's own already-documented "no
/// multi-select via click" gap, just now closed for the drag case).
pub(crate) fn start_desktop_marquee(&mut self, pos: (i32, i32)) {
self.select_desktop_icon(None);
self.desktop_marquee = Some((pos, pos));
}
/// Updates the live end corner of an in-progress marquee and re-
/// selects whatever icon cells the resulting rectangle now overlaps --
/// called from every pointer-motion event while a marquee is active,
/// same shape as `update_desktop_icon_drag`.
pub(crate) fn update_desktop_marquee(&mut self, pos: (i32, i32)) {
let Some((start, _)) = self.desktop_marquee else { return };
self.desktop_marquee = Some((start, pos));
let (x0, y0) = (start.0.min(pos.0), start.1.min(pos.1));
let (x1, y1) = (start.0.max(pos.0), start.1.max(pos.1));
// Only the mirror on whichever monitor the marquee itself *started*
// on - a drag on one monitor selecting another monitor's mirrored
// copies (or double-selecting both) would be actively confusing,
// not a feature. Falls back to every origin if no monitor claims
// the start point at all (shouldn't happen in practice; `Compositor
// ::pointer_monitor`-style clamping already keeps the pointer
// inside some monitor's bounds).
let origins: Vec<(i32, i32)> = {
let wm = self.wm.borrow();
match wm.monitors().iter().find(|m| m.full_geometry.contains_point(start.0, start.1)) {
Some(m) => vec![(m.geometry.x + GRID_MARGIN, m.geometry.y + GRID_MARGIN)],
None => self.desktop_icons.as_ref().map(|i| i.origins.clone()).unwrap_or_default(),
}
};
let Some(icons) = &mut self.desktop_icons else { return };
let mut changed = Vec::new();
for icon in &mut icons.icons {
let overlaps = origins.iter().any(|&origin| {
let (left, top) = icon.top_left(origin);
let (right, bottom) = (left + CELL_WIDTH, top + CELL_HEIGHT);
left < x1 && right > x0 && top < y1 && bottom > y0
});
if icon.selected != overlaps {
icon.selected = overlaps;
changed.push(icon.id.clone());
}
}
for id in changed {
self.rebuild_icon_buffer(&id);
}
}
/// Ends an in-progress marquee, if any - the final `update_desktop_
/// marquee` call already left the right icons selected, so this only
/// needs to clear the drag state itself (and the rendered outline with
/// it).
pub(crate) fn end_desktop_marquee(&mut self) {
self.desktop_marquee = None;
}
/// True when this press is the second of a double-click on the same
/// icon - same 400ms threshold and reset-after-a-double shape as
/// `is_double_click`, keyed by `DesktopIcon::id` since an icon has no
/// `WindowId` of its own.
pub(crate) fn is_double_click_icon(&mut self, id: &str, time: u32) -> bool {
const DOUBLE_CLICK_MS: u32 = 400;
let doubled = match &self.last_icon_click {
Some((last_id, last_time)) => last_id == id && time.saturating_sub(*last_time) <= DOUBLE_CLICK_MS,
None => false,
};
self.last_icon_click = if doubled { None } else { Some((id.to_string(), time)) };
doubled
}
/// `origin` is whichever mirror was actually clicked (`icon_at`'s own
/// return value, threaded through by the caller) - with the icon
/// mirrored onto several monitors, grabbing it relative to the copy
/// under the pointer, not always the primary monitor's, is what makes
/// the drag track the cursor instead of jumping to a different
/// monitor's copy the instant the drag starts.
pub(crate) fn start_desktop_icon_drag(&mut self, id: &str, origin: (i32, i32), pointer: (i32, i32)) {
let Some(icons) = &self.desktop_icons else { return };
let Some(icon) = icons.icons.iter().find(|i| i.id == id) else { return };
let top_left = icon.top_left(origin);
let grab_offset = (pointer.0 - top_left.0, pointer.1 - top_left.1);
self.desktop_icon_drag = Some((id.to_string(), grab_offset, top_left));
}
/// Updates the live position of whichever icon is being dragged, if
/// any - called from every pointer-motion event, same as
/// `WindowManager::update_resize`'s own per-motion-event update.
pub(crate) fn update_desktop_icon_drag(&mut self, pointer: (i32, i32)) {
if let Some((_, grab_offset, live_pos)) = &mut self.desktop_icon_drag {
*live_pos = (pointer.0 - grab_offset.0, pointer.1 - grab_offset.1);
}
}
/// Ends an in-progress drag (if any): snaps to the nearest free grid
/// cell (occupied cells other than the dragged icon's own previous one
/// are avoided by walking outward from the raw target, closest first)
/// and persists it.
pub(crate) fn end_desktop_icon_drag(&mut self) {
let Some((id, _, live_pos)) = self.desktop_icon_drag.take() else { return };
// The cell math below needs the origin of whichever monitor the
// icon was actually dropped on, not always the first mirror --
// recomputed fresh (same formula `desktop_icon_origins` uses)
// rather than searched for in `icons.origins`, since a drop
// just past every monitor's own strict icon-grid rect (but still
// on-screen) should still resolve to that monitor's grid, not fall
// through to a stale/wrong one.
let origin = self
.wm
.borrow()
.monitors()
.iter()
.find(|m| m.full_geometry.contains_point(live_pos.0, live_pos.1))
.map(|m| (m.geometry.x + GRID_MARGIN, m.geometry.y + GRID_MARGIN))
.unwrap_or(self.desktop_icons.as_ref().map(|i| i.origins.first().copied().unwrap_or((0, 0))).unwrap_or((0, 0)));
let Some(icons) = &mut self.desktop_icons else { return };
let raw = (live_pos.0 - origin.0, live_pos.1 - origin.1);
let raw_cell = ((raw.0 as f64 / CELL_WIDTH as f64).round() as i32, (raw.1 as f64 / CELL_HEIGHT as f64).round() as i32).max_zero();
let occupied: std::collections::HashSet<(i32, i32)> = icons.icons.iter().filter(|i| i.id != id).map(|i| i.cell).collect();
let cell = nearest_free_cell(raw_cell, &occupied);
if let Some(icon) = icons.icons.iter_mut().find(|i| i.id == id) {
icon.cell = cell;
}
self.rebuild_icon_buffer(&id);
crate::desktop_icons_state::save_icon(&id, cell);
}
pub(crate) fn open_desktop_icon(&mut self, id: &str) {
let Some(icons) = &self.desktop_icons else { return };
let Some(icon) = icons.icons.iter().find(|i| i.id == id) else { return };
let target = icon.target.display().to_string();
let file_manager = self.wm.borrow().file_manager.clone();
if file_manager.is_empty() {
spawn_shell(&format!("xdg-open {}", shell_quote(&target)));
} else {
spawn_shell(&format!("{file_manager} {}", shell_quote(&target)));
}
}
/// Enters inline rename mode for `id`, pre-filled with its current
/// label - only ever called for a real file/folder icon (`desktop_
/// menu.rs`'s own `open_for_icon` never offers Rename for anything
/// else), but harmless if that assumption is ever wrong: `commit_
/// icon_rename` re-checks the icon's kind before touching the
/// filesystem.
pub(crate) fn start_rename_icon(&mut self, id: &str) {
let Some(icons) = &self.desktop_icons else { return };
let Some(icon) = icons.icons.iter().find(|i| i.id == id) else { return };
self.renaming_icon = Some((id.to_string(), icon.label.clone()));
self.rebuild_icon_buffer(id);
}
/// Routes one keystroke into the in-progress rename buffer - same
/// shape as `native_lock_key`'s own `BackSpace`/`Return`/`Escape`/
/// printable-character handling.
pub(crate) fn desktop_icon_rename_key(&mut self, name: &str, utf8: &str) {
let Some((id, mut buffer)) = self.renaming_icon.take() else { return };
match name {
"BackSpace" => {
buffer.pop();
self.renaming_icon = Some((id.clone(), buffer));
self.rebuild_icon_buffer(&id);
}
"Return" | "KP_Enter" => self.commit_icon_rename(&id, &buffer),
"Escape" => self.rebuild_icon_buffer(&id),
_ => {
if !utf8.is_empty() && utf8.chars().all(|c| !c.is_control()) {
buffer.push_str(utf8);
}
self.renaming_icon = Some((id.clone(), buffer));
self.rebuild_icon_buffer(&id);
}
}
}
/// Renames the real file/folder on disk and carries its saved grid
/// cell forward under the new name, so a rename doesn't also bump the
/// icon to a fresh default position. A blank name, or renaming
/// anything other than a real file/folder (shouldn't happen - see
/// `start_rename_icon`'s own doc comment), just cancels with no
/// filesystem change.
fn commit_icon_rename(&mut self, id: &str, new_name: &str) {
let new_name = new_name.trim();
let Some(icons) = &self.desktop_icons else { return };
let Some(icon) = icons.icons.iter().find(|i| i.id == id) else { return };
if new_name.is_empty() || !matches!(icon.kind, IconKind::Folder | IconKind::File) {
self.rebuild_icon_buffer(id);
return;
}
let Some(parent) = icon.target.parent() else {
self.rebuild_icon_buffer(id);
return;
};
let new_path = parent.join(new_name);
if let Err(e) = std::fs::rename(&icon.target, &new_path) {
log::warn!("desktop_icons: couldn't rename {:?} to {new_name:?}: {e}", icon.target);
self.rebuild_icon_buffer(id);
return;
}
let cell = icon.cell;
crate::desktop_icons_state::save_icon(new_name, cell);
self.desktop_icon_buffers.remove(id);
self.refresh_desktop_icons();
}
/// Moves the real file/folder into `~/.local/share/Trash` - see
/// `trash.rs`'s own module doc comment for why this needs no
/// confirmation.
pub(crate) fn delete_desktop_icon(&mut self, id: &str) {
let Some(icons) = &self.desktop_icons else { return };
let Some(icon) = icons.icons.iter().find(|i| i.id == id) else { return };
if let Err(e) = crate::trash::move_to_trash(&icon.target) {
log::warn!("desktop_icons: couldn't move {:?} to trash: {e}", icon.target);
return;
}
self.desktop_icon_buffers.remove(id);
self.refresh_desktop_icons();
}
pub(crate) fn empty_trash(&mut self) {
let Ok(home) = std::env::var("HOME").map(std::path::PathBuf::from) else { return };
crate::trash::empty(&home);
self.desktop_icon_buffers.remove("trash");
}
/// Spawns `general.terminal` (or the first of `TERMINAL_CANDIDATES`
/// found on `$PATH`) with `~/Desktop` as its working directory.
pub(crate) fn open_terminal_here(&mut self) {
let Ok(home) = std::env::var("HOME") else { return };
let desktop = format!("{home}/Desktop");
let configured = self.wm.borrow().terminal.clone();
let command = if !configured.is_empty() {
Some(configured)
} else {
TERMINAL_CANDIDATES.iter().find(|bin| on_path(bin)).map(|s| s.to_string())
};
match command {
Some(command) => spawn_shell_in_dir(&command, &desktop),
None => log::warn!("desktop_icons: no terminal found on $PATH and general.terminal is unset"),
}
}
/// Opens `~/Desktop` itself via `file_manager`/`xdg-open` - the
/// concrete path to a real file manager's own richer menu.
pub(crate) fn open_desktop_in_file_manager(&mut self) {
let Ok(home) = std::env::var("HOME") else { return };
let desktop = format!("{home}/Desktop");
let file_manager = self.wm.borrow().file_manager.clone();
if file_manager.is_empty() {
spawn_shell(&format!("xdg-open {}", shell_quote(&desktop)));
} else {
spawn_shell(&format!("{file_manager} {}", shell_quote(&desktop)));
}
}
/// Creates `~/Desktop/New Folder`, de-duplicated as `New Folder (2)`,
/// `(3)`, ... against whatever's already there, then rescans so it
/// shows up as an icon immediately.
pub(crate) fn new_desktop_folder(&mut self) {
let Ok(home) = std::env::var("HOME") else { return };
let desktop = std::path::PathBuf::from(home).join("Desktop");
let mut name = "New Folder".to_string();
let mut n = 2;
while desktop.join(&name).exists() {
name = format!("New Folder ({n})");
n += 1;
}
if let Err(e) = std::fs::create_dir(desktop.join(&name)) {
log::warn!("desktop_icons: couldn't create {name:?}: {e}");
return;
}
self.refresh_desktop_icons();
}
/// "New > Text Document" (Windows) / a blank file (macOS's own desktop
/// menu has no direct equivalent, but every mainstream file manager
/// does) - the concrete gap behind "not even new file" reported live
/// against this menu next to Windows'/macOS' own. Same collision-
/// avoidance and refresh as `new_desktop_folder` just above.
pub(crate) fn new_desktop_text_file(&mut self) {
let Ok(home) = std::env::var("HOME") else { return };
let desktop = std::path::PathBuf::from(home).join("Desktop");
let mut name = "New Text Document.txt".to_string();
let mut n = 2;
while desktop.join(&name).exists() {
name = format!("New Text Document ({n}).txt");
n += 1;
}
if let Err(e) = std::fs::write(desktop.join(&name), "") {
log::warn!("desktop_icons: couldn't create {name:?}: {e}");
return;
}
self.refresh_desktop_icons();
}
pub(crate) fn open_desktop_icon_menu(&mut self, icon_id: &str, pos: (i32, i32)) {
let Some(icons) = &self.desktop_icons else { return };
let Some(icon) = icons.icons.iter().find(|i| i.id == icon_id) else { return };
let menu = DesktopMenu::open_for_icon(icon, pos);
self.build_desktop_menu_buffer(menu);
}
pub(crate) fn open_desktop_menu(&mut self, pos: (i32, i32)) {
let menu = DesktopMenu::open_for_desktop(pos);
self.build_desktop_menu_buffer(menu);
}
fn build_desktop_menu_buffer(&mut self, menu: DesktopMenu) {
let theme = self.wm.borrow().theme;
let items: Vec<(&str, bool)> = menu.items.iter().map(|&(label, _)| (label, false)).collect();
let data = decoration::render_context_menu(menu.width, menu.row_height, &items, theme.titlebar_bg, theme.titlebar_fg_focused, theme.titlebar_fg_unfocused, theme.default_border_color);
let buffer = MemoryRenderBuffer::from_slice(&data, Fourcc::Argb8888, (menu.width as i32, menu.height()), 1, Transform::Normal, None);
self.desktop_menu_buffer = Some(buffer);
self.desktop_menu = Some(menu);
}
pub(crate) fn close_desktop_menu(&mut self) {
self.desktop_menu = None;
self.desktop_menu_buffer = None;
}
pub(crate) fn run_desktop_menu_action(&mut self, action: DesktopMenuAction) {
match action {
DesktopMenuAction::OpenIcon(id) => self.open_desktop_icon(&id),
DesktopMenuAction::Rename(id) => self.start_rename_icon(&id),
DesktopMenuAction::Delete(id) => self.delete_desktop_icon(&id),
DesktopMenuAction::EmptyTrash => self.empty_trash(),
DesktopMenuAction::NewFolder => self.new_desktop_folder(),
DesktopMenuAction::NewTextFile => self.new_desktop_text_file(),
DesktopMenuAction::OpenTerminalHere => self.open_terminal_here(),
DesktopMenuAction::OpenInFileManager => self.open_desktop_in_file_manager(),
DesktopMenuAction::Refresh => self.refresh_desktop_icons(),
// Never actually reached - the click-dispatch site intercepts
// `Separator` first, same as `context_menu::MenuAction::
// Separator`'s own dispatch. Handled here too so this match
// stays exhaustive.
DesktopMenuAction::Separator => {}
}
}
}
trait MaxZero {
fn max_zero(self) -> Self;
}
impl MaxZero for (i32, i32) {
fn max_zero(self) -> Self {
(self.0.max(0), self.1.max(0))
}
}
/// Breadth-first search outward from `target` over grid cells (`target`
/// itself first, then its 4-neighbours, then theirs, ...) for the first
/// one not in `occupied` - a dropped icon always lands *somewhere* rather
/// than silently failing to move when its raw target cell is already
/// taken.
fn nearest_free_cell(target: (i32, i32), occupied: &std::collections::HashSet<(i32, i32)>) -> (i32, i32) {
if !occupied.contains(&target) && target.0 >= 0 && target.1 >= 0 {
return target;
}
use std::collections::VecDeque;
let mut seen = std::collections::HashSet::new();
let mut queue = VecDeque::new();
queue.push_back(target);
seen.insert(target);
while let Some((c, r)) = queue.pop_front() {
if c >= 0 && r >= 0 && !occupied.contains(&(c, r)) {
return (c, r);
}
for (dc, dr) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
let next = (c + dc, r + dr);
if seen.insert(next) {
queue.push_back(next);
}
}
}
target
}
fn shell_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', "'\\''"))
}
fn spawn_shell(command: &str) {
#[cfg(unix)]
let result = std::process::Command::new("sh").arg("-c").arg(command).spawn();
#[cfg(windows)]
let result = std::process::Command::new("cmd").arg("/C").arg(command).spawn();
if let Err(e) = result {
log::warn!("desktop_icons: spawn '{command}' failed: {e}");
}
}
/// Same fire-and-forget shell spawn as `spawn_shell`, but with a working
/// directory - `open_terminal_here`'s own reason to exist as a separate
/// function rather than reusing `spawn_shell` with a `cd` prefix, which
/// would need its own quoting for `dir`.
fn spawn_shell_in_dir(command: &str, dir: &str) {
#[cfg(unix)]
let result = std::process::Command::new("sh").arg("-c").arg(command).current_dir(dir).spawn();
#[cfg(windows)]
let result = std::process::Command::new("cmd").arg("/C").arg(command).current_dir(dir).spawn();
if let Err(e) = result {
log::warn!("desktop_icons: spawn '{command}' in {dir:?} failed: {e}");
}
}
/// Whether `bin` resolves to a real, regular file somewhere on `$PATH` --
/// enough to pick a terminal candidate without a full `which`-equivalent
/// (no executable-bit/`PATHEXT` check on Windows; this whole feature is
/// Linux/BSD-desktop-shaped already, see `TERMINAL_CANDIDATES`' own
/// entries).
fn on_path(bin: &str) -> bool {
std::env::var_os("PATH").map(|paths| std::env::split_paths(&paths).any(|dir| dir.join(bin).is_file())).unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shell_quote_wraps_in_single_quotes() {
assert_eq!(shell_quote("/home/x/pic.png"), "'/home/x/pic.png'");
}
#[test]
fn shell_quote_escapes_an_embedded_single_quote() {
assert_eq!(shell_quote("it's.png"), "'it'\\''s.png'");
}
#[test]
fn nearest_free_cell_returns_the_target_when_its_free() {
let occupied = std::collections::HashSet::new();
assert_eq!(nearest_free_cell((2, 3), &occupied), (2, 3));
}
#[test]
fn nearest_free_cell_finds_an_adjacent_slot_when_the_target_is_taken() {
let mut occupied = std::collections::HashSet::new();
occupied.insert((0, 0));
let (c, r) = nearest_free_cell((0, 0), &occupied);
assert!((c, r) != (0, 0));
assert!(!occupied.contains(&(c, r)));
assert_eq!(c.abs() + r.abs(), 1, "the nearest free cell is exactly one step away");
}
#[test]
fn nearest_free_cell_never_returns_a_negative_column_or_row() {
let mut occupied = std::collections::HashSet::new();
occupied.insert((0, 0));
occupied.insert((1, 0));
occupied.insert((0, 1));
let (c, r) = nearest_free_cell((0, 0), &occupied);
assert!(c >= 0 && r >= 0);
}
}
|