chore: clippy

This commit is contained in:
Vukašin Vojinović 2026-01-24 17:03:31 +01:00
parent 339e4c104e
commit 1e25e7dd69
11 changed files with 938 additions and 981 deletions

View file

@ -1230,11 +1230,11 @@ impl App {
}; };
for item in items { for item in items {
if item.selected { if item.selected {
if let Some(path) = item.path_opt() { if let Some(path) = item.path_opt()
if op_sel.selected.contains(path) || op_sel.ignored.contains(path) { && (op_sel.selected.contains(path) || op_sel.ignored.contains(path))
// Ignore if path in selected or ignored paths {
continue; // Ignore if path in selected or ignored paths
} continue;
} }
// Return if there is a previous selection not matching // Return if there is a previous selection not matching
@ -1891,50 +1891,47 @@ impl App {
children.push(item.preview_view(Some(&self.mime_app_cache), military_time)); children.push(item.preview_view(Some(&self.mime_app_cache), military_time));
} }
PreviewKind::Location(location) => { PreviewKind::Location(location) => {
if let Some(tab) = self.tab_model.data::<Tab>(entity) { if let Some(tab) = self.tab_model.data::<Tab>(entity)
if let Some(items) = tab.items_opt() { && let Some(items) = tab.items_opt()
for item in items { {
if item.location_opt.as_ref() == Some(location) { for item in items {
children.push( if item.location_opt.as_ref() == Some(location) {
item.preview_view(Some(&self.mime_app_cache), military_time), children
); .push(item.preview_view(Some(&self.mime_app_cache), military_time));
// Only show one property view to avoid issues like hangs when generating // Only show one property view to avoid issues like hangs when generating
// preview images on thousands of files // preview images on thousands of files
break; break;
}
} }
} }
} }
} }
PreviewKind::Selected => { PreviewKind::Selected => {
if let Some(tab) = self.tab_model.data::<Tab>(entity) { if let Some(tab) = self.tab_model.data::<Tab>(entity)
if let Some(items) = tab.items_opt() { && let Some(items) = tab.items_opt()
let preview_opt = { {
let mut selected = items.iter().filter(|item| item.selected); let preview_opt = {
let mut selected = items.iter().filter(|item| item.selected);
match (selected.next(), selected.next()) { match (selected.next(), selected.next()) {
// At least two selected items // At least two selected items
(Some(_), Some(_)) => Some(tab.multi_preview_view()), (Some(_), Some(_)) => Some(tab.multi_preview_view()),
// Exactly one selected item // Exactly one selected item
(Some(item), None) => Some( (Some(item), None) => {
item.preview_view(Some(&self.mime_app_cache), military_time), Some(item.preview_view(Some(&self.mime_app_cache), military_time))
),
// No selected items
_ => None,
} }
}; // No selected items
_ => None,
if let Some(preview) = preview_opt {
children.push(preview);
} }
};
if children.is_empty() { if let Some(preview) = preview_opt {
if let Some(item) = &tab.parent_item_opt { children.push(preview);
children.push( }
item.preview_view(Some(&self.mime_app_cache), military_time),
); if children.is_empty()
} && let Some(item) = &tab.parent_item_opt
} {
children.push(item.preview_view(Some(&self.mime_app_cache), military_time));
} }
} }
} }
@ -2062,11 +2059,11 @@ impl App {
.map(|favorite| { .map(|favorite| {
if let Favorite::Path(path) = favorite { if let Favorite::Path(path) = favorite {
for (from, to) in path_changes.iter().map(|(f, t)| (f.as_ref(), t.as_ref())) { for (from, to) in path_changes.iter().map(|(f, t)| (f.as_ref(), t.as_ref())) {
if path.starts_with(from) { if path.starts_with(from)
if let Ok(relative) = path.strip_prefix(from) { && let Ok(relative) = path.strip_prefix(from)
favorites_changed = true; {
return Favorite::from_path(to.join(relative)); favorites_changed = true;
} return Favorite::from_path(to.join(relative));
} }
} }
} }
@ -2235,17 +2232,16 @@ impl Application for App {
let mut commands = vec![app.update_config()]; let mut commands = vec![app.update_config()];
for location in flags.locations { for location in flags.locations {
if let Some(path) = location.path_opt() { if let Some(path) = location.path_opt()
if path.is_file() { && path.is_file()
if let Some(parent) = path.parent() { && let Some(parent) = path.parent()
commands.push(app.open_tab( {
Location::Path(parent.to_path_buf()), commands.push(app.open_tab(
true, Location::Path(parent.to_path_buf()),
Some(vec![path.clone()]), true,
)); Some(vec![path.clone()]),
continue; ));
} continue;
}
} }
commands.push(app.open_tab(location, true, None)); commands.push(app.open_tab(location, true, None));
} }
@ -2405,14 +2401,13 @@ impl Application for App {
// TODO do we need to choose the correct mounter? // TODO do we need to choose the correct mounter?
self.mounter_items.keys().copied().next() self.mounter_items.keys().copied().next()
}) })
&& let Some(mounter) = MOUNTERS.get(&key)
{ {
if let Some(mounter) = MOUNTERS.get(&key) { return mounter.network_drive(uri.clone()).map(move |()| {
return mounter.network_drive(uri.clone()).map(move |()| { cosmic::Action::App(Message::NetworkDriveOpenEntityAfterMount {
cosmic::Action::App(Message::NetworkDriveOpenEntityAfterMount { entity,
entity, })
}) });
});
}
} }
log::warn!( log::warn!(
@ -2468,12 +2463,12 @@ impl Application for App {
return self.update(message); return self.update(message);
} }
} }
if let Some(data) = self.nav_model.data::<MounterData>(entity) { if let Some(data) = self.nav_model.data::<MounterData>(entity)
if let Some(mounter) = MOUNTERS.get(&data.0) { && let Some(mounter) = MOUNTERS.get(&data.0)
return mounter {
.mount(data.1.clone()) return mounter
.map(|()| cosmic::action::none()); .mount(data.1.clone())
} .map(|()| cosmic::action::none());
} }
Task::none() Task::none()
} }
@ -2505,11 +2500,11 @@ impl Application for App {
} }
// Close gallery mode if open // Close gallery mode if open
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { if let Some(tab) = self.tab_model.data_mut::<Tab>(entity)
if tab.gallery { && tab.gallery
tab.gallery = false; {
return Task::none(); tab.gallery = false;
} return Task::none();
} }
// Close menus and context panes in order per message // Close menus and context panes in order per message
@ -2635,22 +2630,22 @@ impl Application for App {
} }
Message::Compress(entity_opt) => { Message::Compress(entity_opt) => {
let paths: Box<[_]> = self.selected_paths(entity_opt).collect(); let paths: Box<[_]> = self.selected_paths(entity_opt).collect();
if let Some(current_path) = paths.first() { if let Some(current_path) = paths.first()
if let Some(destination) = current_path.parent().zip(current_path.file_stem()) { && let Some(destination) = current_path.parent().zip(current_path.file_stem())
let to = destination.0.to_path_buf(); {
let name = destination.1.to_str().unwrap_or_default().to_string(); let to = destination.0.to_path_buf();
let archive_type = ArchiveType::default(); let name = destination.1.to_str().unwrap_or_default().to_string();
return self.push_dialog( let archive_type = ArchiveType::default();
DialogPage::Compress { return self.push_dialog(
paths, DialogPage::Compress {
to, paths,
name, to,
archive_type, name,
password: None, archive_type,
}, password: None,
Some(self.dialog_text_input.clone()), },
); Some(self.dialog_text_input.clone()),
} );
} }
} }
Message::Config(config) => { Message::Config(config) => {
@ -2664,10 +2659,10 @@ impl Application for App {
} }
} }
Message::Copy(entity_opt) => { Message::Copy(entity_opt) => {
if let Some(entity) = entity_opt { if let Some(entity) = entity_opt
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { && let Some(tab) = self.tab_model.data_mut::<Tab>(entity)
tab.refresh_cut(&[]); {
} tab.refresh_cut(&[]);
} }
let paths = self.selected_paths(entity_opt); let paths = self.selected_paths(entity_opt);
let contents = ClipboardCopy::new(ClipboardKind::Copy, paths); let contents = ClipboardCopy::new(ClipboardKind::Copy, paths);
@ -2975,22 +2970,21 @@ impl Application for App {
DialogResult::Cancel => {} DialogResult::Cancel => {}
DialogResult::Open(selected_paths) => { DialogResult::Open(selected_paths) => {
let mut archive_paths = None; let mut archive_paths = None;
if let Some(file_dialog) = &self.file_dialog_opt { if let Some(file_dialog) = &self.file_dialog_opt
if let Some(window) = self.windows.remove(&file_dialog.window_id()) { && let Some(window) = self.windows.remove(&file_dialog.window_id())
if let WindowKind::FileDialog(paths) = window.kind { && let WindowKind::FileDialog(paths) = window.kind
archive_paths = paths; {
} archive_paths = paths;
}
} }
if let Some(archive_paths) = archive_paths { if let Some(archive_paths) = archive_paths
if !selected_paths.is_empty() { && !selected_paths.is_empty()
self.file_dialog_opt = None; {
return self.operation(Operation::Extract { self.file_dialog_opt = None;
paths: archive_paths, return self.operation(Operation::Extract {
to: selected_paths[0].clone(), paths: archive_paths,
password: None, to: selected_paths[0].clone(),
}); password: None,
} });
} }
} }
} }
@ -3020,56 +3014,53 @@ impl Application for App {
&& !modifiers.control() && !modifiers.control()
&& !modifiers.alt() && !modifiers.alt()
&& matches!(key, Key::Character(_)) && matches!(key, Key::Character(_))
&& let Some(text) = text
{ {
if let Some(text) = text { match self.config.type_to_search {
match self.config.type_to_search { TypeToSearch::Recursive => {
TypeToSearch::Recursive => { let mut term = self.search_get().unwrap_or_default().to_string();
let mut term = term.push_str(&text);
self.search_get().unwrap_or_default().to_string(); return self.search_set_active(Some(term));
term.push_str(&text); }
return self.search_set_active(Some(term)); TypeToSearch::EnterPath => {
} if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) {
TypeToSearch::EnterPath => { let location = tab
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { .edit_location
let location = tab .as_ref()
.edit_location .map_or_else(|| &tab.location, |x| &x.location);
.as_ref() // Try to add text to end of location
.map_or_else(|| &tab.location, |x| &x.location); if let Location::Network(uri, ..) = location {
// Try to add text to end of location let mut uri_string = uri.clone();
if let Location::Network(uri, ..) = location { uri_string.push_str(&text);
let mut uri_string = uri.clone(); tab.edit_location =
uri_string.push_str(&text); Some(location.with_uri(uri_string).into());
tab.edit_location = } else if let Some(path) = location.path_opt() {
Some(location.with_uri(uri_string).into()); let mut path_string = path.to_string_lossy().into_owned();
} else if let Some(path) = location.path_opt() { path_string.push_str(&text);
let mut path_string = tab.edit_location =
path.to_string_lossy().into_owned(); Some(location.with_path(path_string.into()).into());
path_string.push_str(&text);
tab.edit_location =
Some(location.with_path(path_string.into()).into());
}
} }
} }
TypeToSearch::SelectByPrefix => { }
// Reset buffer if timeout elapsed TypeToSearch::SelectByPrefix => {
if let Some(last_key) = self.type_select_last_key { // Reset buffer if timeout elapsed
if last_key.elapsed() >= tab::TYPE_SELECT_TIMEOUT { if let Some(last_key) = self.type_select_last_key
self.type_select_prefix.clear(); && last_key.elapsed() >= tab::TYPE_SELECT_TIMEOUT
} {
} self.type_select_prefix.clear();
}
// Accumulate character and select // Accumulate character and select
self.type_select_prefix.push_str(&text.to_lowercase()); self.type_select_prefix.push_str(&text.to_lowercase());
self.type_select_last_key = Some(Instant::now()); self.type_select_last_key = Some(Instant::now());
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) {
tab.select_by_prefix(&self.type_select_prefix); tab.select_by_prefix(&self.type_select_prefix);
if let Some(offset) = tab.select_focus_scroll() { if let Some(offset) = tab.select_focus_scroll() {
return scrollable::scroll_to( return scrollable::scroll_to(
tab.scrollable_id.clone(), tab.scrollable_id.clone(),
offset, offset,
); );
}
} }
} }
} }
@ -3106,21 +3097,22 @@ impl Application for App {
let mut unmounted = Vec::new(); let mut unmounted = Vec::new();
if let Some(old_items) = self.mounter_items.get(&mounter_key) { if let Some(old_items) = self.mounter_items.get(&mounter_key) {
for old_item in old_items { for old_item in old_items {
if let Some(old_path) = old_item.path() { if let Some(old_path) = old_item.path()
if old_item.is_mounted() { && old_item.is_mounted()
let mut still_mounted = false; {
for item in &mounter_items { let mut still_mounted = false;
if let Some(path) = item.path() { for item in &mounter_items {
if path == old_path && item.is_mounted() { if let Some(path) = item.path()
still_mounted = true; && path == old_path
break; && item.is_mounted()
} {
} still_mounted = true;
} break;
if !still_mounted {
unmounted.push(old_path);
} }
} }
if !still_mounted {
unmounted.push(old_path);
}
} }
} }
} }
@ -3254,17 +3246,17 @@ impl Application for App {
} }
Message::NewItem(entity_opt, dir) => { Message::NewItem(entity_opt, dir) => {
let entity = entity_opt.unwrap_or_else(|| self.tab_model.active()); let entity = entity_opt.unwrap_or_else(|| self.tab_model.active());
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { if let Some(tab) = self.tab_model.data_mut::<Tab>(entity)
if let Some(path) = tab.location.path_opt() { && let Some(path) = tab.location.path_opt()
return Task::batch([ {
self.dialog_pages.push_back(DialogPage::NewItem { return Task::batch([
parent: path.clone(), self.dialog_pages.push_back(DialogPage::NewItem {
name: String::new(), parent: path.clone(),
dir, name: String::new(),
}), dir,
widget::text_input::focus(self.dialog_text_input.clone()), }),
]); widget::text_input::focus(self.dialog_text_input.clone()),
} ]);
} }
} }
#[cfg(feature = "notify")] #[cfg(feature = "notify")]
@ -3277,57 +3269,57 @@ impl Application for App {
let mut needs_reload = Vec::new(); let mut needs_reload = Vec::new();
let entities: Box<[_]> = self.tab_model.iter().collect(); let entities: Box<[_]> = self.tab_model.iter().collect();
for entity in entities { for entity in entities {
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { if let Some(tab) = self.tab_model.data_mut::<Tab>(entity)
if let Some(path) = tab.location.path_opt() { && let Some(path) = tab.location.path_opt()
let mut contains_change = false; {
for event in &events { let mut contains_change = false;
for event_path in &event.paths { for event in &events {
if event_path.starts_with(path) { for event_path in &event.paths {
if let notify::EventKind::Modify( if event_path.starts_with(path) {
notify::event::ModifyKind::Metadata(_) if let notify::EventKind::Modify(
| notify::event::ModifyKind::Data(_), notify::event::ModifyKind::Metadata(_)
) = event.kind | notify::event::ModifyKind::Data(_),
{ ) = event.kind
// If metadata or data changed, find the matching item and reload it {
//TODO: this could be further optimized by looking at what exactly changed // If metadata or data changed, find the matching item and reload it
if let Some(items) = &mut tab.items_opt { //TODO: this could be further optimized by looking at what exactly changed
for item in items.iter_mut() { if let Some(items) = &mut tab.items_opt {
if item.path_opt() == Some(event_path) { for item in items.iter_mut() {
//TODO: reload more, like mime types? if item.path_opt() == Some(event_path) {
match fs::metadata(event_path) { //TODO: reload more, like mime types?
Ok(new_metadata) => { match fs::metadata(event_path) {
if let ItemMetadata::Path { Ok(new_metadata) => {
metadata, if let ItemMetadata::Path {
.. metadata,
} = &mut item.metadata ..
{ } = &mut item.metadata
*metadata = new_metadata; {
} *metadata = new_metadata;
}
Err(err) => {
log::warn!(
"failed to reload metadata for {}: {}",
path.display(),
err
);
} }
} }
//TODO item.thumbnail_opt =
Err(err) => {
log::warn!(
"failed to reload metadata for {}: {}",
path.display(),
err
);
}
} }
//TODO item.thumbnail_opt =
} }
} }
} else {
// Any other events reload the whole tab
contains_change = true;
break;
} }
} else {
// Any other events reload the whole tab
contains_change = true;
break;
} }
} }
} }
if contains_change { }
needs_reload.push((entity, tab.location.clone())); if contains_change {
} needs_reload.push((entity, tab.location.clone()));
} }
} }
} }
@ -3351,20 +3343,21 @@ impl Application for App {
if let Some(terminal) = self.mime_app_cache.terminal() { if let Some(terminal) = self.mime_app_cache.terminal() {
let mut paths = Box::from([]); let mut paths = Box::from([]);
let entity = entity_opt.unwrap_or_else(|| self.tab_model.active()); let entity = entity_opt.unwrap_or_else(|| self.tab_model.active());
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { if let Some(tab) = self.tab_model.data_mut::<Tab>(entity)
if let Some(path) = tab.location.path_opt() { && let Some(path) = tab.location.path_opt()
if let Some(items) = tab.items_opt() { {
paths = if let Some(items) = tab.items_opt() {
items paths = items
.iter() .iter()
.filter_map(|item| { .filter_map(
if item.selected { item.path_opt() } else { None } |item| {
}) if item.selected { item.path_opt() } else { None }
.collect(); },
} )
if paths.is_empty() { .collect();
paths = Box::from([path]); }
} if paths.is_empty() {
paths = Box::from([path]);
} }
} }
for path in paths { for path in paths {
@ -3454,30 +3447,30 @@ impl Application for App {
}, },
Message::OpenWithDialog(entity_opt) => { Message::OpenWithDialog(entity_opt) => {
let entity = entity_opt.unwrap_or_else(|| self.tab_model.active()); let entity = entity_opt.unwrap_or_else(|| self.tab_model.active());
if let Some(tab) = self.tab_model.data::<Tab>(entity) { if let Some(tab) = self.tab_model.data::<Tab>(entity)
if let Some(items) = tab.items_opt() { && let Some(items) = tab.items_opt()
for item in items { {
if !item.selected { for item in items {
continue; if !item.selected {
} continue;
let Some(path) = item.path_opt() else {
continue;
};
return self.push_dialog(
DialogPage::OpenWith {
path: path.clone(),
mime: item.mime.clone(),
selected: 0,
store_opt: "x-scheme-handler/mime"
.parse::<mime_guess::Mime>()
.ok()
.and_then(|mime| {
self.mime_app_cache.get(&mime).first().cloned()
}),
},
Some(CONFIRM_OPEN_WITH_BUTTON_ID.clone()),
);
} }
let Some(path) = item.path_opt() else {
continue;
};
return self.push_dialog(
DialogPage::OpenWith {
path: path.clone(),
mime: item.mime.clone(),
selected: 0,
store_opt: "x-scheme-handler/mime"
.parse::<mime_guess::Mime>()
.ok()
.and_then(|mime| {
self.mime_app_cache.get(&mime).first().cloned()
}),
},
Some(CONFIRM_OPEN_WITH_BUTTON_ID.clone()),
);
} }
} }
} }
@ -3488,19 +3481,18 @@ impl Application for App {
} }
Message::Paste(entity_opt) => { Message::Paste(entity_opt) => {
let entity = entity_opt.unwrap_or_else(|| self.tab_model.active()); let entity = entity_opt.unwrap_or_else(|| self.tab_model.active());
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { if let Some(tab) = self.tab_model.data_mut::<Tab>(entity)
if let Some(path) = tab.location.path_opt() { && let Some(path) = tab.location.path_opt()
let to = path.clone(); {
return clipboard::read_data::<ClipboardPaste>().map(move |contents_opt| { let to = path.clone();
match contents_opt { return clipboard::read_data::<ClipboardPaste>().map(move |contents_opt| {
Some(contents) => cosmic::action::app(Message::PasteContents( match contents_opt {
to.clone(), Some(contents) => {
contents, cosmic::action::app(Message::PasteContents(to.clone(), contents))
)),
None => cosmic::action::none(),
} }
}); None => cosmic::action::none(),
} }
});
} }
} }
Message::PasteContents(to, mut contents) => { Message::PasteContents(to, mut contents) => {
@ -3733,38 +3725,38 @@ impl Application for App {
} }
Message::Rename(entity_opt) => { Message::Rename(entity_opt) => {
let entity = entity_opt.unwrap_or_else(|| self.tab_model.active()); let entity = entity_opt.unwrap_or_else(|| self.tab_model.active());
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { if let Some(tab) = self.tab_model.data_mut::<Tab>(entity)
if let Some(items) = tab.items_opt() { && let Some(items) = tab.items_opt()
let selected: Box<[_]> = items {
.iter() let selected: Box<[_]> = items
.filter_map(|item| { .iter()
if item.selected { .filter_map(|item| {
item.path_opt().cloned() if item.selected {
} else { item.path_opt().cloned()
None } else {
} None
}
})
.collect();
if !selected.is_empty() {
//TODO: batch rename
let tasks = selected
.into_iter()
.filter_map(|path| {
let parent = path.parent()?.to_path_buf();
let name = path.file_name()?.to_str()?.to_string();
let dir = path.is_dir();
Some(self.dialog_pages.push_back(DialogPage::RenameItem {
from: path,
parent,
name,
dir,
}))
}) })
.collect(); .chain(std::iter::once(widget::text_input::focus(
if !selected.is_empty() { self.dialog_text_input.clone(),
//TODO: batch rename )));
let tasks = selected return Task::batch(tasks);
.into_iter()
.filter_map(|path| {
let parent = path.parent()?.to_path_buf();
let name = path.file_name()?.to_str()?.to_string();
let dir = path.is_dir();
Some(self.dialog_pages.push_back(DialogPage::RenameItem {
from: path,
parent,
name,
dir,
}))
})
.chain(std::iter::once(widget::text_input::focus(
self.dialog_text_input.clone(),
)));
return Task::batch(tasks);
}
} }
} }
} }
@ -3787,15 +3779,15 @@ impl Application for App {
Message::RestoreFromTrash(entity_opt) => { Message::RestoreFromTrash(entity_opt) => {
let mut trash_items = Vec::new(); let mut trash_items = Vec::new();
let entity = entity_opt.unwrap_or_else(|| self.tab_model.active()); let entity = entity_opt.unwrap_or_else(|| self.tab_model.active());
if let Some(tab) = self.tab_model.data_mut::<Tab>(entity) { if let Some(tab) = self.tab_model.data_mut::<Tab>(entity)
if let Some(items) = tab.items_opt() { && let Some(items) = tab.items_opt()
for item in items { {
if item.selected { for item in items {
if let ItemMetadata::Trash { entry, .. } = &item.metadata { if item.selected {
trash_items.push(entry.clone()); if let ItemMetadata::Trash { entry, .. } = &item.metadata {
} else { trash_items.push(entry.clone());
//TODO: error on trying to restore non-trash file? } else {
} //TODO: error on trying to restore non-trash file?
} }
} }
} }
@ -3840,13 +3832,13 @@ impl Application for App {
// Close old context menu // Close old context menu
let active = self.tab_model.active(); let active = self.tab_model.active();
if let Some(tab) = self.tab_model.data_mut::<Tab>(active) { if let Some(tab) = self.tab_model.data_mut::<Tab>(active)
if tab.context_menu.is_some() { && tab.context_menu.is_some()
tasks.push(self.update(Message::TabMessage( {
Some(active), tasks.push(self.update(Message::TabMessage(
tab::Message::ContextMenu(None, None), Some(active),
))); tab::Message::ContextMenu(None, None),
} )));
} }
// Activate new tab // Activate new tab
@ -4042,10 +4034,10 @@ impl Application for App {
// Destroy previous popup // Destroy previous popup
let mut window_ids = Vec::new(); let mut window_ids = Vec::new();
for (window_id, window) in &self.windows { for (window_id, window) in &self.windows {
if let WindowKind::ContextMenu(e, _) = &window.kind { if let WindowKind::ContextMenu(e, _) = &window.kind
if *e == entity { && *e == entity
window_ids.push(*window_id); {
} window_ids.push(*window_id);
} }
} }
for window_id in window_ids { for window_id in window_ids {
@ -4453,12 +4445,12 @@ impl Application for App {
} }
} }
Message::NavBarClose(entity) => { Message::NavBarClose(entity) => {
if let Some(data) = self.nav_model.data::<MounterData>(entity) { if let Some(data) = self.nav_model.data::<MounterData>(entity)
if let Some(mounter) = MOUNTERS.get(&data.0) { && let Some(mounter) = MOUNTERS.get(&data.0)
return mounter {
.unmount(data.1.clone()) return mounter
.map(|()| cosmic::action::none()); .unmount(data.1.clone())
} .map(|()| cosmic::action::none());
} }
} }
Message::NavBarContext(entity) => { Message::NavBarContext(entity) => {
@ -4755,15 +4747,14 @@ impl Application for App {
if let Some(p) = paths.next() { if let Some(p) = paths.next() {
{ {
for (k, mounter_items) in &self.mounter_items { for (k, mounter_items) in &self.mounter_items {
if let Some(mounter) = MOUNTERS.get(k) { if let Some(mounter) = MOUNTERS.get(k)
if let Some(item) = mounter_items && let Some(item) = mounter_items
.iter() .iter()
.find(|&item| item.path().is_some_and(|path| path == p)) .find(|&item| item.path().is_some_and(|path| path == p))
{ {
return mounter return mounter
.unmount(item.clone()) .unmount(item.clone())
.map(|()| cosmic::action::none()); .map(|()| cosmic::action::none());
}
} }
} }
} }
@ -4786,15 +4777,14 @@ impl Application for App {
} }
Message::SaveSortNames => { Message::SaveSortNames => {
self.must_save_sort_names = false; self.must_save_sort_names = false;
if let Some(state_handler) = self.state_handler.as_ref() { if let Some(state_handler) = self.state_handler.as_ref()
if let Err(err) = state_handler && let Err(err) = state_handler
.set::<&FxOrderMap<String, (HeadingOptions, bool)>>( .set::<&FxOrderMap<String, (HeadingOptions, bool)>>(
"sort_names", "sort_names",
&self.state.sort_names, &self.state.sort_names,
) )
{ {
log::warn!("Failed to save sort names: {err:?}"); log::warn!("Failed to save sort names: {err:?}");
}
} }
} }
Message::NetworkDriveOpenEntityAfterMount { entity } => { Message::NetworkDriveOpenEntityAfterMount { entity } => {
@ -4890,13 +4880,13 @@ impl Application for App {
fn dialog(&self) -> Option<Element<'_, Message>> { fn dialog(&self) -> Option<Element<'_, Message>> {
//TODO: should gallery view just be a dialog? //TODO: should gallery view just be a dialog?
let entity = self.tab_model.active(); let entity = self.tab_model.active();
if let Some(tab) = self.tab_model.data::<Tab>(entity) { if let Some(tab) = self.tab_model.data::<Tab>(entity)
if tab.gallery { && tab.gallery
return Some( {
tab.gallery_view() return Some(
.map(move |x| Message::TabMessage(Some(entity), x)), tab.gallery_view()
); .map(move |x| Message::TabMessage(Some(entity), x)),
} );
} }
let dialog_page = self.dialog_pages.front()?; let dialog_page = self.dialog_pages.front()?;
@ -5778,19 +5768,19 @@ impl Application for App {
let mut tab_column = widget::column::with_capacity(4); let mut tab_column = widget::column::with_capacity(4);
if self.core.is_condensed() { if self.core.is_condensed()
if let Some(term) = self.search_get() { && let Some(term) = self.search_get()
tab_column = tab_column.push( {
widget::container( tab_column = tab_column.push(
widget::text_input::search_input("", term) widget::container(
.width(Length::Fill) widget::text_input::search_input("", term)
.id(self.search_id.clone()) .width(Length::Fill)
.on_clear(Message::SearchClear) .id(self.search_id.clone())
.on_input(Message::SearchInput), .on_clear(Message::SearchClear)
) .on_input(Message::SearchInput),
.padding(space_xxs), )
); .padding(space_xxs),
} );
} }
if self.tab_model.len() > 1 { if self.tab_model.len() > 1 {
@ -6088,14 +6078,14 @@ impl Application for App {
let should_rescan = let should_rescan =
events.iter().any(|event| !event.kind.is_access()); events.iter().any(|event| !event.kind.is_access());
if should_rescan { if should_rescan
if let Err(e) = futures::executor::block_on(async { && let Err(e) = futures::executor::block_on(async {
output.send(Message::RescanTrash).await output.send(Message::RescanTrash).await
}) { })
log::warn!( {
"trash needs to be rescanned but sending message failed: {e:?}" log::warn!(
); "trash needs to be rescanned but sending message failed: {e:?}"
} );
} }
} }
Err(e) => { Err(e) => {
@ -6173,14 +6163,12 @@ impl Application for App {
|| kind.is_modify() || kind.is_modify()
|| kind.is_remove() || kind.is_remove()
|| kind.is_other() || kind.is_other()
}) && let Err(e) = futures::executor::block_on(async {
output.send(Message::RescanRecents).await
}) { }) {
if let Err(e) = futures::executor::block_on(async { log::warn!(
output.send(Message::RescanRecents).await "open recents tabs need to be updated but sending message failed: {e:?}"
}) { );
log::warn!(
"open recents tabs need to be updated but sending message failed: {e:?}"
);
}
} }
} }
Err(e) => { Err(e) => {
@ -6297,17 +6285,16 @@ impl Application for App {
let mut selected_previews = Vec::new(); let mut selected_previews = Vec::new();
match self.mode { match self.mode {
Mode::App => { Mode::App => {
if self.core.window.show_context { if self.core.window.show_context
if let ContextPage::Preview(entity_opt, PreviewKind::Selected) = && let ContextPage::Preview(entity_opt, PreviewKind::Selected) =
self.context_page self.context_page
{ {
selected_previews selected_previews
.push(Some(entity_opt.unwrap_or_else(|| self.tab_model.active()))); .push(Some(entity_opt.unwrap_or_else(|| self.tab_model.active())));
}
} }
} }
Mode::Desktop => { Mode::Desktop => {
for window_kind in self.windows.iter().map(|(_, window)| &window.kind) { for window_kind in self.windows.values().map(|window| &window.kind) {
if let WindowKind::Preview(entity_opt, _) = window_kind { if let WindowKind::Preview(entity_opt, _) = window_kind {
selected_previews selected_previews
.push(Some(entity_opt.unwrap_or_else(|| self.tab_model.active()))); .push(Some(entity_opt.unwrap_or_else(|| self.tab_model.active())));
@ -6322,8 +6309,7 @@ impl Application for App {
tab.subscription( tab.subscription(
selected_previews selected_previews
.iter() .iter()
.find(|preview| preview.as_ref() == Some(entity).as_ref()) .any(|preview| preview.as_ref() == Some(entity).as_ref()),
.is_some(),
) )
.with(entity) .with(entity)
.map(|(entity, tab_msg)| Message::TabMessage(Some(entity), tab_msg)), .map(|(entity, tab_msg)| Message::TabMessage(Some(entity), tab_msg)),

View file

@ -179,11 +179,11 @@ impl<T: AsRef<str>> From<T> for DialogLabel {
}); });
} }
if let Some(span) = spans.last_mut() { if let Some(span) = spans.last_mut()
if underline == span.underline { && underline == span.underline
span.text.push(c); {
continue; span.text.push(c);
} continue;
} }
spans.push(DialogLabelSpan { spans.push(DialogLabelSpan {
@ -718,10 +718,10 @@ impl App {
children.push(preview); children.push(preview);
} }
if children.is_empty() { if children.is_empty()
if let Some(item) = &self.tab.parent_item_opt { && let Some(item) = &self.tab.parent_item_opt
children.push(item.preview_view(None, military_time)); {
} children.push(item.preview_view(None, military_time));
} }
} }
} }
@ -1279,12 +1279,12 @@ impl Application for App {
return self.update(message); return self.update(message);
} }
if let Some(data) = self.nav_model.data::<MounterData>(entity) { if let Some(data) = self.nav_model.data::<MounterData>(entity)
if let Some(mounter) = MOUNTERS.get(&data.0) { && let Some(mounter) = MOUNTERS.get(&data.0)
return mounter {
.mount(data.1.clone()) return mounter
.map(|()| cosmic::action::none()); .mount(data.1.clone())
} .map(|()| cosmic::action::none());
} }
Task::none() Task::none()
} }
@ -1322,10 +1322,10 @@ impl Application for App {
// Close the dialog if the focused widget is the dialog's main text input instead of // Close the dialog if the focused widget is the dialog's main text input instead of
// unfocussing the widget. // unfocussing the widget.
if let operation::Outcome::Some(focused) = operation::focusable::find_focused().finish() { if let operation::Outcome::Some(focused) = operation::focusable::find_focused().finish()
if self.dialog_text_input == focused { && self.dialog_text_input == focused
return self.update(Message::Cancel); {
} return self.update(Message::Cancel);
} }
self.update(Message::Cancel) self.update(Message::Cancel)
@ -1419,14 +1419,14 @@ impl Application for App {
} }
// Check key binds from accept label // Check key binds from accept label
if let Some(key_bind) = &self.accept_label.key_bind_opt { if let Some(key_bind) = &self.accept_label.key_bind_opt
if key_bind.matches(modifiers, &key) { && key_bind.matches(modifiers, &key)
return self.update(if self.flags.kind.save() { {
Message::Save(false) return self.update(if self.flags.kind.save() {
} else { Message::Save(false)
Message::Open } else {
}); Message::Open
} });
} }
// Uncaptured keys with only shift modifiers go to the search or location box // Uncaptured keys with only shift modifiers go to the search or location box
@ -1434,45 +1434,44 @@ impl Application for App {
&& !modifiers.control() && !modifiers.control()
&& !modifiers.alt() && !modifiers.alt()
&& matches!(key, Key::Character(_)) && matches!(key, Key::Character(_))
&& let Some(text) = text
{ {
if let Some(text) = text { match self.flags.config.type_to_search {
match self.flags.config.type_to_search { TypeToSearch::Recursive => {
TypeToSearch::Recursive => { let mut term = self.search_get().unwrap_or_default().to_string();
let mut term = self.search_get().unwrap_or_default().to_string(); term.push_str(&text);
term.push_str(&text); return self.search_set(Some(term));
return self.search_set(Some(term)); }
TypeToSearch::EnterPath => {
let location = (self.tab.edit_location)
.as_ref()
.map_or_else(|| &self.tab.location, |x| &x.location);
// Try to add text to end of location
if let Some(path) = location.path_opt() {
let mut path_string = path.to_string_lossy().to_string();
path_string.push_str(&text);
self.tab.edit_location =
Some(location.with_path(PathBuf::from(path_string)).into());
} }
TypeToSearch::EnterPath => { }
let location = (self.tab.edit_location) TypeToSearch::SelectByPrefix => {
.as_ref() // Reset buffer if timeout elapsed
.map_or_else(|| &self.tab.location, |x| &x.location); if let Some(last_key) = self.type_select_last_key
// Try to add text to end of location && last_key.elapsed() >= tab::TYPE_SELECT_TIMEOUT
if let Some(path) = location.path_opt() { {
let mut path_string = path.to_string_lossy().to_string(); self.type_select_prefix.clear();
path_string.push_str(&text);
self.tab.edit_location =
Some(location.with_path(PathBuf::from(path_string)).into());
}
} }
TypeToSearch::SelectByPrefix => {
// Reset buffer if timeout elapsed
if let Some(last_key) = self.type_select_last_key {
if last_key.elapsed() >= tab::TYPE_SELECT_TIMEOUT {
self.type_select_prefix.clear();
}
}
// Accumulate character and select // Accumulate character and select
self.type_select_prefix.push_str(&text.to_lowercase()); self.type_select_prefix.push_str(&text.to_lowercase());
self.type_select_last_key = Some(Instant::now()); self.type_select_last_key = Some(Instant::now());
self.tab.select_by_prefix(&self.type_select_prefix); self.tab.select_by_prefix(&self.type_select_prefix);
if let Some(offset) = self.tab.select_focus_scroll() { if let Some(offset) = self.tab.select_focus_scroll() {
return scrollable::scroll_to( return scrollable::scroll_to(
self.tab.scrollable_id.clone(), self.tab.scrollable_id.clone(),
offset, offset,
); );
}
} }
} }
} }
@ -1486,21 +1485,22 @@ impl Application for App {
let mut unmounted = Vec::new(); let mut unmounted = Vec::new();
if let Some(old_items) = self.mounter_items.get(&mounter_key) { if let Some(old_items) = self.mounter_items.get(&mounter_key) {
for old_item in old_items { for old_item in old_items {
if let Some(old_path) = old_item.path() { if let Some(old_path) = old_item.path()
if old_item.is_mounted() { && old_item.is_mounted()
let mut still_mounted = false; {
for item in &mounter_items { let mut still_mounted = false;
if let Some(path) = item.path() { for item in &mounter_items {
if path == old_path && item.is_mounted() { if let Some(path) = item.path()
still_mounted = true; && path == old_path
break; && item.is_mounted()
} {
} still_mounted = true;
} break;
if !still_mounted {
unmounted.push(Location::Path(old_path));
} }
} }
if !still_mounted {
unmounted.push(Location::Path(old_path));
}
} }
} }
} }
@ -1601,16 +1601,16 @@ impl Application for App {
let mut paths = Vec::new(); let mut paths = Vec::new();
if let Some(items) = self.tab.items_opt() { if let Some(items) = self.tab.items_opt() {
for item in items { for item in items {
if item.selected { if item.selected
if let Some(path) = item.path_opt() { && let Some(path) = item.path_opt()
paths.push(path.clone()); {
let _ = update_recently_used( paths.push(path.clone());
path, let _ = update_recently_used(
Self::APP_ID.to_string(), path,
"cosmic-files".to_string(), Self::APP_ID.to_string(),
None, "cosmic-files".to_string(),
); None,
} );
} }
} }
} }
@ -1640,11 +1640,11 @@ impl Application for App {
} }
// If we are in directory mode, return the current directory // If we are in directory mode, return the current directory
if self.flags.kind.is_dir() { if self.flags.kind.is_dir()
if let Location::Path(tab_path) = &self.tab.location { && let Location::Path(tab_path) = &self.tab.location
self.result_opt = Some(DialogResult::Open(vec![tab_path.clone()])); {
return window::close(self.flags.window_id); self.result_opt = Some(DialogResult::Open(vec![tab_path.clone()]));
} return window::close(self.flags.window_id);
} }
} }
Message::Preview => { Message::Preview => {
@ -1654,26 +1654,24 @@ impl Application for App {
}); });
} }
Message::Save(replace) => { Message::Save(replace) => {
if let DialogKind::SaveFile { filename } = &self.flags.kind { if let DialogKind::SaveFile { filename } = &self.flags.kind
if !filename.is_empty() { && !filename.is_empty()
if let Some(tab_path) = self.tab.location.path_opt() { && let Some(tab_path) = self.tab.location.path_opt()
let path = tab_path.join(filename); {
if path.is_dir() { let path = tab_path.join(filename);
// cd to directory if path.is_dir() {
let message = Message::TabMessage(tab::Message::Location( // cd to directory
Location::Path(path), let message =
)); Message::TabMessage(tab::Message::Location(Location::Path(path)));
return self.update(message); return self.update(message);
} else if !replace && path.exists() { } else if !replace && path.exists() {
self.dialog_pages.push_back(DialogPage::Replace { self.dialog_pages.push_back(DialogPage::Replace {
filename: filename.clone(), filename: filename.clone(),
}); });
return widget::button::focus(REPLACE_BUTTON_ID.clone()); return widget::button::focus(REPLACE_BUTTON_ID.clone());
}
self.result_opt = Some(DialogResult::Open(vec![path]));
return window::close(self.flags.window_id);
}
} }
self.result_opt = Some(DialogResult::Open(vec![path]));
return window::close(self.flags.window_id);
} }
} }
Message::ScrollTab(scroll_speed) => { Message::ScrollTab(scroll_speed) => {
@ -1703,16 +1701,14 @@ impl Application for App {
let tab_commands = self.tab.update(tab_message, self.modifiers); let tab_commands = self.tab.update(tab_message, self.modifiers);
// Update filename box when anything is selected // Update filename box when anything is selected
if let DialogKind::SaveFile { filename } = &mut self.flags.kind { if let DialogKind::SaveFile { filename } = &mut self.flags.kind
if let Some(click_i) = click_i_opt { && let Some(click_i) = click_i_opt
if let Some(items) = self.tab.items_opt() { && let Some(items) = self.tab.items_opt()
if let Some(item) = items.get(click_i) { && let Some(item) = items.get(click_i)
if item.selected && !item.metadata.is_dir() { && item.selected
filename.clone_from(&item.name); && !item.metadata.is_dir()
} {
} filename.clone_from(&item.name);
}
}
} }
let mut commands = Vec::new(); let mut commands = Vec::new();
@ -1840,34 +1836,34 @@ impl Application for App {
Message::TabRescan(location, parent_item_opt, mut items, selection_paths) => { Message::TabRescan(location, parent_item_opt, mut items, selection_paths) => {
if location == self.tab.location { if location == self.tab.location {
// Filter // Filter
if let Some(filter_i) = self.filter_selected { if let Some(filter_i) = self.filter_selected
if let Some(filter) = self.filters.get(filter_i) { && let Some(filter) = self.filters.get(filter_i)
// Parse globs (Mime implements PartialEq with &str, so no need to parse) {
let mut parsed_globs = Vec::new(); // Parse globs (Mime implements PartialEq with &str, so no need to parse)
let mut mimes = Vec::new(); let mut parsed_globs = Vec::new();
for pattern in &filter.patterns { let mut mimes = Vec::new();
match pattern { for pattern in &filter.patterns {
DialogFilterPattern::Glob(value) => { match pattern {
match glob::Pattern::new(value) { DialogFilterPattern::Glob(value) => {
Ok(glob) => parsed_globs.push(glob), match glob::Pattern::new(value) {
Err(err) => { Ok(glob) => parsed_globs.push(glob),
log::warn!("failed to parse glob {value:?}: {err}"); Err(err) => {
} log::warn!("failed to parse glob {value:?}: {err}");
} }
} }
DialogFilterPattern::Mime(value) => mimes.push(value.as_str()),
} }
DialogFilterPattern::Mime(value) => mimes.push(value.as_str()),
} }
}
items.retain(|item| { items.retain(|item| {
// Directories are always shown // Directories are always shown
item.metadata.is_dir() item.metadata.is_dir()
// Check for mime type match (first because it is faster) // Check for mime type match (first because it is faster)
|| mimes.iter().copied().any(|mime| mime == item.mime) || mimes.iter().copied().any(|mime| mime == item.mime)
// Check for glob match (last because it is slower) // Check for glob match (last because it is slower)
|| parsed_globs.iter().any(|glob| glob.matches(&item.name)) || parsed_globs.iter().any(|glob| glob.matches(&item.name))
}); });
}
} }
// Select based on filename // Select based on filename
@ -1944,19 +1940,19 @@ impl Application for App {
let mut col = widget::column::with_capacity(2); let mut col = widget::column::with_capacity(2);
if self.core.is_condensed() { if self.core.is_condensed()
if let Some(term) = self.search_get() { && let Some(term) = self.search_get()
col = col.push( {
widget::container( col = col.push(
widget::text_input::search_input("", term) widget::container(
.width(Length::Fill) widget::text_input::search_input("", term)
.id(self.search_id.clone()) .width(Length::Fill)
.on_clear(Message::SearchClear) .id(self.search_id.clone())
.on_input(Message::SearchInput), .on_clear(Message::SearchClear)
) .on_input(Message::SearchInput),
.padding(space_xxs), )
); .padding(space_xxs),
} );
} }
col = col.push( col = col.push(

View file

@ -392,16 +392,16 @@ impl LargeImageManager {
generation: u64, generation: u64,
) -> bool { ) -> bool {
// Check if this decode is still current (not superseded by a newer one) // Check if this decode is still current (not superseded by a newer one)
if let Some(&current_gen) = self.decode_generations.get(&path) { if let Some(&current_gen) = self.decode_generations.get(&path)
if generation != current_gen { && generation != current_gen
log::info!( {
"Discarding outdated decode for {} (generation {} != current {})", log::info!(
path.display(), "Discarding outdated decode for {} (generation {} != current {})",
generation, path.display(),
current_gen generation,
); current_gen
return false; );
} return false;
} }
log::info!( log::info!(
@ -556,7 +556,7 @@ impl LargeImageManager {
/// Check if sufficient memory is available, clearing cache if needed. /// Check if sufficient memory is available, clearing cache if needed.
/// Returns true if memory is available, false otherwise. /// Returns true if memory is available, false otherwise.
fn ensure_memory_available(&mut self, path: &PathBuf, width: u32, height: u32) -> bool { fn ensure_memory_available(&mut self, path: &Path, width: u32, height: u32) -> bool {
let (has_memory, error_opt) = check_memory_available(width, height); let (has_memory, error_opt) = check_memory_available(width, height);
if has_memory { if has_memory {
@ -565,7 +565,7 @@ impl LargeImageManager {
if self.cache_is_empty() { if self.cache_is_empty() {
if let Some(error_msg) = error_opt { if let Some(error_msg) = error_opt {
self.store_error(path.clone(), error_msg); self.store_error(path.to_path_buf(), error_msg);
log::warn!( log::warn!(
"Cannot load {}: insufficient memory and cache is empty", "Cannot load {}: insufficient memory and cache is empty",
path.display() path.display()
@ -588,7 +588,7 @@ impl LargeImageManager {
} }
if let Some(error_msg) = error_opt_after { if let Some(error_msg) = error_opt_after {
self.store_error(path.clone(), error_msg); self.store_error(path.to_path_buf(), error_msg);
log::warn!( log::warn!(
"Cannot load {}: insufficient memory even after cache clear", "Cannot load {}: insufficient memory even after cache clear",
path.display() path.display()

View file

@ -62,10 +62,10 @@ pub static LOCALE: LazyLock<Locale> = LazyLock::new(|| {
} }
// Try language-only fallback (e.g., "en" from "en-US") // Try language-only fallback (e.g., "en" from "en-US")
if let Some(lang) = cleaned_locale.split('-').next() { if let Some(lang) = cleaned_locale.split('-').next()
if let Ok(locale) = Locale::try_from_str(lang) { && let Ok(locale) = Locale::try_from_str(lang)
return locale; {
} return locale;
} }
} }
} }

View file

@ -310,7 +310,7 @@ impl MimeAppCache {
for (mime, filenames) in list.removed_associations.iter() { for (mime, filenames) in list.removed_associations.iter() {
for filename in filenames { for filename in filenames {
log::trace!("remove {mime}={filename}"); log::trace!("remove {mime}={filename}");
if let Some(apps) = self.cache.get_mut(&mime) { if let Some(apps) = self.cache.get_mut(mime) {
apps.retain(|x| !filename_eq(&x.path, filename)); apps.retain(|x| !filename_eq(&x.path, filename));
} }
} }
@ -319,7 +319,7 @@ impl MimeAppCache {
for (mime, filenames) in list.default_apps.iter() { for (mime, filenames) in list.default_apps.iter() {
for filename in filenames { for filename in filenames {
log::trace!("default {mime}={filename}"); log::trace!("default {mime}={filename}");
if let Some(apps) = self.cache.get_mut(&mime) { if let Some(apps) = self.cache.get_mut(mime) {
let mut found = false; let mut found = false;
for app in apps.iter_mut() { for app in apps.iter_mut() {
if filename_eq(&app.path, filename) { if filename_eq(&app.path, filename) {

View file

@ -23,12 +23,11 @@ fn resolve_uri(uri: &str) -> (String, gio::File) {
TARGET_URI_ATTRIBUTE, TARGET_URI_ATTRIBUTE,
gio::FileQueryInfoFlags::NONE, gio::FileQueryInfoFlags::NONE,
gio::Cancellable::NONE, gio::Cancellable::NONE,
) { ) && let Some(resolved_uri) = file_info.attribute_as_string(TARGET_URI_ATTRIBUTE)
if let Some(resolved_uri) = file_info.attribute_as_string(TARGET_URI_ATTRIBUTE) { {
let resolved_uri = String::from(resolved_uri); let resolved_uri = String::from(resolved_uri);
let file = gio::File::for_uri(&resolved_uri); let file = gio::File::for_uri(&resolved_uri);
return (resolved_uri, file); return (resolved_uri, file);
}
} }
(uri.to_string(), file) (uri.to_string(), file)
@ -60,7 +59,7 @@ fn items(monitor: &gio::VolumeMonitor, sizes: IconSizes) -> MounterItems {
gio::Cancellable::NONE, gio::Cancellable::NONE,
) )
.ok() .ok()
.and_then(|info| Some(info.boolean(gio::FILE_ATTRIBUTE_FILESYSTEM_REMOTE))) .map(|info| info.boolean(gio::FILE_ATTRIBUTE_FILESYSTEM_REMOTE))
.unwrap_or(true); // Default to remote if query fails .unwrap_or(true); // Default to remote if query fails
MounterItem::Gvfs(Item { MounterItem::Gvfs(Item {
@ -457,9 +456,9 @@ impl Gvfs {
log::info!("mount {name}: result {res:?}"); log::info!("mount {name}: result {res:?}");
// Update the mounter_item with mount information after successful mount // Update the mounter_item with mount information after successful mount
let mut updated_item = mounter_item.clone(); let mut updated_item = mounter_item.clone();
if res.is_ok() { if res.is_ok()
if let MounterItem::Gvfs(ref mut item) = updated_item { && let MounterItem::Gvfs(ref mut item) = updated_item
if let Some(mount) = volume_for_callback.get_mount() { && let Some(mount) = volume_for_callback.get_mount() {
let root = MountExt::root(&mount); let root = MountExt::root(&mount);
item.path_opt = root.path(); item.path_opt = root.path();
item.is_mounted = true; item.is_mounted = true;
@ -469,14 +468,9 @@ impl Gvfs {
gio::FILE_ATTRIBUTE_FILESYSTEM_REMOTE, gio::FILE_ATTRIBUTE_FILESYSTEM_REMOTE,
gio::Cancellable::NONE, gio::Cancellable::NONE,
) )
.ok() .ok().map(|info| info.boolean(gio::FILE_ATTRIBUTE_FILESYSTEM_REMOTE))
.and_then(|info| {
Some(info.boolean(gio::FILE_ATTRIBUTE_FILESYSTEM_REMOTE))
})
.unwrap_or(true); .unwrap_or(true);
} }
}
}
event_tx.send(Event::MountResult(updated_item, match res { event_tx.send(Event::MountResult(updated_item, match res {
Ok(()) => { Ok(()) => {
_ = complete_tx.send(Ok(())); _ = complete_tx.send(Ok(()));

View file

@ -246,19 +246,18 @@ struct State {
impl State { impl State {
fn drag_rect(&self, cursor: mouse::Cursor) -> Option<Rectangle> { fn drag_rect(&self, cursor: mouse::Cursor) -> Option<Rectangle> {
if let Some(drag_source) = self.drag_initiated { if let Some(drag_source) = self.drag_initiated
if let Some(position) = cursor.position().or(self.last_virtual_position) { && let Some(position) = cursor.position().or(self.last_virtual_position)
if position.distance(drag_source) > 1.0 { && position.distance(drag_source) > 1.0
let min_x = drag_source.x.min(position.x); {
let max_x = drag_source.x.max(position.x); let min_x = drag_source.x.min(position.x);
let min_y = drag_source.y.min(position.y); let max_x = drag_source.x.max(position.x);
let max_y = drag_source.y.max(position.y); let min_y = drag_source.y.min(position.y);
return Some(Rectangle::new( let max_y = drag_source.y.max(position.y);
Point::new(min_x, min_y), return Some(Rectangle::new(
Size::new(max_x - min_x, max_y - min_y), Point::new(min_x, min_y),
)); Size::new(max_x - min_x, max_y - min_y),
} ));
}
} }
None None
} }
@ -527,12 +526,12 @@ fn update<Message: Clone>(
let offset = layout.virtual_offset(); let offset = layout.virtual_offset();
let layout_bounds = layout.bounds(); let layout_bounds = layout.bounds();
let viewport_changed = state.viewport.map_or(true, |v| v != *viewport); let viewport_changed = state.viewport != Some(*viewport);
if let Some(message) = widget.on_resize.as_ref() { if let Some(message) = widget.on_resize.as_ref()
if viewport_changed { && viewport_changed
shell.publish(message(*viewport)); {
} shell.publish(message(*viewport));
} }
state.viewport = Some(*viewport); state.viewport = Some(*viewport);
@ -664,113 +663,112 @@ fn update<Message: Clone>(
} }
} }
if let Some(message) = widget.on_right_press.as_ref() { if let Some(message) = widget.on_right_press.as_ref()
if matches!( && matches!(
event, event,
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right)) Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right))
) { )
let point_opt = if widget.on_right_press_window_position { {
cursor.position_over(layout_bounds).map(|mut p| { let point_opt = if widget.on_right_press_window_position {
p.x -= offset.x; cursor.position_over(layout_bounds).map(|mut p| {
p.y -= offset.y; p.x -= offset.x;
p p.y -= offset.y;
}) p
} else { })
cursor.position_in(layout_bounds) } else {
}; cursor.position_in(layout_bounds)
shell.publish(message(point_opt)); };
shell.publish(message(point_opt));
if widget.on_right_press_no_capture { if widget.on_right_press_no_capture {
return event::Status::Ignored; return event::Status::Ignored;
}
return event::Status::Captured;
} }
return event::Status::Captured;
} }
if let Some(message) = widget.on_right_release.as_ref() { if let Some(message) = widget.on_right_release.as_ref()
if matches!( && matches!(
event, event,
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Right)) Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Right))
) { )
shell.publish(message(cursor.position_in(layout_bounds))); {
shell.publish(message(cursor.position_in(layout_bounds)));
return event::Status::Captured; return event::Status::Captured;
}
} }
if let Some(message) = widget.on_middle_press.as_ref() { if let Some(message) = widget.on_middle_press.as_ref()
if matches!( && matches!(
event, event,
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle)) Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle))
) { )
shell.publish(message(cursor.position_in(layout_bounds))); {
shell.publish(message(cursor.position_in(layout_bounds)));
return event::Status::Captured; return event::Status::Captured;
}
} }
if let Some(message) = widget.on_middle_release.as_ref() { if let Some(message) = widget.on_middle_release.as_ref()
if matches!( && matches!(
event, event,
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Middle)) Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Middle))
) { )
shell.publish(message(cursor.position_in(layout_bounds))); {
shell.publish(message(cursor.position_in(layout_bounds)));
return event::Status::Captured; return event::Status::Captured;
}
} }
if let Some(message) = widget.on_back_press.as_ref() { if let Some(message) = widget.on_back_press.as_ref()
if matches!( && matches!(
event, event,
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Back)) Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Back))
) { )
shell.publish(message(cursor.position_in(layout_bounds))); {
shell.publish(message(cursor.position_in(layout_bounds)));
return event::Status::Captured; return event::Status::Captured;
}
} }
if let Some(message) = widget.on_back_release.as_ref() { if let Some(message) = widget.on_back_release.as_ref()
if matches!( && matches!(
event, event,
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Back)) Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Back))
) { )
shell.publish(message(cursor.position_in(layout_bounds))); {
shell.publish(message(cursor.position_in(layout_bounds)));
return event::Status::Captured; return event::Status::Captured;
}
} }
if let Some(message) = widget.on_forward_press.as_ref() { if let Some(message) = widget.on_forward_press.as_ref()
if matches!( && matches!(
event, event,
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Forward)) Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Forward))
) { )
shell.publish(message(cursor.position_in(layout_bounds))); {
shell.publish(message(cursor.position_in(layout_bounds)));
return event::Status::Captured; return event::Status::Captured;
}
} }
if let Some(message) = widget.on_forward_release.as_ref() { if let Some(message) = widget.on_forward_release.as_ref()
if matches!( && matches!(
event, event,
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Forward)) Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Forward))
) { )
shell.publish(message(cursor.position_in(layout_bounds))); {
shell.publish(message(cursor.position_in(layout_bounds)));
return event::Status::Captured; return event::Status::Captured;
}
} }
if let Some(on_scroll) = widget.on_scroll.as_ref() { if let Some(on_scroll) = widget.on_scroll.as_ref()
if let Event::Mouse(mouse::Event::WheelScrolled { delta }) = event { && let Event::Mouse(mouse::Event::WheelScrolled { delta }) = event
if let Some(message) = on_scroll(*delta) { && let Some(message) = on_scroll(*delta)
shell.publish(message); {
return event::Status::Captured; shell.publish(message);
} return event::Status::Captured;
}
} }
if let Some((message, drag_rect)) = widget.on_drag.as_ref().zip(state.drag_rect(cursor)) { if let Some((message, drag_rect)) = widget.on_drag.as_ref().zip(state.drag_rect(cursor)) {

View file

@ -957,10 +957,10 @@ impl Operation {
let dir_name = get_directory_name(file_name); let dir_name = get_directory_name(file_name);
let mut new_dir = to.join(dir_name); let mut new_dir = to.join(dir_name);
if new_dir.exists() { if new_dir.exists()
if let Some(new_dir_parent) = new_dir.parent() { && let Some(new_dir_parent) = new_dir.parent()
new_dir = copy_unique_path(&new_dir, new_dir_parent); {
} new_dir = copy_unique_path(&new_dir, new_dir_parent);
} }
op_sel.ignored.push(path.clone()); op_sel.ignored.push(path.clone());

View file

@ -138,10 +138,10 @@ impl Context {
}), }),
is_cleanup: false, is_cleanup: false,
}; };
if matches!(method, Method::Move { .. }) { if matches!(method, Method::Move { .. })
if let Some(cleanup_op) = op.move_cleanup_op() { && let Some(cleanup_op) = op.move_cleanup_op()
cleanup_ops.push(cleanup_op); {
} cleanup_ops.push(cleanup_op);
} }
if let Some(parent) = op.to.parent() { if let Some(parent) = op.to.parent() {
target_dirs.insert(parent.to_path_buf()); target_dirs.insert(parent.to_path_buf());

View file

@ -934,43 +934,43 @@ pub fn scan_path(tab_path: &PathBuf, sizes: IconSizes) -> Vec<Item> {
#[cfg(feature = "gvfs")] #[cfg(feature = "gvfs")]
{ {
if let Ok(path_meta) = fs::metadata(tab_path) { if let Ok(path_meta) = fs::metadata(tab_path)
if fs_kind(&path_meta) == FsKind::Gvfs { && fs_kind(&path_meta) == FsKind::Gvfs
let file = gio::File::for_path(tab_path); {
let file = gio::File::for_path(tab_path);
// gio crate expects a comma delimited string // gio crate expects a comma delimited string
let attr_string = [ let attr_string = [
gio::FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME.as_str(), gio::FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME.as_str(),
gio::FILE_ATTRIBUTE_FILESYSTEM_REMOTE.as_str(), gio::FILE_ATTRIBUTE_FILESYSTEM_REMOTE.as_str(),
gio::FILE_ATTRIBUTE_TIME_MODIFIED.as_str(), gio::FILE_ATTRIBUTE_TIME_MODIFIED.as_str(),
gio::FILE_ATTRIBUTE_STANDARD_SIZE.as_str(), gio::FILE_ATTRIBUTE_STANDARD_SIZE.as_str(),
gio::FILE_ATTRIBUTE_STANDARD_TYPE.as_str(), gio::FILE_ATTRIBUTE_STANDARD_TYPE.as_str(),
gio::FILE_ATTRIBUTE_STANDARD_NAME.as_str(), gio::FILE_ATTRIBUTE_STANDARD_NAME.as_str(),
] ]
.join(","); .join(",");
match gio::prelude::FileExt::enumerate_children( match gio::prelude::FileExt::enumerate_children(
&file, &file,
attr_string.as_str(), attr_string.as_str(),
gio::FileQueryInfoFlags::NONE, gio::FileQueryInfoFlags::NONE,
gio::Cancellable::NONE, gio::Cancellable::NONE,
) { ) {
Ok(res) => { Ok(res) => {
remote_scannable = true; remote_scannable = true;
items = res items = res
.filter_map(|file| { .filter_map(|file| {
let file = file.ok()?; let file = file.ok()?;
Some(item_from_gvfs_info(tab_path.join(file.name()), file, sizes)) Some(item_from_gvfs_info(tab_path.join(file.name()), file, sizes))
}) })
.collect(); .collect();
} }
Err(err) => { Err(err) => {
log::warn!( log::warn!(
"could not enumerate {} via gio: {}", "could not enumerate {} via gio: {}",
tab_path.display(), tab_path.display(),
err err
); );
}
} }
} }
} }
@ -1410,11 +1410,11 @@ impl EditLocation {
self.selected = Some(selected); self.selected = Some(selected);
// Automatically resolve if there is only one completion // Automatically resolve if there is only one completion
if completions.len() == 1 { if completions.len() == 1
if let Some(resolved) = self.resolve() { && let Some(resolved) = self.resolve()
self.location = resolved; {
self.selected = None; self.location = resolved;
} self.selected = None;
} }
} }
} else { } else {
@ -2033,10 +2033,10 @@ impl ItemThumbnail {
if let Some((item_thumbnail, temp_file)) = if let Some((item_thumbnail, temp_file)) =
Self::generate_thumbnail_external(path, &mime, thumbnail_size, thumbnail_dir) Self::generate_thumbnail_external(path, &mime, thumbnail_size, thumbnail_dir)
{ {
if let Ok(cache) = thumbnail_cacher { if let Ok(cache) = thumbnail_cacher
if let Err(err) = cache.update_with_temp_file(temp_file) { && let Err(err) = cache.update_with_temp_file(temp_file)
log::warn!("failed to update cache for {}: {}", path.display(), err); {
} log::warn!("failed to update cache for {}: {}", path.display(), err);
} }
return item_thumbnail; return item_thumbnail;
} }
@ -2076,16 +2076,15 @@ impl ItemThumbnail {
// If we weren't able to create a thumbnail, but we should have // If we weren't able to create a thumbnail, but we should have
// been able to, create a fail marker so that it isn't tried the // been able to, create a fail marker so that it isn't tried the
// next time. // next time.
if let Ok(cacher) = thumbnail_cacher { if let Ok(cacher) = thumbnail_cacher
if tried_supported_file { && tried_supported_file
if let Err(err) = cacher.create_fail_marker() { && let Err(err) = cacher.create_fail_marker()
log::warn!( {
"failed to create thumbnail fail marker for {}: {}", log::warn!(
path.display(), "failed to create thumbnail fail marker for {}: {}",
err path.display(),
); err
} );
}
} }
Self::NotImage Self::NotImage
@ -2273,13 +2272,13 @@ impl Item {
widget::button::icon(widget::icon::from_name("go-next-symbolic")) widget::button::icon(widget::icon::from_name("go-next-symbolic"))
.on_press(Message::ItemRight), .on_press(Message::ItemRight),
); );
if self.can_gallery() { if self.can_gallery()
if let Some(_path) = self.path_opt() { && let Some(_path) = self.path_opt()
row = row.push( {
widget::button::icon(widget::icon::from_name("view-fullscreen-symbolic")) row = row.push(
.on_press(Message::Gallery(true)), widget::button::icon(widget::icon::from_name("view-fullscreen-symbolic"))
); .on_press(Message::Gallery(true)),
} );
} }
row.into() row.into()
} }
@ -2445,11 +2444,11 @@ impl Item {
} }
} }
if let Some(path) = self.path_opt() { if let Some(path) = self.path_opt()
if let Ok(img) = image::image_dimensions(path) { && let Ok(img) = image::image_dimensions(path)
let (width, height) = img; {
details = details.push(widget::text::body(format!("{width}x{height}"))); let (width, height) = img;
} details = details.push(widget::text::body(format!("{width}x{height}")));
} }
column = column.push(details); column = column.push(details);
@ -2637,12 +2636,11 @@ async fn calculate_dir_size(path: &Path, controller: Controller) -> Result<u64,
.map_err(|s| OperationError::from_state(s, &controller))?; .map_err(|s| OperationError::from_state(s, &controller))?;
//TODO: report more errors? //TODO: report more errors?
if let Ok(entry) = entry_res { if let Ok(entry) = entry_res
if let Ok(metadata) = entry.metadata() { && let Ok(metadata) = entry.metadata()
if metadata.is_file() { && metadata.is_file()
total += metadata.len(); {
} total += metadata.len();
}
} }
// Yield in case this process takes a while. // Yield in case this process takes a while.
@ -2768,10 +2766,10 @@ impl Tab {
let selected = self.selected_locations(); let selected = self.selected_locations();
for item in &mut items { for item in &mut items {
item.selected = false; item.selected = false;
if let Some(location) = &item.location_opt { if let Some(location) = &item.location_opt
if selected.contains(location) { && selected.contains(location)
item.selected = true; {
} item.selected = true;
} }
} }
self.items_opt = Some(items); self.items_opt = Some(items);
@ -2790,10 +2788,9 @@ impl Tab {
for item in items.iter_mut() { for item in items.iter_mut() {
item.cut = false; item.cut = false;
if let Some(location_path) = item.location_opt.as_ref().and_then(Location::path_opt) if let Some(location_path) = item.location_opt.as_ref().and_then(Location::path_opt)
&& locations.contains(location_path)
{ {
if locations.contains(location_path) { item.cut = true;
item.cut = true;
}
} }
} }
} }
@ -2883,11 +2880,11 @@ impl Tab {
if let Some(ref mut items) = self.items_opt { if let Some(ref mut items) = self.items_opt {
for (i, item) in items.iter_mut().enumerate() { for (i, item) in items.iter_mut().enumerate() {
item.selected = false; item.selected = false;
if let Some(path) = item.path_opt() { if let Some(path) = item.path_opt()
if paths.contains(path) { && paths.contains(path)
item.selected = true; {
self.select_focus = Some(i); item.selected = true;
} self.select_focus = Some(i);
} }
} }
} }
@ -3087,10 +3084,10 @@ impl Tab {
return Vec::new(); return Vec::new();
}; };
if let Some((w, h)) = original_dims { if let Some((w, h)) = original_dims
if !should_use_tiling(*w, *h) { && !should_use_tiling(*w, *h)
return Vec::new(); {
} return Vec::new();
} }
let Some(path) = item.path_opt() else { let Some(path) = item.path_opt() else {
@ -3391,15 +3388,13 @@ impl Tab {
self.date_time_formatter = date_time_formatter(self.config.military_time); self.date_time_formatter = date_time_formatter(self.config.military_time);
self.time_formatter = time_formatter(self.config.military_time); self.time_formatter = time_formatter(self.config.military_time);
} }
if show_hidden_changed { if show_hidden_changed && let Location::Search(path, term, ..) = &self.location {
if let Location::Search(path, term, ..) = &self.location { cd = Some(Location::Search(
cd = Some(Location::Search( path.clone(),
path.clone(), term.clone(),
term.clone(), self.config.show_hidden,
self.config.show_hidden, Instant::now(),
Instant::now(), ));
));
}
} }
// Unhighlight all items when config changes // Unhighlight all items when config changes
if let Some(ref mut items) = self.items_opt { if let Some(ref mut items) = self.items_opt {
@ -3420,11 +3415,12 @@ impl Tab {
self.location_context_menu_index = None; self.location_context_menu_index = None;
//TODO: hack for clearing selecting when right clicking empty space //TODO: hack for clearing selecting when right clicking empty space
if self.context_menu.is_some() && self.last_right_click.take().is_none() { if self.context_menu.is_some()
if let Some(ref mut items) = self.items_opt { && self.last_right_click.take().is_none()
for item in items.iter_mut() { && let Some(ref mut items) = self.items_opt
item.selected = false; {
} for item in items.iter_mut() {
item.selected = false;
} }
} }
} }
@ -3512,11 +3508,11 @@ impl Tab {
} }
} }
Message::EditLocationComplete(selected) => { Message::EditLocationComplete(selected) => {
if let Some(mut edit_location) = self.edit_location.take() { if let Some(mut edit_location) = self.edit_location.take()
if !matches!(edit_location.location, Location::Network(..)) { && !matches!(edit_location.location, Location::Network(..))
edit_location.selected = Some(selected); {
cd = edit_location.resolve(); edit_location.selected = Some(selected);
} cd = edit_location.resolve();
} }
} }
Message::EditLocationEnable => { Message::EditLocationEnable => {
@ -3532,11 +3528,11 @@ impl Tab {
&& edit_location && edit_location
.completions .completions
.as_ref() .as_ref()
.map_or(false, |completions| !completions.is_empty()) .is_some_and(|completions| !completions.is_empty())
&& edit_location && edit_location
.location .location
.path_opt() .path_opt()
.map_or(false, |path| !path.exists()) .is_some_and(|path| !path.exists())
{ {
edit_location.selected = Some(0); edit_location.selected = Some(0);
} }
@ -3634,19 +3630,19 @@ impl Tab {
} }
} }
Message::GoNext => { Message::GoNext => {
if let Some(history_i) = self.history_i.checked_add(1) { if let Some(history_i) = self.history_i.checked_add(1)
if let Some(location) = self.history.get(history_i) { && let Some(location) = self.history.get(history_i)
cd = Some(location.clone()); {
history_i_opt = Some(history_i); cd = Some(location.clone());
} history_i_opt = Some(history_i);
} }
} }
Message::GoPrevious => { Message::GoPrevious => {
if let Some(history_i) = self.history_i.checked_sub(1) { if let Some(history_i) = self.history_i.checked_sub(1)
if let Some(location) = self.history.get(history_i) { && let Some(location) = self.history.get(history_i)
cd = Some(location.clone()); {
history_i_opt = Some(history_i); cd = Some(location.clone());
} history_i_opt = Some(history_i);
} }
} }
Message::ItemDown => { Message::ItemDown => {
@ -3825,10 +3821,10 @@ impl Tab {
Message::LocationUp => { Message::LocationUp => {
// Sets location to the path's parent // Sets location to the path's parent
// Does nothing if path is root or location is Trash // Does nothing if path is root or location is Trash
if let Location::Path(ref path) = self.location { if let Location::Path(ref path) = self.location
if let Some(parent) = path.parent() { && let Some(parent) = path.parent()
cd = Some(Location::Path(parent.to_owned())); {
} cd = Some(Location::Path(parent.to_owned()));
} }
} }
Message::Open(path_opt) => { Message::Open(path_opt) => {
@ -3870,27 +3866,25 @@ impl Tab {
match mode { match mode {
Mode::App => { Mode::App => {
if is_only_one_selected { if is_only_one_selected {
return ResolveResult::Cd(location.clone()); ResolveResult::Cd(location.clone())
} else { } else {
return ResolveResult::OpenInTab(path_opt.cloned()); ResolveResult::OpenInTab(path_opt.cloned())
} }
} }
Mode::Desktop => { Mode::Desktop => match location {
return match location { Location::Trash => ResolveResult::OpenTrash,
Location::Trash => ResolveResult::OpenTrash, _ => ResolveResult::Open(path_opt.cloned()),
_ => ResolveResult::Open(path_opt.cloned()), },
};
}
Mode::Dialog(_) => { Mode::Dialog(_) => {
if is_only_one_selected { if is_only_one_selected {
return ResolveResult::Cd(location.clone()); ResolveResult::Cd(location.clone())
} else { } else {
return ResolveResult::Skip; ResolveResult::Skip
} }
} }
} }
} else { } else {
return ResolveResult::Open(path_opt.cloned()); ResolveResult::Open(path_opt.cloned())
} }
} }
let mut open_files = Vec::new(); let mut open_files = Vec::new();
@ -3935,14 +3929,13 @@ impl Tab {
if mod_ctrl || mod_shift { if mod_ctrl || mod_shift {
self.update(Message::Click(click_i_opt), modifiers); self.update(Message::Click(click_i_opt), modifiers);
} }
if let Some(ref mut items) = self.items_opt { if let Some(ref mut items) = self.items_opt
if !click_i_opt && !click_i_opt
.is_some_and(|click_i| items.get(click_i).is_some_and(|x| x.selected)) .is_some_and(|click_i| items.get(click_i).is_some_and(|x| x.selected))
{ {
// If item not selected, clear selection on other items // If item not selected, clear selection on other items
for (i, item) in items.iter_mut().enumerate() { for (i, item) in items.iter_mut().enumerate() {
item.selected = Some(i) == click_i_opt; item.selected = Some(i) == click_i_opt;
}
} }
} }
//TODO: hack for clearing selecting when right clicking empty space //TODO: hack for clearing selecting when right clicking empty space
@ -3990,12 +3983,12 @@ impl Tab {
} }
Message::Resize(viewport) => { Message::Resize(viewport) => {
// Scroll to ensure focused item still in view // Scroll to ensure focused item still in view
if self.viewport_opt.map(|v| v.size()) != Some(viewport.size()) { if self.viewport_opt.map(|v| v.size()) != Some(viewport.size())
if let Some(offset) = self.select_focus_scroll() { && let Some(offset) = self.select_focus_scroll()
commands.push(Command::Iced( {
scrollable::scroll_to(self.scrollable_id.clone(), offset).into(), commands.push(Command::Iced(
)); scrollable::scroll_to(self.scrollable_id.clone(), offset).into(),
} ));
} }
self.viewport_opt = Some(viewport); self.viewport_opt = Some(viewport);
@ -4099,20 +4092,17 @@ impl Tab {
} }
} }
Message::SelectLast => { Message::SelectLast => {
if let Some(ref items) = self.items_opt { if let Some(ref items) = self.items_opt
if let Some(last_pos) = items.iter().filter_map(|item| item.pos_opt.get()).max() && let Some(last_pos) = items.iter().filter_map(|item| item.pos_opt.get()).max()
{ && self.select_position(last_pos.0, last_pos.1, mod_shift)
if self.select_position(last_pos.0, last_pos.1, mod_shift) { {
if let Some(offset) = self.select_focus_scroll() { if let Some(offset) = self.select_focus_scroll() {
commands.push(Command::Iced( commands.push(Command::Iced(
scrollable::scroll_to(self.scrollable_id.clone(), offset) scrollable::scroll_to(self.scrollable_id.clone(), offset).into(),
.into(), ));
)); }
} if let Some(id) = self.select_focus_id() {
if let Some(id) = self.select_focus_id() { commands.push(Command::Iced(widget::button::focus(id).into()));
commands.push(Command::Iced(widget::button::focus(id).into()));
}
}
} }
} }
} }
@ -4136,13 +4126,13 @@ impl Tab {
} }
} }
Message::TabComplete(path, completions) => { Message::TabComplete(path, completions) => {
if let Some(edit_location) = &mut self.edit_location { if let Some(edit_location) = &mut self.edit_location
if edit_location.location.path_opt() == Some(&path) { && edit_location.location.path_opt() == Some(&path)
edit_location.completions = Some(completions); {
commands.push(Command::Iced( edit_location.completions = Some(completions);
widget::text_input::focus(self.edit_location_id.clone()).into(), commands.push(Command::Iced(
)); widget::text_input::focus(self.edit_location_id.clone()).into(),
} ));
} }
} }
Message::Thumbnail(path, thumbnail) => { Message::Thumbnail(path, thumbnail) => {
@ -4276,10 +4266,10 @@ impl Tab {
} }
Message::DirectorySize(path, dir_size) => { Message::DirectorySize(path, dir_size) => {
let location = Location::Path(path); let location = Location::Path(path);
if let Some(ref mut item) = self.parent_item_opt { if let Some(ref mut item) = self.parent_item_opt
if item.location_opt.as_ref() == Some(&location) { && item.location_opt.as_ref() == Some(&location)
item.dir_size.clone_from(&dir_size); {
} item.dir_size.clone_from(&dir_size);
} }
if let Some(ref mut items) = self.items_opt { if let Some(ref mut items) = self.items_opt {
for item in items.iter_mut() { for item in items.iter_mut() {
@ -4317,13 +4307,12 @@ impl Tab {
} else { } else {
// Select parent if location is not directory // Select parent if location is not directory
let mut selected_paths = None; let mut selected_paths = None;
if let Some(path) = location.path_opt() { if let Some(path) = location.path_opt()
if !path.is_dir() { && !path.is_dir()
if let Some(parent) = path.parent() { && let Some(parent) = path.parent()
selected_paths = Some(vec![path.clone()]); {
location = location.with_path(parent.to_path_buf()); selected_paths = Some(vec![path.clone()]);
} location = location.with_path(parent.to_path_buf());
}
} }
if location != self.location || selected_paths.is_some() { if location != self.location || selected_paths.is_some() {
if location.path_opt().is_none_or(|path| path.is_dir()) { if location.path_opt().is_none_or(|path| path.is_dir()) {
@ -4531,99 +4520,93 @@ impl Tab {
//TODO: display error messages when image not found? //TODO: display error messages when image not found?
let mut name_opt = None; let mut name_opt = None;
let mut element_opt: Option<Element<Message>> = None; let mut element_opt: Option<Element<Message>> = None;
if let Some(index) = self.select_focus { if let Some(index) = self.select_focus
if let Some(items) = &self.items_opt { && let Some(items) = &self.items_opt
if let Some(item) = items.get(index) { && let Some(item) = items.get(index)
name_opt = Some(widget::text::heading(&item.display_name)); {
match item name_opt = Some(widget::text::heading(&item.display_name));
.thumbnail_opt match item
.as_ref() .thumbnail_opt
.unwrap_or(&ItemThumbnail::NotImage) .as_ref()
{ .unwrap_or(&ItemThumbnail::NotImage)
ItemThumbnail::NotImage => {} {
ItemThumbnail::Image(handle, original_dims) => { ItemThumbnail::NotImage => {}
// Determine which image to show based on async decode state ItemThumbnail::Image(handle, original_dims) => {
let mut is_loading = false; // Determine which image to show based on async decode state
let mut error_msg_opt = None; let mut is_loading = false;
let image_handle = if let Some(path) = item.path_opt() { let mut error_msg_opt = None;
if let Some(error_msg) = self.large_image_manager.get_error(path) { let image_handle = if let Some(path) = item.path_opt() {
error_msg_opt = Some(error_msg.clone()); if let Some(error_msg) = self.large_image_manager.get_error(path) {
handle.clone() error_msg_opt = Some(error_msg.clone());
} else if self.large_image_manager.is_decoding(path) { handle.clone()
// Currently decoding (initial or re-decode) --> show cached/thumbnail with loading indicator } else if self.large_image_manager.is_decoding(path) {
is_loading = true; // Currently decoding (initial or re-decode) --> show cached/thumbnail with loading indicator
// Use decoded handle if available (re-decode), otherwise thumbnail (initial decode) is_loading = true;
self.large_image_manager // Use decoded handle if available (re-decode), otherwise thumbnail (initial decode)
.get_decoded(path) self.large_image_manager
.cloned() .get_decoded(path)
.unwrap_or_else(|| handle.clone()) .cloned()
} else if let Some(decoded_handle) = .unwrap_or_else(|| handle.clone())
self.large_image_manager.get_decoded(path) } else if let Some(decoded_handle) =
{ self.large_image_manager.get_decoded(path)
// Decoded and not currently decoding --> use it {
decoded_handle.clone() // Decoded and not currently decoding --> use it
} else if let Some((w, h)) = original_dims { decoded_handle.clone()
// Check if image needs tiling } else if let Some((w, h)) = original_dims {
if should_use_tiling(*w, *h) { // Check if image needs tiling
// Large image --> show thumbnail only if should_use_tiling(*w, *h) {
handle.clone() // Large image --> show thumbnail only
} else {
// Normal-sized image --> load full resolution directly
widget::image::Handle::from_path(path)
}
} else {
// No dimensions available --> show thumbnail
handle.clone()
}
} else {
handle.clone() handle.clone()
}; } else {
// Normal-sized image --> load full resolution directly
widget::image::Handle::from_path(path)
}
} else {
// No dimensions available --> show thumbnail
handle.clone()
}
} else {
handle.clone()
};
let content: cosmic::Element<'_, Message> = let content: cosmic::Element<'_, Message> =
if let Some(error_msg) = error_msg_opt { if let Some(error_msg) = error_msg_opt {
widget::column() widget::column()
.push(widget::image(image_handle)) .push(widget::image(image_handle))
.push(widget::text(format!("⚠ {}", error_msg)).size(13)) .push(widget::text(format!("⚠ {}", error_msg)).size(13))
.padding(space_xs) .padding(space_xs)
.align_x(cosmic::iced::Alignment::Center) .align_x(cosmic::iced::Alignment::Center)
.into() .into()
} else if is_loading { } else if is_loading {
widget::column() widget::column()
.push(widget::image(image_handle)) .push(widget::image(image_handle))
.push(widget::text("Loading higher resolution...").size(14)) .push(widget::text("Loading higher resolution...").size(14))
.padding(space_xs) .padding(space_xs)
.align_x(cosmic::iced::Alignment::Center) .align_x(cosmic::iced::Alignment::Center)
.into() .into()
} else { } else {
//TODO: use widget::image::viewer, when its zoom can be reset //TODO: use widget::image::viewer, when its zoom can be reset
widget::image(image_handle).into() widget::image(image_handle).into()
}; };
element_opt = element_opt = Some(widget::container(content).center(Length::Fill).into());
Some(widget::container(content).center(Length::Fill).into()); }
} ItemThumbnail::Svg(handle) => {
ItemThumbnail::Svg(handle) => { element_opt = Some(
element_opt = Some( widget::svg(handle.clone())
widget::svg(handle.clone()) .width(Length::Fill)
.width(Length::Fill) .height(Length::Fill)
.height(Length::Fill) .into(),
.into(), );
); }
} ItemThumbnail::Text(text) => {
ItemThumbnail::Text(text) => { element_opt = Some(
element_opt = Some( widget::container(widget::text_editor(text).padding(space_xxs).class(
widget::container( cosmic::theme::iced::TextEditor::Custom(Box::new(text_editor_class)),
widget::text_editor(text).padding(space_xxs).class( ))
cosmic::theme::iced::TextEditor::Custom(Box::new( .center(Length::Fill)
text_editor_class, .into(),
)), );
),
)
.center(Length::Fill)
.into(),
);
}
}
} }
} }
} }
@ -4862,32 +4845,32 @@ impl Tab {
); );
let mut popover = let mut popover =
widget::popover(text_input).position(widget::popover::Position::Bottom); widget::popover(text_input).position(widget::popover::Position::Bottom);
if let Some(completions) = &edit_location.completions { if let Some(completions) = &edit_location.completions
if !completions.is_empty() { && !completions.is_empty()
let mut column = {
widget::column::with_capacity(completions.len()).padding(space_xxs); let mut column =
for (i, (name, _path)) in completions.iter().enumerate() { widget::column::with_capacity(completions.len()).padding(space_xxs);
let selected = edit_location.selected == Some(i); for (i, (name, _path)) in completions.iter().enumerate() {
column = column.push( let selected = edit_location.selected == Some(i);
widget::button::custom(widget::text::body(name)) column = column.push(
//TODO: match to design widget::button::custom(widget::text::body(name))
.class(if selected { //TODO: match to design
theme::Button::Standard .class(if selected {
} else { theme::Button::Standard
theme::Button::HeaderBar } else {
}) theme::Button::HeaderBar
.on_press(Message::EditLocationComplete(i)) })
.padding(space_xxs) .on_press(Message::EditLocationComplete(i))
.width(Length::Fill), .padding(space_xxs)
); .width(Length::Fill),
}
popover = popover.popup(
widget::container(column)
.class(theme::Container::Dropdown)
//TODO: This is a hack to get the popover to be the right width
.max_width(size.width - 140.0),
); );
} }
popover = popover.popup(
widget::container(column)
.class(theme::Container::Dropdown)
//TODO: This is a hack to get the popover to be the right width
.max_width(size.width - 140.0),
);
} }
row = row.push(popover); row = row.push(popover);
let mut column = widget::column::with_capacity(4).padding([0, space_s]); let mut column = widget::column::with_capacity(4).padding([0, space_s]);
@ -5913,13 +5896,13 @@ impl Tab {
.wayland_on_right_press_window_position(); .wayland_on_right_press_window_position();
let mut popover = widget::popover(mouse_area); let mut popover = widget::popover(mouse_area);
if let Some(point) = self.context_menu { if let Some(point) = self.context_menu
if !cfg!(feature = "wayland") || !crate::is_wayland() { && (!cfg!(feature = "wayland") || !crate::is_wayland())
let context_menu = menu::context_menu(self, key_binds, &modifiers); {
popover = popover let context_menu = menu::context_menu(self, key_binds, modifiers);
.popup(context_menu) popover = popover
.position(widget::popover::Position::Point(point)); .popup(context_menu)
} .position(widget::popover::Position::Point(point));
} }
let mut tab_column = widget::column::with_capacity(3); let mut tab_column = widget::column::with_capacity(3);
@ -5939,21 +5922,21 @@ impl Tab {
} }
match &self.location { match &self.location {
Location::Trash => { Location::Trash => {
if let Some(items) = self.items_opt() { if let Some(items) = self.items_opt()
if !items.is_empty() { && !items.is_empty()
tab_column = tab_column.push( {
widget::layer_container(widget::row::with_children([ tab_column = tab_column.push(
widget::horizontal_space().into(), widget::layer_container(widget::row::with_children([
widget::button::standard(fl!("empty-trash")) widget::horizontal_space().into(),
.on_press(Message::EmptyTrash) widget::button::standard(fl!("empty-trash"))
.into(), .on_press(Message::EmptyTrash)
])) .into(),
.padding([space_xxs, space_xs]) ]))
.layer(cosmic_theme::Layer::Primary) .padding([space_xxs, space_xs])
.apply(widget::container) .layer(cosmic_theme::Layer::Primary)
.padding([0, 0, 7, 0]), .apply(widget::container)
); .padding([0, 0, 7, 0]),
} );
} }
} }
Location::Network(uri, _display_name, _path) if uri == "network:///" => { Location::Network(uri, _display_name, _path) if uri == "network:///" => {
@ -6250,10 +6233,10 @@ impl Tab {
let mut selected_items: Vec<&Item> = let mut selected_items: Vec<&Item> =
items.iter().filter(|item| item.selected).collect(); items.iter().filter(|item| item.selected).collect();
if selected_items.is_empty() { if selected_items.is_empty()
if let Some(p) = self.parent_item_opt.as_ref() { && let Some(p) = self.parent_item_opt.as_ref()
selected_items.push(p) {
} selected_items.push(p)
} }
for item in selected_items { for item in selected_items {
// Item must have a path // Item must have a path

View file

@ -66,10 +66,10 @@ impl ThumbnailCacher {
if let (Some(cache_base_dir), Ok(metadata)) = ( if let (Some(cache_base_dir), Ok(metadata)) = (
THUMBNAIL_CACHE_BASE_DIR.as_ref(), THUMBNAIL_CACHE_BASE_DIR.as_ref(),
std::fs::metadata(&self.file_path), std::fs::metadata(&self.file_path),
) { ) && metadata.is_file()
if metadata.is_file() && self.file_path.starts_with(cache_base_dir) { && self.file_path.starts_with(cache_base_dir)
return CachedThumbnail::Valid((self.file_path.clone(), None)); {
} return CachedThumbnail::Valid((self.file_path.clone(), None));
} }
// Use cached thumbnail if it is valid. // Use cached thumbnail if it is valid.