Skip to content

Commit

Permalink
refactor: restructure Rust GTK app layout, event handling, and styling
Browse files Browse the repository at this point in the history
- Reorganize widget creation and layout:
  - Simplify `summary_box` creation and remove redundant code.
  - Move `reply_entry` and `reply_revealer` to a more appropriate hierarchy position.
  - Conditionally append `app_icon` to `app_name_box` based on configuration.

- Improve event handling logic:
  - Reimplement mouse hover (`EventControllerMotion`) and click (`GestureClick`) events.
  - Enhance gesture handling organization using `connect_enter`, `connect_leave`, and `connect_released`.

- Refactor notification management:
  - Use `glib::spawn_future_local` in `handle_notification` for asynchronous management.
  - Move gesture control logic to window setup for better modularity.

- Optimize setup and configuration:
  - Introduce `logger_init` and `setup_styling` for centralized logging and CSS loading.
  - Streamline configuration for theme and styling.

- Simplify `main` function:
  - Refactor for improved application setup, event connections, and notification management.
  - Enhance error handling and remove redundant calls.

- Update CSS and styling:
  - Restructure `load_css` under `setup_styling` for better dynamic theme handling.

- Add fixes and improvements:
  - Include comments and `FIXME`/`TODO` notes for future enhancements.
  - Handle edge cases related to window overflow.
  • Loading branch information
bzglve committed Sep 9, 2024
1 parent 24b92ad commit 85856fd
Show file tree
Hide file tree
Showing 8 changed files with 568 additions and 503 deletions.
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rustyfications"
version = "0.1.11-alpha"
version = "0.1.12-alpha"
edition = "2021"
authors = ["bzglve"]

Expand Down
88 changes: 50 additions & 38 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ mod level_filter {
}

