diff --git a/Cargo.lock b/Cargo.lock index a373400..1135432 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -247,6 +247,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "arc-swap" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6" + [[package]] name = "arrayref" version = "0.3.7" @@ -901,8 +907,14 @@ dependencies = [ "alacritty_terminal", "cosmic-text", "env_logger", + "fork", + "i18n-embed", + "i18n-embed-fl", + "lazy_static", "libcosmic", "log", + "rust-embed", + "serde", "tokio", ] @@ -917,7 +929,7 @@ dependencies = [ "rangemap", "rustc-hash", "rustybuzz", - "self_cell", + "self_cell 1.0.3", "swash", "sys-locale", "unicode-bidi", @@ -1088,6 +1100,19 @@ dependencies = [ "syn 2.0.42", ] +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if 1.0.0", + "hashbrown 0.14.3", + "lock_api", + "once_cell", + "parking_lot_core 0.9.9", +] + [[package]] name = "data-url" version = "0.3.1" @@ -1174,6 +1199,17 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" +[[package]] +name = "displaydoc" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.42", +] + [[package]] name = "dlib" version = "0.5.2" @@ -1411,6 +1447,15 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "find-crate" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59a98bbaacea1c0eb6a0876280051b892eb73594fd90cf3b20e9c817029c57d2" +dependencies = [ + "toml 0.5.11", +] + [[package]] name = "flate2" version = "1.0.28" @@ -1433,6 +1478,50 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" +[[package]] +name = "fluent" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61f69378194459db76abd2ce3952b790db103ceb003008d3d50d97c41ff847a7" +dependencies = [ + "fluent-bundle", + "unic-langid", +] + +[[package]] +name = "fluent-bundle" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e242c601dec9711505f6d5bbff5bedd4b61b2469f2e8bb8e57ee7c9747a87ffd" +dependencies = [ + "fluent-langneg", + "fluent-syntax", + "intl-memoizer", + "intl_pluralrules", + "rustc-hash", + "self_cell 0.10.3", + "smallvec", + "unic-langid", +] + +[[package]] +name = "fluent-langneg" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ad0989667548f06ccd0e306ed56b61bd4d35458d54df5ec7587c0e8ed5e94" +dependencies = [ + "unic-langid", +] + +[[package]] +name = "fluent-syntax" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0abed97648395c902868fee9026de96483933faa54ea3b40d652f7dfe61ca78" +dependencies = [ + "thiserror", +] + [[package]] name = "flume" version = "0.10.14" @@ -1529,6 +1618,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "fork" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf2ca97a59201425e7ee4d197c9c4fea282fe87a97d666a580bda889b95b8e88" +dependencies = [ + "libc", +] + [[package]] name = "form_urlencoded" version = "1.2.1" @@ -1955,6 +2053,76 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" +[[package]] +name = "i18n-config" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ce3c48cbc21fd5b22b9331f32b5b51f6ad85d969b99e793427332e76e7640" +dependencies = [ + "log", + "serde", + "serde_derive", + "thiserror", + "toml 0.8.8", + "unic-langid", +] + +[[package]] +name = "i18n-embed" +version = "0.13.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92a86226a7a16632de6723449ee5fe70bac5af718bc642ee9ca2f0f6e14fa1fa" +dependencies = [ + "arc-swap", + "fluent", + "fluent-langneg", + "fluent-syntax", + "i18n-embed-impl", + "intl-memoizer", + "lazy_static", + "locale_config", + "log", + "parking_lot 0.12.1", + "rust-embed", + "thiserror", + "unic-langid", + "walkdir", +] + +[[package]] +name = "i18n-embed-fl" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26a3d3569737dfaac7fc1c4078e6af07471c3060b8e570bcd83cdd5f4685395" +dependencies = [ + "dashmap", + "find-crate", + "fluent", + "fluent-syntax", + "i18n-config", + "i18n-embed", + "lazy_static", + "proc-macro-error", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.42", + "unic-langid", +] + +[[package]] +name = "i18n-embed-impl" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81093c4701672f59416582fe3145676126fd23ba5db910acad0793c1108aaa58" +dependencies = [ + "find-crate", + "i18n-config", + "proc-macro2", + "quote", + "syn 2.0.42", +] + [[package]] name = "iced" version = "0.12.0" @@ -2226,6 +2394,25 @@ dependencies = [ "web-sys", ] +[[package]] +name = "intl-memoizer" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c310433e4a310918d6ed9243542a6b83ec1183df95dff8f23f87bb88a264a66f" +dependencies = [ + "type-map", + "unic-langid", +] + +[[package]] +name = "intl_pluralrules" +version = "7.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972" +dependencies = [ + "unic-langid", +] + [[package]] name = "io-lifetimes" version = "1.0.11" @@ -2480,6 +2667,19 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456" +[[package]] +name = "locale_config" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d2c35b16f4483f6c26f0e4e9550717a2f6575bcd6f12a53ff0c490a94a6934" +dependencies = [ + "lazy_static", + "objc", + "objc-foundation", + "regex", + "winapi 0.3.9", +] + [[package]] name = "lock_api" version = "0.4.11" @@ -3414,7 +3614,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" dependencies = [ "once_cell", - "toml_edit", + "toml_edit 0.19.15", ] [[package]] @@ -3698,6 +3898,40 @@ version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3cd14fd5e3b777a7422cca79358c57a8f6e3a703d9ac187448d0daf220c2407f" +[[package]] +name = "rust-embed" +version = "6.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a36224c3276f8c4ebc8c20f158eca7ca4359c8db89991c4925132aaaf6702661" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "6.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49b94b81e5b2c284684141a2fb9e2a31be90638caf040bf9afbc5a0416afe1ac" +dependencies = [ + "proc-macro2", + "quote", + "rust-embed-utils", + "syn 2.0.42", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "7.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d38ff6bf570dc3bb7100fce9f7b60c33fa71d80e88da3f2580df4ff2bdded74" +dependencies = [ + "sha2", + "walkdir", +] + [[package]] name = "rust-ini" version = "0.18.0" @@ -3803,6 +4037,15 @@ dependencies = [ "tiny-skia 0.8.4", ] +[[package]] +name = "self_cell" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14e4d63b804dc0c7ec4a1e52bcb63f02c7ac94476755aa579edac21e01f915d" +dependencies = [ + "self_cell 1.0.3", +] + [[package]] name = "self_cell" version = "1.0.3" @@ -3840,6 +4083,15 @@ dependencies = [ "syn 2.0.42", ] +[[package]] +name = "serde_spanned" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" +dependencies = [ + "serde", +] + [[package]] name = "serde_yaml" version = "0.8.26" @@ -3863,6 +4115,17 @@ dependencies = [ "digest", ] +[[package]] +name = "sha2" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" +dependencies = [ + "cfg-if 1.0.0", + "cpufeatures", + "digest", +] + [[package]] name = "signal-hook" version = "0.3.17" @@ -4253,6 +4516,15 @@ dependencies = [ "tracing", ] +[[package]] +name = "tinystr" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83c02bf3c538ab32ba913408224323915f4ef9a6d61c0e85d493f355921c0ece" +dependencies = [ + "displaydoc", +] + [[package]] name = "tinyvec" version = "1.6.0" @@ -4286,11 +4558,35 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "toml" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" +dependencies = [ + "serde", +] + +[[package]] +name = "toml" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a195ec8c9da26928f773888e0742ca3ca1040c6cd859c919c9f59c1954ab35" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit 0.21.0", +] + [[package]] name = "toml_datetime" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" +dependencies = [ + "serde", +] [[package]] name = "toml_edit" @@ -4303,6 +4599,19 @@ dependencies = [ "winnow", ] +[[package]] +name = "toml_edit" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d34d383cd00a163b4a5b85053df514d45bc330f6de7737edfe0a93311d1eaa03" +dependencies = [ + "indexmap 2.1.0", + "serde", + "serde_spanned", + "toml_datetime", + "winnow", +] + [[package]] name = "tracing" version = "0.1.40" @@ -4340,6 +4649,15 @@ version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4" +[[package]] +name = "type-map" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d3364c5e96cb2ad1603037ab253ddd34d7fb72a58bdddf4b7350760fc69a46" +dependencies = [ + "rustc-hash", +] + [[package]] name = "typenum" version = "1.17.0" @@ -4357,6 +4675,25 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "unic-langid" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238722e6d794ed130f91f4ea33e01fcff4f188d92337a21297892521c72df516" +dependencies = [ + "unic-langid-impl", +] + +[[package]] +name = "unic-langid-impl" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd55a2063fdea4ef1f8633243a7b0524cbeef1905ae04c31a1c9b9775c55bc6" +dependencies = [ + "serde", + "tinystr", +] + [[package]] name = "unicode-bidi" version = "0.3.14" diff --git a/Cargo.toml b/Cargo.toml index 4846a16..698f0d3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,8 +8,14 @@ edition = "2021" [dependencies] alacritty_terminal = "0.19" env_logger = "0.10" +lazy_static = "1" log = "0.4" -tokio = { version = "1.35", features = ["sync"] } +serde = { version = "1", features = ["serde_derive"] } +tokio = { version = "1", features = ["sync"] } +# Internationalization +i18n-embed = { version = "0.13", features = ["fluent-system", "desktop-requester"] } +i18n-embed-fl = "0.6" +rust-embed = "6" [dependencies.cosmic-text] git = "https://github.com/pop-os/cosmic-text.git" @@ -31,3 +37,6 @@ smithay-client-toolkit = { git = "https://github.com/pop-os/client-toolkit", bra [profile.release-with-debug] inherits = "release" debug = true + +[target.'cfg(unix)'.dependencies] +fork = "0.1" diff --git a/i18n.toml b/i18n.toml new file mode 100644 index 0000000..05c50ba --- /dev/null +++ b/i18n.toml @@ -0,0 +1,4 @@ +fallback_language = "en" + +[fluent] +assets_dir = "i18n" \ No newline at end of file diff --git a/i18n/en/cosmic_term.ftl b/i18n/en/cosmic_term.ftl new file mode 100644 index 0000000..4dd5d53 --- /dev/null +++ b/i18n/en/cosmic_term.ftl @@ -0,0 +1,15 @@ +# Context Pages + +## Settings +settings = Settings + +### Appearance +appearance = Appearance +theme = Theme +match-desktop = Match desktop +dark = Dark +light = Light +syntax-dark = Syntax dark +syntax-light = Syntax light +default-font = Default font +default-font-size = Default font size diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..e6977fe --- /dev/null +++ b/src/config.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-3.0-only + +use cosmic::{ + cosmic_config::{self, cosmic_config_derive::CosmicConfigEntry, CosmicConfigEntry}, + theme, +}; +use cosmic_text::Metrics; +use serde::{Deserialize, Serialize}; + +pub const CONFIG_VERSION: u64 = 1; + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub enum AppTheme { + Dark, + Light, + System, +} + +impl AppTheme { + pub fn theme(&self) -> theme::Theme { + match self { + Self::Dark => theme::Theme::dark(), + Self::Light => theme::Theme::light(), + Self::System => theme::system_preference(), + } + } +} + +#[derive(Clone, CosmicConfigEntry, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct Config { + pub app_theme: AppTheme, + pub font_name: String, + pub font_size: u16, + pub syntax_theme_dark: String, + pub syntax_theme_light: String, +} + +impl Default for Config { + fn default() -> Self { + Self { + app_theme: AppTheme::System, + font_name: "Fira Mono".to_string(), + font_size: 14, + syntax_theme_dark: "COSMIC Dark".to_string(), + syntax_theme_light: "COSMIC Light".to_string(), + } + } +} + +impl Config { + // Calculate metrics from font size + pub fn metrics(&self) -> Metrics { + let font_size = self.font_size.max(1) as f32; + let line_height = (font_size * 1.4).ceil(); + Metrics::new(font_size, line_height) + } + + // Get current syntax theme based on dark mode + pub fn syntax_theme(&self) -> &str { + let dark = self.app_theme.theme().theme_type.is_dark(); + if dark { + &self.syntax_theme_dark + } else { + &self.syntax_theme_light + } + } +} diff --git a/src/localize.rs b/src/localize.rs new file mode 100644 index 0000000..f5c6fb9 --- /dev/null +++ b/src/localize.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-only + +use i18n_embed::{ + fluent::{fluent_language_loader, FluentLanguageLoader}, + DefaultLocalizer, LanguageLoader, Localizer, +}; +use rust_embed::RustEmbed; + +#[derive(RustEmbed)] +#[folder = "i18n/"] +struct Localizations; + +lazy_static::lazy_static! { + pub static ref LANGUAGE_LOADER: FluentLanguageLoader = { + let loader: FluentLanguageLoader = fluent_language_loader!(); + + loader + .load_fallback_language(&Localizations) + .expect("Error while loading fallback language"); + + loader + }; +} + +#[macro_export] +macro_rules! fl { + ($message_id:literal) => {{ + i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER, $message_id) + }}; + + ($message_id:literal, $($args:expr),*) => {{ + i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER, $message_id, $($args), *) + }}; +} + +// Get the `Localizer` to be used for localizing this library. +pub fn localizer() -> Box { + Box::from(DefaultLocalizer::new(&*LANGUAGE_LOADER, &Localizations)) +} + +pub fn localize() { + let localizer = localizer(); + let requested_languages = i18n_embed::DesktopLanguageRequester::requested_languages(); + + if let Err(error) = localizer.select(&requested_languages) { + eprintln!("Error while loading language for App List {}", error); + } +} diff --git a/src/main.rs b/src/main.rs index fb9e9fa..5226980 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,8 +6,10 @@ use alacritty_terminal::{ }; use cosmic::{ app::{message, Command, Core, Settings}, + cosmic_config::{self, CosmicConfigEntry}, cosmic_theme, executor, iced::{ + advanced::graphics::text::font_system, clipboard, event, futures::SinkExt, keyboard::{Event as KeyEvent, KeyCode, Modifiers}, @@ -15,14 +17,19 @@ use cosmic::{ widget::row, window, Alignment, Event, Length, }, - iced_core::Size, style, widget::{self, segmented_button}, - ApplicationExt, Element, + Application, ApplicationExt, Element, }; -use std::{any::TypeId, collections::HashMap, sync::Mutex}; +use cosmic_text::Family; +use std::{any::TypeId, collections::HashMap, process, sync::Mutex}; use tokio::sync::mpsc; +use config::{AppTheme, Config, CONFIG_VERSION}; +mod config; + +mod localize; + use self::terminal::{Terminal, TerminalScroll}; mod terminal; @@ -34,7 +41,36 @@ mod terminal_theme; /// Runs application with these settings #[rustfmt::skip] fn main() -> Result<(), Box> { - env_logger::init(); + #[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()) + } + }; // Set up environmental variables for terminal let mut term_config = TermConfig::default(); @@ -42,57 +78,208 @@ fn main() -> Result<(), Box> { term_config.env.insert("TERM".to_string(), "xterm-256color".to_string()); tty::setup_env(&term_config); - let settings = Settings::default() - .antialiasing(true) - .client_decorations(true) - .debug(false) - .default_icon_theme("Cosmic") - .default_text_size(16.0) - .scale_factor(1.0) - .size(Size::new(1024., 768.)) - .theme(cosmic::Theme::dark()); + let mut settings = Settings::default(); + settings = settings.theme(config.app_theme.theme()); - cosmic::app::run::(settings, term_config)?; + #[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, + term_config, + }; + cosmic::app::run::(settings, flags)?; Ok(()) } +#[derive(Clone, Debug)] +pub struct Flags { + config_handler: Option, + config: Config, + term_config: TermConfig, +} + /// Messages that are used specifically by our [`App`]. #[derive(Clone, Debug)] pub enum Message { + AppTheme(AppTheme), + Config(Config), Copy, + DefaultFont(usize), + DefaultFontSize(usize), Paste, PasteValue(String), + SystemThemeModeChange(cosmic_theme::ThemeMode), + SyntaxTheme(usize, bool), TabActivate(segmented_button::Entity), TabClose(segmented_button::Entity), TabNew, TermEvent(segmented_button::Entity, TermEvent), TermEventTx(mpsc::Sender<(segmented_button::Entity, TermEvent)>), + ToggleContextPage(ContextPage), +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ContextPage { + Settings, +} + +impl ContextPage { + fn title(&self) -> String { + match self { + Self::Settings => fl!("settings"), + } + } } /// The [`App`] stores application-specific state. pub struct App { core: Core, tab_model: segmented_button::Model, + config_handler: Option, + config: Config, + app_themes: Vec, + font_names: Vec, + font_size_names: Vec, + font_sizes: Vec, + theme_names: Vec, + themes: HashMap, + context_page: ContextPage, term_event_tx_opt: Option>, term_config: TermConfig, - terminal_theme: String, - terminal_themes: HashMap, } -/// Implement [`cosmic::Application`] to integrate with COSMIC. -impl cosmic::Application for App { +impl App { + fn update_config(&mut self) -> Command { + //TODO: provide iterator over data + let entities: Vec<_> = self.tab_model.iter().collect(); + for entity in entities { + if let Some(terminal) = self.tab_model.data::>(entity) { + let mut terminal = terminal.lock().unwrap(); + terminal.set_config(&self.config, &self.themes); + } + } + cosmic::app::command::set_theme(self.config.app_theme.theme()) + } + + fn save_config(&mut self) -> Command { + 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 { + 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 Terminal"), + ), + None => (String::new(), "COSMIC Terminal".to_string()), + }; + self.set_header_title(header_title); + self.set_window_title(window_title) + } + + fn settings(&self) -> Element { + let app_theme_selected = match self.config.app_theme { + AppTheme::Dark => 1, + AppTheme::Light => 2, + AppTheme::System => 0, + }; + let dark_selected = self + .theme_names + .iter() + .position(|theme_name| theme_name == &self.config.syntax_theme_dark); + let light_selected = self + .theme_names + .iter() + .position(|theme_name| theme_name == &self.config.syntax_theme_light); + let font_selected = { + let mut font_system = font_system().write().unwrap(); + let current_font_name = font_system.raw().db().family_name(&Family::Monospace); + self.font_names + .iter() + .position(|font_name| font_name == current_font_name) + }; + let font_size_selected = self + .font_sizes + .iter() + .position(|font_size| font_size == &self.config.font_size); + 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, + }) + }, + )), + ) + .add( + widget::settings::item::builder(fl!("syntax-dark")).control(widget::dropdown( + &self.theme_names, + dark_selected, + move |index| Message::SyntaxTheme(index, true), + )), + ) + .add( + widget::settings::item::builder(fl!("syntax-light")).control(widget::dropdown( + &self.theme_names, + light_selected, + move |index| Message::SyntaxTheme(index, false), + )), + ) + .add( + widget::settings::item::builder(fl!("default-font")).control(widget::dropdown( + &self.font_names, + font_selected, + |index| Message::DefaultFont(index), + )), + ) + .add( + widget::settings::item::builder(fl!("default-font-size")).control( + widget::dropdown(&self.font_size_names, font_size_selected, |index| { + Message::DefaultFontSize(index) + }), + ), + ) + .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 = TermConfig; + 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 = "org.cosmic.AppDemo"; + const APP_ID: &'static str = "com.system76.CosmicTerm"; fn core(&self) -> &Core { &self.core @@ -103,16 +290,64 @@ impl cosmic::Application for App { } /// Creates the application, and optionally emits command on initialize. - fn init(mut core: Core, term_config: Self::Flags) -> (Self, Command) { + fn init(mut core: Core, flags: Self::Flags) -> (Self, Command) { core.window.content_container = false; + // Update font name from config + { + let mut font_system = font_system().write().unwrap(); + font_system + .raw() + .db_mut() + .set_monospace_family(&flags.config.font_name); + } + + let app_themes = vec![fl!("match-desktop"), fl!("dark"), fl!("light")]; + + let font_names = { + let mut font_names = Vec::new(); + let mut font_system = font_system().write().unwrap(); + //TODO: do not repeat, used in Tab::new + let attrs = cosmic_text::Attrs::new().family(Family::Monospace); + for face in font_system.raw().db().faces() { + if attrs.matches(face) && face.monospaced { + //TODO: get localized name if possible + let font_name = face + .families + .get(0) + .map_or_else(|| face.post_script_name.to_string(), |x| x.0.to_string()); + font_names.push(font_name); + } + } + font_names.sort(); + font_names + }; + + let mut font_size_names = Vec::new(); + let mut font_sizes = Vec::new(); + for font_size in 4..=32 { + font_size_names.push(format!("{}px", font_size)); + font_sizes.push(font_size); + } + + let themes = terminal_theme::terminal_themes(); + let mut theme_names: Vec<_> = themes.keys().map(|x| x.clone()).collect(); + theme_names.sort(); + let mut app = App { core, tab_model: segmented_button::ModelBuilder::default().build(), + config_handler: flags.config_handler, + config: flags.config, + app_themes, + font_names, + font_size_names, + font_sizes, + theme_names, + themes, + context_page: ContextPage::Settings, + term_config: flags.term_config, term_event_tx_opt: None, - term_config, - terminal_theme: "Cosmic Dark".to_string(), - terminal_themes: terminal_theme::terminal_themes(), }; let command = app.update_title(); @@ -123,6 +358,18 @@ impl cosmic::Application for App { /// Handle application events here. fn update(&mut self, message: Self::Message) -> Command { match message { + Message::AppTheme(app_theme) => { + self.config.app_theme = app_theme; + return self.save_config(); + } + 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(); + } + } Message::Copy => { if let Some(terminal) = self .tab_model @@ -135,6 +382,44 @@ impl cosmic::Application for App { } } } + Message::DefaultFont(index) => { + match self.font_names.get(index) { + Some(font_name) => { + if font_name != &self.config.font_name { + // Update font name from config + { + let mut font_system = font_system().write().unwrap(); + font_system.raw().db_mut().set_monospace_family(font_name); + } + + let entities: Vec<_> = self.tab_model.iter().collect(); + for entity in entities { + if let Some(terminal) = + self.tab_model.data::>(entity) + { + let mut terminal = terminal.lock().unwrap(); + terminal.update_cell_size(); + } + } + + self.config.font_name = font_name.to_string(); + return self.save_config(); + } + } + None => { + log::warn!("failed to find font with index {}", index); + } + } + } + Message::DefaultFontSize(index) => match self.font_sizes.get(index) { + Some(font_size) => { + self.config.font_size = *font_size; + return self.save_config(); + } + None => { + log::warn!("failed to find font with index {}", index); + } + }, Message::Paste => { return clipboard::read(|value_opt| match value_opt { Some(value) => message::app(Message::PasteValue(value)), @@ -150,6 +435,22 @@ impl cosmic::Application for App { terminal.paste(value); } } + Message::SystemThemeModeChange(_theme_mode) => { + return self.update_config(); + } + Message::SyntaxTheme(index, dark) => match self.theme_names.get(index) { + Some(theme_name) => { + if dark { + self.config.syntax_theme_dark = theme_name.to_string(); + } else { + self.config.syntax_theme_light = theme_name.to_string(); + } + return self.save_config(); + } + None => { + log::warn!("failed to find syntax theme with index {}", index); + } + }, Message::TabActivate(entity) => { self.tab_model.activate(entity); return self.update_title(); @@ -175,7 +476,7 @@ impl cosmic::Application for App { return self.update_title(); } Message::TabNew => match &self.term_event_tx_opt { - Some(term_event_tx) => match self.terminal_themes.get(&self.terminal_theme) { + Some(term_event_tx) => match self.themes.get(self.config.syntax_theme()) { Some(colors) => { let entity = self .tab_model @@ -194,7 +495,11 @@ impl cosmic::Application for App { .data_set::>(entity, Mutex::new(terminal)); } None => { - log::error!("failed to find terminal theme {:?}", self.terminal_theme); + log::error!( + "failed to find terminal theme {:?}", + self.config.syntax_theme() + ); + //TODO: fall back to known good theme } }, None => { @@ -250,11 +555,30 @@ impl cosmic::Application for App { Message::TermEventTx(term_event_tx) => { self.term_event_tx_opt = Some(term_event_tx); } + Message::ToggleContextPage(context_page) => { + 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()); + } } Command::none() } + fn context_drawer(&self) -> Option> { + if !self.core.window.show_context { + return None; + } + + Some(match self.context_page { + ContextPage::Settings => self.settings(), + }) + } + fn header_start(&self) -> Vec> { let cosmic_theme::Spacing { space_xxs, .. } = self.core().system_theme().cosmic().spacing; @@ -268,6 +592,21 @@ impl cosmic::Application for App { .into()] } + fn header_end(&self) -> Vec> { + let cosmic_theme::Spacing { space_xxs, .. } = self.core().system_theme().cosmic().spacing; + + vec![row![widget::button( + widget::icon::from_name("preferences-system-symbolic") + .size(16) + .icon() + ) + .on_press(Message::ToggleContextPage(ContextPage::Settings)) + .padding(space_xxs) + .style(style::Button::Icon)] + .align_items(Alignment::Center) + .into()] + } + /// Creates a view after each update. fn view(&self) -> Element { let cosmic_theme::Spacing { space_xxs, .. } = self.core().system_theme().cosmic().spacing; @@ -309,7 +648,10 @@ impl cosmic::Application for App { } fn subscription(&self) -> Subscription { - struct TerminalEventWorker; + struct ConfigSubscription; + struct TerminalEventSubscription; + struct ThemeSubscription; + Subscription::batch([ event::listen_with(|event, _status| match event { Event::Keyboard(KeyEvent::KeyPressed { @@ -345,7 +687,7 @@ impl cosmic::Application for App { _ => None, }), subscription::channel( - TypeId::of::(), + TypeId::of::(), 100, |mut output| async move { let (event_tx, mut event_rx) = mpsc::channel(100); @@ -364,23 +706,30 @@ impl cosmic::Application for App { panic!("terminal event channel closed"); }, ), + cosmic_config::config_subscription( + TypeId::of::(), + Self::APP_ID.into(), + CONFIG_VERSION, + ) + .map(|(_, res)| match res { + Ok(config) => Message::Config(config), + Err((errs, config)) => { + log::info!("errors loading config: {:?}", errs); + Message::Config(config) + } + }), + cosmic_config::config_subscription::<_, cosmic_theme::ThemeMode>( + TypeId::of::(), + cosmic_theme::THEME_MODE_ID.into(), + cosmic_theme::ThemeMode::version(), + ) + .map(|(_, u)| match u { + Ok(t) => Message::SystemThemeModeChange(t), + Err((errs, t)) => { + log::info!("errors loading theme mode: {:?}", errs); + Message::SystemThemeModeChange(t) + } + }), ]) } } - -impl App -where - Self: cosmic::Application, -{ - fn update_title(&mut self) -> Command { - 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 Terminal"), - ), - None => (String::new(), "COSMIC Terminal".to_string()), - }; - self.set_header_title(header_title); - self.set_window_title(window_title) - } -} diff --git a/src/terminal.rs b/src/terminal.rs index 3e06094..3647a04 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -8,7 +8,7 @@ use alacritty_terminal::{ sync::FairMutex, term::{ cell::Flags, - color::{Colors, Rgb}, + color::{self, Colors, Rgb}, viewport_to_point, TermMode, }, tty, Term, @@ -19,6 +19,7 @@ use cosmic_text::{ }; use std::{ borrow::Cow, + collections::HashMap, mem, sync::{Arc, Weak}, time::Instant, @@ -281,6 +282,71 @@ impl Terminal { } } + pub fn set_config(&mut self, config: &crate::Config, themes: &HashMap) { + let mut update_cell_size = false; + let mut update = false; + + let metrics = config.metrics(); + if metrics != self.buffer.metrics() { + { + let mut font_system = font_system().write().unwrap(); + self.with_buffer_mut(|buffer| buffer.set_metrics(font_system.raw(), metrics)); + } + update_cell_size = true; + } + + if let Some(colors) = themes.get(config.syntax_theme()) { + let mut changed = false; + for i in 0..color::COUNT { + if self.colors[i] != colors[i] { + self.colors[i] = colors[i]; + changed = true; + } + } + if changed { + self.default_attrs = Attrs::new() + .family(Family::Monospace) + .color(convert_color(&colors, Color::Named(NamedColor::Foreground))) + .metadata( + convert_color(&colors, Color::Named(NamedColor::Background)).0 as usize, + ); + update = true; + } + } + + if update_cell_size { + self.update_cell_size(); + } else if update { + self.update(); + } + } + + pub fn update_cell_size(&mut self) { + let default_attrs = self.default_attrs; + let (cell_width, cell_height) = { + let mut font_system = font_system().write().unwrap(); + self.with_buffer_mut(|buffer| { + buffer.set_wrap(font_system.raw(), Wrap::None); + + // Use size of space to determine cell size + buffer.set_text(font_system.raw(), " ", default_attrs, Shaping::Advanced); + let layout = buffer.line_layout(font_system.raw(), 0).unwrap(); + (layout[0].w, buffer.metrics().line_height) + }) + }; + + let old_size = self.size; + self.size = Size { + width: 0, + height: 0, + cell_width, + cell_height, + }; + self.resize(old_size.width, old_size.height); + + self.update(); + } + pub fn update(&mut self) -> bool { let instant = Instant::now(); diff --git a/src/terminal_theme.rs b/src/terminal_theme.rs index 9503a47..4819957 100644 --- a/src/terminal_theme.rs +++ b/src/terminal_theme.rs @@ -85,6 +85,55 @@ fn cosmic_dark() -> Colors { colors } +fn cosmic_light() -> Colors { + let mut colors = auto_colors(); + + let encode_rgb = |data: u32| -> Rgb { + Rgb { + r: (data >> 16) as u8, + g: (data >> 8) as u8, + b: data as u8, + } + }; + + colors[NamedColor::Black] = Some(encode_rgb(0x292929)); + colors[NamedColor::Red] = Some(encode_rgb(0x8C151F)); + colors[NamedColor::Green] = Some(encode_rgb(0x145129)); + colors[NamedColor::Yellow] = Some(encode_rgb(0x624000)); + colors[NamedColor::Blue] = Some(encode_rgb(0x003F5F)); + colors[NamedColor::Magenta] = Some(encode_rgb(0x6D169C)); + colors[NamedColor::Cyan] = Some(encode_rgb(0x004F57)); + colors[NamedColor::White] = Some(encode_rgb(0xBEBEBE)); + + colors[NamedColor::BrightBlack] = Some(encode_rgb(0x808080)); + colors[NamedColor::BrightRed] = Some(encode_rgb(0x9D2329)); + colors[NamedColor::BrightGreen] = Some(encode_rgb(0x235D34)); + colors[NamedColor::BrightYellow] = Some(encode_rgb(0x714B00)); + colors[NamedColor::BrightBlue] = Some(encode_rgb(0x054B6F)); + colors[NamedColor::BrightMagenta] = Some(encode_rgb(0x7A28A9)); + colors[NamedColor::BrightCyan] = Some(encode_rgb(0x005C5D)); + colors[NamedColor::BrightWhite] = Some(encode_rgb(0xD7D7D7)); + + // Set special colors + colors[NamedColor::Foreground] = colors[NamedColor::Black]; + colors[NamedColor::Background] = colors[NamedColor::BrightWhite]; + colors[NamedColor::Cursor] = colors[NamedColor::Black]; + /*TODO + colors[NamedColor::DimBlack] = colors[NamedColor::]; + colors[NamedColor::DimRed] = colors[NamedColor::]; + colors[NamedColor::DimGreen] = colors[NamedColor::]; + colors[NamedColor::DimYellow] = colors[NamedColor::]; + colors[NamedColor::DimBlue] = colors[NamedColor::]; + colors[NamedColor::DimMagenta] = colors[NamedColor::]; + colors[NamedColor::DimCyan] = colors[NamedColor::]; + colors[NamedColor::DimWhite] = colors[NamedColor::]; + */ + colors[NamedColor::BrightForeground] = colors[NamedColor::BrightWhite]; + //TODO colors[NamedColor::DimForeground] = colors[NamedColor::]; + + colors +} + fn gruvbox_dark() -> Colors { let mut colors = auto_colors(); @@ -229,7 +278,8 @@ fn pop_dark() -> Colors { pub fn terminal_themes() -> HashMap { let mut themes = HashMap::new(); - themes.insert("Cosmic Dark".to_string(), cosmic_dark()); + themes.insert("COSMIC Dark".to_string(), cosmic_dark()); + themes.insert("COSMIC Light".to_string(), cosmic_light()); themes.insert("gruvbox-dark".to_string(), gruvbox_dark()); themes.insert("OneHalfDark".to_string(), one_half_dark()); themes.insert("Pop Dark".to_string(), pop_dark());