Restructure the shared parts of the lib

main
Tassilo Horn 3 years ago
parent 7035268413
commit 6e10aa4c24
  1. 1
      Cargo.lock
  2. 4
      swayr/src/cmds.rs
  3. 24
      swayr/src/config.rs
  4. 74
      swayr/src/fmt_replace.rs
  5. 4
      swayr/src/layout.rs
  6. 4
      swayr/src/lib.rs
  7. 63
      swayr/src/shared/fmt.rs
  8. 0
      swayr/src/shared/ipc.rs
  9. 18
      swayr/src/shared/mod.rs
  10. 36
      swayr/src/shared/util.rs
  11. 8
      swayr/src/tree.rs
  12. 3
      swayrbar/Cargo.toml
  13. 2
      swayrbar/src/bar/module/battery.rs
  14. 2
      swayrbar/src/bar/module/sysinfo.rs
  15. 6
      swayrbar/src/bar/module/window.rs
  16. 1
      swayrbar/src/fmt_replace.rs
  17. 1
      swayrbar/src/ipc.rs
  18. 4
      swayrbar/src/lib.rs
  19. 1
      swayrbar/src/rtfmt.rs
  20. 1
      swayrbar/src/shared

1
Cargo.lock generated

@ -636,6 +636,7 @@ version = "0.0.1"
dependencies = [ dependencies = [
"battery", "battery",
"chrono", "chrono",
"directories",
"env_logger", "env_logger",
"log", "log",
"once_cell", "once_cell",

@ -16,9 +16,9 @@
//! Functions and data structures of the swayr client. //! Functions and data structures of the swayr client.
use crate::config as cfg; use crate::config as cfg;
use crate::ipc;
use crate::ipc::NodeMethods;
use crate::layout; use crate::layout;
use crate::shared::ipc;
use crate::shared::ipc::NodeMethods;
use crate::tree as t; use crate::tree as t;
use crate::util; use crate::util;
use crate::util::DisplayFormat; use crate::util::DisplayFormat;

@ -15,13 +15,11 @@
//! TOML configuration for swayr. //! TOML configuration for swayr.
use directories::ProjectDirs; use crate::shared::util as shared_util;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use std::fs::DirBuilder;
use std::fs::OpenOptions; use std::fs::OpenOptions;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::path::Path;
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct Config { pub struct Config {
@ -304,24 +302,8 @@ impl Default for Config {
} }
} }
fn get_config_file_path() -> Box<Path> {
let proj_dirs = ProjectDirs::from("", "", "swayr").expect("");
let user_config_dir = proj_dirs.config_dir();
if !user_config_dir.exists() {
let sys_config_file = Path::new("/etc/xdg/swayr/config.toml");
if sys_config_file.exists() {
return sys_config_file.into();
}
DirBuilder::new()
.recursive(true)
.create(user_config_dir)
.unwrap();
}
user_config_dir.join("config.toml").into_boxed_path()
}
pub fn save_config(cfg: Config) { pub fn save_config(cfg: Config) {
let path = get_config_file_path(); let path = shared_util::get_config_file_path("swayr");
let content = let content =
toml::to_string_pretty(&cfg).expect("Cannot serialize config."); toml::to_string_pretty(&cfg).expect("Cannot serialize config.");
let mut file = OpenOptions::new() let mut file = OpenOptions::new()
@ -334,7 +316,7 @@ pub fn save_config(cfg: Config) {
} }
pub fn load_config() -> Config { pub fn load_config() -> Config {
let path = get_config_file_path(); let path = shared_util::get_config_file_path("swayr");
if !path.exists() { if !path.exists() {
save_config(Config::default()); save_config(Config::default());
// Tell the user that a fresh default config has been created. // Tell the user that a fresh default config has been created.

@ -1,74 +0,0 @@
// Copyright (C) 2022 Tassilo Horn <tsdh@gnu.org>
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
use once_cell::sync::Lazy;
use regex::Regex;
pub static PLACEHOLDER_RX: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r"\{(?P<name>[^}:]+)(?::(?P<fmtstr>\{[^}]*\})(?P<clipstr>[^}]*))?\}",
)
.unwrap()
});
pub fn maybe_html_escape(do_it: bool, text: String) -> String {
if do_it {
text.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('&', "&amp;")
} else {
text
}
}
macro_rules! fmt_replace {
( $fmt_str:expr, $html_escape:expr,
{ $( $($pat:pat_param)|+ => $exp:expr, )+ }
) => {
$crate::fmt_replace::PLACEHOLDER_RX
.replace_all($fmt_str, |caps: &regex::Captures| {
let value: String = match &caps["name"] {
$(
$( $pat )|+ => {
let val = $crate::rtfmt::FmtArg::from($exp);
let fmt_str = caps.name("fmtstr")
.map_or("{}", |m| m.as_str());
let clipped_str = caps.name("clipstr")
.map_or("", |m| m.as_str());
$crate::fmt_replace::maybe_html_escape(
$html_escape,
$crate::rtfmt::format(fmt_str, val, clipped_str),
)
}
)+
_ => caps[0].to_string(),
};
value
}).into()
};
}
pub(crate) use fmt_replace;
#[test]
fn foo() {
let foo = "{a}, {b}";
let html_escape = true;
let x: String = fmt_replace!(foo, html_escape, {
"a" => "1".to_string(),
"b" => "2".to_string(),
"c" => "3".to_owned(),
});
}

@ -16,8 +16,8 @@
//! Functions and data structures of the swayrd demon. //! Functions and data structures of the swayrd demon.
use crate::config; use crate::config;
use crate::ipc; use crate::shared::ipc;
use crate::ipc::NodeMethods; use crate::shared::ipc::NodeMethods;
use std::collections::HashMap; use std::collections::HashMap;
use swayipc as s; use swayipc as s;

@ -22,9 +22,7 @@ pub mod client;
pub mod cmds; pub mod cmds;
pub mod config; pub mod config;
pub mod demon; pub mod demon;
pub mod fmt_replace;
pub mod ipc;
pub mod layout; pub mod layout;
pub mod rtfmt; pub mod shared;
pub mod tree; pub mod tree;
pub mod util; pub mod util;

@ -13,10 +13,8 @@
// You should have received a copy of the GNU General Public License along with // You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>. // this program. If not, see <https://www.gnu.org/licenses/>.
//! Provides runtime formatting of strings since our format strings are read use once_cell::sync::Lazy;
//! from the swayr config, not specified as literals, e.g., `{name:{:.30}}` in use regex::Regex;
//! `format.window_format`.
use rt_format::{ use rt_format::{
Format, FormatArgument, NoNamedArguments, ParsedFormat, Specifier, Format, FormatArgument, NoNamedArguments, ParsedFormat, Specifier,
}; };
@ -148,3 +146,60 @@ fn test_format() {
assert_eq!(format("{:.5}", "sway window", "..."), "sw..."); assert_eq!(format("{:.5}", "sway window", "..."), "sw...");
assert_eq!(format("{:.2}", "sway", "..."), "..."); assert_eq!(format("{:.2}", "sway", "..."), "...");
} }
pub static PLACEHOLDER_RX: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r"\{(?P<name>[^}:]+)(?::(?P<fmtstr>\{[^}]*\})(?P<clipstr>[^}]*))?\}",
)
.unwrap()
});
pub fn maybe_html_escape(do_it: bool, text: String) -> String {
if do_it {
text.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('&', "&amp;")
} else {
text
}
}
macro_rules! fmt_replace {
( $fmt_str:expr, $html_escape:expr,
{ $( $($pat:pat_param)|+ => $exp:expr, )+ }
) => {
$crate::shared::fmt::PLACEHOLDER_RX
.replace_all($fmt_str, |caps: &regex::Captures| {
let value: String = match &caps["name"] {
$(
$( $pat )|+ => {
let val = $crate::shared::fmt::FmtArg::from($exp);
let fmt_str = caps.name("fmtstr")
.map_or("{}", |m| m.as_str());
let clipped_str = caps.name("clipstr")
.map_or("", |m| m.as_str());
$crate::shared::fmt::maybe_html_escape(
$html_escape,
$crate::shared::fmt::format(fmt_str, val, clipped_str),
)
}
)+
_ => caps[0].to_string(),
};
value
}).into()
};
}
pub(crate) use fmt_replace;
#[test]
fn foo() {
let foo = "{a}, {b}";
let html_escape = true;
let x: String = fmt_replace!(foo, html_escape, {
"a" => "1".to_string(),
"b" => "2".to_string(),
"c" => "3".to_owned(),
});
}