pub mod edge {
use gtk_layer_shell::Edge as GtkEdge;
use serde::{Deserialize, Serialize};

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
Expand All @@ -60,13 +61,31 @@ pub mod edge {
pub padding: i32,
}

impl From<Edge> for gtk_layer_shell::Edge {
impl EdgeInfo {
pub fn total_margin(&self) -> i32 {
self.margin + self.padding
}
}

impl From<Edge> for GtkEdge {
fn from(value: Edge) -> Self {
match value {
Edge::Left => gtk_layer_shell::Edge::Left,
Edge::Right => gtk_layer_shell::Edge::Right,
Edge::Top => gtk_layer_shell::Edge::Top,
Edge::Bottom => gtk_layer_shell::Edge::Bottom,
Edge::Left => Self::Left,
Edge::Right => Self::Right,
Edge::Top => Self::Top,
Edge::Bottom => Self::Bottom,
}
}
}

impl From<GtkEdge> for Edge {
fn from(value: GtkEdge) -> Self {
match value {
GtkEdge::Left => Self::Left,
GtkEdge::Right => Self::Right,
GtkEdge::Top => Self::Top,
GtkEdge::Bottom => Self::Bottom,
_ => unreachable!(),
}
}
}
Expand Down Expand Up @@ -114,7 +133,6 @@ mod defaults {

pub fn edges() -> HashMap<Edge, EdgeInfo> {
let mut val = HashMap::new();

val.insert(
Edge::Top,
EdgeInfo {
Expand All @@ -129,7 +147,6 @@ mod defaults {
padding: 0,
},
);

val
}
}
Expand Down Expand Up @@ -159,15 +176,20 @@ pub struct Config {
impl Config {
pub fn new() -> Option<Self> {
let config_path = Self::find_config_path()?;
println!("Found config file {:?}", config_path);

match ron::from_str::<Self>(&fs::read_to_string(&config_path).unwrap()) {
Ok(config) if Self::validate_config(&config) => Some(config),
Ok(_) => None,
Err(e) => {
eprintln!("{}", e);
None
}
println!("Found config file: {:?}", config_path);

let config_string = fs::read_to_string(&config_path).ok()?;
let config = ron::from_str::<Self>(&config_string);
if let Err(e) = config {
eprintln!("{}", e);
return None;
}
let config = config.unwrap();

if config.validate() {
Some(config)
} else {
None
}
}

Expand All @@ -179,25 +201,20 @@ impl Config {

glib::system_config_dirs().iter().find_map(|dir| {
let system_config = dir.join("rustyfications/config.ron");
if system_config.exists() {
Some(system_config)
} else {
None
}
system_config.exists().then_some(system_config)
})
}

fn validate_config(config: &Self) -> bool {
if config.edges.contains_key(&edge::Edge::Left)
&& config.edges.contains_key(&edge::Edge::Right)
|| config.edges.contains_key(&edge::Edge::Top)
&& config.edges.contains_key(&edge::Edge::Bottom)
fn validate(&self) -> bool {
if self.edges.contains_key(&edge::Edge::Left) && self.edges.contains_key(&edge::Edge::Right)
|| self.edges.contains_key(&edge::Edge::Top)
&& self.edges.contains_key(&edge::Edge::Bottom)
{
eprintln!("Using two opposite edges is not allowed");
return false;
false
} else {
true
}

true
}
}

Expand All @@ -218,13 +235,8 @@ impl Default for Config {
}

pub static CONFIG: LazyLock<Mutex<Config>> = LazyLock::new(|| {
Mutex::new({
match Config::new() {
Some(c) => c,
None => {
println!("Using default configuration");
Config::default()
}
}
})
Mutex::new(Config::new().unwrap_or_else(|| {
println!("Using default configuration");
Config::default()
}))
});
6 changes: 3 additions & 3 deletions src/dbus/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mod server_info;
use std::{cmp::Ordering, collections::HashMap, time::Duration, vec};

pub use action::Action;
use futures::channel::mpsc::Sender;
use futures::channel::mpsc;
pub use hints::Hints;
pub use id::Id;
#[allow(unused_imports)]
Expand Down Expand Up @@ -62,7 +62,7 @@ pub enum Reason {
#[derive(Debug)]
pub struct IFace {
server_info: ServerInfo,
sender: Sender<Message>,
sender: mpsc::Sender<Message>,
}

#[interface(name = "org.freedesktop.Notifications")]
Expand Down Expand Up @@ -212,7 +212,7 @@ impl IFace {
}

impl IFace {
pub fn new(server_info: ServerInfo, sender: Sender<Message>) -> Self {
pub fn new(server_info: ServerInfo, sender: mpsc::Sender<Message>) -> Self {
info!("Creating new IFace instance");
Self {
server_info,
Expand Down
96 changes: 47 additions & 49 deletions src/gui/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,44 +16,42 @@ pub fn init_layer_shell(window: &impl LayerShell) {

let edges = CONFIG.lock().unwrap().edges.clone();

window.set_anchor(Edge::Left, edges.contains_key(&ConfigEdge::Left));
window.set_anchor(Edge::Right, edges.contains_key(&ConfigEdge::Right));
window.set_anchor(Edge::Top, edges.contains_key(&ConfigEdge::Top));
window.set_anchor(Edge::Bottom, edges.contains_key(&ConfigEdge::Bottom));

for (edge, edge_info) in edges.iter() {
window.set_margin((*edge).into(), edge_info.margin + edge_info.padding);
for edge in [Edge::Left, Edge::Right, Edge::Top, Edge::Bottom] {
window.set_anchor(edge, edges.contains_key(&ConfigEdge::from(edge)));
}

edges.iter().for_each(|(config_edge, edge_info)| {
window.set_margin((*config_edge).into(), edge_info.total_margin());
});
}

pub fn margins_update(runtime_data: RuntimeData) {
let edges = CONFIG.lock().unwrap().edges.clone();

let runtime_data = runtime_data.borrow();
let windows = runtime_data.windows.iter();

let new_on_top = CONFIG.lock().unwrap().new_on_top;
let iter: Box<dyn Iterator<Item = (&u32, &Window)>> = if new_on_top {
Box::new(windows.rev())
} else {
Box::new(windows)
};
let windows_iter: Box<dyn Iterator<Item = (&u32, &Window)>> =
if CONFIG.lock().unwrap().new_on_top {
Box::new(runtime_data.windows.iter().rev())
} else {
Box::new(runtime_data.windows.iter())
};

let mut indent = edges
let mut top_bottom_indent = edges
.get(&ConfigEdge::Top)
.or(edges.get(&ConfigEdge::Bottom))
.unwrap_or(&EdgeInfo::default())
.padding;
for (_, window) in iter {
.or_else(|| edges.get(&ConfigEdge::Bottom))
.map_or(0, |edge_info| edge_info.padding);

for (_, window) in windows_iter {
if edges.contains_key(&ConfigEdge::Top) {
window.inner.set_margin(Edge::Top, indent);
window.inner.set_margin(Edge::Top, top_bottom_indent);
} else if edges.contains_key(&ConfigEdge::Bottom) {
window.inner.set_margin(Edge::Bottom, indent);
window.inner.set_margin(Edge::Bottom, top_bottom_indent);
}
indent += window.inner.height()

top_bottom_indent += window.inner.height()
+ edges
.get(&ConfigEdge::Left)
.or(edges.get(&ConfigEdge::Right))
.or_else(|| edges.get(&ConfigEdge::Right))
.unwrap_or(&EdgeInfo::default())
.margin;
}
Expand All @@ -69,35 +67,35 @@ pub mod pixbuf {
pub fn new_from_str(value: &str) -> Option<Pixbuf> {
if PathBuf::from(value).is_absolute() {
return Pixbuf::from_file(value).ok();
} else {
let itheme = gtk::IconTheme::for_display(&gdk::Display::default().unwrap());
if itheme.has_icon(value) {
let ipaint = itheme.lookup_icon(
value,
&["image-missing"],
CONFIG.lock().unwrap().icon_size,
1,
TextDirection::None,
IconLookupFlags::empty(),
);
let image_path = ipaint
.file()
.unwrap()
.path()
.unwrap()
.to_string_lossy()
.to_string();
return Pixbuf::from_file(image_path).ok();
}

let icon_theme = gtk::IconTheme::for_display(&gdk::Display::default()?);

if icon_theme.has_icon(value) {
let icon_info = icon_theme.lookup_icon(
value,
&["image-missing"],
CONFIG.lock().unwrap().icon_size,
1,
TextDirection::None,
IconLookupFlags::empty(),
);

if let Some(image_path) = icon_info.file().and_then(|file| file.path()) {
return Pixbuf::from_file(image_path.to_string_lossy().as_ref()).ok();
}
}

None
}

pub fn crop_square(value: &Pixbuf) -> Pixbuf {
let height = value.height();
let width = value.width();
let side = height.min(width);

value.new_subpixbuf((width - side) / 2, (height - side) / 2, side, side)
pub fn crop_square(pixbuf: &Pixbuf) -> Pixbuf {
let side = pixbuf.height().min(pixbuf.width());
pixbuf.new_subpixbuf(
(pixbuf.width() - side) / 2,
(pixbuf.height() - side) / 2,
side,
side,
)
}
}
Loading

0 comments on commit 85856fd

Please sign in to comment.