Remove lazy_static dep.

This commit is contained in:
Mark Tomlin 2024-01-18 00:25:22 -05:00 committed by Jeremy Soller
parent d7e9e3085f
commit b97eb0603b
7 changed files with 74 additions and 60 deletions

1
Cargo.lock generated
View file

@ -1031,7 +1031,6 @@ dependencies = [
"i18n-embed", "i18n-embed",
"i18n-embed-fl", "i18n-embed-fl",
"ignore", "ignore",
"lazy_static",
"lexical-sort", "lexical-sort",
"libcosmic", "libcosmic",
"log", "log",

View file

@ -9,7 +9,6 @@ license = "GPL-3.0-only"
env_logger = "0.10.0" env_logger = "0.10.0"
grep = "0.3.1" grep = "0.3.1"
ignore = "0.4.21" ignore = "0.4.21"
lazy_static = "1.4.0"
lexical-sort = "0.3.1" lexical-sort = "0.3.1"
log = "0.4.20" log = "0.4.20"
patch = "0.7.0" patch = "0.7.0"

View file

@ -1,5 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
use std::sync::OnceLock;
use i18n_embed::{ use i18n_embed::{
fluent::{fluent_language_loader, FluentLanguageLoader}, fluent::{fluent_language_loader, FluentLanguageLoader},
DefaultLocalizer, LanguageLoader, Localizer, DefaultLocalizer, LanguageLoader, Localizer,
@ -10,8 +12,22 @@ use rust_embed::RustEmbed;
#[folder = "i18n/"] #[folder = "i18n/"]
struct Localizations; struct Localizations;
lazy_static::lazy_static! { pub static LANGUAGE_LOADER: OnceLock<FluentLanguageLoader> = OnceLock::new();
pub static ref LANGUAGE_LOADER: FluentLanguageLoader = {
#[macro_export]
macro_rules! fl {
($message_id:literal) => {{
i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER.get().unwrap(), $message_id)
}};
($message_id:literal, $($args:expr),*) => {{
i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER.get().unwrap(), $message_id, $($args), *)
}};
}
// Get the `Localizer` to be used for localizing this library.
pub fn localizer() -> Box<dyn Localizer> {
LANGUAGE_LOADER.get_or_init(|| {
let loader: FluentLanguageLoader = fluent_language_loader!(); let loader: FluentLanguageLoader = fluent_language_loader!();
loader loader
@ -19,23 +35,12 @@ lazy_static::lazy_static! {
.expect("Error while loading fallback language"); .expect("Error while loading fallback language");
loader loader
}; });
}
#[macro_export] Box::from(DefaultLocalizer::new(
macro_rules! fl { LANGUAGE_LOADER.get().unwrap(),
($message_id:literal) => {{ &Localizations,
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<dyn Localizer> {
Box::from(DefaultLocalizer::new(&*LANGUAGE_LOADER, &Localizations))
} }
pub fn localize() { pub fn localize() {

View file

@ -23,7 +23,7 @@ use std::{
env, fs, io, env, fs, io,
path::{Path, PathBuf}, path::{Path, PathBuf},
process, process,
sync::Mutex, sync::{Mutex, OnceLock},
}; };
use tokio::time; use tokio::time;
@ -60,17 +60,28 @@ use self::text_box::text_box;
mod text_box; mod text_box;
//TODO: re-use iced FONT_SYSTEM //TODO: re-use iced FONT_SYSTEM
lazy_static::lazy_static! { static FONT_SYSTEM: OnceLock<Mutex<FontSystem>> = OnceLock::new();
static ref FONT_SYSTEM: Mutex<FontSystem> = Mutex::new(FontSystem::new()); static ICON_CACHE: OnceLock<Mutex<IconCache>> = OnceLock::new();
static ref ICON_CACHE: Mutex<IconCache> = Mutex::new(IconCache::new()); static LINE_NUMBER_CACHE: OnceLock<Mutex<LineNumberCache>> = OnceLock::new();
static ref LINE_NUMBER_CACHE: Mutex<LineNumberCache> = Mutex::new(LineNumberCache::new()); static SWASH_CACHE: OnceLock<Mutex<SwashCache>> = OnceLock::new();
static ref SWASH_CACHE: Mutex<SwashCache> = Mutex::new(SwashCache::new()); static SYNTAX_SYSTEM: OnceLock<SyntaxSystem> = OnceLock::new();
static ref SYNTAX_SYSTEM: SyntaxSystem = {
pub fn icon_cache_get(name: &'static str, size: u16) -> icon::Icon {
let mut icon_cache = ICON_CACHE.get().unwrap().lock().unwrap();
icon_cache.get(name, size)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
FONT_SYSTEM.get_or_init(|| Mutex::new(FontSystem::new()));
ICON_CACHE.get_or_init(|| Mutex::new(IconCache::new()));
LINE_NUMBER_CACHE.get_or_init(|| Mutex::new(LineNumberCache::new()));
SWASH_CACHE.get_or_init(|| Mutex::new(SwashCache::new()));
SYNTAX_SYSTEM.get_or_init(|| {
let lazy_theme_set = two_face::theme::LazyThemeSet::from(two_face::theme::extra()); let lazy_theme_set = two_face::theme::LazyThemeSet::from(two_face::theme::extra());
let mut theme_set = syntect::highlighting::ThemeSet::from(&lazy_theme_set); let mut theme_set = syntect::highlighting::ThemeSet::from(&lazy_theme_set);
for (theme_name, theme_data) in &[ for (theme_name, theme_data) in &[
("COSMIC Dark", cosmic_syntax_theme::COSMIC_DARK_TM_THEME), ("COSMIC Dark", cosmic_syntax_theme::COSMIC_DARK_TM_THEME),
("COSMIC Light", cosmic_syntax_theme::COSMIC_LIGHT_TM_THEME) ("COSMIC Light", cosmic_syntax_theme::COSMIC_LIGHT_TM_THEME),
] { ] {
let mut cursor = io::Cursor::new(theme_data); let mut cursor = io::Cursor::new(theme_data);
match syntect::highlighting::ThemeSet::load_from_reader(&mut cursor) { match syntect::highlighting::ThemeSet::load_from_reader(&mut cursor) {
@ -87,15 +98,8 @@ lazy_static::lazy_static! {
syntax_set: two_face::syntax::extra_no_newlines(), syntax_set: two_face::syntax::extra_no_newlines(),
theme_set, theme_set,
} }
}; });
}
pub fn icon_cache_get(name: &'static str, size: u16) -> icon::Icon {
let mut icon_cache = ICON_CACHE.lock().unwrap();
icon_cache.get(name, size)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(all(unix, not(target_os = "redox")))] #[cfg(all(unix, not(target_os = "redox")))]
match fork::daemon(true, true) { match fork::daemon(true, true) {
Ok(fork::Fork::Child) => (), Ok(fork::Fork::Child) => (),
@ -829,7 +833,7 @@ impl App {
.iter() .iter()
.position(|theme_name| theme_name == &self.config.syntax_theme_light); .position(|theme_name| theme_name == &self.config.syntax_theme_light);
let font_selected = { let font_selected = {
let font_system = FONT_SYSTEM.lock().unwrap(); let font_system = FONT_SYSTEM.get().unwrap().lock().unwrap();
let current_font_name = font_system.db().family_name(&Family::Monospace); let current_font_name = font_system.db().family_name(&Family::Monospace);
self.font_names self.font_names
.iter() .iter()
@ -920,7 +924,7 @@ impl Application for App {
fn init(core: Core, flags: Self::Flags) -> (Self, Command<Self::Message>) { fn init(core: Core, flags: Self::Flags) -> (Self, Command<Self::Message>) {
// Update font name from config // Update font name from config
{ {
let mut font_system = FONT_SYSTEM.lock().unwrap(); let mut font_system = FONT_SYSTEM.get().unwrap().lock().unwrap();
font_system font_system
.db_mut() .db_mut()
.set_monospace_family(&flags.config.font_name); .set_monospace_family(&flags.config.font_name);
@ -930,7 +934,7 @@ impl Application for App {
let font_names = { let font_names = {
let mut font_names = Vec::new(); let mut font_names = Vec::new();
let font_system = FONT_SYSTEM.lock().unwrap(); let font_system = FONT_SYSTEM.get().unwrap().lock().unwrap();
//TODO: do not repeat, used in Tab::new //TODO: do not repeat, used in Tab::new
let attrs = cosmic_text::Attrs::new().family(Family::Monospace); let attrs = cosmic_text::Attrs::new().family(Family::Monospace);
for face in font_system.db().faces() { for face in font_system.db().faces() {
@ -954,8 +958,9 @@ impl Application for App {
font_sizes.push(font_size); font_sizes.push(font_size);
} }
let mut theme_names = Vec::with_capacity(SYNTAX_SYSTEM.theme_set.themes.len()); let mut theme_names =
for (theme_name, _theme) in SYNTAX_SYSTEM.theme_set.themes.iter() { Vec::with_capacity(SYNTAX_SYSTEM.get().unwrap().theme_set.themes.len());
for (theme_name, _theme) in SYNTAX_SYSTEM.get().unwrap().theme_set.themes.iter() {
theme_names.push(theme_name.to_string()); theme_names.push(theme_name.to_string());
} }
@ -1172,13 +1177,14 @@ impl Application for App {
if font_name != &self.config.font_name { if font_name != &self.config.font_name {
// Update font name from config // Update font name from config
{ {
let mut font_system = FONT_SYSTEM.lock().unwrap(); let mut font_system = FONT_SYSTEM.get().unwrap().lock().unwrap();
font_system.db_mut().set_monospace_family(font_name); font_system.db_mut().set_monospace_family(font_name);
} }
// Reset line number cache // Reset line number cache
{ {
let mut line_number_cache = LINE_NUMBER_CACHE.lock().unwrap(); let mut line_number_cache =
LINE_NUMBER_CACHE.get().unwrap().lock().unwrap();
line_number_cache.clear(); line_number_cache.clear();
} }

View file

@ -1,7 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
use cosmic::widget::icon; use cosmic::widget::icon;
use std::{collections::HashMap, path::Path, sync::Mutex}; use std::{collections::HashMap, path::Path, sync::Mutex, sync::OnceLock};
pub const FALLBACK_MIME_ICON: &str = "text-x-generic"; pub const FALLBACK_MIME_ICON: &str = "text-x-generic";
@ -39,18 +39,18 @@ impl MimeIconCache {
} }
} }
lazy_static::lazy_static! { static MIME_ICON_CACHE: OnceLock<Mutex<MimeIconCache>> = OnceLock::new();
static ref MIME_ICON_CACHE: Mutex<MimeIconCache> = Mutex::new(MimeIconCache::new());
}
pub fn mime_icon<P: AsRef<Path>>(path: P, size: u16) -> icon::Icon { pub fn mime_icon<P: AsRef<Path>>(path: P, size: u16) -> icon::Icon {
MIME_ICON_CACHE.get_or_init(|| Mutex::new(MimeIconCache::new()));
//TODO: smarter path handling //TODO: smarter path handling
let path = path let path = path
.as_ref() .as_ref()
.to_str() .to_str()
.expect("failed to convert path to UTF-8") .expect("failed to convert path to UTF-8")
.to_owned(); .to_owned();
let mut mime_icon_cache = MIME_ICON_CACHE.lock().unwrap(); let mut mime_icon_cache = MIME_ICON_CACHE.get().unwrap().lock().unwrap();
match mime_icon_cache.get(MimeIconKey { path, size }) { match mime_icon_cache.get(MimeIconKey { path, size }) {
Some(handle) => icon::icon(handle).size(size), Some(handle) => icon::icon(handle).size(size),
None => icon::from_name(FALLBACK_MIME_ICON).size(size).icon(), None => icon::from_name(FALLBACK_MIME_ICON).size(size).icon(),

View file

@ -47,14 +47,18 @@ impl EditorTab {
let mut buffer = Buffer::new_empty(config.metrics()); let mut buffer = Buffer::new_empty(config.metrics());
buffer.set_text( buffer.set_text(
&mut FONT_SYSTEM.lock().unwrap(), &mut FONT_SYSTEM.get().unwrap().lock().unwrap(),
"", "",
attrs, attrs,
Shaping::Advanced, Shaping::Advanced,
); );
let editor = let editor = SyntaxEditor::new(
SyntaxEditor::new(Arc::new(buffer), &SYNTAX_SYSTEM, config.syntax_theme()).unwrap(); Arc::new(buffer),
SYNTAX_SYSTEM.get().unwrap(),
config.syntax_theme(),
)
.unwrap();
let mut tab = Self { let mut tab = Self {
path_opt: None, path_opt: None,
@ -71,7 +75,7 @@ impl EditorTab {
pub fn set_config(&mut self, config: &Config) { pub fn set_config(&mut self, config: &Config) {
let mut editor = self.editor.lock().unwrap(); let mut editor = self.editor.lock().unwrap();
let mut font_system = FONT_SYSTEM.lock().unwrap(); let mut font_system = FONT_SYSTEM.get().unwrap().lock().unwrap();
let mut editor = editor.borrow_with(&mut font_system); let mut editor = editor.borrow_with(&mut font_system);
editor.set_auto_indent(config.auto_indent); editor.set_auto_indent(config.auto_indent);
editor.set_passthrough(!config.vim_bindings); editor.set_passthrough(!config.vim_bindings);
@ -89,7 +93,7 @@ impl EditorTab {
pub fn open(&mut self, path: PathBuf) { pub fn open(&mut self, path: PathBuf) {
let mut editor = self.editor.lock().unwrap(); let mut editor = self.editor.lock().unwrap();
let mut font_system = FONT_SYSTEM.lock().unwrap(); let mut font_system = FONT_SYSTEM.get().unwrap().lock().unwrap();
let mut editor = editor.borrow_with(&mut font_system); let mut editor = editor.borrow_with(&mut font_system);
match editor.load_text(&path, self.attrs) { match editor.load_text(&path, self.attrs) {
Ok(()) => { Ok(()) => {
@ -111,7 +115,7 @@ impl EditorTab {
pub fn reload(&mut self) { pub fn reload(&mut self) {
let mut editor = self.editor.lock().unwrap(); let mut editor = self.editor.lock().unwrap();
let mut font_system = FONT_SYSTEM.lock().unwrap(); let mut font_system = FONT_SYSTEM.get().unwrap().lock().unwrap();
let mut editor = editor.borrow_with(&mut font_system); let mut editor = editor.borrow_with(&mut font_system);
if let Some(path) = &self.path_opt { if let Some(path) = &self.path_opt {
// Save scroll // Save scroll

View file

@ -246,7 +246,7 @@ where
let mut editor = self.editor.lock().unwrap(); let mut editor = self.editor.lock().unwrap();
//TODO: set size? //TODO: set size?
editor editor
.borrow_with(&mut FONT_SYSTEM.lock().unwrap()) .borrow_with(&mut FONT_SYSTEM.get().unwrap().lock().unwrap())
.shape_as_needed(true); .shape_as_needed(true);
editor.with_buffer(|buffer| { editor.with_buffer(|buffer| {
@ -348,7 +348,7 @@ where
let image_w = image_w - scrollbar_w; let image_w = image_w - scrollbar_w;
// Lock font system (used throughout) // Lock font system (used throughout)
let mut font_system = FONT_SYSTEM.lock().unwrap(); let mut font_system = FONT_SYSTEM.get().unwrap().lock().unwrap();
// Calculate line number information // Calculate line number information
let (line_number_chars, editor_offset_x) = if self.line_numbers { let (line_number_chars, editor_offset_x) = if self.line_numbers {
@ -363,7 +363,7 @@ where
// Calculate line number width // Calculate line number width
let mut line_number_width = 0.0; let mut line_number_width = 0.0;
{ {
let mut line_number_cache = LINE_NUMBER_CACHE.lock().unwrap(); let mut line_number_cache = LINE_NUMBER_CACHE.get().unwrap().lock().unwrap();
if let Some(layout_line) = line_number_cache if let Some(layout_line) = line_number_cache
.get( .get(
&mut font_system, &mut font_system,
@ -410,7 +410,7 @@ where
// Draw to pixel buffer // Draw to pixel buffer
let mut pixels_u8 = vec![0; image_w as usize * image_h as usize * 4]; let mut pixels_u8 = vec![0; image_w as usize * image_h as usize * 4];
{ {
let mut swash_cache = SWASH_CACHE.lock().unwrap(); let mut swash_cache = SWASH_CACHE.get().unwrap().lock().unwrap();
let pixels = unsafe { let pixels = unsafe {
std::slice::from_raw_parts_mut( std::slice::from_raw_parts_mut(
@ -454,7 +454,8 @@ where
// Draw line numbers // Draw line numbers
//TODO: move to cosmic-text? //TODO: move to cosmic-text?
editor.with_buffer(|buffer| { editor.with_buffer(|buffer| {
let mut line_number_cache = LINE_NUMBER_CACHE.lock().unwrap(); let mut line_number_cache =
LINE_NUMBER_CACHE.get().unwrap().lock().unwrap();
let mut last_line_number = 0; let mut last_line_number = 0;
for run in buffer.layout_runs() { for run in buffer.layout_runs() {
let line_number = run.line_i.saturating_add(1); let line_number = run.line_i.saturating_add(1);
@ -695,7 +696,7 @@ where
let mut editor = self.editor.lock().unwrap(); let mut editor = self.editor.lock().unwrap();
let buffer_size = editor.with_buffer(|buffer| buffer.size()); let buffer_size = editor.with_buffer(|buffer| buffer.size());
let last_changed = editor.changed(); let last_changed = editor.changed();
let mut font_system = FONT_SYSTEM.lock().unwrap(); let mut font_system = FONT_SYSTEM.get().unwrap().lock().unwrap();
let mut editor = editor.borrow_with(&mut font_system); let mut editor = editor.borrow_with(&mut font_system);
let mut status = Status::Ignored; let mut status = Status::Ignored;