@ -0,0 +1,18 @@
// Copyright (C) 2021-2022 Tassilo Horn <tsdh@gnu.org>
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
pub mod fmt;
pub mod ipc;
pub mod util;

@ -0,0 +1,36 @@
// Copyright (C) 2021-2022 Tassilo Horn <tsdh@gnu.org>
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
/// Utility stuff shared by swayr and swayrbar.
use directories::ProjectDirs;
use std::fs::DirBuilder;
use std::path::Path;
pub fn get_config_file_path(project: &str) -> Box<Path> {
let proj_dirs = ProjectDirs::from("", "", project).expect("");
let user_config_dir = proj_dirs.config_dir();
if !user_config_dir.exists() {
let sys_path = format!("/etc/xdg/{}/config.toml", project);
let sys_config_file = Path::new(sys_path.as_str());
if sys_config_file.exists() {
return sys_config_file.into();
}
DirBuilder::new()
.recursive(true)
.create(user_config_dir)
.unwrap();
}
user_config_dir.join("config.toml").into_boxed_path()
}

@ -16,9 +16,9 @@
//! Convenience data structures built from the IPC structs. //! Convenience data structures built from the IPC structs.
use crate::config; use crate::config;
use crate::fmt_replace::fmt_replace; use crate::shared::fmt::fmt_replace;
use crate::ipc; use crate::shared::ipc;
use crate::ipc::NodeMethods; use crate::shared::ipc::NodeMethods;
use crate::util; use crate::util;
use crate::util::DisplayFormat; use crate::util::DisplayFormat;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -186,7 +186,7 @@ impl<'a> Tree<'a> {
self.as_display_nodes(&v, IndentLevel::WorkspacesZeroWindowsOne) self.as_display_nodes(&v, IndentLevel::WorkspacesZeroWindowsOne)
} }
fn sort_by_urgency_and_lru_time_1(&self, v: &mut Vec<&s::Node>) { fn sort_by_urgency_and_lru_time_1(&self, v: &mut [&s::Node]) {
v.sort_by(|a, b| { v.sort_by(|a, b| {
if a.urgent && !b.urgent { if a.urgent && !b.urgent {
cmp::Ordering::Less cmp::Ordering::Less

@ -7,11 +7,10 @@ repository = "https://git.sr.ht/~tsdh/swayr"
authors = ["Tassilo Horn <tsdh@gnu.org>"] authors = ["Tassilo Horn <tsdh@gnu.org>"]
license = "GPL-3.0+" license = "GPL-3.0+"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
battery = "0.7.8" battery = "0.7.8"
chrono = "0.4" chrono = "0.4"
directories = "4.0"
env_logger = { version = "0.9.0", default-features = false, features = ["termcolor", "atty", "humantime"] } # without regex env_logger = { version = "0.9.0", default-features = false, features = ["termcolor", "atty", "humantime"] } # without regex
log = "0.4" log = "0.4"
once_cell = "1.10.0" once_cell = "1.10.0"

@ -17,7 +17,7 @@
use crate::bar::config; use crate::bar::config;
use crate::bar::module::BarModuleFn; use crate::bar::module::BarModuleFn;
use crate::fmt_replace::fmt_replace; use crate::shared::fmt::fmt_replace;
use battery as bat; use battery as bat;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use swaybar_types as s; use swaybar_types as s;

@ -17,7 +17,7 @@
use crate::bar::config; use crate::bar::config;
use crate::bar::module::BarModuleFn; use crate::bar::module::BarModuleFn;
use crate::fmt_replace::fmt_replace; use crate::shared::fmt::fmt_replace;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Mutex; use std::sync::Mutex;
use std::sync::Once; use std::sync::Once;

@ -19,9 +19,9 @@ use std::collections::HashMap;
use crate::bar::config; use crate::bar::config;
use crate::bar::module::BarModuleFn; use crate::bar::module::BarModuleFn;
use crate::fmt_replace::fmt_replace; use crate::shared::fmt::fmt_replace;
use crate::ipc; use crate::shared::ipc;
use crate::ipc::NodeMethods; use crate::shared::ipc::NodeMethods;
use swaybar_types as s; use swaybar_types as s;
const NAME: &str = "window"; const NAME: &str = "window";

@ -1 +0,0 @@
../../swayr/src/fmt_replace.rs

@ -1 +0,0 @@
../../swayr/src/ipc.rs

@ -14,6 +14,4 @@
// this program. If not, see <https://www.gnu.org/licenses/>. // this program. If not, see <https://www.gnu.org/licenses/>.
pub mod bar; pub mod bar;
pub mod fmt_replace; pub mod shared;
pub mod ipc;
pub mod rtfmt;

@ -1 +0,0 @@
../../swayr/src/rtfmt.rs

@ -0,0 +1 @@
../../swayr/src/shared
Loading…
Cancel
Save