cosmic-files/src/main.rs

1140 lines
40 KiB
Rust
Raw Normal View History

2024-01-03 15:27:32 -07:00
// Copyright 2023 System76 <info@system76.com>
// SPDX-License-Identifier: GPL-3.0-only
use cosmic::{
app::{message, Command, Core, Settings},
2024-01-03 15:27:32 -07:00
cosmic_config::{self, CosmicConfigEntry},
cosmic_theme, executor,
iced::{
event,
2024-01-30 11:26:23 -07:00
futures::{self, SinkExt},
keyboard::{Event as KeyEvent, KeyCode, Modifiers},
subscription::{self, Subscription},
2024-01-10 12:57:30 -07:00
window, Event, Length, Point,
},
2024-01-03 15:27:32 -07:00
style,
widget::{self, segmented_button},
Application, ApplicationExt, Element,
};
2024-01-30 11:26:23 -07:00
use notify::Watcher;
use std::{
any::TypeId,
2024-01-30 11:26:23 -07:00
collections::{BTreeMap, HashMap, HashSet},
env, fs, io,
path::PathBuf,
process, time,
};
2024-01-03 15:27:32 -07:00
use config::{AppTheme, Config, CONFIG_VERSION};
mod config;
2024-01-29 12:21:54 -07:00
use key_bind::{key_binds, KeyBind};
mod key_bind;
2024-01-29 11:58:50 -07:00
mod localize;
2024-01-05 11:18:38 -07:00
mod menu;
mod mouse_area;
mod mime_icon;
use operation::Operation;
2024-01-29 11:58:50 -07:00
mod operation;
use tab::{ItemMetadata, Location, Tab};
2024-01-03 15:27:32 -07:00
mod tab;
/// Runs application with these settings
#[rustfmt::skip]
fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(all(unix, not(target_os = "redox")))]
match fork::daemon(true, true) {
Ok(fork::Fork::Child) => (),
Ok(fork::Fork::Parent(_child_pid)) => process::exit(0),
Err(err) => {
eprintln!("failed to daemonize: {:?}", err);
process::exit(1);
}
}
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init();
localize::localize();
let (config_handler, config) = match cosmic_config::Config::new(App::APP_ID, CONFIG_VERSION) {
Ok(config_handler) => {
let config = match Config::get_entry(&config_handler) {
Ok(ok) => ok,
Err((errs, config)) => {
log::info!("errors loading config: {:?}", errs);
config
}
};
(Some(config_handler), config)
}
Err(err) => {
log::error!("failed to create config handler: {}", err);
(None, Config::default())
}
};
let mut settings = Settings::default();
settings = settings.theme(config.app_theme.theme());
#[cfg(target_os = "redox")]
{
// Redox does not support resize if doing CSDs
settings = settings.client_decorations(false);
}
//TODO: allow size limits on iced_winit
//settings = settings.size_limits(Limits::NONE.min_width(400.0).min_height(200.0));
let flags = Flags {
config_handler,
config,
};
cosmic::app::run::<App>(settings, flags)?;
Ok(())
}
2024-01-03 17:04:08 -07:00
fn home_dir() -> PathBuf {
match dirs::home_dir() {
Some(home) => home,
None => {
log::warn!("failed to locate home directory");
PathBuf::from("/")
}
}
}
2024-01-03 15:27:32 -07:00
#[derive(Clone, Debug)]
pub struct Flags {
config_handler: Option<cosmic_config::Config>,
config: Config,
}
2024-01-29 12:21:54 -07:00
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2024-01-03 15:27:32 -07:00
pub enum Action {
Copy,
2024-01-10 11:39:04 -07:00
Cut,
2024-01-05 16:17:23 -07:00
MoveToTrash,
2024-01-05 12:33:54 -07:00
NewFile,
NewFolder,
2024-01-03 15:27:32 -07:00
Paste,
2024-01-05 14:44:20 -07:00
Properties,
2024-01-10 09:47:47 -07:00
RestoreFromTrash,
2024-01-03 15:27:32 -07:00
SelectAll,
Settings,
2024-01-29 12:21:54 -07:00
TabClose,
2024-01-03 15:27:32 -07:00
TabNew,
2024-01-29 12:21:54 -07:00
TabNext,
TabPrev,
TabViewGrid,
TabViewList,
WindowClose,
WindowNew,
2024-01-03 15:27:32 -07:00
}
impl Action {
2024-01-29 12:21:54 -07:00
pub fn message(self, entity_opt: Option<segmented_button::Entity>) -> Message {
2024-01-03 15:27:32 -07:00
match self {
2024-01-29 12:21:54 -07:00
Action::Copy => Message::Copy(entity_opt),
Action::Cut => Message::Cut(entity_opt),
Action::MoveToTrash => Message::MoveToTrash(entity_opt),
Action::NewFile => Message::NewFile(entity_opt),
Action::NewFolder => Message::NewFolder(entity_opt),
Action::Paste => Message::Paste(entity_opt),
2024-01-05 14:44:20 -07:00
Action::Properties => Message::ToggleContextPage(ContextPage::Properties),
2024-01-29 12:21:54 -07:00
Action::RestoreFromTrash => Message::RestoreFromTrash(entity_opt),
Action::SelectAll => Message::SelectAll(entity_opt),
2024-01-03 15:27:32 -07:00
Action::Settings => Message::ToggleContextPage(ContextPage::Settings),
2024-01-29 12:21:54 -07:00
Action::TabClose => Message::TabClose(entity_opt),
2024-01-03 15:27:32 -07:00
Action::TabNew => Message::TabNew,
2024-01-29 12:21:54 -07:00
Action::TabNext => Message::TabNext,
Action::TabPrev => Message::TabPrev,
Action::TabViewGrid => {
Message::TabMessage(entity_opt, tab::Message::View(tab::View::Grid))
}
Action::TabViewList => {
Message::TabMessage(entity_opt, tab::Message::View(tab::View::List))
}
2024-01-29 12:21:54 -07:00
Action::WindowClose => Message::WindowClose,
Action::WindowNew => Message::WindowNew,
2024-01-03 15:27:32 -07:00
}
}
}
/// Messages that are used specifically by our [`App`].
#[derive(Clone, Debug)]
pub enum Message {
Todo,
AppTheme(AppTheme),
Config(Config),
2024-01-05 11:18:38 -07:00
Copy(Option<segmented_button::Entity>),
2024-01-10 11:39:04 -07:00
Cut(Option<segmented_button::Entity>),
2024-01-29 12:21:54 -07:00
Key(Modifiers, KeyCode),
Modifiers(Modifiers),
2024-01-05 16:17:23 -07:00
MoveToTrash(Option<segmented_button::Entity>),
2024-01-05 12:33:54 -07:00
NewFile(Option<segmented_button::Entity>),
NewFolder(Option<segmented_button::Entity>),
2024-01-30 11:26:23 -07:00
NotifyEvent(notify::Event),
NotifyWatcher(WatcherWrapper),
2024-01-05 11:18:38 -07:00
Paste(Option<segmented_button::Entity>),
PendingComplete(u64),
PendingError(u64, String),
PendingProgress(u64, f32),
2024-01-10 09:47:47 -07:00
RestoreFromTrash(Option<segmented_button::Entity>),
2024-01-05 11:18:38 -07:00
SelectAll(Option<segmented_button::Entity>),
2024-01-03 15:27:32 -07:00
SystemThemeModeChange(cosmic_theme::ThemeMode),
TabActivate(segmented_button::Entity),
TabNext,
TabPrev,
2024-01-10 11:39:04 -07:00
TabClose(Option<segmented_button::Entity>),
2024-01-03 15:27:32 -07:00
TabContextAction(segmented_button::Entity, Action),
TabContextMenu(segmented_button::Entity, Option<Point>),
2024-01-10 11:39:04 -07:00
TabMessage(Option<segmented_button::Entity>, tab::Message),
2024-01-03 15:27:32 -07:00
TabNew,
TabRescan(segmented_button::Entity, Vec<tab::Item>),
2024-01-03 15:27:32 -07:00
ToggleContextPage(ContextPage),
2024-01-10 11:39:04 -07:00
WindowClose,
WindowNew,
2024-01-03 15:27:32 -07:00
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContextPage {
Operations,
2024-01-05 14:44:20 -07:00
Properties,
2024-01-03 15:27:32 -07:00
Settings,
}
impl ContextPage {
fn title(&self) -> String {
match self {
Self::Operations => fl!("operations"),
2024-01-05 14:44:20 -07:00
Self::Properties => fl!("properties"),
2024-01-03 15:27:32 -07:00
Self::Settings => fl!("settings"),
}
}
}
2024-01-30 11:26:23 -07:00
#[derive(Debug)]
pub struct WatcherWrapper {
watcher_opt: Option<notify::RecommendedWatcher>,
}
impl Clone for WatcherWrapper {
fn clone(&self) -> Self {
Self { watcher_opt: None }
}
}
impl PartialEq for WatcherWrapper {
fn eq(&self, _other: &Self) -> bool {
false
}
}
2024-01-03 15:27:32 -07:00
/// The [`App`] stores application-specific state.
pub struct App {
core: Core,
2024-01-09 15:34:48 -07:00
nav_model: segmented_button::SingleSelectModel,
2024-01-03 15:27:32 -07:00
tab_model: segmented_button::Model<segmented_button::SingleSelect>,
config_handler: Option<cosmic_config::Config>,
config: Config,
app_themes: Vec<String>,
context_page: ContextPage,
2024-01-29 12:21:54 -07:00
key_binds: HashMap<KeyBind, Action>,
modifiers: Modifiers,
pending_operation_id: u64,
pending_operations: BTreeMap<u64, (Operation, f32)>,
complete_operations: BTreeMap<u64, Operation>,
failed_operations: BTreeMap<u64, (Operation, String)>,
2024-01-30 11:26:23 -07:00
watcher_opt: Option<(notify::RecommendedWatcher, HashSet<PathBuf>)>,
2024-01-03 15:27:32 -07:00
}
impl App {
2024-01-05 16:17:23 -07:00
fn open_tab(&mut self, location: Location) -> Command<Message> {
let tab = Tab::new(location.clone());
let entity = self
.tab_model
2024-01-03 15:27:32 -07:00
.insert()
.text(tab.title())
.data(tab)
.closable()
.activate()
.id();
2024-01-30 11:26:23 -07:00
Command::batch([
self.update_title(),
self.update_watcher(),
self.rescan_tab(entity, location),
])
}
fn operation(&mut self, operation: Operation) {
let id = self.pending_operation_id;
self.pending_operation_id += 1;
self.pending_operations.insert(id, (operation, 0.0));
//TODO: have some button to show current status
self.core.window.show_context = true;
self.context_page = ContextPage::Operations;
}
2024-01-05 16:17:23 -07:00
fn rescan_tab(
&mut self,
entity: segmented_button::Entity,
2024-01-05 16:17:23 -07:00
location: Location,
) -> Command<Message> {
Command::perform(
async move {
2024-01-05 16:17:23 -07:00
match tokio::task::spawn_blocking(move || location.scan()).await {
Ok(items) => message::app(Message::TabRescan(entity, items)),
Err(err) => {
log::warn!("failed to rescan: {}", err);
message::none()
}
}
},
|x| x,
)
2024-01-03 15:27:32 -07:00
}
fn update_config(&mut self) -> Command<Message> {
cosmic::app::command::set_theme(self.config.app_theme.theme())
}
fn save_config(&mut self) -> Command<Message> {
match self.config_handler {
Some(ref config_handler) => match self.config.write_entry(&config_handler) {
Ok(()) => {}
Err(err) => {
log::error!("failed to save config: {}", err);
}
},
None => {}
}
self.update_config()
}
fn update_title(&mut self) -> Command<Message> {
let (header_title, window_title) = match self.tab_model.text(self.tab_model.active()) {
Some(tab_title) => (
tab_title.to_string(),
format!("{tab_title} — COSMIC File Manager"),
),
None => (String::new(), "COSMIC File Manager".to_string()),
};
self.set_header_title(header_title);
self.set_window_title(window_title)
}
2024-01-30 11:26:23 -07:00
fn update_watcher(&mut self) -> Command<Message> {
if let Some((mut watcher, old_paths)) = self.watcher_opt.take() {
let mut new_paths = HashSet::new();
for entity in self.tab_model.iter() {
if let Some(tab) = self.tab_model.data::<Tab>(entity) {
if let Location::Path(path) = &tab.location {
new_paths.insert(path.clone());
}
}
}
// Unwatch paths no longer used
for path in old_paths.iter() {
if !new_paths.contains(path) {
match watcher.unwatch(path) {
Ok(()) => {
log::debug!("unwatching {:?}", path);
}
Err(err) => {
log::debug!("failed to unwatch {:?}: {}", path, err);
}
}
}
}
// Watch new paths
for path in new_paths.iter() {
if !old_paths.contains(path) {
//TODO: should this be recursive?
match watcher.watch(path, notify::RecursiveMode::NonRecursive) {
Ok(()) => {
log::debug!("watching {:?}", path);
}
Err(err) => {
log::debug!("failed to watch {:?}: {}", path, err);
}
}
}
}
self.watcher_opt = Some((watcher, new_paths));
}
//TODO: should any of this run in a command?
Command::none()
}
fn operations(&self) -> Element<Message> {
let mut children = Vec::new();
//TODO: get height from theme?
let progress_bar_height = Length::Fixed(4.0);
if !self.pending_operations.is_empty() {
let mut section = widget::settings::view_section(fl!("pending"));
for (id, (op, progress)) in self.pending_operations.iter().rev() {
section = section.add(widget::column::with_children(vec![
widget::text(format!("{:?}", op)).into(),
widget::progress_bar(0.0..=100.0, *progress)
.height(progress_bar_height)
.into(),
]));
}
children.push(section.into());
}
if !self.failed_operations.is_empty() {
let mut section = widget::settings::view_section(fl!("failed"));
for (id, (op, error)) in self.failed_operations.iter().rev() {
section = section.add(widget::column::with_children(vec![
widget::text(format!("{:?}", op)).into(),
widget::text(error).into(),
]));
}
children.push(section.into());
}
if !self.complete_operations.is_empty() {
let mut section = widget::settings::view_section(fl!("complete"));
for (id, op) in self.complete_operations.iter().rev() {
section = section.add(widget::text(format!("{:?}", op)));
}
children.push(section.into());
}
widget::settings::view_column(children).into()
}
2024-01-05 14:44:20 -07:00
fn properties(&self) -> Element<Message> {
let mut children = Vec::new();
let entity = self.tab_model.active();
if let Some(tab) = self.tab_model.data::<Tab>(entity) {
if let Some(ref items) = tab.items_opt {
for item in items.iter() {
2024-01-10 09:47:47 -07:00
if item.selected {
2024-01-05 14:58:50 -07:00
children.push(item.property_view(&self.core));
2024-01-05 14:44:20 -07:00
}
}
}
}
widget::settings::view_column(children).into()
}
2024-01-03 15:27:32 -07:00
fn settings(&self) -> Element<Message> {
let app_theme_selected = match self.config.app_theme {
AppTheme::Dark => 1,
AppTheme::Light => 2,
AppTheme::System => 0,
};
widget::settings::view_column(vec![widget::settings::view_section(fl!("appearance"))
.add(
widget::settings::item::builder(fl!("theme")).control(widget::dropdown(
&self.app_themes,
Some(app_theme_selected),
move |index| {
Message::AppTheme(match index {
1 => AppTheme::Dark,
2 => AppTheme::Light,
_ => AppTheme::System,
})
},
)),
)
.into()])
.into()
}
}
/// Implement [`Application`] to integrate with COSMIC.
impl Application for App {
/// Default async executor to use with the app.
type Executor = executor::Default;
/// Argument received
type Flags = Flags;
/// Message type specific to our [`App`].
type Message = Message;
/// The unique application ID to supply to the window manager.
const APP_ID: &'static str = "com.system76.CosmicFiles";
fn core(&self) -> &Core {
&self.core
}
fn core_mut(&mut self) -> &mut Core {
&mut self.core
}
/// Creates the application, and optionally emits command on initialize.
fn init(core: Core, flags: Self::Flags) -> (Self, Command<Self::Message>) {
let app_themes = vec![fl!("match-desktop"), fl!("dark"), fl!("light")];
2024-01-09 15:34:48 -07:00
let mut nav_model = segmented_button::ModelBuilder::default();
if let Some(dir) = dirs::home_dir() {
nav_model = nav_model.insert(move |b| {
b.text(fl!("home"))
.icon(widget::icon::icon(tab::folder_icon_symbolic(&dir, 16)).size(16))
.data(Location::Path(dir.clone()))
});
}
2024-01-09 15:34:48 -07:00
//TODO: Sort by name?
for dir_opt in &[
dirs::document_dir(),
dirs::download_dir(),
dirs::audio_dir(),
dirs::picture_dir(),
dirs::video_dir(),
] {
if let Some(dir) = dir_opt {
if let Some(file_name) = dir.file_name().and_then(|x| x.to_str()) {
nav_model = nav_model.insert(move |b| {
b.text(file_name.to_string())
.icon(widget::icon::icon(tab::folder_icon_symbolic(&dir, 16)).size(16))
.data(Location::Path(dir.clone()))
});
}
}
}
nav_model = nav_model.insert(|b| {
b.text(fl!("trash"))
.icon(widget::icon::icon(tab::trash_icon_symbolic(16)))
2024-01-09 15:34:48 -07:00
.data(Location::Trash)
});
2024-01-03 15:27:32 -07:00
let mut app = App {
core,
2024-01-09 15:34:48 -07:00
nav_model: nav_model.build(),
2024-01-03 15:27:32 -07:00
tab_model: segmented_button::ModelBuilder::default().build(),
config_handler: flags.config_handler,
config: flags.config,
app_themes,
context_page: ContextPage::Settings,
2024-01-29 12:21:54 -07:00
key_binds: key_binds(),
modifiers: Modifiers::empty(),
pending_operation_id: 0,
pending_operations: BTreeMap::new(),
complete_operations: BTreeMap::new(),
failed_operations: BTreeMap::new(),
2024-01-30 11:26:23 -07:00
watcher_opt: None,
2024-01-03 15:27:32 -07:00
};
let mut commands = Vec::new();
2024-01-03 15:27:32 -07:00
for arg in env::args().skip(1) {
2024-01-05 16:17:23 -07:00
let location = match fs::canonicalize(&arg) {
Ok(absolute) => Location::Path(absolute),
Err(err) => {
log::warn!("failed to canonicalize {:?}: {}", arg, err);
continue;
}
};
commands.push(app.open_tab(location));
2024-01-03 15:27:32 -07:00
}
if app.tab_model.iter().next().is_none() {
2024-01-05 16:17:23 -07:00
commands.push(app.open_tab(Location::Path(home_dir())));
2024-01-03 15:27:32 -07:00
}
(app, Command::batch(commands))
2024-01-03 15:27:32 -07:00
}
// The default nav_bar widget needs to have its width reduced for cosmic-files
fn nav_bar(&self) -> Option<Element<message::Message<Self::Message>>> {
if !self.core().nav_bar_active() {
return None;
}
let nav_model = self.nav_model()?;
let mut nav = crate::widget::nav_bar(nav_model, |entity| {
message::cosmic(cosmic::app::cosmic::Message::NavBar(entity))
});
if !self.core().is_condensed() {
nav = nav.max_width(200);
}
Some(Element::from(nav))
}
2024-01-09 15:34:48 -07:00
fn nav_model(&self) -> Option<&segmented_button::SingleSelectModel> {
Some(&self.nav_model)
}
fn on_nav_select(&mut self, entity: segmented_button::Entity) -> Command<Self::Message> {
let location_opt = self.nav_model.data::<Location>(entity).clone();
if let Some(location) = location_opt {
2024-01-10 11:39:04 -07:00
let message = Message::TabMessage(None, tab::Message::Location(location.clone()));
2024-01-09 15:34:48 -07:00
return self.update(message);
}
Command::none()
}
2024-01-03 15:27:32 -07:00
/// Handle application events here.
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
// Helper for updating config values efficiently
macro_rules! config_set {
($name: ident, $value: expr) => {
match &self.config_handler {
Some(config_handler) => {
match paste::paste! { self.config.[<set_ $name>](config_handler, $value) } {
Ok(_) => {}
Err(err) => {
log::warn!(
"failed to save config {:?}: {}",
stringify!($name),
err
);
}
}
}
None => {
self.config.$name = $value;
log::warn!(
"failed to save config {:?}: no config handler",
stringify!($name)
);
}
}
};
}
2024-01-03 15:27:32 -07:00
match message {
Message::Todo => {
log::warn!("TODO");
}
Message::AppTheme(app_theme) => {
config_set!(app_theme, app_theme);
return self.update_config();
2024-01-03 15:27:32 -07:00
}
Message::Config(config) => {
if config != self.config {
log::info!("update config");
//TODO: update syntax theme by clearing tabs, only if needed
self.config = config;
return self.update_config();
}
}
2024-01-05 11:18:38 -07:00
Message::Copy(entity_opt) => {
log::warn!("TODO: COPY");
}
2024-01-10 11:39:04 -07:00
Message::Cut(entity_opt) => {
log::warn!("TODO: CUT");
}
2024-01-29 12:21:54 -07:00
Message::Key(modifiers, key_code) => {
let entity = self.tab_model.active();
for (key_bind, action) in self.key_binds.iter() {
if key_bind.matches(modifiers, key_code) {
return self.update(action.message(Some(entity)));
}
}
}
Message::Modifiers(modifiers) => {
self.modifiers = modifiers;
}
2024-01-05 16:17:23 -07:00
Message::MoveToTrash(entity_opt) => {
let mut paths = Vec::new();
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(ref mut items) = tab.items_opt {
for item in items.iter_mut() {
if item.selected {
paths.push(item.path.clone());
}
}
}
}
if !paths.is_empty() {
self.operation(Operation::Delete { paths });
}
2024-01-05 16:17:23 -07:00
}
2024-01-05 12:33:54 -07:00
Message::NewFile(entity_opt) => {
log::warn!("TODO: NEW FILE");
}
Message::NewFolder(entity_opt) => {
log::warn!("TODO: NEW FOLDER");
}
2024-01-30 11:26:23 -07:00
Message::NotifyEvent(event) => {
log::debug!("{:?}", event);
let mut needs_reload = Vec::new();
for entity in self.tab_model.iter() {
if let Some(tab) = self.tab_model.data::<Tab>(entity) {
//TODO: support reloading trash, somehow
if let Location::Path(path) = &tab.location {
let mut contains_change = false;
for event_path in event.paths.iter() {
if event_path.starts_with(&path) {
contains_change = true;
break;
}
}
if contains_change {
needs_reload.push((entity, tab.location.clone()));
}
}
}
}
let mut commands = Vec::with_capacity(needs_reload.len());
for (entity, location) in needs_reload {
commands.push(self.rescan_tab(entity, location));
}
return Command::batch(commands);
}
Message::NotifyWatcher(mut watcher_wrapper) => match watcher_wrapper.watcher_opt.take()
{
Some(mut watcher) => {
self.watcher_opt = Some((watcher, HashSet::new()));
return self.update_watcher();
}
None => {
log::warn!("message did not contain notify watcher");
}
},
2024-01-05 11:18:38 -07:00
Message::Paste(entity_opt) => {
log::warn!("TODO: PASTE");
}
Message::PendingComplete(id) => {
if let Some((op, _)) = self.pending_operations.remove(&id) {
self.complete_operations.insert(id, op);
}
}
Message::PendingError(id, err) => {
if let Some((op, _)) = self.pending_operations.remove(&id) {
self.failed_operations.insert(id, (op, err));
}
}
Message::PendingProgress(id, new_progress) => {
if let Some((_, progress)) = self.pending_operations.get_mut(&id) {
*progress = new_progress;
}
}
2024-01-10 09:47:47 -07:00
Message::RestoreFromTrash(entity_opt) => {
let mut paths = Vec::new();
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(ref mut items) = tab.items_opt {
for item in items.iter_mut() {
if item.selected {
match &item.metadata {
ItemMetadata::Trash { entry, .. } => {
paths.push(entry.clone());
}
_ => {
//TODO: error on trying to restore non-trash file?
}
}
}
}
}
}
if !paths.is_empty() {
self.operation(Operation::Restore { paths });
}
2024-01-10 09:47:47 -07:00
}
2024-01-05 11:18:38 -07:00
Message::SelectAll(entity_opt) => {
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(ref mut items) = tab.items_opt {
for item in items.iter_mut() {
2024-01-05 14:58:50 -07:00
if item.hidden {
//TODO: option to show hidden files
continue;
}
2024-01-10 09:47:47 -07:00
item.selected = true;
item.click_time = None;
2024-01-05 11:18:38 -07:00
}
}
}
}
2024-01-03 15:27:32 -07:00
Message::SystemThemeModeChange(_theme_mode) => {
return self.update_config();
}
Message::TabActivate(entity) => {
self.tab_model.activate(entity);
return self.update_title();
}
Message::TabNext => {
let len = self.tab_model.iter().count();
let pos = self
.tab_model
.position(self.tab_model.active())
// Wraparound to 0 if i + 1 > num of tabs
.map(|i| (i as usize + 1) % len)
.expect("should always be at least one tab open");
let entity = self.tab_model.iter().nth(pos);
if let Some(entity) = entity {
return self.update(Message::TabActivate(entity));
}
}
Message::TabPrev => {
let pos = self
.tab_model
.position(self.tab_model.active())
.and_then(|i| (i as usize).checked_sub(1))
// Subtraction underflow => last tab; i.e. it wraps around
.unwrap_or_else(|| {
self.tab_model
.iter()
.count()
.checked_sub(1)
.unwrap_or_default()
});
let entity = self.tab_model.iter().nth(pos);
if let Some(entity) = entity {
return self.update(Message::TabActivate(entity));
}
}
2024-01-10 11:39:04 -07:00
Message::TabClose(entity_opt) => {
let entity = entity_opt.unwrap_or_else(|| self.tab_model.active());
2024-01-03 15:27:32 -07:00
// Activate closest item
if let Some(position) = self.tab_model.position(entity) {
if position > 0 {
self.tab_model.activate_position(position - 1);
} else {
self.tab_model.activate_position(position + 1);
}
}
// Remove item
self.tab_model.remove(entity);
// If that was the last tab, close window
if self.tab_model.iter().next().is_none() {
return window::close(window::Id::MAIN);
}
2024-01-30 11:26:23 -07:00
return Command::batch([self.update_title(), self.update_watcher()]);
2024-01-03 15:27:32 -07:00
}
Message::TabContextAction(entity, action) => {
match self.tab_model.data_mut::<Tab>(entity) {
Some(tab) => {
// Close context menu
{
tab.context_menu = None;
}
// Run action's message
2024-01-29 12:21:54 -07:00
return self.update(action.message(Some(entity)));
2024-01-03 15:27:32 -07:00
}
_ => {}
}
}
Message::TabContextMenu(entity, position_opt) => {
match self.tab_model.data_mut::<Tab>(entity) {
Some(tab) => {
// Update context menu position
tab.context_menu = position_opt;
}
_ => {}
}
2024-01-05 15:10:46 -07:00
// Disable side context page
self.core.window.show_context = false;
2024-01-03 15:27:32 -07:00
}
2024-01-10 11:39:04 -07:00
Message::TabMessage(entity_opt, tab_message) => {
let entity = entity_opt.unwrap_or_else(|| self.tab_model.active());
let mut update_opt = None;
2024-01-03 15:27:32 -07:00
match self.tab_model.data_mut::<Tab>(entity) {
Some(tab) => {
if tab.update(tab_message, self.modifiers) {
2024-01-05 16:17:23 -07:00
update_opt = Some((tab.title(), tab.location.clone()));
2024-01-03 15:27:32 -07:00
}
}
_ => (),
}
if let Some((tab_title, tab_path)) = update_opt {
2024-01-03 15:27:32 -07:00
self.tab_model.text_set(entity, tab_title);
return Command::batch([
self.update_title(),
2024-01-30 11:26:23 -07:00
self.update_watcher(),
self.rescan_tab(entity, tab_path),
]);
2024-01-03 15:27:32 -07:00
}
}
Message::TabNew => {
let active = self.tab_model.active();
2024-01-05 16:17:23 -07:00
let location = match self.tab_model.data::<Tab>(active) {
Some(tab) => tab.location.clone(),
None => Location::Path(home_dir()),
2024-01-03 15:27:32 -07:00
};
2024-01-05 16:17:23 -07:00
return self.open_tab(location);
2024-01-03 15:27:32 -07:00
}
Message::TabRescan(entity, items) => match self.tab_model.data_mut::<Tab>(entity) {
Some(tab) => {
tab.items_opt = Some(items);
}
_ => (),
},
//TODO: TABRELOAD
2024-01-03 15:27:32 -07:00
Message::ToggleContextPage(context_page) => {
2024-01-05 15:10:46 -07:00
//TODO: ensure context menus are closed
2024-01-03 15:27:32 -07:00
if self.context_page == context_page {
self.core.window.show_context = !self.core.window.show_context;
} else {
self.context_page = context_page;
self.core.window.show_context = true;
}
self.set_context_title(context_page.title());
}
2024-01-10 11:39:04 -07:00
Message::WindowClose => {
return window::close(window::Id::MAIN);
}
Message::WindowNew => match env::current_exe() {
Ok(exe) => match process::Command::new(&exe).spawn() {
Ok(_child) => {}
Err(err) => {
log::error!("failed to execute {:?}: {}", exe, err);
}
},
Err(err) => {
log::error!("failed to get current executable path: {}", err);
}
},
2024-01-03 15:27:32 -07:00
}
Command::none()
}
fn context_drawer(&self) -> Option<Element<Message>> {
if !self.core.window.show_context {
return None;
}
Some(match self.context_page {
ContextPage::Operations => self.operations(),
2024-01-05 14:44:20 -07:00
ContextPage::Properties => self.properties(),
2024-01-03 15:27:32 -07:00
ContextPage::Settings => self.settings(),
})
}
fn header_start(&self) -> Vec<Element<Self::Message>> {
vec![menu::menu_bar(&self.key_binds).into()]
2024-01-10 12:57:30 -07:00
}
fn header_end(&self) -> Vec<Element<Self::Message>> {
vec![]
2024-01-09 15:34:48 -07:00
}
2024-01-03 15:27:32 -07:00
/// Creates a view after each update.
fn view(&self) -> Element<Self::Message> {
let cosmic_theme::Spacing { space_xxs, .. } = self.core().system_theme().cosmic().spacing;
let mut tab_column = widget::column::with_capacity(1);
if self.tab_model.iter().count() > 1 {
tab_column = tab_column.push(
widget::container(
widget::view_switcher::horizontal(&self.tab_model)
.button_height(32)
.button_spacing(space_xxs)
.on_activate(Message::TabActivate)
2024-01-10 11:39:04 -07:00
.on_close(|entity| Message::TabClose(Some(entity))),
2024-01-03 15:27:32 -07:00
)
.style(style::Container::Background)
.width(Length::Fill),
);
}
let entity = self.tab_model.active();
match self.tab_model.data::<Tab>(entity) {
Some(tab) => {
2024-01-05 11:18:38 -07:00
let mut mouse_area = mouse_area::MouseArea::new(
2024-01-03 15:27:32 -07:00
tab.view(self.core())
2024-01-10 11:39:04 -07:00
.map(move |message| Message::TabMessage(Some(entity), message)),
2024-01-05 11:18:38 -07:00
)
2024-01-10 11:39:04 -07:00
.on_press(move |_point_opt| {
Message::TabMessage(Some(entity), tab::Message::Click(None))
});
2024-01-05 11:18:38 -07:00
if tab.context_menu.is_some() {
mouse_area = mouse_area
.on_right_press(move |_point_opt| Message::TabContextMenu(entity, None));
} else {
mouse_area = mouse_area.on_right_press(move |point_opt| {
Message::TabContextMenu(entity, point_opt)
});
}
2024-01-10 10:15:16 -07:00
let mut popover = widget::popover(mouse_area, menu::context_menu(entity, &tab));
2024-01-05 11:18:38 -07:00
match tab.context_menu {
Some(point) => {
let rounded = Point::new(point.x.round(), point.y.round());
popover = popover.position(rounded);
2024-01-05 11:18:38 -07:00
}
None => {
popover = popover.show_popup(false);
}
}
tab_column = tab_column.push(popover);
2024-01-03 15:27:32 -07:00
}
None => {
//TODO
}
}
let content: Element<_> = tab_column.into();
// Uncomment to debug layout:
//content.explain(cosmic::iced::Color::WHITE)
content
}
fn subscription(&self) -> Subscription<Self::Message> {
struct ConfigSubscription;
struct ThemeSubscription;
2024-01-30 11:26:23 -07:00
struct WatcherSubscription;
2024-01-03 15:27:32 -07:00
let mut subscriptions = vec![
event::listen_with(|event, _status| match event {
Event::Keyboard(KeyEvent::KeyPressed {
2024-01-29 12:21:54 -07:00
key_code,
modifiers,
}) => Some(Message::Key(modifiers, key_code)),
Event::Keyboard(KeyEvent::ModifiersChanged(modifiers)) => {
2024-01-29 12:21:54 -07:00
Some(Message::Modifiers(modifiers))
}
_ => None,
}),
2024-01-03 15:27:32 -07:00
cosmic_config::config_subscription(
TypeId::of::<ConfigSubscription>(),
Self::APP_ID.into(),
CONFIG_VERSION,
)
.map(|update| {
if !update.errors.is_empty() {
log::info!(
"errors loading config {:?}: {:?}",
update.keys,
update.errors
);
2024-01-03 15:27:32 -07:00
}
Message::Config(update.config)
2024-01-03 15:27:32 -07:00
}),
cosmic_config::config_subscription::<_, cosmic_theme::ThemeMode>(
TypeId::of::<ThemeSubscription>(),
cosmic_theme::THEME_MODE_ID.into(),
cosmic_theme::ThemeMode::version(),
)
.map(|update| {
if !update.errors.is_empty() {
log::info!(
"errors loading theme mode {:?}: {:?}",
update.keys,
update.errors
);
2024-01-03 15:27:32 -07:00
}
Message::SystemThemeModeChange(update.config)
2024-01-03 15:27:32 -07:00
}),
2024-01-30 11:26:23 -07:00
subscription::channel(
TypeId::of::<WatcherSubscription>(),
100,
|mut output| async move {
let watcher_res = {
let mut output = output.clone();
//TODO: debounce
notify::recommended_watcher(
move |event_res: Result<notify::Event, notify::Error>| match event_res {
Ok(event) => {
match &event.kind {
notify::EventKind::Access(_)
| notify::EventKind::Modify(
notify::event::ModifyKind::Metadata(_),
) => {
// Data not mutated
return;
}
_ => {}
}
match futures::executor::block_on(async {
output.send(Message::NotifyEvent(event)).await
}) {
Ok(()) => {}
Err(err) => {
log::warn!("failed to send notify event: {:?}", err);
}
}
}
Err(err) => {
log::warn!("failed to watch files: {:?}", err);
}
},
)
};
match watcher_res {
Ok(watcher) => {
match output
.send(Message::NotifyWatcher(WatcherWrapper {
watcher_opt: Some(watcher),
}))
.await
{
Ok(()) => {}
Err(err) => {
log::warn!("failed to send notify watcher: {:?}", err);
}
}
}
Err(err) => {
log::warn!("failed to create file watcher: {:?}", err);
}
}
//TODO: how to properly kill this task?
loop {
tokio::time::sleep(time::Duration::new(1, 0)).await;
}
},
),
];
for (id, (pending_operation, _)) in self.pending_operations.iter() {
//TODO: use recipe?
let id = *id;
let pending_operation = pending_operation.clone();
subscriptions.push(subscription::channel(
id,
16,
move |mut msg_tx| async move {
match pending_operation.perform(id, &mut msg_tx).await {
Ok(()) => {
msg_tx.send(Message::PendingComplete(id)).await;
}
Err(err) => {
msg_tx
.send(Message::PendingError(id, err.to_string()))
.await;
}
}
loop {
tokio::time::sleep(time::Duration::new(1, 0)).await;
}
},
));
}
Subscription::batch(subscriptions)
2024-01-03 15:27:32 -07:00
}
}