57 Commits
Author SHA1 Message Date
Kenny Levinsen a8cd777ca9 Clean up command-line arguments, usage text 2025-02-27 16:38:52 +01:00
Kenny Levinsen 83179d2c7e state: Increase xdg_toplevel default dimensions
The previous values are too small for the default toplevel layout.
2025-02-27 16:38:52 +01:00
Kenny Levinsen 7e112ddd1f keyboard: Update to xkbcommon 0.8 2025-02-27 16:38:52 +01:00
Kenny Levinsen 9fd054fc2c Fix damage issue when multiple buffers are in use
wldash was originally written to expect server-side shm buffer
optimizations, which make it so only a single buffer has to be in use.
This simplifies damage tracking and repaint needs.

Support for using multiple buffers was added to support e.g., jay, but
the damage handling was not in place for this to work. Fix that by
tracking damage per buffer.
2025-02-27 16:38:52 +01:00
Kenny Levinsen 40aec97f79 Cargo format 2025-02-27 14:48:41 +01:00
Kenny Levinsen 9031361dd1 Cargo update 2025-02-27 14:48:41 +01:00
Kenny Levinsen f337ce6e95 layer-shell: Change to overlay 2025-01-12 23:08:24 +01:00
Kenny Levinsen bc9ba0045c launcher: Support launch_cmd config 2025-01-12 22:51:45 +01:00
Kenny Levinsen 2b3048faca Rework the initial wayland init a bit 2025-01-12 22:50:00 +01:00
Kenny Levinsen f09abf1d53 backlight: Auto-detect type 2025-01-12 22:47:16 +01:00
Kenny Levinsen 5776886884 keyboard: Fix repeat deadline handling
The calloop timer is only responsible for ensuring wakeup at the right
time, but we can also be woken up before time so we need to check the
deadline.

At the same time, We may end up being significantly delayed past the
deadline if something else was slow. If we are too far behind, reset the
base of the repeat timer by just offsetting from the current time.
2024-01-30 00:56:12 +01:00
Kenny Levinsen 7ee58d8d68 server: Make optional 2023-11-10 15:22:37 +01:00
Kenny Levinsen c169843bcb Add basic server operation 2023-11-10 15:10:10 +01:00
Kenny Levinsen 1d1f7d3a8e draw: Fix a bug I forgot the details of 2023-11-10 14:01:14 +01:00
Kenny Levinsen a882e26e2b widgets/backlight: Set support 2023-11-10 14:00:48 +01:00
Kenny Levinsen 84c241a90e keyboard: Use xkb_common::keysyms 2023-11-10 14:00:06 +01:00
Kenny Levinsen 921938cc0d Resolve keyboard after first draw 2023-11-10 13:59:09 +01:00
Kenny Levinsen 8835708b31 Make background configurable 2023-11-10 13:58:56 +01:00
Kenny Levinsen c01c810c10 Configurable config file 2023-09-28 23:40:20 +02:00
Kenny Levinsen b451a2de31 Fix keyboard resolve on sway 2023-08-22 14:39:20 +02:00
Kenny Levinsen ebeb21f3c2 Fix fontmap resolution on sway 2023-08-22 14:38:36 +02:00
Kenny Levinsen 558d528f70 Fix xdg_toplevel background 2023-05-20 17:34:52 +02:00
Kenny Levinsen 6351cc242d launcher: Use XDG_ACTIVATION_TOKEN for shell cmds 2023-04-04 01:53:29 +02:00
Kenny Levinsen 66e66e19ad launcher: Cache desktop files 2023-04-04 01:53:02 +02:00
Kenny Levinsen 3a77696569 calendar: Missed preload of 'N' 2023-03-01 11:48:25 +01:00
Kenny Levinsen a975da5074 config: Apply margins to default 2023-02-14 23:52:54 +01:00
Kenny Levinsen 9d1f310f12 cargo fmt 2023-02-14 10:23:20 +01:00
Kenny Levinsen 54e4ba16dd Add InvertedVerticalLayout 2023-02-14 10:23:12 +01:00
Kenny Levinsen 764a1e3444 config: Remove default configuration 2023-02-14 00:30:46 +01:00
Kenny Levinsen 6fac465c3a calendar: Highlight current week 2023-02-14 00:28:40 +01:00
Kenny Levinsen 5097faab66 launcher: Save prompt on exit 2023-02-14 00:28:40 +01:00
Kenny Levinsen 8202963a6f Add vertical line 2023-02-14 00:28:40 +01:00
Kenny Levinsen b09f642fd6 Avoid panic on very long prompt lines 2023-02-14 00:28:40 +01:00
Kenny Levinsen 59e2f658db keyboard: Rename realize to resolve 2023-02-13 19:43:15 +01:00
Kenny Levinsen 022f6a719a cargo fmt 2023-02-13 18:49:44 +01:00
Kenny Levinsen 8826cab89d keyboard: Add keyrepeat handling 2023-02-13 17:39:54 +01:00
Kenny Levinsen 9e48eb053d config: Generate configs 2023-02-12 17:02:44 +01:00
Kenny Levinsen db085168dc config: Add config support 2023-02-11 18:24:34 +01:00
Kenny Levinsen 353ed1f189 launcher: Shrink margin 2023-02-08 22:57:06 +01:00
Kenny Levinsen 45e5a750f9 calendar: Fix hiding when shrunk 2023-02-08 22:56:52 +01:00
Kenny Levinsen 6e90b1f0e8 More better 2023-02-08 22:53:41 +01:00
Kenny Levinsen 3c69a31030 calc: Store history 2023-02-07 00:36:06 +01:00
Kenny Levinsen b9f4e74062 calc: Improve history 2023-02-06 18:57:34 +01:00
Kenny Levinsen 6f0ca36826 Moar speed 2023-02-06 18:34:07 +01:00
Kenny Levinsen 69959e86dc Fix memset hack 2023-02-04 16:52:32 +01:00
Kenny Levinsen 74591902e9 Support toggle between V1 and V2 UIs 2023-02-04 16:52:18 +01:00
Kenny Levinsen 3a2badbfd9 wlr-layer-shell support 2023-02-04 14:42:29 +01:00
Kenny Levinsen b49b9e9764 More stuff 2023-02-02 23:52:59 +01:00
Kenny Levinsen 7593cd48a4 Add calendar, refactor more 2023-01-16 00:25:34 +01:00
Kenny Levinsen 3a40bb18c5 Refactor slightly 2023-01-13 21:53:07 +01:00
Kenny Levinsen b2a9475e4c cargo fmt 2023-01-12 00:13:27 +01:00
Kenny Levinsen be6ee9899c cargo update 2023-01-12 00:13:15 +01:00
Kenny Levinsen d3002d2180 Exit when no longer activated 2023-01-12 00:13:08 +01:00
Kenny Levinsen 25644c2b15 backlight: Add 2023-01-11 23:54:52 +01:00
Kenny Levinsen dd790468ad battery: Minor cleanup 2023-01-11 23:54:39 +01:00
Kenny Levinsen 0a4544a608 launcher: Add ctrl k/u handling 2023-01-11 23:54:14 +01:00
Kenny Levinsen 8e80c0a69c Initial commit 2023-01-11 00:28:54 +01:00
35 changed files with 7210 additions and 103 deletions
+1
View File
@@ -0,0 +1 @@
/target
-1
View File
@@ -1 +0,0 @@
wldash.org
Generated
+1355
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
[package]
name = "wldash2"
version = "0.1.0"
edition = "2021"
[profile.release]
#debug = true
lto = "fat"
panic = "abort"
[dependencies]
wayland-client = { version = "0.30", features = ["calloop", "log"] }
wayland-protocols = { version = "0.30", features = ["client", "unstable", "staging"] }
wayland-protocols-wlr = { version = "0.1", features = ["client"] }
nix = "0.26" # 0.27 is breaking
memmap = "0.7"
fontconfig = { version = "0.8.0", optional = true }
rusttype = "0.9"
# fontdue = "0.7"
calloop = { version = "0.10" } # update breaks
chrono = "0.4"
walkdir = "2.4"
unicode-segmentation = "1.10"
fuzzy-matcher = "0.3"
shlex = "1.3"
xkbcommon = { version = "0.8", features = ["wayland"] }
rcalc_lib = "1.0"
#alsa = { version = "0.7", optional = true }
dbus = "0.9"
libpulse-binding = "2.28"
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.9"
simd-json = "0.13"
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 201 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 781 KiB

-102
View File
@@ -1,102 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>wldash</title>
<meta http-equiv="refresh" content="0; URL=https://kl.wtf/projects/wldash">
<link rel="canonical" href="https://kl.wtf/projects/wldash">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
display: grid;
justify-items: center;
align-items: center;
}
h1 {
font-size: 3em;
text-align: center;
font-family: monospace;
}
h2 {
text-align: center;
font-family: monospace;
}
h3 {
font-family: monospace;
}
header {
width: 100%;
max-width: 720px;
}
section {
width: 100%;
max-width: 720px;
}
a {
text-decoration: unset;
color: rgb(100, 100, 100);
}
li {
list-style-type: '— ';
}
p {
margin-bottom: 2em;
}
img {
width: 100%;
border-radius: 10px;
}
</style>
</head>
<body>
<header>
<h1>wldash</h1>
<h2>wayland launcher/dashboard</h2>
</header>
<section>
<img src="images/wldash.jpg" alt="screenshot of wldash" />
<p>
<a href="https://github.com/kennylevinsen/wldash"><code>wldash</code></a> is a convenient dashboard and launcher for Wayland (requires wlr-layer-shell-unstable-v1 support), allowing easy access to things like date and time, backlight and volume control.
</p>
<h3>How to get wldash</h3>
<ul>
<li><a href="https://github.com/kennylevinsen/wldash/releases">Download the latest release from GitHub</a></li>
<li>To build:
<pre><code>
git clone https://github.com/kennylevinsen/wldash
cd wldash
cargo build --release
cp ./target/release/wldash /usr/local/bin/
wldash
</code></pre>
</li>
</ul>
<h3>Usage</h3>
<p>
Run <code>wldash print-config</code> to see the current configuration. Use that as template to write a new one to <code>~/.config/wldash/config.json</code>. The widgets, their size and layout can be configured as well.
</p>
<p>
To make wldash toggle itself every time it is started, instantiate with <code>wldash start-or-kill</code>.
</p>
<p>
To run arbitrary command, type <code>!</code>. To use built-in calculator, type <code>=</code>.
</p>
<p>
Hint: Try to scroll, left-click and right-click on things.
</p>
<h3>Links</h3>
<p>
<ul>
<li>Github link: <a href="https://github.com/kennylevinsen/wldash">https://github.com/kennylevinsen/wldash</a></li>
<li>IRC: #wldash @ irc.freenode.net</li>
</ul>
</p>
<h3>Donate</h3>
<ul>
<li><a href="https://en.liberapay.com/kennylevinsen/">LiberaPay</a></li>
</ul>
<p>
<a href="https://kl.wtf/">© 2019, Kenny Levinsen</a>
</p>
</section>
</body>
</html>
+295
View File
@@ -0,0 +1,295 @@
use std::{
ffi::CStr,
fs::File,
io,
os::unix::io::{FromRawFd, RawFd},
time::SystemTime,
time::UNIX_EPOCH,
};
#[cfg(target_os = "linux")]
use nix::sys::memfd;
use nix::{
errno::Errno,
fcntl,
sys::{mman, stat},
unistd,
};
use memmap::MmapMut;
use wayland_client::{
protocol::{wl_buffer, wl_shm, wl_shm_pool},
Dispatch, QueueHandle,
};
use crate::color::Color;
use crate::widgets::Geometry;
fn create_shm_fd() -> io::Result<RawFd> {
// Only try memfd on linux
#[cfg(target_os = "linux")]
loop {
match memfd::memfd_create(
CStr::from_bytes_with_nul(b"wldash\0").unwrap(),
memfd::MemFdCreateFlag::MFD_CLOEXEC,
) {
Ok(fd) => return Ok(fd),
Err(Errno::EINTR) => continue,
Err(Errno::ENOSYS) => break,
Err(errno) => return Err(io::Error::from(errno)),
}
}
// Fallback to using shm_open
let sys_time = SystemTime::now();
let mut mem_file_handle = format!(
"/wldash-{}",
sys_time.duration_since(UNIX_EPOCH).unwrap().subsec_nanos()
);
loop {
match mman::shm_open(
mem_file_handle.as_str(),
fcntl::OFlag::O_CREAT
| fcntl::OFlag::O_EXCL
| fcntl::OFlag::O_RDWR
| fcntl::OFlag::O_CLOEXEC,
stat::Mode::S_IRUSR | stat::Mode::S_IWUSR,
) {
Ok(fd) => match mman::shm_unlink(mem_file_handle.as_str()) {
Ok(_) => return Ok(fd),
Err(errno) => match unistd::close(fd) {
Ok(_) => return Err(io::Error::from(errno)),
Err(errno) => return Err(io::Error::from(errno)),
},
},
Err(Errno::EEXIST) => {
// If a file with that handle exists then change the handle
mem_file_handle = format!(
"/wldash-{}",
sys_time.duration_since(UNIX_EPOCH).unwrap().subsec_nanos()
);
continue;
}
Err(Errno::EINTR) => continue,
Err(errno) => return Err(io::Error::from(errno)),
}
}
}
pub struct ShmBuffer {
pub file: File,
pub mmap: MmapMut,
pub buffer: wl_buffer::WlBuffer,
pub refcnt: u32,
pub id: u32,
pub last_damage: Vec<Geometry>,
}
impl ShmBuffer {
fn new<D>(
shm: &wl_shm::WlShm,
qh: &QueueHandle<D>,
width: i32,
height: i32,
stride: i32,
format: wl_shm::Format,
id: u32,
) -> io::Result<ShmBuffer>
where
D: Dispatch<wl_shm_pool::WlShmPool, ()> + Dispatch<wl_buffer::WlBuffer, ()> + 'static,
{
let mem_fd = create_shm_fd()?;
let file = unsafe { File::from_raw_fd(mem_fd) };
file.set_len((height * stride) as u64)?;
let pool = shm.create_pool(mem_fd, height * stride, &qh, ());
let mmap = unsafe { MmapMut::map_mut(&file).unwrap() };
let buffer = pool.create_buffer(0, width, height, stride, format, &qh, ());
Ok(ShmBuffer {
refcnt: 0,
file,
mmap,
buffer,
id,
last_damage: Vec::new(),
})
}
pub fn acquire(&mut self) {
self.refcnt += 1;
}
pub fn release(&mut self) {
self.refcnt -= 1;
}
}
pub struct BufferManager {
pub buffers: Vec<ShmBuffer>,
pub next_id: u32,
}
impl BufferManager {
pub fn new() -> BufferManager {
BufferManager {
buffers: Vec::new(),
next_id: 0,
}
}
pub fn clear_buffers(&mut self) {
for buf in self.buffers.iter_mut() {
buf.buffer.destroy()
}
self.buffers.clear()
}
pub fn next_buffer(&mut self) -> Option<&mut ShmBuffer> {
for buf in self.buffers.iter_mut() {
if buf.refcnt == 0 {
return Some(buf);
}
}
None
}
pub fn add_buffer<D>(
&mut self,
wl_shm: &wl_shm::WlShm,
dimensions: (i32, i32),
qh: &QueueHandle<D>,
) where
D: Dispatch<wl_shm_pool::WlShmPool, ()> + Dispatch<wl_buffer::WlBuffer, ()> + 'static,
{
let mut buf = ShmBuffer::new(
wl_shm,
qh,
dimensions.0,
dimensions.1,
dimensions.0 * 4,
wl_shm::Format::Argb8888,
self.next_id,
)
.expect("unable to add buffer");
self.next_id += 1;
BufferView::new(&mut buf.mmap, (dimensions.0 as u32, dimensions.1 as u32));
self.buffers.push(buf);
}
}
pub struct BufferView<'a> {
view: &'a mut [u32],
dimensions: (u32, u32),
subdimensions: Option<(u32, u32, u32, u32)>,
}
impl<'a> BufferView<'a> {
pub fn new(buf: &'a mut MmapMut, dimensions: (u32, u32)) -> BufferView {
let view = unsafe {
std::slice::from_raw_parts_mut(
buf.as_mut_ptr() as *mut u32,
(dimensions.0 * dimensions.1) as usize,
)
};
BufferView {
view,
dimensions,
subdimensions: None,
}
}
#[inline]
pub fn get_bounds(&self) -> (u32, u32, u32, u32) {
if let Some(subdim) = self.subdimensions {
subdim
} else {
(0, 0, self.dimensions.0, self.dimensions.1)
}
}
pub fn subdimensions(&mut self, subdimensions: (u32, u32, u32, u32)) -> BufferView {
let bounds = self.get_bounds();
if cfg!(debug_assertions)
&& (subdimensions.0 + subdimensions.2 > bounds.2
|| subdimensions.1 + subdimensions.3 > bounds.3)
{
panic!(
"cannot create subdimensions larger than buffer: {:?} > {:?}",
subdimensions, bounds
);
}
BufferView {
view: self.view,
dimensions: self.dimensions,
subdimensions: Some((
subdimensions.0 + bounds.0,
subdimensions.1 + bounds.1,
subdimensions.2,
subdimensions.3,
)),
}
}
pub fn subgeometry(&mut self, geo: Geometry) -> BufferView {
self.subdimensions((geo.x, geo.y, geo.width, geo.height))
}
pub fn offset(&mut self, offset: (u32, u32)) -> BufferView {
let bounds = self.get_bounds();
if cfg!(debug_assertions) && (offset.0 > bounds.2 || offset.1 > bounds.3) {
panic!(
"cannot create offset outside buffer: {:?} > {:?}",
offset, bounds
);
}
BufferView {
view: self.view,
dimensions: self.dimensions,
subdimensions: Some((
offset.0 + bounds.0,
offset.1 + bounds.1,
bounds.2 - offset.0,
bounds.3 - offset.1,
)),
}
}
pub fn memset(&mut self, c: Color) {
if let Some(subdim) = self.subdimensions {
for y in subdim.1..(subdim.1 + subdim.3) {
let start = (subdim.0 + y * self.dimensions.0) as usize;
let end = start + subdim.2 as usize;
self.view[start..end].fill(c.0);
}
} else {
self.view.fill(c.0);
}
}
pub fn clear(&mut self) {
if let Some(subdim) = self.subdimensions {
for y in subdim.1..(subdim.1 + subdim.3) {
let start = (subdim.0 + y * self.dimensions.0) as usize;
let end = start + subdim.2 as usize;
self.view[start..end].fill(0x0);
}
} else {
self.view.fill(0x0);
}
}
#[inline]
pub fn put_raw(&mut self, pos: (u32, u32), c: Color) {
self.view[(pos.0 + pos.1 * self.dimensions.0) as usize] = c.0
}
#[inline]
pub fn put_line_raw(&mut self, pos: (u32, u32), len: u32, c: Color) {
let start = (pos.0 + (pos.1 * self.dimensions.0)) as usize;
let len = len as usize;
self.view[start..start + len].fill(c.0);
}
}
+42
View File
@@ -0,0 +1,42 @@
#[derive(Copy, Clone)]
pub struct Color(pub u32);
impl Color {
pub const WHITE: Color = Color(0xFFFFFFFF);
pub const GREY35: Color = Color(0xFF595959);
pub const GREY50: Color = Color(0xFF7F7F7F);
pub const GREY75: Color = Color(0xFFBFBFBF);
pub const GREY80: Color = Color(0xFFCCCCCC);
pub const RED: Color = Color(0xFFFF0000);
pub const YELLOW: Color = Color(0xFFFFFF00);
pub const LIGHTGREEN: Color = Color(0xFF7FFF7F);
pub const LIGHTORANGE: Color = Color(0xFFFFBF00);
pub const DARKORANGE: Color = Color(0xFFFF7F00);
pub const BUFF: Color = Color(0xFFFFBF7F);
#[allow(unused)]
pub fn new(red: u8, green: u8, blue: u8, opacity: u8) -> Color {
Color((opacity as u32) << 24 | (red as u32) << 16 | (green as u32) << 8 | (blue as u32))
}
fn red(self) -> u8 {
((self.0 >> 16) & 0xFF) as u8
}
fn green(self) -> u8 {
((self.0 >> 8) & 0xFF) as u8
}
fn blue(self) -> u8 {
(self.0 & 0xFF) as u8
}
pub fn alpha(self, alpha: f32) -> Color {
unsafe {
Color(
(255. * alpha).to_int_unchecked::<u32>() << 24
| (self.red() as f32 * alpha).to_int_unchecked::<u32>() << 16
| (self.green() as f32 * alpha).to_int_unchecked::<u32>() << 8
| (self.blue() as f32 * alpha).to_int_unchecked::<u32>(),
)
}
}
}
+387
View File
@@ -0,0 +1,387 @@
use serde::{self, Deserialize, Serialize};
use std::collections::HashMap;
use std::default::Default;
use std::sync::{Arc, Mutex};
use crate::{
event::Events,
fonts::{find_font, FontMap},
widgets::{
Backlight, Battery, Calendar, Clock, Date, HorizontalLayout, IndexedLayout, Interface,
InvertedHorizontalLayout, InvertedVerticalLayout, Layout, Line, Margin, PulseAudio,
VerticalLayout, Widget as RealWidget,
},
};
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum OperationMode {
LayerSurface((u32, u32)),
XdgToplevel,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum Widget {
Margin {
margins: (u32, u32, u32, u32),
widget: Box<Widget>,
},
HorizontalLayout(Vec<Widget>),
InvertedHorizontalLayout(Vec<Widget>),
VerticalLayout(Vec<Widget>),
InvertedVerticalLayout(Vec<Widget>),
HorizontalLine(u32),
VerticalLine(u32),
Clock {
font: Option<String>,
font_size: f32,
},
Date {
font: Option<String>,
font_size: f32,
},
Calendar {
font_primary: Option<String>,
font_secondary: Option<String>,
font_size: f32,
sections_x: i32,
sections_y: i32,
},
Launcher {
font: Option<String>,
font_size: f32,
launch_cmd: Option<String>,
},
Battery {
font: Option<String>,
font_size: f32,
},
Backlight {
device: Option<String>,
font: Option<String>,
font_size: f32,
},
PulseAudio {
font: Option<String>,
font_size: f32,
},
}
impl Default for OperationMode {
fn default() -> OperationMode {
OperationMode::LayerSurface((1024, 768))
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub struct Config {
pub font_paths: Option<HashMap<String, String>>,
pub widget: Widget,
pub mode: OperationMode,
pub background: Option<u32>,
pub server: Option<bool>,
}
impl Config {
pub fn generate_v1() -> Config {
let has_battery = Battery::detect();
let has_backlight = Backlight::detect();
let sans = find_font("sans");
let monospace = find_font("monospace");
let mut bars = Vec::new();
if has_battery {
bars.push(Widget::Margin {
margins: (0, 0, 0, 8),
widget: Box::new(Widget::Battery {
font: None,
font_size: 24.,
}),
});
}
if has_backlight {
bars.push(Widget::Margin {
margins: (0, 0, 0, 8),
widget: Box::new(Widget::Backlight {
device: None,
font: None,
font_size: 24.,
}),
});
}
bars.push(Widget::Margin {
margins: (0, 0, 0, 8),
widget: Box::new(Widget::PulseAudio {
font: None,
font_size: 24.,
}),
});
let widget = Widget::Margin {
margins: (20, 20, 20, 20),
widget: Box::new(Widget::VerticalLayout(vec![
Widget::HorizontalLayout(vec![
Widget::VerticalLayout(vec![
Widget::Date {
font: None,
font_size: 48.,
},
Widget::Clock {
font: None,
font_size: 256.,
},
]),
Widget::Margin {
margins: (88, 0, 0, 0),
widget: Box::new(Widget::VerticalLayout(bars)),
},
]),
Widget::Calendar {
font_primary: None,
font_secondary: None,
font_size: 36.,
sections_x: 3,
sections_y: 1,
},
Widget::Launcher {
font: None,
font_size: 32.,
launch_cmd: None,
},
])),
};
let map = HashMap::from([
("sans".to_string(), sans),
("monospace".to_string(), monospace),
]);
Config {
font_paths: Some(map),
widget: widget,
mode: OperationMode::LayerSurface((1024, 768)),
background: Some(0xFAFAFAFA),
server: None,
}
}
pub fn generate_v2(clay: bool) -> Config {
let has_battery = Battery::detect();
let has_backlight = Backlight::detect();
let sans = find_font("sans");
let monospace = find_font("monospace");
let mut bars = Vec::new();
if has_battery {
bars.push(Widget::Margin {
margins: (16, 8, 8, 0),
widget: Box::new(Widget::Battery {
font: None,
font_size: 24.,
}),
});
}
if has_backlight {
bars.push(Widget::Margin {
margins: (16, 8, 8, 0),
widget: Box::new(Widget::Backlight {
device: None,
font: None,
font_size: 24.,
}),
});
}
bars.push(Widget::Margin {
margins: (16, 8, 8, 0),
widget: Box::new(Widget::PulseAudio {
font: None,
font_size: 24.,
}),
});
let widget = Widget::VerticalLayout(vec![
Widget::HorizontalLayout(vec![
Widget::Margin {
margins: (8, 0, 0, 0),
widget: Box::new(Widget::Clock {
font: None,
font_size: 128.,
}),
},
Widget::Margin {
margins: (16, 64, 0, 0),
widget: Box::new(Widget::Date {
font: None,
font_size: 48.,
}),
},
Widget::VerticalLayout(bars),
]),
Widget::HorizontalLine(1),
Widget::InvertedHorizontalLayout(vec![
Widget::Margin {
margins: (16, 8, 16, 0),
widget: Box::new(Widget::Calendar {
font_primary: None,
font_secondary: None,
font_size: 24.,
sections_x: 1,
sections_y: if clay { -1 } else { 3 },
}),
},
Widget::VerticalLine(1),
Widget::Margin {
margins: (8, 0, 0, 0),
widget: Box::new(Widget::Launcher {
font: None,
font_size: 32.,
launch_cmd: None,
}),
},
]),
]);
let map = HashMap::from([
("sans".to_string(), sans),
("monospace".to_string(), monospace),
]);
Config {
font_paths: Some(map),
widget: widget,
mode: if clay {
OperationMode::XdgToplevel
} else {
OperationMode::LayerSurface((1024, 1))
},
background: Some(0xFAFAFAFA),
server: None,
}
}
}
fn leak_or_default(v: Option<String>, d: &'static str) -> &'static str {
match v {
Some(v) => Box::leak(v.into_boxed_str()),
None => d,
}
}
fn leak_or_none(v: Option<String>) -> Option<&'static str> {
match v {
Some(v) => Some(Box::leak(v.into_boxed_str())),
None => None,
}
}
impl Widget {
pub fn construct_widgets(
self,
v: &mut Vec<Box<dyn RealWidget>>,
mut fm: &mut FontMap,
events: &Arc<Mutex<Events>>,
) {
match self {
Widget::Margin { widget, .. } => widget.construct_widgets(v, fm, events),
Widget::HorizontalLayout(widgets) => widgets
.into_iter()
.for_each(|w| w.construct_widgets(v, fm, events)),
Widget::InvertedHorizontalLayout(widgets) => widgets
.into_iter()
.for_each(|w| w.construct_widgets(v, fm, events)),
Widget::VerticalLayout(widgets) => widgets
.into_iter()
.for_each(|w| w.construct_widgets(v, fm, events)),
Widget::InvertedVerticalLayout(widgets) => widgets
.into_iter()
.for_each(|w| w.construct_widgets(v, fm, events)),
Widget::HorizontalLine(width) => v.push(Box::new(Line::new(width, false))),
Widget::VerticalLine(width) => v.push(Box::new(Line::new(width, true))),
Widget::Clock { font, font_size } => v.push(Box::new(Clock::new(
&mut fm,
leak_or_default(font, "sans"),
font_size,
))),
Widget::Date { font, font_size } => v.push(Box::new(Date::new(
&mut fm,
leak_or_default(font, "sans"),
font_size,
))),
Widget::Calendar {
font_primary,
font_secondary,
font_size,
sections_x,
sections_y,
} => v.push(Box::new(Calendar::new(
&mut fm,
leak_or_default(font_primary, "monospace"),
leak_or_default(font_secondary, "sans"),
font_size,
sections_x,
sections_y,
))),
Widget::Launcher {
font,
font_size,
launch_cmd,
} => v.push(Box::new(Interface::new(
events.clone(),
&mut fm,
leak_or_default(font, "sans"),
font_size,
launch_cmd,
))),
Widget::Battery { font, font_size } => v.push(Box::new(Battery::new(
events.clone(),
&mut fm,
leak_or_default(font, "sans"),
font_size,
))),
Widget::Backlight {
device,
font,
font_size,
} => v.push(Box::new(Backlight::new(
leak_or_none(device),
&mut fm,
leak_or_default(font, "sans"),
font_size,
))),
Widget::PulseAudio { font, font_size } => v.push(Box::new(PulseAudio::new(
events.clone(),
&mut fm,
Box::leak(font.unwrap_or_else(|| "sans".to_string()).into_boxed_str()),
font_size,
))),
}
}
pub fn construct_layout(&self, idx: &mut usize) -> Box<dyn Layout> {
match self {
Widget::Margin { margins, widget } => {
Margin::new(widget.construct_layout(idx), *margins)
}
Widget::HorizontalLayout(widgets) => {
HorizontalLayout::new(widgets.iter().map(|w| w.construct_layout(idx)).collect())
}
Widget::InvertedHorizontalLayout(widgets) => InvertedHorizontalLayout::new(
widgets.iter().map(|w| w.construct_layout(idx)).collect(),
),
Widget::VerticalLayout(widgets) => {
VerticalLayout::new(widgets.iter().map(|w| w.construct_layout(idx)).collect())
}
Widget::InvertedVerticalLayout(widgets) => InvertedVerticalLayout::new(
widgets.iter().map(|w| w.construct_layout(idx)).collect(),
),
_ => IndexedLayout::new({
let i = *idx;
*idx += 1;
i
}),
}
}
}
+346
View File
@@ -0,0 +1,346 @@
use crate::buffer::BufferView;
use crate::{color::Color, fonts::FontRef};
use rusttype::{point, Scale};
use std::collections::HashMap;
struct CachedGlyph {
dimensions: (u32, u32),
origin: (i32, i32),
render: Vec<f32>,
advance: i32,
}
impl CachedGlyph {
fn new(font: FontRef, size: f32, ch: char) -> CachedGlyph {
let scale = Scale::uniform(size);
let v_metrics = font.v_metrics(scale);
let glyph = font.glyph(ch).scaled(scale);
let advance = glyph.h_metrics().advance_width as i32;
let glyph = glyph.positioned(point(0.0, v_metrics.ascent));
if let Some(bounding_box) = glyph.pixel_bounding_box() {
let origin = (bounding_box.min.x, bounding_box.min.y);
let dimensions = (
(bounding_box.max.x - bounding_box.min.x) as u32,
(bounding_box.max.y - bounding_box.min.y) as u32,
);
let mut render = vec![0.0; (dimensions.0 * dimensions.1) as usize];
glyph.draw(|x, y, o| {
let pos = x + (y * dimensions.0);
render[pos as usize] = o;
});
CachedGlyph {
origin,
dimensions,
render,
advance,
}
} else {
CachedGlyph {
origin: (0, 0),
dimensions: (0, 0),
render: Vec::new(),
advance: (size / 4.0) as i32,
}
}
}
fn draw(&self, buf: &mut BufferView, pos: (i32, i32), c: Color) {
let bounds = buf.get_bounds();
if pos.0 as u32 + self.dimensions.0 > bounds.2 {
return;
}
let offset = (bounds.0 as i32, bounds.1 as i32);
let width = self.dimensions.0 as i32 - 1;
let mut x = 0;
let mut y = 0;
for v in &self.render {
buf.put_raw(
(
(x + pos.0 + self.origin.0 + offset.0) as u32,
(y + pos.1 + self.origin.1 + offset.1) as u32,
),
c.alpha(*v),
);
if x == width {
y += 1;
x = 0;
} else {
x += 1;
}
}
}
}
pub struct Font<'a> {
glyphs: HashMap<char, CachedGlyph>,
font: FontRef<'a>,
size: f32,
}
impl<'a> Font<'a> {
pub fn new(font: FontRef<'a>, size: f32) -> Font {
Font {
glyphs: HashMap::new(),
font,
size,
}
}
pub fn height(&self) -> f32 {
let scale = Scale::uniform(self.size);
let m = self.font.v_metrics(scale);
m.ascent - m.descent
}
pub fn add_str_to_cache(&mut self, s: &str) {
for ch in s.chars() {
if self.glyphs.get(&ch).is_none() {
let glyph = CachedGlyph::new(self.font, self.size, ch);
self.glyphs.insert(ch, glyph);
}
}
}
pub fn draw_text(
&self,
buf: &mut BufferView,
c: Color,
s: &str,
) -> Result<(u32, u32), ::std::io::Error> {
let mut x_off = 0;
let mut off = 0;
let mut glyphs = Vec::with_capacity(s.len());
for ch in s.chars() {
let glyph = match self.glyphs.get(&ch) {
Some(glyph) => glyph,
None => {
return Err(::std::io::Error::new(
::std::io::ErrorKind::Other,
format!("glyph for {:} not in cache", ch),
))
}
};
glyphs.push(glyph);
if glyph.origin.1 < off {
off = glyph.origin.1
}
}
for glyph in glyphs {
glyph.draw(buf, (x_off, -off), c);
x_off += glyph.advance;
}
Ok((x_off as u32, self.size as u32))
}
pub fn draw_text_with_cursor(
&self,
buf: &mut BufferView,
c: Color,
s: &str,
cursor: usize,
) -> Result<(u32, u32), ::std::io::Error> {
let mut x_off: i32 = 0;
let mut off: i32 = 0;
let mut glyphs = Vec::with_capacity(s.len());
for ch in s.chars() {
let glyph = match self.glyphs.get(&ch) {
Some(glyph) => glyph,
None => {
return Err(::std::io::Error::new(
::std::io::ErrorKind::Other,
format!("glyph for {:} not in cache", ch),
))
}
};
glyphs.push(glyph);
if glyph.origin.1 < off {
off = glyph.origin.1
}
}
let height = self.size.ceil() as u32;
for (i, glyph) in glyphs.iter().enumerate() {
if i == cursor {
self.draw_cursor(buf, c, x_off as u32, height)?;
}
glyph.draw(buf, (x_off, -off), c);
x_off += glyph.advance;
}
if cursor == glyphs.len() {
self.draw_cursor(buf, c, x_off as u32, height)?;
}
Ok((x_off as u32, self.size as u32))
}
fn draw_cursor(
&self,
buf: &mut BufferView,
c: Color,
offset: u32,
height: u32,
) -> Result<(), ::std::io::Error> {
// draw cursor
let bounds = buf.get_bounds();
if offset + 1 > bounds.2 {
return Ok(());
}
for i in bounds.1 + 1..height + bounds.1 {
buf.put_raw((bounds.0 + offset, i), c);
}
Ok(())
}
pub fn auto_widest(&mut self, s: &str) -> Result<u32, ::std::io::Error> {
self.add_str_to_cache(s);
let mut max = 0;
for ch in s.chars() {
let glyph = match self.glyphs.get(&ch) {
Some(glyph) => glyph,
None => {
return Err(::std::io::Error::new(
::std::io::ErrorKind::Other,
format!("glyph for {:} not in cache", ch),
))
}
};
let width = glyph.advance;
if width > max {
max = width
}
}
Ok(max as u32)
}
pub fn auto_draw_text(
&mut self,
buf: &mut BufferView,
c: Color,
s: &str,
) -> Result<(u32, u32), ::std::io::Error> {
self.add_str_to_cache(s);
self.draw_text(buf, c, s)
}
pub fn auto_draw_text_with_cursor(
&mut self,
buf: &mut BufferView,
c: Color,
s: &str,
cursor: usize,
) -> Result<(u32, u32), ::std::io::Error> {
self.add_str_to_cache(s);
self.draw_text_with_cursor(buf, c, s, cursor)
}
pub fn draw_text_fixed_width(
&self,
buf: &mut BufferView,
c: Color,
distances: &[u32],
s: &str,
) -> Result<(u32, u32), ::std::io::Error> {
let mut x_off = 0;
let mut off = 0;
let mut glyphs = Vec::with_capacity(s.len());
for ch in s.chars() {
let glyph = match self.glyphs.get(&ch) {
Some(glyph) => glyph,
None => {
return Err(::std::io::Error::new(
::std::io::ErrorKind::Other,
format!("glyph for {:} not in cache", ch),
))
}
};
glyphs.push(glyph);
if glyph.origin.1 < off {
off = glyph.origin.1
}
}
for (idx, glyph) in glyphs.into_iter().enumerate() {
glyph.draw(buf, (x_off, -off), c);
x_off += distances[idx] as i32;
}
Ok((x_off as u32, self.size as u32))
}
pub fn draw_text_individual_colors(
&self,
buf: &mut BufferView,
color: &[Color],
s: &str,
) -> Result<(u32, u32), ::std::io::Error> {
let mut x_off = 0;
let mut off = 0;
let mut glyphs = Vec::with_capacity(s.len());
for ch in s.chars() {
let glyph = match self.glyphs.get(&ch) {
Some(glyph) => glyph,
None => {
return Err(::std::io::Error::new(
::std::io::ErrorKind::Other,
format!("glyph for {:} not in cache", ch),
))
}
};
glyphs.push(glyph);
if glyph.origin.1 < off {
off = glyph.origin.1
}
}
for (idx, glyph) in glyphs.into_iter().enumerate() {
glyph.draw(buf, (x_off, -off), color[idx]);
x_off += glyph.advance;
}
Ok((x_off as u32, self.size as u32))
}
pub fn auto_draw_text_individual_colors(
&mut self,
buf: &mut BufferView,
color: &[Color],
s: &str,
) -> Result<(u32, u32), ::std::io::Error> {
self.add_str_to_cache(s);
self.draw_text_individual_colors(buf, color, s)
}
}
pub fn draw_box(buf: &mut BufferView, c: Color, dim: (u32, u32)) -> Result<(), ::std::io::Error> {
let bounds = buf.get_bounds();
buf.put_line_raw((bounds.0, bounds.1), dim.0, c);
buf.put_line_raw((bounds.0, bounds.1 + dim.1 - 1), dim.0, c);
for y in bounds.1..dim.1 + bounds.1 {
buf.put_raw((bounds.0, y), c);
buf.put_raw((bounds.0 + dim.0 - 1, y), c);
}
Ok(())
}
pub fn draw_bar(
buf: &mut BufferView,
color: Color,
length: u32,
height: u32,
fill: f32,
) -> Result<(), ::std::io::Error> {
let mut fill_pos = ((length as f32) * fill) as u32;
if fill_pos > length {
fill_pos = length;
}
let bounds = buf.get_bounds();
for y in bounds.1..height + bounds.1 {
buf.put_line_raw((bounds.0, y), fill_pos, color);
}
Ok(())
}
+61
View File
@@ -0,0 +1,61 @@
use std::sync::{Arc, Mutex};
use calloop::ping::Ping;
use crate::keyboard::KeyEvent;
#[derive(Copy, Clone, Debug)]
pub enum PointerButton {
Left,
Right,
Middle,
ScrollVertical(f64),
ScrollHorizontal(f64),
}
#[derive(Debug)]
pub struct PointerEvent {
pub button: PointerButton,
pub pos: (u32, u32),
}
#[derive(Debug)]
pub enum Event {
NewMinute,
PowerUpdate,
LauncherUpdate,
AudioUpdate,
KeyEvent(KeyEvent),
PointerEvent(PointerEvent),
TokenUpdate(String),
FocusLost,
}
pub struct Events {
dirty: bool,
events: Vec<Event>,
ping: Ping,
}
impl Events {
pub fn new(ping: Ping) -> Arc<Mutex<Events>> {
Arc::new(Mutex::new(Events {
dirty: false,
events: Vec::new(),
ping,
}))
}
pub fn add_event(&mut self, ev: Event) {
self.events.push(ev);
if !self.dirty {
self.dirty = true;
self.ping.ping();
}
}
pub fn flush(&mut self) -> Vec<Event> {
self.dirty = false;
self.events.drain(..).collect()
}
}
+159
View File
@@ -0,0 +1,159 @@
//! Utility module for fonts
use crate::draw;
use rusttype::Font;
use std::{
cell::RefCell, collections::HashMap, fs::File, hash, io::Read, mem, path::Path, rc::Rc, thread,
};
/// FontRef is used to store Fonts on widgets.
pub type FontRef<'a> = &'a rusttype::Font<'a>;
#[cfg(feature = "fontconfig")]
pub(crate) fn find_font(name: &str) -> String {
use fontconfig::Fontconfig as FontConfig;
let fc = FontConfig::new().unwrap();
fc.find(name, None)
.unwrap()
.path
.to_str()
.unwrap()
.to_string()
}
#[cfg(not(feature = "fontconfig"))]
pub(crate) fn find_font(_name: &str) -> String {
panic!("fontconfig not enabled so font search not available");
}
/// FontLoader is a marker struct that is used to load files
pub(crate) struct FontLoader;
impl FontLoader {
/// Given a path, loads it as a Font, which can be rendered to the screen.
pub(crate) fn from_path<'a, P>(path: P) -> Option<Font<'a>>
where
P: AsRef<Path>,
{
let mut file = File::open(path).expect("Font file not found");
let mut data = match file.metadata() {
Ok(metadata) => Vec::with_capacity(metadata.len() as usize),
Err(_) => vec![],
};
file.read_to_end(&mut data).unwrap();
Font::try_from_vec(data)
}
}
#[derive(Debug, Copy, Clone)]
struct ComparableF32(f32);
impl ComparableF32 {
fn key(&self) -> u64 {
self.0.to_bits() as u64
}
}
impl hash::Hash for ComparableF32 {
fn hash<H>(&self, state: &mut H)
where
H: hash::Hasher,
{
self.key().hash(state)
}
}
impl PartialEq for ComparableF32 {
fn eq(&self, other: &ComparableF32) -> bool {
self.key() == other.key()
}
}
impl Eq for ComparableF32 {}
pub struct FontMap {
fonts: HashMap<(&'static str, ComparableF32), draw::Font<'static>>,
font_paths: HashMap<&'static str, String>,
required_fonts: HashMap<&'static str, (&'static str, Vec<(f32, &'static str)>)>,
}
impl FontMap {
pub fn new() -> FontMap {
FontMap {
fonts: HashMap::new(),
font_paths: HashMap::new(),
required_fonts: HashMap::new(),
}
}
pub fn queue_font(&mut self, font_name: &'static str, size: f32, preload: &'static str) {
match self.required_fonts.get_mut(font_name) {
Some(v) => v.1.push((size, preload)),
None => {
self.required_fonts
.insert(font_name, (font_name, vec![(size, preload)]));
}
}
}
pub fn add_font_path(&mut self, font_name: &'static str, font_path: String) {
self.font_paths.insert(font_name, font_path);
}
pub fn load_fonts(&mut self) {
for (font_name, v) in self.required_fonts.iter() {
let path = match self.font_paths.get(font_name) {
Some(res) => res,
_ => {
let s = find_font(font_name);
self.font_paths.insert(font_name, s);
self.font_paths.get(font_name).unwrap()
}
};
let fontref = Box::leak(Box::new(
FontLoader::from_path(path).expect("unable to load font"),
));
for (size, preload) in &v.1 {
if let Some(font) = self.fonts.get_mut(&(font_name, ComparableF32(*size))) {
font.add_str_to_cache(preload);
} else {
let mut font = draw::Font::new(fontref, *size);
font.add_str_to_cache(preload);
self.fonts.insert((font_name, ComparableF32(*size)), font);
}
}
}
}
pub fn get_font(&mut self, font_name: &'static str, size: f32) -> &mut draw::Font<'static> {
self.fonts
.get_mut(&(font_name, ComparableF32(size)))
.expect("no font at specified size")
}
}
pub enum MaybeFontMap {
Waiting(thread::JoinHandle<FontMap>),
Ready(Rc<RefCell<FontMap>>),
Invalid,
}
impl MaybeFontMap {
pub fn unwrap(&self) -> Rc<RefCell<FontMap>> {
match self {
MaybeFontMap::Ready(f) => f.clone(),
_ => panic!("fontmap not yet ready"),
}
}
pub fn resolve(&mut self) {
if matches!(self, MaybeFontMap::Waiting(_)) {
let s = mem::replace(self, MaybeFontMap::Invalid);
match s {
MaybeFontMap::Waiting(handle) => {
*self = MaybeFontMap::Ready(Rc::new(RefCell::new(handle.join().unwrap())));
}
_ => unreachable!(),
}
}
}
}
+160
View File
@@ -0,0 +1,160 @@
//! Utilities for keymap interpretation of keyboard input
//!
//! This module provides an implementation for `wl_keyboard`
//! objects using `libxkbcommon` to interpret the keyboard input
//! given the user keymap.
//!
//! The entry point of this module is the [`map_keyboard`](fn.map_keyboard.html)
//! function which, given a `wl_seat` and a callback, setup keymap interpretation
//! and key repetition for the `wl_keyboard` of this seat.
//!
//! Key repetition relies on an event source, that needs to be inserted in your
//! calloop event loop. Not doing so will prevent key repetition to work
//! (but the rest of the functionnality will not be affected).
use std::{
default::Default,
os::unix::io::{AsRawFd, OwnedFd},
};
use wayland_client::{protocol::wl_keyboard, WEnum};
use xkbcommon::xkb;
pub use xkbcommon::xkb::keysyms;
mod repeat;
mod state;
pub use self::repeat::{KeyRepeatSource, RepeatMessage};
use self::state::KbState;
pub use self::state::ModifiersState;
#[derive(Debug, Clone)]
pub struct KeyEvent {
pub rawkey: u32,
pub keysym: u32,
pub state: WEnum<wl_keyboard::KeyState>,
pub modifiers: ModifiersState,
pub utf8: Option<String>,
pub repeats: bool,
}
pub struct KeymapDescription {
fd: OwnedFd,
size: u32,
}
impl KeymapDescription {
fn new(fd: OwnedFd, size: u32) -> KeymapDescription {
KeymapDescription { fd: fd, size: size }
}
}
impl Clone for KeymapDescription {
fn clone(&self) -> Self {
KeymapDescription::new(self.fd.try_clone().expect("unable to clone fd"), self.size)
}
}
pub struct Keyboard {
state: Option<KbState>,
desc: Option<KeymapDescription>,
}
impl Keyboard {
pub fn new() -> Keyboard {
Keyboard {
state: None,
desc: None,
}
}
pub fn keymap(&mut self, format: WEnum<wl_keyboard::KeymapFormat>, fd: OwnedFd, size: u32) {
match format {
WEnum::Value(wl_keyboard::KeymapFormat::XkbV1) => {
self.desc = Some(KeymapDescription::new(fd, size));
}
WEnum::Value(wl_keyboard::KeymapFormat::NoKeymap) => {
// TODO: how to handle this (hopefully never occuring) case?
}
_ => unreachable!(),
}
}
pub fn resolve(&mut self) {
if self.state.is_some() {
return;
}
if let Some(desc) = self.desc.take() {
self.state = Some(
KbState::new_from_fd(desc.fd, desc.size as usize).expect("unable to load keymap"),
);
}
}
pub fn key(&mut self, key: u32, key_state: WEnum<wl_keyboard::KeyState>) -> KeyEvent {
if let Some(state) = &mut self.state {
let (sym, utf8, repeats) = {
// Get the values to generate a key event
let sym = state.get_one_sym_raw(key);
let utf8 = if key_state == WEnum::Value(wl_keyboard::KeyState::Pressed) {
match state.compose_feed(sym) {
Some(xkb::compose::FeedResult::Accepted) => {
if let Some(status) = state.compose_status() {
match status {
xkb::compose::Status::Composed => state.compose_get_utf8(),
xkb::compose::Status::Nothing => state.get_utf8_raw(key),
_ => None,
}
} else {
state.get_utf8_raw(key)
}
}
Some(_) => {
// XKB_COMPOSE_FEED_IGNORED
None
}
None => {
// XKB COMPOSE is not initialized
state.get_utf8_raw(key)
}
}
} else {
None
};
let repeats = state.key_repeats(xkb::Keycode::new(key + 8));
(sym, utf8, repeats)
};
KeyEvent {
rawkey: key,
keysym: sym,
state: key_state,
modifiers: state.mods_state(),
utf8,
repeats,
}
} else {
KeyEvent {
rawkey: key,
keysym: 0,
state: key_state,
modifiers: Default::default(),
utf8: None,
repeats: false,
}
}
}
pub fn modifiers(
&mut self,
mods_depressed: u32,
mods_latched: u32,
mods_locked: u32,
group: u32,
) {
if let Some(state) = &mut self.state {
state.update_modifiers(mods_depressed, mods_latched, mods_locked, group);
}
}
}
+173
View File
@@ -0,0 +1,173 @@
use std::time::Duration;
use calloop::{
channel::{self, Channel},
timer::{TimeoutAction, Timer},
EventSource, Poll, PostAction, Readiness, Token, TokenFactory,
};
use wayland_client::{protocol::wl_keyboard, WEnum};
use super::KeyEvent;
#[derive(Debug)]
pub enum RepeatMessage {
StopRepeat,
KeyEvent(KeyEvent),
RepeatInfo((u32, u32)),
}
#[derive(Debug)]
pub struct KeyRepeatSource {
channel: Channel<RepeatMessage>,
timer: Timer,
rate: Duration,
delay: Duration,
disabled: bool,
key: Option<KeyEvent>,
}
impl KeyRepeatSource {
pub fn new(ch: channel::Channel<RepeatMessage>) -> KeyRepeatSource {
KeyRepeatSource {
channel: ch,
timer: Timer::immediate(),
delay: Duration::ZERO,
rate: Duration::ZERO,
disabled: true,
key: None,
}
}
}
impl EventSource for KeyRepeatSource {
type Event = KeyEvent;
type Metadata = ();
type Ret = ();
type Error = calloop::Error;
fn process_events<F>(
&mut self,
readiness: Readiness,
token: Token,
mut callback: F,
) -> calloop::Result<PostAction>
where
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
let mut removed = false;
let timer = &mut self.timer;
let rate = &mut self.rate;
let delay = &mut self.delay;
let key = &mut self.key;
let disabled = &mut self.disabled;
let mut reregister = false;
let now = std::time::Instant::now();
// Check if the key repeat should stop
let channel_pa = self
.channel
.process_events(readiness, token, |event, _| match event {
channel::Event::Msg(message) => match message {
RepeatMessage::StopRepeat => {
key.take();
}
RepeatMessage::KeyEvent(event) => match event.state {
WEnum::Value(wl_keyboard::KeyState::Pressed) => {
key.replace(event);
reregister = true;
timer.set_deadline(now + *delay);
}
WEnum::Value(wl_keyboard::KeyState::Released) => match key {
Some(k) if k.keysym == event.keysym => {
key.take();
}
_ => (),
},
_ => (),
},
RepeatMessage::RepeatInfo((new_rate, new_delay)) => {
*rate = Duration::from_micros(1_000_000 / new_rate as u64);
*delay = Duration::from_millis(new_delay as u64);
*disabled = false;
if key.is_some() {
timer.set_deadline(now + *delay);
}
}
},
channel::Event::Closed => {
removed = true;
}
})
.map_err(|err| calloop::Error::OtherError(Box::new(err)))?;
// Keyboard was destroyed
if removed {
return Ok(PostAction::Remove);
}
// Re-register the timer to start it again
if reregister {
return Ok(PostAction::Reregister);
}
let timer_pa = timer.process_events(readiness, token, |deadline, _| {
if self.disabled || key.is_none() {
return TimeoutAction::Drop;
}
if deadline - now > std::time::Duration::from_millis(5) {
// We have not yet reached the deadline within our tolerance
return TimeoutAction::ToInstant(deadline);
}
// Invoke the event
callback(key.as_ref().unwrap().clone(), &mut ());
let mut next_deadline = deadline;
if now - deadline > *rate * 2 {
// We're way behind, let's just set a new time
println!("KeyRepeatSource::process_events: More than two repeat cycles behind, resetting");
next_deadline = now + *rate;
} else {
while next_deadline < now {
next_deadline += *rate;
}
}
TimeoutAction::ToInstant(next_deadline)
})?;
// Only disable or remove if both want to, otherwise continue or re-register
Ok(match (timer_pa, channel_pa) {
(PostAction::Disable, PostAction::Disable) => PostAction::Disable,
(PostAction::Remove, PostAction::Remove) => PostAction::Remove,
(PostAction::Reregister, _) | (_, PostAction::Reregister) => PostAction::Reregister,
_ => PostAction::Continue,
})
}
fn register(
&mut self,
poll: &mut Poll,
token_factory: &mut TokenFactory,
) -> calloop::Result<()> {
self.channel.register(poll, token_factory)?;
self.timer.register(poll, token_factory)
}
fn reregister(
&mut self,
poll: &mut Poll,
token_factory: &mut TokenFactory,
) -> calloop::Result<()> {
self.channel.reregister(poll, token_factory)?;
self.timer.reregister(poll, token_factory)
}
fn unregister(&mut self, poll: &mut Poll) -> calloop::Result<()> {
self.channel.unregister(poll)?;
self.timer.unregister(poll)
}
}
+163
View File
@@ -0,0 +1,163 @@
use std::{env, os::unix::io::OwnedFd};
use xkbcommon::xkb;
pub struct KbState {
xkb_context: xkb::Context,
xkb_keymap: xkb::Keymap,
xkb_state: xkb::State,
xkb_compose_table: Option<xkb::compose::Table>,
xkb_compose_state: Option<xkb::compose::State>,
mods_state: ModifiersState,
}
/// Represents the current state of the keyboard modifiers
///
/// Each field of this struct represents a modifier and is `true` if this modifier is active.
///
/// For some modifiers, this means that the key is currently pressed, others are toggled
/// (like caps lock).
#[derive(Copy, Clone, Debug, Default)]
pub struct ModifiersState {
/// The "control" key
pub ctrl: bool,
/// The "alt" key
pub alt: bool,
/// The "shift" key
pub shift: bool,
/// The "Caps lock" key
pub caps_lock: bool,
/// The "logo" key
///
/// Also known as the "windows" key on most keyboards
pub logo: bool,
/// The "Num lock" key
pub num_lock: bool,
}
impl ModifiersState {
fn new() -> ModifiersState {
ModifiersState::default()
}
fn update_with(&mut self, state: &xkb::State) {
self.ctrl = state.mod_name_is_active("Control", xkb::STATE_MODS_EFFECTIVE);
self.alt = state.mod_name_is_active("Mod1", xkb::STATE_MODS_EFFECTIVE);
self.shift = state.mod_name_is_active("Shift", xkb::STATE_MODS_EFFECTIVE);
self.caps_lock = state.mod_name_is_active("Lock", xkb::STATE_MODS_EFFECTIVE);
self.num_lock = state.mod_name_is_active("Mod2", xkb::STATE_MODS_EFFECTIVE);
self.logo = state.mod_name_is_active("Mod4", xkb::STATE_MODS_EFFECTIVE);
}
}
// Safety: No.
unsafe impl Send for KbState {}
impl KbState {
pub(crate) fn update_modifiers(
&mut self,
mods_depressed: u32,
mods_latched: u32,
mods_locked: u32,
group: u32,
) {
let mask =
self.xkb_state
.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
if (mask & xkb::STATE_MODS_EFFECTIVE) > 0 {
// effective value of mods have changed, we need to update our state
self.mods_state.update_with(&self.xkb_state);
}
}
pub(crate) fn get_one_sym_raw(&mut self, keycode: u32) -> u32 {
self.xkb_state
.key_get_one_sym(xkb::Keycode::new(keycode + 8))
.raw()
}
pub(crate) fn get_utf8_raw(&mut self, keycode: u32) -> Option<String> {
Some(self.xkb_state.key_get_utf8(xkb::Keycode::new(keycode + 8)))
}
pub(crate) fn compose_feed(&mut self, keysym: u32) -> Option<xkb::compose::FeedResult> {
match &mut self.xkb_compose_state {
Some(compose_state) => Some(compose_state.feed(xkb::Keysym::new(keysym))),
None => None,
}
}
pub(crate) fn compose_status(&mut self) -> Option<xkb::compose::Status> {
match &mut self.xkb_compose_state {
Some(compose_state) => Some(compose_state.status()),
None => None,
}
}
pub(crate) fn compose_get_utf8(&mut self) -> Option<String> {
match &mut self.xkb_compose_state {
Some(compose_state) => compose_state.utf8(),
None => None,
}
}
pub(crate) fn new_from_fd(fd: OwnedFd, size: usize) -> Result<KbState, std::io::Error> {
let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
let xkb_keymap = unsafe {
xkb::Keymap::new_from_fd(
&xkb_context,
fd,
size,
xkb::KEYMAP_FORMAT_TEXT_V1,
xkb::KEYMAP_COMPILE_NO_FLAGS,
)?
.unwrap()
};
let xkb_state = xkb::State::new(&xkb_keymap);
let mut me = KbState {
xkb_context,
xkb_keymap,
xkb_state,
xkb_compose_table: None,
xkb_compose_state: None,
mods_state: ModifiersState::new(),
};
me.init_compose();
Ok(me)
}
pub(crate) fn init_compose(&mut self) {
let locale = env::var_os("LC_ALL")
.and_then(|v| if v.is_empty() { None } else { Some(v) })
.or_else(|| env::var_os("LC_CTYPE"))
.and_then(|v| if v.is_empty() { None } else { Some(v) })
.or_else(|| env::var_os("LANG"))
.and_then(|v| if v.is_empty() { None } else { Some(v) })
.unwrap_or_else(|| "C".into());
let compose_table = match xkb::compose::Table::new_from_locale(
&self.xkb_context,
&locale,
xkb::compose::COMPILE_NO_FLAGS,
) {
Ok(t) => t,
Err(_) => return,
};
let compose_state = xkb::compose::State::new(&compose_table, xkb::compose::STATE_NO_FLAGS);
self.xkb_compose_table = Some(compose_table);
self.xkb_compose_state = Some(compose_state);
}
pub(crate) fn key_repeats(&mut self, keycode: xkb::Keycode) -> bool {
self.xkb_keymap.key_repeats(keycode)
}
#[inline]
pub(crate) fn mods_state(&self) -> ModifiersState {
self.mods_state
}
}
+353
View File
@@ -0,0 +1,353 @@
mod buffer;
mod color;
mod config;
mod draw;
mod event;
mod fonts;
mod keyboard;
mod state;
mod utils;
mod widgets;
use wayland_client::{Connection, QueueHandle, WaylandSource};
use calloop::{
timer::{TimeoutAction, Timer},
EventLoop,
};
use chrono::{Duration, Local, Timelike};
use buffer::BufferView;
use config::Config;
use event::{Event, Events};
use fonts::{FontMap, MaybeFontMap};
use keyboard::{KeyRepeatSource, RepeatMessage};
use state::State;
use utils::{
desktop::{load_desktop_files, write_desktop_cache},
xdg,
};
use widgets::{Geometry, Widget};
use std::{
env,
fs::File,
io::{BufRead, BufReader, Write},
os::unix::net::{UnixListener, UnixStream},
rc::Rc,
thread,
};
fn print_usage() {
println!(
"
usage: wldash [OPTIONS]
OPTIONS:
--config CONFIG_FILE use the specified config file
(~/.config/wldash/config.yml by default)
--write-default-config [v1|v2|toplevel] generate and write a new config file
(v2 by default)
--desktop-refresh refresh desktop file cache
"
);
}
fn main() {
let mut args = env::args();
// Skip program name
_ = args.next();
let mut config_file = format!("{}/wldash/config.yml", xdg::config_folder());
loop {
match args.next() {
Some(ref s) if s == "--config" => match args.next() {
Some(ref s) => config_file = s.clone(),
None => panic!("missing argument to --config"),
},
Some(ref s) if s == "--write-default-config" => {
let config = match args.next() {
Some(ref s) if s == "v1" => Config::generate_v1(),
Some(ref s) if s == "v2" => Config::generate_v2(false),
Some(ref s) if s == "toplevel" => Config::generate_v2(true),
None => Config::generate_v2(false),
Some(s) => panic!("unknown argument: {}", s),
};
match File::create(config_file) {
Ok(f) => serde_yaml::to_writer(f, &config).unwrap(),
Err(_) => panic!("uh"),
}
std::process::exit(0);
}
Some(ref s) if s == "--desktop-refresh" => {
let v = load_desktop_files();
write_desktop_cache(&v).unwrap();
std::process::exit(0);
}
Some(ref s) if s == "--help" => {
print_usage();
std::process::exit(0);
}
Some(_) => {
print_usage();
std::process::exit(1);
}
None => break,
}
}
let conn = Connection::connect_to_env().unwrap();
let event_queue = conn.new_event_queue();
let qhandle: QueueHandle<State> = event_queue.handle();
let display = conn.display();
display.get_registry(&qhandle, ());
display.sync(&qhandle, ());
let (ping_sender, ping_source) = calloop::ping::make_ping().unwrap();
let (keyrepeat_sender, keyrepeat_channel) = calloop::channel::channel::<RepeatMessage>();
let mut event_loop: EventLoop<State> =
EventLoop::try_new().expect("Failed to initialize the event loop!");
let handle = event_loop.handle();
handle
.insert_source(
WaylandSource::new(event_queue).expect("Could not create WaylandSource!"),
|_event, queue, mut state| queue.dispatch_pending(&mut state),
)
.expect("Failed to insert event source!");
handle
.insert_source(ping_source, |(), &mut (), state| {
let events = state.events.lock().unwrap().flush();
for widget in state.widgets.iter_mut() {
for event in events.iter() {
widget.event(event);
}
}
state.dirty = true;
})
.expect("Failed to insert ping source!");
let clock_source = Timer::from_duration(std::time::Duration::from_secs(1));
handle
.insert_source(clock_source, |_event, _metadata, state| {
let now = Local::now().naive_local();
let target = (now + Duration::seconds(60))
.with_second(0)
.unwrap()
.with_nanosecond(0)
.unwrap();
let d = target - now;
for widget in state.widgets.iter_mut() {
widget.event(&Event::NewMinute);
}
state.dirty = true;
// The timer event source requires us to return a TimeoutAction to
// specify if the timer should be rescheduled. In our case we just drop it.
TimeoutAction::ToDuration(d.to_std().unwrap())
})
.expect("Failed to insert event source!");
let keyrepeat_source = KeyRepeatSource::new(keyrepeat_channel);
handle
.insert_source(keyrepeat_source, |event, _metadata, state| {
let ev = Event::KeyEvent(event);
for widget in state.widgets.iter_mut() {
widget.event(&ev);
}
state.dirty = true;
})
.expect("Failed to insert keyrepeat source!");
let socket_path = match env::var("XDG_RUNTIME_DIR") {
Ok(dir) => dir + "/wldash",
Err(_) => "/tmp/wldash".to_string(),
};
let events = Events::new(ping_sender);
let mut fm = FontMap::new();
let config: Config = match File::open(config_file) {
Ok(f) => serde_yaml::from_reader(f).unwrap(),
Err(_) => panic!("configuration file missing"),
};
if let Some(true) = config.server {
if let Ok(mut socket) = UnixStream::connect(socket_path.clone()) {
socket.write_all(b"kill\n").unwrap();
return;
};
let _ = std::fs::remove_file(socket_path.clone());
let _ = thread::Builder::new()
.name("ipc_server".to_string())
.spawn(move || {
let listener = UnixListener::bind(socket_path.clone()).unwrap();
loop {
match listener.accept() {
Ok((stream, _)) => {
let _ = thread::Builder::new().name("ipc_client".to_string()).spawn(
move || {
let r = BufReader::new(stream);
for line in r.lines() {
match line {
Ok(ref cmd) if cmd == "kill" => {
std::process::exit(0);
}
_ => {}
}
}
},
);
}
_ => (),
}
}
});
}
if let Some(font_paths) = config.font_paths {
for (key, value) in font_paths.into_iter() {
fm.add_font_path(Box::leak(key.into_boxed_str()), value);
}
}
let layout = Rc::new(config.widget.construct_layout(&mut 0));
let mut widgets: Vec<Box<dyn Widget>> = Vec::new();
config
.widget
.construct_widgets(&mut widgets, &mut fm, &events);
let font_thread = thread::Builder::new()
.name("fontloader".to_string())
.spawn(move || {
fm.load_fonts();
fm
})
.unwrap();
let mut state = State::new(
config.mode,
config.background,
widgets,
layout,
MaybeFontMap::Waiting(font_thread),
events,
keyrepeat_sender,
);
// Initial setup
//
while state.running && !state.ready {
event_loop
.dispatch(None, &mut state)
.expect("Could not dispatch event loop");
}
state.check_registry(&qhandle);
while state.running {
event_loop
.dispatch(None, &mut state)
.expect("Could not dispatch event loop");
if !state.configured || !state.dirty || !state.ready {
continue;
}
let mut force = false;
if state.bufmgr.buffers.len() == 0 {
state.add_buffer(&qhandle);
force = true;
}
let mut bufcnt = state.bufmgr.buffers.len();
let buf = match state.bufmgr.next_buffer() {
Some(b) => b,
None => {
if state.bufmgr.buffers.len() >= 3 {
continue;
}
state.add_buffer(&qhandle);
bufcnt = state.bufmgr.buffers.len();
match state.bufmgr.next_buffer() {
Some(b) => b,
None => {
continue;
}
}
}
};
if buf.last_damage.len() == 0 {
for _ in 0..state.widgets.len() {
buf.last_damage.push(Geometry::new());
}
}
state.dirty = false;
buf.acquire();
let mut bufview = BufferView::new(
&mut buf.mmap,
(state.dimensions.0 as u32, state.dimensions.1 as u32),
);
let surface = state.main_surface.wl_surface.as_ref().unwrap().clone();
if force {
for (idx, widget) in state.widgets.iter_mut().enumerate() {
if force || widget.get_dirty() {
let geo = widget.geometry();
let mut subview = bufview.subgeometry(geo);
buf.last_damage[idx] =
widget.draw(&mut state.fonts.unwrap().borrow_mut(), &mut subview);
}
}
surface.damage_buffer(0, 0, 0x7FFFFFFF, 0x7FFFFFFF);
} else {
let mut drew = false;
for (idx, widget) in state.widgets.iter_mut().enumerate() {
if bufcnt > 1 || widget.get_dirty() {
drew = true;
let old_damage = buf.last_damage[idx];
bufview.subgeometry(old_damage).clear();
let geo = widget.geometry();
let mut subview = bufview.subgeometry(geo);
let new_damage =
widget.draw(&mut state.fonts.unwrap().borrow_mut(), &mut subview);
let combined_damage = new_damage.expand(old_damage);
buf.last_damage[idx] = new_damage;
surface.damage_buffer(
combined_damage.x as i32,
combined_damage.y as i32,
combined_damage.width as i32,
combined_damage.height as i32,
);
}
}
if !drew {
buf.release();
conn.flush().unwrap();
continue;
}
}
state.ready = false;
surface.attach(Some(&buf.buffer), 0, 0);
surface.frame(&qhandle, ());
surface.commit();
conn.flush().unwrap();
// Now is a good as time as any to load the keymap
state.keyboard.resolve();
}
}
+865
View File
@@ -0,0 +1,865 @@
use std::{
cmp::max,
default::Default,
env,
rc::Rc,
sync::{Arc, Mutex},
};
use wayland_client::{
protocol::{
wl_buffer, wl_callback, wl_compositor, wl_keyboard, wl_pointer, wl_registry, wl_seat,
wl_shm, wl_shm_pool, wl_subcompositor, wl_subsurface, wl_surface,
},
Connection, Dispatch, QueueHandle, WEnum,
};
use wayland_protocols::{
wp::{
single_pixel_buffer::v1::client::wp_single_pixel_buffer_manager_v1,
viewporter::client::{wp_viewport, wp_viewporter},
},
xdg::{
activation::v1::client::{xdg_activation_token_v1, xdg_activation_v1},
shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base},
},
};
use wayland_protocols_wlr::layer_shell::v1::client::{zwlr_layer_shell_v1, zwlr_layer_surface_v1};
use crate::{
buffer::BufferManager,
config::OperationMode,
event::{Event, Events, PointerButton, PointerEvent},
fonts::{FontMap, MaybeFontMap},
keyboard::{Keyboard, RepeatMessage},
widgets::{Geometry, Layout, Widget, WidgetUpdater},
};
use calloop::channel::Sender;
#[derive(Default)]
pub struct MainSurface {
pub wl_surface: Option<wl_surface::WlSurface>,
xdg_surface: Option<(xdg_surface::XdgSurface, xdg_toplevel::XdgToplevel)>,
layer_surface: Option<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1>,
}
#[derive(Default)]
pub struct BackgroundSurface {
wl_surface: Option<wl_surface::WlSurface>,
subsurface: Option<wl_subsurface::WlSubsurface>,
viewport: Option<wp_viewport::WpViewport>,
}
#[derive(Default)]
pub struct Protocols {
wl_compositor: Option<wl_compositor::WlCompositor>,
wl_subcompositor: Option<wl_subcompositor::WlSubcompositor>,
wl_shm: Option<wl_shm::WlShm>,
xdg_wm_base: Option<xdg_wm_base::XdgWmBase>,
xdg_activation: Option<xdg_activation_v1::XdgActivationV1>,
zwlr_layer_shell: Option<zwlr_layer_shell_v1::ZwlrLayerShellV1>,
viewporter: Option<wp_viewporter::WpViewporter>,
wp_single_pixel_buffer_manager:
Option<wp_single_pixel_buffer_manager_v1::WpSinglePixelBufferManagerV1>,
}
pub struct State {
mode: OperationMode,
background: Option<u32>,
pub main_surface: MainSurface,
pub bg_surface: BackgroundSurface,
pub protocols: Protocols,
pub running: bool,
pub ready: bool,
pub dirty: bool,
activated: bool,
pub configured: bool,
pub dimensions: (i32, i32),
pub bufmgr: BufferManager,
pub widgets: Vec<Box<dyn Widget>>,
pub keyboard: Keyboard,
pub keyrepeat_sender: Sender<RepeatMessage>,
pointer: Option<(f64, f64)>,
pub fonts: MaybeFontMap,
pub events: Arc<Mutex<Events>>,
layout: Rc<Box<dyn Layout>>,
}
impl State {
pub fn new(
mode: OperationMode,
background: Option<u32>,
widgets: Vec<Box<dyn Widget>>,
layout: Rc<Box<dyn Layout>>,
fonts: MaybeFontMap,
events: Arc<Mutex<Events>>,
keyrepeat_sender: Sender<RepeatMessage>,
) -> State {
State {
protocols: Default::default(),
bg_surface: Default::default(),
main_surface: Default::default(),
running: true,
dirty: true,
activated: false,
configured: false,
dimensions: (320, 240),
bufmgr: BufferManager::new(),
keyboard: Keyboard::new(),
pointer: None,
keyrepeat_sender,
mode,
background,
widgets,
fonts,
events,
layout,
ready: false,
}
}
pub fn add_buffer(&mut self, qh: &QueueHandle<Self>) {
self.bufmgr.add_buffer(
self.protocols.wl_shm.as_ref().expect("missing wl_shm"),
self.dimensions,
qh,
);
}
pub fn activate(&mut self, qh: &QueueHandle<Self>) {
let key = match env::var("XDG_ACTIVATION_TOKEN") {
Ok(token) => token,
Err(_) => return,
};
match (
&self.main_surface.wl_surface,
&self.protocols.xdg_activation,
) {
(Some(surface), Some(activation)) => {
activation.activate(key, surface);
let activation_token = activation.get_activation_token(qh, ());
activation_token.commit();
env::remove_var("XDG_ACTIVATION_TOKEN");
}
_ => (),
}
}
}
impl WidgetUpdater for State {
fn geometry_update(
&mut self,
idx: usize,
fonts: &mut FontMap,
geometry: &Geometry,
) -> Geometry {
self.widgets[idx].geometry_update(fonts, geometry)
}
fn minimum_size(&mut self, idx: usize, fonts: &mut FontMap) -> Geometry {
self.widgets[idx].minimum_size(fonts)
}
}
impl State {
pub fn check_registry(&mut self, qh: &QueueHandle<Self>) {
let wl_compositor = self
.protocols
.wl_compositor
.as_ref()
.expect("wl_compositor missing");
let main_surface = wl_compositor.create_surface(qh, ());
let bg_surface = wl_compositor.create_surface(qh, ());
self.main_surface.wl_surface = Some(main_surface.clone());
self.bg_surface.wl_surface = Some(bg_surface.clone());
self.activate(qh);
let wl_subcompositor = self
.protocols
.wl_subcompositor
.as_ref()
.expect("wl_subcompositor missing");
let subsurface = wl_subcompositor.get_subsurface(&bg_surface, &main_surface, qh, ());
subsurface.place_below(&main_surface);
self.bg_surface.subsurface = Some(subsurface.clone());
match self.mode {
OperationMode::XdgToplevel => {
self.fonts.resolve();
let xdg_wm_base = self
.protocols
.xdg_wm_base
.as_ref()
.expect("xdg_wm_base missing");
let xdg_surface = xdg_wm_base.get_xdg_surface(&main_surface, qh, ());
let toplevel = xdg_surface.get_toplevel(qh, ());
toplevel.set_title("wldash".into());
main_surface.commit();
self.main_surface.xdg_surface = Some((xdg_surface, toplevel));
}
OperationMode::LayerSurface(size) => {
self.fonts.resolve();
let layer_shell = self
.protocols
.zwlr_layer_shell
.as_ref()
.expect("zwlr_layer_shell_v1 missing");
let layer_surface = layer_shell.get_layer_surface(
&main_surface,
None,
zwlr_layer_shell_v1::Layer::Overlay,
"launcher".to_string(),
qh,
(),
);
let fonts = self.fonts.unwrap();
let layout = self.layout.clone();
let min_size = layout.minimum_size(&mut fonts.borrow_mut(), self);
layer_surface.set_keyboard_interactivity(
zwlr_layer_surface_v1::KeyboardInteractivity::Exclusive,
);
layer_surface.set_anchor(
zwlr_layer_surface_v1::Anchor::Left
.union(zwlr_layer_surface_v1::Anchor::Bottom)
.union(zwlr_layer_surface_v1::Anchor::Right)
.union(zwlr_layer_surface_v1::Anchor::Top),
);
layer_surface.set_size(max(size.0, min_size.width), max(size.1, min_size.height));
main_surface.commit();
self.main_surface.layer_surface = Some(layer_surface);
}
}
let viewporter = self
.protocols
.viewporter
.as_ref()
.expect("wp_viewporter missing");
let viewport = viewporter.get_viewport(&bg_surface, qh, ());
self.bg_surface.viewport = Some(viewport);
if let Some(background) = self.background {
let wp_single_pixel_buffer_manager = self
.protocols
.wp_single_pixel_buffer_manager
.as_ref()
.expect("wp_single_pixel_buffer_manager_v1 missing");
let buffer =
wp_single_pixel_buffer_manager.create_u32_rgba_buffer(0, 0, 0, background, qh, ());
bg_surface.attach(Some(&buffer), 0, 0);
bg_surface.damage_buffer(0, 0, 1, 1);
}
}
}
impl Dispatch<wl_registry::WlRegistry, ()> for State {
fn event(
state: &mut Self,
registry: &wl_registry::WlRegistry,
event: wl_registry::Event,
_: &(),
_: &Connection,
qh: &QueueHandle<Self>,
) {
if let wl_registry::Event::Global {
name, interface, ..
} = event
{
match &interface[..] {
"wl_compositor" => {
state.protocols.wl_compositor =
Some(registry.bind::<wl_compositor::WlCompositor, _, _>(name, 5, qh, ()));
}
"wl_subcompositor" => {
state.protocols.wl_subcompositor = Some(
registry.bind::<wl_subcompositor::WlSubcompositor, _, _>(name, 1, qh, ()),
);
}
"wl_shm" => {
state.protocols.wl_shm =
Some(registry.bind::<wl_shm::WlShm, _, _>(name, 1, qh, ()));
}
"wl_seat" => {
registry.bind::<wl_seat::WlSeat, _, _>(name, 8, qh, ());
}
"xdg_wm_base" => {
if let OperationMode::XdgToplevel = state.mode {
state.protocols.xdg_wm_base =
Some(registry.bind::<xdg_wm_base::XdgWmBase, _, _>(name, 2, qh, ()));
}
}
"xdg_activation_v1" => {
state.protocols.xdg_activation = Some(
registry.bind::<xdg_activation_v1::XdgActivationV1, _, _>(name, 1, qh, ()),
);
}
"zwlr_layer_shell_v1" => {
if let OperationMode::LayerSurface(_) = state.mode {
state.protocols.zwlr_layer_shell = Some(
registry.bind::<zwlr_layer_shell_v1::ZwlrLayerShellV1, _, _>(
name,
4,
qh,
(),
),
);
}
}
"wp_viewporter" => {
state.protocols.viewporter =
Some(registry.bind::<wp_viewporter::WpViewporter, _, _>(name, 1, qh, ()));
}
"wp_single_pixel_buffer_manager_v1" => {
state.protocols.wp_single_pixel_buffer_manager = Some(registry.bind::<wp_single_pixel_buffer_manager_v1::WpSinglePixelBufferManagerV1, _, _>(name, 1, qh, ()));
}
_ => {}
}
}
}
}
impl Dispatch<wl_callback::WlCallback, ()> for State {
fn event(
state: &mut Self,
_: &wl_callback::WlCallback,
event: wl_callback::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
wl_callback::Event::Done { callback_data: _ } => state.ready = true,
_ => {}
}
}
}
impl Dispatch<wl_compositor::WlCompositor, ()> for State {
fn event(
_: &mut Self,
_: &wl_compositor::WlCompositor,
_: wl_compositor::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<wl_subcompositor::WlSubcompositor, ()> for State {
fn event(
_: &mut Self,
_: &wl_subcompositor::WlSubcompositor,
_: wl_subcompositor::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<wl_surface::WlSurface, ()> for State {
fn event(
_: &mut Self,
_: &wl_surface::WlSurface,
_: wl_surface::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<wl_subsurface::WlSubsurface, ()> for State {
fn event(
_: &mut Self,
_: &wl_subsurface::WlSubsurface,
_: wl_subsurface::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<wl_shm::WlShm, ()> for State {
fn event(
_: &mut Self,
_: &wl_shm::WlShm,
_: wl_shm::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<wl_shm_pool::WlShmPool, ()> for State {
fn event(
_: &mut Self,
_: &wl_shm_pool::WlShmPool,
_: wl_shm_pool::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<wl_buffer::WlBuffer, ()> for State {
fn event(
state: &mut Self,
buffer: &wl_buffer::WlBuffer,
_: wl_buffer::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
for buf in state.bufmgr.buffers.iter_mut() {
if &buf.buffer == buffer {
buf.release();
}
}
}
}
impl Dispatch<zwlr_layer_shell_v1::ZwlrLayerShellV1, ()> for State {
fn event(
_: &mut Self,
_: &zwlr_layer_shell_v1::ZwlrLayerShellV1,
_: zwlr_layer_shell_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, ()> for State {
fn event(
state: &mut Self,
layer_surface: &zwlr_layer_surface_v1::ZwlrLayerSurfaceV1,
event: zwlr_layer_surface_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
zwlr_layer_surface_v1::Event::Configure {
serial,
mut width,
mut height,
} => {
if (width, height) == (0, 0) {
if state.configured {
return;
}
(width, height) = (640, 480);
}
layer_surface.ack_configure(serial);
state.configured = true;
state.dirty = true;
let dim = (width as i32, height as i32);
if state.configured && state.dimensions == dim {
return;
}
state.bufmgr.clear_buffers();
state.dimensions = dim;
let fonts = state.fonts.unwrap();
let layout = state.layout.clone();
layout.geometry_update(
&mut fonts.borrow_mut(),
&Geometry {
x: 0,
y: 0,
width: width as u32,
height: height as u32,
},
state,
);
let surface = state
.bg_surface
.wl_surface
.as_ref()
.expect("bg surface was not ready");
let viewport = state
.bg_surface
.viewport
.as_ref()
.expect("bg viewport was not ready");
viewport.set_destination(dim.0, dim.1);
surface.commit();
}
zwlr_layer_surface_v1::Event::Closed => {
std::process::exit(0);
}
_ => (),
}
}
}
impl Dispatch<xdg_wm_base::XdgWmBase, ()> for State {
fn event(
_: &mut Self,
wm_base: &xdg_wm_base::XdgWmBase,
event: xdg_wm_base::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
if let xdg_wm_base::Event::Ping { serial } = event {
wm_base.pong(serial);
}
}
}
impl Dispatch<xdg_surface::XdgSurface, ()> for State {
fn event(
state: &mut Self,
xdg_surface: &xdg_surface::XdgSurface,
event: xdg_surface::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
if let xdg_surface::Event::Configure { serial, .. } = event {
xdg_surface.ack_configure(serial);
state.configured = true;
state.dirty = true;
}
}
}
impl Dispatch<xdg_toplevel::XdgToplevel, ()> for State {
fn event(
state: &mut Self,
_: &xdg_toplevel::XdgToplevel,
event: xdg_toplevel::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
xdg_toplevel::Event::Configure {
mut width,
mut height,
states,
..
} => {
if (width, height) == (0, 0) {
if state.configured {
return;
}
(width, height) = (1280, 720);
}
let activated = states
.iter()
.find(|&st| *st as u32 == xdg_toplevel::State::Activated as u32)
.is_some();
if activated {
state.activated = true;
} else if state.activated && !activated {
let ev = Event::FocusLost;
for widget in state.widgets.iter_mut() {
widget.event(&ev);
}
}
if !state.configured || state.dimensions != (width, height) {
let surface = state
.bg_surface
.wl_surface
.as_ref()
.expect("bg surface was not ready");
let viewport = state
.bg_surface
.viewport
.as_ref()
.expect("bg viewportw as not ready");
viewport.set_destination(width, height);
surface.commit();
state.bufmgr.clear_buffers();
state.dimensions = (width, height);
state.fonts.resolve();
let fonts = state.fonts.unwrap();
let layout = state.layout.clone();
layout.geometry_update(
&mut fonts.borrow_mut(),
&Geometry {
x: 0,
y: 0,
width: width as u32,
height: height as u32,
},
state,
);
}
}
xdg_toplevel::Event::Close => {
state.running = false;
}
_ => (),
}
}
}
impl Dispatch<wl_seat::WlSeat, ()> for State {
fn event(
_: &mut Self,
seat: &wl_seat::WlSeat,
event: wl_seat::Event,
_: &(),
_: &Connection,
qh: &QueueHandle<Self>,
) {
if let wl_seat::Event::Capabilities {
capabilities: WEnum::Value(capabilities),
} = event
{
if capabilities.contains(wl_seat::Capability::Keyboard) {
seat.get_keyboard(qh, ());
}
if capabilities.contains(wl_seat::Capability::Pointer) {
seat.get_pointer(qh, ());
}
}
}
}
impl Dispatch<wl_keyboard::WlKeyboard, ()> for State {
fn event(
state: &mut Self,
_: &wl_keyboard::WlKeyboard,
event: wl_keyboard::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
wl_keyboard::Event::Leave { .. } => {
state
.keyrepeat_sender
.send(RepeatMessage::StopRepeat)
.unwrap();
}
wl_keyboard::Event::Key {
key,
state: kbstate,
..
} => {
if key == 1 {
state.running = false;
return;
}
state.keyboard.resolve();
let k = state.keyboard.key(key, kbstate);
let repeats = k.repeats;
let ev = Event::KeyEvent(k);
for widget in state.widgets.iter_mut() {
widget.event(&ev);
}
if repeats {
if let Event::KeyEvent(k) = ev {
state
.keyrepeat_sender
.send(RepeatMessage::KeyEvent(k))
.unwrap();
}
}
state.dirty = true;
}
wl_keyboard::Event::Modifiers {
mods_depressed,
mods_latched,
mods_locked,
group,
..
} => {
state
.keyboard
.modifiers(mods_depressed, mods_latched, mods_locked, group);
}
wl_keyboard::Event::Keymap { format, fd, size } => {
// TODO: Keymap loading blocks xdg configure, consider delaying
state.keyboard.keymap(format, fd, size);
}
wl_keyboard::Event::RepeatInfo { rate, delay } => {
state
.keyrepeat_sender
.send(RepeatMessage::RepeatInfo((rate as u32, delay as u32)))
.unwrap();
}
_ => (),
}
}
}
// TODO: Move to dedicated pointer module
const BTN_LEFT: u32 = 0x110;
const BTN_RIGHT: u32 = 0x111;
const BTN_MIDDLE: u32 = 0x112;
impl Dispatch<wl_pointer::WlPointer, ()> for State {
fn event(
state: &mut Self,
_: &wl_pointer::WlPointer,
event: wl_pointer::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
wl_pointer::Event::Enter {
surface_x,
surface_y,
..
} => {
state.pointer = Some((surface_x, surface_y));
}
wl_pointer::Event::Motion {
surface_x,
surface_y,
..
} => {
state.pointer = Some((surface_x, surface_y));
}
wl_pointer::Event::Leave { .. } => state.pointer = None,
wl_pointer::Event::Axis { axis, value, .. } => match state.pointer {
Some((x, y)) => {
let axis = match axis {
WEnum::Value(wl_pointer::Axis::VerticalScroll) => {
PointerButton::ScrollVertical(value)
}
WEnum::Value(wl_pointer::Axis::HorizontalScroll) => {
PointerButton::ScrollHorizontal(value)
}
_ => return,
};
let pos = (x as u32, y as u32);
for widget in state.widgets.iter_mut() {
let geo = widget.geometry();
if geo.contains(pos) {
let pos = (pos.0 - geo.x, pos.1 - geo.y);
let ev = Event::PointerEvent(PointerEvent {
button: axis,
pos: pos,
});
widget.event(&ev);
state.dirty = true;
break;
}
}
}
_ => (),
},
wl_pointer::Event::Button {
button,
state: button_state,
..
} => match (button, button_state, state.pointer) {
(button, WEnum::Value(wl_pointer::ButtonState::Pressed), Some((x, y))) => {
let button = match button {
BTN_LEFT => PointerButton::Left,
BTN_RIGHT => PointerButton::Right,
BTN_MIDDLE => PointerButton::Middle,
_ => return,
};
let pos = (x as u32, y as u32);
for widget in state.widgets.iter_mut() {
let geo = widget.geometry();
if geo.contains(pos) {
let pos = (pos.0 - geo.x, pos.1 - geo.y);
let ev = Event::PointerEvent(PointerEvent {
button: button,
pos: pos,
});
widget.event(&ev);
state.dirty = true;
break;
}
}
}
_ => (),
},
_ => (),
}
}
}
impl Dispatch<wp_single_pixel_buffer_manager_v1::WpSinglePixelBufferManagerV1, ()> for State {
fn event(
_: &mut Self,
_: &wp_single_pixel_buffer_manager_v1::WpSinglePixelBufferManagerV1,
_: wp_single_pixel_buffer_manager_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<wp_viewporter::WpViewporter, ()> for State {
fn event(
_: &mut Self,
_: &wp_viewporter::WpViewporter,
_: wp_viewporter::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<wp_viewport::WpViewport, ()> for State {
fn event(
_: &mut Self,
_: &wp_viewport::WpViewport,
_: wp_viewport::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<xdg_activation_v1::XdgActivationV1, ()> for State {
fn event(
_: &mut Self,
_: &xdg_activation_v1::XdgActivationV1,
_: xdg_activation_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for State {
fn event(
state: &mut Self,
_: &xdg_activation_token_v1::XdgActivationTokenV1,
event: xdg_activation_token_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
match event {
xdg_activation_token_v1::Event::Done { token } => {
let ev = Event::TokenUpdate(token);
for widget in state.widgets.iter_mut() {
widget.event(&ev);
}
}
_ => (),
}
}
}
+117
View File
@@ -0,0 +1,117 @@
use std::{
cmp::Ordering,
collections::HashSet,
error::Error,
fs::{read_to_string, File},
io::{Error as io_error, ErrorKind},
};
use serde::{self, Deserialize, Serialize};
use simd_json;
use walkdir::WalkDir;
use crate::utils::{inish, xdg};
#[derive(Serialize, Deserialize, Clone, Debug, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub struct Desktop {
pub entry_type: String,
pub name: String,
pub no_display: bool,
pub hidden: bool,
pub exec: Option<String>,
pub url: Option<String>,
pub term: bool,
pub keywords: Vec<String>,
}
impl Desktop {
fn parse(f: &str) -> Result<Desktop, Box<dyn Error>> {
let s = read_to_string(f)?;
let config = inish::parse(&s)?;
match config.get("Desktop Entry") {
Some(section) => Ok(Desktop {
entry_type: section.get("Type").unwrap_or(&"").to_string(),
name: section.get("Name").unwrap_or(&"").to_string(),
term: section.get("Terminal").unwrap_or(&"") == &"true",
no_display: section.get("NoDisplay").unwrap_or(&"") == &"true",
hidden: section.get("Hidden").unwrap_or(&"") == &"true",
exec: section.get("Exec").map(|x| x.to_string()),
url: section.get("URL").map(|x| x.to_string()),
keywords: section
.get("Keywords")
.map(|x| {
x.split(';')
.map(|y| y.trim().to_string())
.filter(|z| z != "")
.collect()
})
.unwrap_or_else(|| vec![]),
}),
None => Err(Box::new(io_error::new(
ErrorKind::NotFound,
"no desktop entry in file",
))),
}
}
}
impl Ord for Desktop {
fn cmp(&self, other: &Self) -> Ordering {
self.name.cmp(&other.name)
}
}
impl PartialOrd for Desktop {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Desktop {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
pub fn load_desktop_cache() -> Result<Vec<Desktop>, Box<dyn Error>> {
match File::open(format!("{}/wldash/desktop.json", xdg::cache_folder())) {
Ok(f) => simd_json::from_reader(f).map_err(|e| e.into()),
Err(e) => Err(e.into()),
}
}
pub fn write_desktop_cache(v: &Vec<Desktop>) -> Result<(), Box<dyn Error>> {
match File::create(format!("{}/wldash/desktop.json", xdg::cache_folder())) {
Ok(f) => simd_json::to_writer(f, v).map_err(|e| e.into()),
Err(e) => Err(e.into()),
}
}
pub fn load_desktop_files() -> Vec<Desktop> {
let dirs = xdg::data_folders();
let mut desktop: Vec<Desktop> = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
for dir in dirs {
for entry in WalkDir::new(format!("{}/applications", dir)) {
if let Ok(entry) = entry {
if let Ok(d) = Desktop::parse(entry.path().to_str().unwrap()) {
if d.hidden
|| d.no_display
|| (d.entry_type != "Application" && d.entry_type != "Link")
{
continue;
}
if !seen.contains(&d.name) {
seen.insert(d.name.to_string());
desktop.push(d);
}
}
}
}
}
desktop
}
+134
View File
@@ -0,0 +1,134 @@
use std::{collections::HashMap, error::Error};
fn parse_field<'a>(line: &'a str) -> Result<(&'a str, &'a str), Box<dyn Error>> {
let split = match line.find('=') {
Some(v) => v,
None => return Err("expected equals sign on line, but found none".into()),
};
let (key, value) = line.split_at(split);
let (key, value) = (key.trim(), value.trim_matches('=').trim());
Ok((key, value))
}
type InishSection<'a> = HashMap<&'a str, &'a str>;
type Inish<'a> = HashMap<&'a str, InishSection<'a>>;
pub fn parse<'a>(s: &'a str) -> Result<Inish<'a>, Box<dyn Error>> {
let mut sections: Inish<'a> = HashMap::new();
let mut current_section = HashMap::new();
let mut current_section_name = "";
for line in s.lines() {
let line = line.trim();
let mut chars = line.chars();
let start = chars.next();
let end = chars.last();
match (start, end) {
(Some('#'), _) => continue,
(Some('['), Some(']')) => {
sections.insert(current_section_name, current_section);
current_section = HashMap::new();
let len = line.bytes().count();
current_section_name = &line[1..len - 1].trim();
}
(Some('['), v) => {
return Err(format!(
"expected Some(']') to terminate section name, but got {:?}",
v
)
.into());
}
_ if line.is_empty() => continue,
_ => {
let (key, value) = parse_field(line)?;
current_section.insert(key, value);
}
}
}
sections.insert(current_section_name, current_section);
Ok(sections)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sections() {
let config = parse(
"
[section_a]
[section_b]
",
)
.expect("config didn't parse");
if !config.contains_key("section_a") {
panic!("named section did not exist");
}
if !config.contains_key("section_b") {
panic!("named section did not exist");
}
if !config.contains_key("") {
panic!("unnamed section did not exist");
}
}
#[test]
fn fields() {
let config = parse(
"
field_outside = 'hello'
[section_a]
field_a = 1234
",
)
.expect("config didn't parse");
let section_a = match config.get("section_a") {
Some(v) => v,
None => panic!("named section did not exist"),
};
assert_eq!(section_a.get("field_a"), Some(&"1234"));
let section_unnamed = match config.get("") {
Some(v) => v,
None => panic!("unnamed section did not exist"),
};
assert_eq!(section_unnamed.get("field_outside"), Some(&"'hello'"));
}
#[test]
fn whitespaces() {
let config = parse(
"
field outside = 'hello'
[ section a ]
field a = 1234 ",
)
.expect("config didn't parse");
let section_a = match config.get("section a") {
Some(v) => v,
None => panic!("named section did not exist"),
};
assert_eq!(section_a.get("field a"), Some(&"1234"));
let section_unnamed = match config.get("") {
Some(v) => v,
None => panic!("unnamed section did not exist"),
};
assert_eq!(section_unnamed.get("field outside"), Some(&"'hello'"));
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod desktop;
mod inish;
pub mod xdg;
+40
View File
@@ -0,0 +1,40 @@
use std::env;
pub fn cache_folder() -> String {
match env::var_os("XDG_CACHE_HOME") {
Some(s) => s.into_string().unwrap(),
None => {
let home = env::var_os("HOME").unwrap().into_string().unwrap();
format!("{}/.cache", home)
}
}
}
pub fn config_folder() -> String {
match env::var_os("XDG_CONFIG_HOME") {
Some(s) => s.into_string().unwrap(),
None => {
let home = env::var_os("HOME").unwrap().into_string().unwrap();
format!("{}/.config", home)
}
}
}
pub fn data_folders() -> Vec<String> {
let xdg_data_home = match env::var_os("XDG_DATA_HOME") {
Some(s) => s.into_string().unwrap(),
None => {
let home = env::var_os("HOME").unwrap().into_string().unwrap();
format!("{}/.local/share", home)
}
};
let xdg_data_dirs = match env::var_os("XDG_DATA_DIRS") {
Some(s) => s.into_string().unwrap(),
None => "/usr/local/share:/usr/share".to_string(),
};
// Eww.
std::iter::once(xdg_data_home.to_string())
.chain(xdg_data_dirs.split(':').map(|x| x.to_string()))
.collect()
}
+112
View File
@@ -0,0 +1,112 @@
use std::{
thread,
sync::{Arc, Mutex},
};
use crate::{
color::Color,
fonts::FontMap,
event::{Event, Events, PointerButton},
widgets::bar_widget::{BarWidget, BarWidgetImpl},
};
use alsa::mixer::{
Mixer, Selem, SelemChannelId, SelemId,
};
#[inline]
fn alsa_volume_to_f32(volume: i64, min: i64, max: i64) -> f32 {
(volume - min) as f32 / (max - min) as f32
}
#[inline]
fn f32_to_alsa_volume(volume: f32, min: i64, max: i64) -> i64 {
min + ((max - min) as f32 * volume) as i64
}
fn get_master_volume(selem: &mut Selem) -> f32 {
let (min, max) = selem.get_playback_volume_range();
selem
.get_playback_volume(SelemChannelId::mono())
.map(|volume| alsa_volume_to_f32(volume, min, max))
.unwrap()
}
fn get_mute(selem: &mut Selem) -> bool {
let res = selem.get_playback_switch(SelemChannelId::FrontLeft);
false
}
fn set_master_volume(selem: &mut Selem, volume: f32) {
let (min, max) = selem.get_playback_volume_range();
let volume = f32_to_alsa_volume(volume, min, max);
selem.set_playback_volume_all(volume).unwrap();
}
fn start_monitor(inner: Arc<Mutex<Inner>>) {
thread::Builder::new()
.name("audiomon".to_string())
.spawn(move || {
let mixer = Mixer::new("default", true).unwrap();
let id = SelemId::new("Master", 0);
let mut selem = mixer.find_selem(&id).unwrap();
let mut inner = inner.lock().unwrap();
inner.volume = get_master_volume(&mut selem);
inner.mute = get_mute(&mut selem);
})
.unwrap();
}
struct Inner {
volume: f32,
mute: bool,
}
pub struct AlsaAudio {
inner: Arc<Mutex<Inner>>,
}
impl AlsaAudio {
pub fn new(fm: &mut FontMap, font: &'static str, size: f32) -> BarWidget {
let inner = Arc::new(Mutex::new(Inner{
mute: false,
volume: 0.,
}));
start_monitor(inner.clone());
let dev = AlsaAudio{ inner };
BarWidget::new(Box::new(dev), fm, font, size)
}
}
impl BarWidgetImpl for AlsaAudio {
fn name(&self) -> &'static str {
"audio"
}
fn get_dirty(&self) -> bool {
true
}
fn value(&mut self) -> f32 {
let inner = self.inner.lock().unwrap();
inner.volume
}
fn color(&self) -> Color {
let inner = self.inner.lock().unwrap();
if inner.mute {
Color::DARKORANGE
} else {
Color::WHITE
}
}
fn click(&mut self, pos: f32, btn: PointerButton) {
let inner = self.inner.lock().unwrap();
match btn {
// PointerButton::Left => inner.set_master_volume(pos),
//PointerButton::Right => Some(Change::ToggleMute),
//PointerButton::ScrollVertical(val) => Some(Change::VolumeInc((val / 512.) as f32)),
//PointerButton::ScrollHorizontal(val) => Some(Change::VolumeInc((val / 100.) as f32)),
_ => (),
};
}
}
+105
View File
@@ -0,0 +1,105 @@
use std::{
fs::{self, OpenOptions},
io::{Error, ErrorKind, Write},
path::{Path, PathBuf},
};
use walkdir::WalkDir;
use crate::{
color::Color,
event::PointerButton,
fonts::FontMap,
widgets::bar_widget::{BarWidget, BarWidgetImpl},
};
fn read_file_as_u64(path: &Path) -> Result<u64, Error> {
let mut s = fs::read_to_string(path)?;
s.pop();
s.parse::<u64>()
.map_err(|_e| Error::new(ErrorKind::Other, "unable to parse value"))
}
fn write_file_as_u64(path: &Path, value: u64) -> Result<(), Error> {
let mut file = OpenOptions::new().write(true).open(path)?;
file.write_fmt(format_args!("{}", value))
}
pub struct Backlight {
device_path: PathBuf,
cur: u64,
max: u64,
dirty: bool,
}
impl Backlight {
fn update(&mut self) {
self.cur = read_file_as_u64(self.device_path.join("brightness").as_path()).unwrap();
self.max = read_file_as_u64(self.device_path.join("max_brightness").as_path()).unwrap();
}
pub fn new(path: Option<&str>, fm: &mut FontMap, font: &'static str, size: f32) -> BarWidget {
let mut device_path = None;
if let Some(path) = path {
device_path = Some(Path::new("/sys/class/backlight").to_path_buf().join(path));
} else {
for entry in WalkDir::new("/sys/class/backlight") {
if let Ok(entry) = entry {
device_path = Some(entry.path().to_path_buf());
}
}
}
let mut dev = Backlight {
device_path: device_path.expect("did not find backlight device"),
cur: 0,
max: 0,
dirty: true,
};
dev.update();
BarWidget::new(Box::new(dev), fm, font, size)
}
pub fn detect() -> bool {
for entry in WalkDir::new("/sys/class/backlight") {
if entry.is_ok() {
return true;
}
}
return false;
}
pub fn set(&mut self, brightness: f32) {
let val = (self.max as f32 * brightness) as u64;
let _ = write_file_as_u64(self.device_path.join("brightness").as_path(), val);
self.cur = read_file_as_u64(self.device_path.join("brightness").as_path()).unwrap();
}
}
impl BarWidgetImpl for Backlight {
fn name(&self) -> &'static str {
"backlight"
}
fn get_dirty(&self) -> bool {
self.dirty
}
fn value(&mut self) -> f32 {
if self.cur > self.max {
// what.
return 1.0;
}
self.dirty = false;
self.cur as f32 / self.max as f32
}
fn color(&self) -> Color {
Color::WHITE
}
fn click(&mut self, pos: f32, btn: PointerButton) {
self.dirty = true;
match btn {
PointerButton::Left => self.set(pos),
_ => (),
};
}
}
+119
View File
@@ -0,0 +1,119 @@
use std::{cmp::min, default::Default};
use crate::{
buffer::BufferView,
color::Color,
draw::{draw_bar, draw_box},
event::{Event, PointerButton},
fonts::FontMap,
widgets::{Geometry, Widget},
};
pub trait BarWidgetImpl {
fn get_dirty(&self) -> bool {
false
}
fn name(&self) -> &'static str;
fn value(&mut self) -> f32;
fn color(&self) -> Color;
fn click(&mut self, _pos: f32, _btn: PointerButton) {}
}
pub struct BarWidget {
font: &'static str,
size: f32,
geometry: Geometry,
inner_widget: Box<dyn BarWidgetImpl>,
}
impl BarWidget {
pub fn new(
inner_widget: Box<dyn BarWidgetImpl>,
fm: &mut FontMap,
font: &'static str,
size: f32,
) -> BarWidget {
fm.queue_font(font, size, inner_widget.name());
BarWidget {
geometry: Default::default(),
inner_widget,
font,
size,
}
}
}
impl Widget for BarWidget {
fn geometry(&self) -> Geometry {
self.geometry
}
fn get_dirty(&self) -> bool {
self.inner_widget.get_dirty()
}
fn draw(&mut self, fonts: &mut FontMap, view: &mut BufferView) -> Geometry {
let font = fonts.get_font(self.font, self.size);
let fg = Color::WHITE;
font.draw_text(view, fg, self.inner_widget.name()).unwrap();
let size = self.size.ceil() as u32;
let bar_offset = 4 * size;
let val = self.inner_widget.value();
let c = self.inner_widget.color();
draw_bar(
&mut view.offset((bar_offset, 0)),
c,
self.geometry.width - bar_offset,
size,
val,
)
.unwrap();
draw_box(
&mut view.offset((bar_offset, 0)),
c,
(self.geometry.width - bar_offset, size),
)
.unwrap();
self.geometry
}
fn geometry_update(&mut self, _fonts: &mut FontMap, geometry: &Geometry) -> Geometry {
let w = min(geometry.width, 768);
let mut x = geometry.x;
if geometry.width > w {
x += geometry.width - w;
}
self.geometry = Geometry {
x: x,
y: geometry.y,
width: w,
height: self.size.ceil() as u32,
};
self.geometry
}
fn minimum_size(&mut self, _fonts: &mut FontMap) -> Geometry {
Geometry {
x: 0,
y: 0,
width: self.size.ceil() as u32 * 6,
height: self.size.ceil() as u32,
}
}
fn event(&mut self, event: &Event) {
match event {
Event::PointerEvent(ev) => {
let offset = 4 * self.size.ceil() as u32;
if ev.pos.0 >= offset {
let val = (ev.pos.0 - offset) as f32 / (self.geometry.width - offset) as f32;
self.inner_widget.click(val, ev.button);
}
}
_ => (),
}
}
}
+177
View File
@@ -0,0 +1,177 @@
use std::{
error::Error,
sync::{Arc, Mutex},
thread,
time::Duration,
};
use dbus::blocking::{
stdintf::org_freedesktop_dbus::{Properties, PropertiesPropertiesChanged},
LocalConnection,
};
use crate::{
color::Color,
event::{Event, Events},
fonts::FontMap,
widgets::bar_widget::{BarWidget, BarWidgetImpl},
};
enum UpowerBatteryState {
Unknown,
Charging,
Discharging,
Empty,
FullyCharged,
PendingCharge,
PendingDischarge,
}
impl UpowerBatteryState {
fn from_dbus(val: u64) -> UpowerBatteryState {
match val {
1 => UpowerBatteryState::Charging,
2 => UpowerBatteryState::Discharging,
3 => UpowerBatteryState::Empty,
4 => UpowerBatteryState::FullyCharged,
5 => UpowerBatteryState::PendingCharge,
6 => UpowerBatteryState::PendingDischarge,
_ => UpowerBatteryState::Unknown,
}
}
}
struct InnerBattery {
value: f32,
state: UpowerBatteryState,
dirty: bool,
}
fn get_battery_state() -> Result<UpowerBatteryState, Box<dyn Error>> {
let conn = LocalConnection::new_system()?;
let device_path = "/org/freedesktop/UPower/devices/DisplayDevice";
let proxy = conn.with_proxy(
"org.freedesktop.UPower",
device_path,
Duration::from_millis(500),
);
let state: u32 = proxy.get("org.freedesktop.UPower.Device", "State")?;
Ok(UpowerBatteryState::from_dbus(state as u64))
}
fn start_monitor(inner: Arc<Mutex<InnerBattery>>, events: Arc<Mutex<Events>>) {
thread::Builder::new()
.name("battmon".to_string())
.spawn(move || {
let conn = LocalConnection::new_system().unwrap();
let device_path = "/org/freedesktop/UPower/devices/DisplayDevice";
let proxy = conn.with_proxy(
"org.freedesktop.UPower",
device_path,
Duration::from_millis(500),
);
let capacity: f64 = proxy
.get("org.freedesktop.UPower.Device", "Percentage")
.expect("unable to get property");
let state: u32 = proxy
.get("org.freedesktop.UPower.Device", "State")
.expect("unable to get state");
{
let mut inner = inner.lock().unwrap();
inner.value = capacity as f32 / 100.;
inner.state = UpowerBatteryState::from_dbus(state as u64);
}
proxy
.match_signal(
move |c: PropertiesPropertiesChanged,
_: &LocalConnection,
_: &dbus::Message| {
if c.interface_name != "org.freedesktop.UPower.Device" {
return true;
}
let mut inner = inner.lock().unwrap();
for (key, value) in c.changed_properties {
match key.as_str() {
"State" => {
inner.state =
UpowerBatteryState::from_dbus(value.0.as_u64().unwrap());
inner.dirty = true;
let mut events = events.lock().unwrap();
events.add_event(Event::PowerUpdate);
}
"Percentage" => {
inner.value = value.0.as_f64().unwrap() as f32 / 100.;
inner.dirty = true;
let mut events = events.lock().unwrap();
events.add_event(Event::PowerUpdate);
}
_ => (),
}
}
true
},
)
.unwrap();
loop {
conn.process(Duration::from_millis(60000)).unwrap();
}
})
.unwrap();
}
pub struct Battery {
inner: Arc<Mutex<InnerBattery>>,
}
impl Battery {
pub fn new(
events: Arc<Mutex<Events>>,
fm: &mut FontMap,
font: &'static str,
size: f32,
) -> BarWidget {
let battery = Battery {
inner: Arc::new(Mutex::new(InnerBattery {
value: 0.,
state: UpowerBatteryState::Unknown,
dirty: false,
})),
};
start_monitor(battery.inner.clone(), events);
BarWidget::new(Box::new(battery), fm, font, size)
}
pub fn detect() -> bool {
match get_battery_state() {
Ok(_) => true,
Err(_) => false,
}
}
}
impl BarWidgetImpl for Battery {
fn get_dirty(&self) -> bool {
self.inner.lock().unwrap().dirty
}
fn name(&self) -> &'static str {
"battery"
}
fn value(&mut self) -> f32 {
let mut inner = self.inner.lock().unwrap();
inner.dirty = false;
inner.value
}
fn color(&self) -> Color {
let inner = self.inner.lock().unwrap();
match inner.state {
UpowerBatteryState::Charging | UpowerBatteryState::FullyCharged => Color::LIGHTGREEN,
_ if inner.value > 0.25 => Color::WHITE,
_ if inner.value > 0.1 => Color::DARKORANGE,
_ => Color::RED,
}
}
}
+351
View File
@@ -0,0 +1,351 @@
use std::default::Default;
use crate::{
buffer::BufferView,
color::Color,
event::Event,
fonts::FontMap,
widgets::{Geometry, Widget},
};
use chrono::{Datelike, Local, NaiveDate};
pub struct Calendar {
font: &'static str,
month_font: &'static str,
sections_x: i32,
sections_y: i32,
shown_sections_x: u32,
shown_sections_y: u32,
size: f32,
dirty: bool,
geometry: Geometry,
year_width: u32,
date_width: u32,
day_width: u32,
}
const DAY_FACTOR: f32 = 0.6;
const YEAR_FACTOR: f32 = 0.75;
const MONTH_FACTOR: f32 = 1.25;
const DATE_FACTOR: f32 = 1.;
const LINE_HEIGHT: f32 = 0.85;
impl Calendar {
pub fn new(
fm: &mut FontMap,
font: &'static str,
month_font: &'static str,
size: f32,
sections_x: i32,
sections_y: i32,
) -> Calendar {
fm.queue_font(font, size * DAY_FACTOR, "ADEFHIMNORSTUW");
fm.queue_font(font, size * YEAR_FACTOR, "0123456789");
fm.queue_font(font, size * DATE_FACTOR, "0123456789");
fm.queue_font(
month_font,
size * MONTH_FACTOR,
"ADFJMNOSabcehgilmnoprstuvy",
);
Calendar {
font,
month_font,
size,
sections_x,
sections_y,
shown_sections_x: 0,
shown_sections_y: 0,
dirty: true,
geometry: Default::default(),
date_width: 0,
day_width: 0,
year_width: 0,
}
}
fn draw_month(
&mut self,
fonts: &mut FontMap,
mut view: &mut BufferView,
orig: NaiveDate,
mut time: NaiveDate,
) {
let cal_width = 8 * self.date_width + 7 * (self.date_width / 2);
//
// Draw the week day
//
let day_offset = (self.date_width - self.day_width) / 2;
let date_offset = self.date_width + self.date_width / 2;
for idx in 1..8 {
let day_font = fonts.get_font(self.font, self.size * DAY_FACTOR);
let (wk_chr, c) = match idx {
1 => ("MON", Color::WHITE),
2 => ("TUE", Color::WHITE),
3 => ("WED", Color::WHITE),
4 => ("THU", Color::WHITE),
5 => ("FRI", Color::WHITE),
6 => ("SAT", Color::GREY80),
7 => ("SUN", Color::GREY80),
_ => panic!("impossible value"),
};
day_font
.draw_text(
&mut view.offset((
idx * date_offset + day_offset,
(self.size * MONTH_FACTOR).ceil() as u32
+ (self.size * DAY_FACTOR * 0.2).ceil() as u32,
)),
c,
&wk_chr,
)
.unwrap();
}
//
// Draw the month
//
let month_font = fonts.get_font(self.month_font, self.size * MONTH_FACTOR);
let month_str = match time.month() {
1 => "January",
2 => "February",
3 => "March",
4 => "April",
5 => "May",
6 => "June",
7 => "July",
8 => "August",
9 => "September",
10 => "October",
11 => "November",
12 => "December",
_ => panic!("impossible value"),
};
month_font
.draw_text(&mut view, Color::WHITE, month_str)
.unwrap();
//
// Draw the year
//
if time.year() != orig.year() {
let year_font = fonts.get_font(self.font, self.size * YEAR_FACTOR);
year_font
.draw_text(
&mut view.offset((cal_width - self.year_width, 0)),
Color::GREY80,
&format!("{:}", time.year()),
)
.unwrap();
}
let cal_font = fonts.get_font(self.font, self.size * DATE_FACTOR);
'row: for y_off in 1.. {
//
// Draw the week number
//
let wk = time.iso_week();
cal_font
.draw_text(
&mut view.offset((
0,
y_off * (self.size * LINE_HEIGHT).ceil() as u32
+ (self.size * MONTH_FACTOR).ceil() as u32,
)),
if wk == orig.iso_week() {
Color::WHITE
} else {
Color::GREY75
},
&format!("{:02}", wk.week()),
)
.unwrap();
//
// Draw the dates
//
let x_off = time.weekday().number_from_monday();
for x_pos in x_off..8 {
let c = if time.day() == orig.day() && time.month() == orig.month() {
Color::WHITE
} else if x_pos < 6 {
Color::GREY50
} else {
Color::GREY35
};
cal_font
.draw_text(
&mut view.offset((
x_pos * date_offset,
y_off * (self.size * LINE_HEIGHT).ceil() as u32
+ (self.size * MONTH_FACTOR).ceil() as u32,
)),
c,
&format!("{:02}", time.day()),
)
.unwrap();
let t = time.with_day(time.day() + 1);
if t.is_none() {
break 'row;
}
time = t.unwrap();
}
}
}
}
impl<'a> Widget for Calendar {
fn get_dirty(&self) -> bool {
self.dirty
}
fn geometry(&self) -> Geometry {
self.geometry
}
fn event(&mut self, event: &Event) {
match event {
Event::NewMinute => {
self.dirty = true;
}
_ => (),
}
}
fn draw(&mut self, fonts: &mut FontMap, view: &mut BufferView) -> Geometry {
if self.shown_sections_y == 0 || self.shown_sections_x == 0 {
return Geometry {
x: self.geometry.x,
y: self.geometry.y,
width: 0,
height: 0,
};
}
let time = Local::now().naive_local().date();
let cal_height =
(self.size * MONTH_FACTOR).ceil() as u32 + (self.size * LINE_HEIGHT * 8.).ceil() as u32;
let cal_width = 8 * self.date_width + 7 * (self.date_width / 2);
let cal_pad = self.date_width * 2;
let mut t = time.with_day(1).unwrap();
let cals = self.shown_sections_y * self.shown_sections_x;
if cals >= 3 {
t = t.pred_opt().unwrap().with_day(1).unwrap();
}
for ydx in 0..self.shown_sections_y {
for idx in 0..self.shown_sections_x {
self.draw_month(
fonts,
&mut view.offset(((cal_width + cal_pad) * idx, cal_height * ydx)),
time,
t,
);
t = if t.month() == 12 {
t.with_year(t.year() + 1).unwrap().with_month(1).unwrap()
} else {
t.with_month(t.month() + 1).unwrap()
};
}
}
self.dirty = false;
self.geometry
}
fn geometry_update(&mut self, fonts: &mut FontMap, geometry: &Geometry) -> Geometry {
let year_font = fonts.get_font(self.font, self.size * YEAR_FACTOR);
self.year_width = year_font.auto_widest("0123456789").unwrap() * 4;
let cal_font = fonts.get_font(self.font, self.size * DATE_FACTOR);
self.date_width = cal_font.auto_widest("0123456789").unwrap() * 2;
let day_font = fonts.get_font(self.font, self.size * DAY_FACTOR);
self.day_width = day_font.auto_widest("ADEFHIMNORSTUW").unwrap() * 3;
let cal_width = 8 * self.date_width + 7 * (self.date_width / 2);
let cal_height =
(self.size * MONTH_FACTOR).ceil() as u32 + (self.size * LINE_HEIGHT * 8.).ceil() as u32;
let cal_pad = self.date_width * 2;
if geometry.width < cal_width || geometry.height < cal_height {
self.shown_sections_x = 0;
self.shown_sections_y = 0;
self.geometry = Default::default();
return self.geometry;
}
let possible_sections_x = 1 + (geometry.width - cal_width) / (cal_width + cal_pad);
let possible_sections_y = 1 + (geometry.height - cal_height) / cal_height;
self.shown_sections_x =
if self.sections_x > 0 && self.sections_x < possible_sections_x as i32 {
self.sections_x as u32
} else {
possible_sections_x
};
self.shown_sections_y =
if self.sections_y > 0 && self.sections_y < possible_sections_y as i32 {
self.sections_y as u32
} else {
possible_sections_y
};
self.geometry = Geometry {
x: geometry.x,
y: geometry.y,
width: cal_width * self.shown_sections_x as u32
+ cal_pad * (self.shown_sections_x as u32 - 1),
height: cal_height * self.shown_sections_y as u32,
};
self.geometry
}
fn minimum_size(&mut self, fonts: &mut FontMap) -> Geometry {
let cal_font = fonts.get_font(self.font, self.size * DATE_FACTOR);
let date_width = cal_font.auto_widest("0123456789").unwrap() * 2;
let cal_width = 8 * date_width + 7 * (date_width / 2);
let cal_height =
(self.size * MONTH_FACTOR).ceil() as u32 + (self.size * LINE_HEIGHT * 8.).ceil() as u32;
let cal_pad = date_width * 2;
let sections_x = match self.sections_x {
-1 => 1,
0 => {
return Geometry {
x: 0,
y: 0,
width: 0,
height: 0,
}
}
x => x,
};
let sections_y = match self.sections_y {
-1 => 1,
0 => {
return Geometry {
x: 0,
y: 0,
width: 0,
height: 0,
}
}
y => y,
};
let width = cal_width * sections_x as u32 + cal_pad * (sections_x as u32 - 1);
let height = cal_height * sections_y as u32;
Geometry {
x: 0,
y: 0,
width: width,
height: height,
}
}
}
+96
View File
@@ -0,0 +1,96 @@
use std::default::Default;
use crate::{
buffer::BufferView,
color::Color,
event::Event,
fonts::FontMap,
widgets::{Geometry, Widget},
};
use chrono::{Local, Timelike};
pub struct Clock {
font: &'static str,
size: f32,
dirty: bool,
geometry: Geometry,
digit_width: u32,
colon_width: u32,
}
impl<'a> Clock {
pub fn new(fm: &mut FontMap, font: &'static str, size: f32) -> Clock {
fm.queue_font(font, size, "0123456789: ");
Clock {
font,
size,
dirty: true,
geometry: Default::default(),
digit_width: 0,
colon_width: 0,
}
}
}
impl<'a> Widget for Clock {
fn get_dirty(&self) -> bool {
self.dirty
}
fn geometry(&self) -> Geometry {
self.geometry
}
fn event(&mut self, event: &Event) {
match event {
Event::NewMinute => {
self.dirty = true;
}
_ => (),
}
}
fn draw(&mut self, fonts: &mut FontMap, view: &mut BufferView) -> Geometry {
let time = Local::now().naive_local();
let fg = Color::WHITE;
let digit = self.digit_width;
let colon = self.colon_width;
let font = fonts.get_font(self.font, self.size);
font.draw_text_fixed_width(
view,
fg,
&[digit, digit, colon, digit, digit],
&format!("{:02}:{:02}", time.hour(), time.minute()),
)
.unwrap();
self.dirty = false;
self.geometry
}
fn geometry_update(&mut self, fonts: &mut FontMap, geometry: &Geometry) -> Geometry {
let font = fonts.get_font(self.font, self.size);
self.digit_width = font.auto_widest("0123456789").unwrap();
self.colon_width = font.auto_widest(":").unwrap();
self.geometry = Geometry {
x: geometry.x,
y: geometry.y,
width: self.digit_width * 4 + self.colon_width,
height: self.size.ceil() as u32,
};
self.geometry
}
fn minimum_size(&mut self, fonts: &mut FontMap) -> Geometry {
let font = fonts.get_font(self.font, self.size);
let digit_width = font.auto_widest("0123456789").unwrap();
let colon_width = font.auto_widest(":").unwrap();
Geometry {
x: 0,
y: 0,
width: digit_width * 4 + colon_width,
height: self.size.ceil() as u32,
}
}
}
+92
View File
@@ -0,0 +1,92 @@
use std::default::Default;
use crate::{
buffer::BufferView,
color::Color,
event::Event,
fonts::FontMap,
widgets::{Geometry, Widget},
};
use chrono::{Datelike, Local};
pub struct Date {
font: &'static str,
size: f32,
dirty: bool,
geometry: Geometry,
}
impl Date {
pub fn new(fm: &mut FontMap, font: &'static str, size: f32) -> Date {
fm.queue_font(font, size, "0123456789/, adehinortuFMSTW");
Date {
font,
size,
dirty: true,
geometry: Default::default(),
}
}
}
impl<'a> Widget for Date {
fn get_dirty(&self) -> bool {
self.dirty
}
fn geometry(&self) -> Geometry {
self.geometry
}
fn event(&mut self, event: &Event) {
match event {
Event::NewMinute => {
self.dirty = true;
}
_ => (),
}
}
fn draw(&mut self, fonts: &mut FontMap, view: &mut BufferView) -> Geometry {
let time = Local::now().naive_local();
let fg = Color::WHITE;
let font = fonts.get_font(self.font, self.size);
font.draw_text(
view,
fg,
&format!(
"{}, {:02}/{:02}/{:4}",
time.weekday(),
time.day(),
time.month(),
time.year()
),
)
.unwrap();
self.dirty = false;
self.geometry
}
fn geometry_update(&mut self, fonts: &mut FontMap, geometry: &Geometry) -> Geometry {
let width = (3. + 2. + 2. + 2. + 4.) * self.size / 2.;
let font = fonts.get_font(self.font, self.size);
self.geometry = Geometry {
x: geometry.x,
y: geometry.y,
width: width.ceil() as u32,
height: font.height().ceil() as u32,
};
self.geometry
}
fn minimum_size(&mut self, fonts: &mut FontMap) -> Geometry {
let width = (3. + 2. + 2. + 2. + 4.) * self.size / 2.;
let font = fonts.get_font(self.font, self.size);
Geometry {
x: 0,
y: 0,
width: width.ceil() as u32,
height: font.height().ceil() as u32,
}
}
}
+783
View File
@@ -0,0 +1,783 @@
use std::{
cmp::{max, min, Ordering},
collections::HashMap,
default::Default,
fs::{read_to_string, File},
io::Write,
process::{exit, Command},
sync::{Arc, Mutex},
thread,
};
use crate::{
buffer::BufferView,
color::Color,
event::{Event, Events, PointerButton, PointerEvent},
fonts::FontMap,
keyboard::{keysyms, KeyEvent},
utils::{
desktop::{load_desktop_cache, load_desktop_files, write_desktop_cache, Desktop},
xdg,
},
widgets::{Geometry, Widget},
};
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use unicode_segmentation::UnicodeSegmentation;
use wayland_client::{protocol::wl_keyboard, WEnum};
struct Matcher {
matches: HashMap<Desktop, i64>,
}
impl Matcher {
fn new() -> Self {
Self {
matches: HashMap::new(),
}
}
fn try_match(&mut self, dtop: Desktop, val: &str, input: &str, prio: f32) {
let fuzzy_matcher = SkimMatcherV2::default();
if let Some(ma) = fuzzy_matcher.fuzzy_match(val, input) {
let ma = ((ma as f32) * prio) as i64;
if let Some(ma_old) = self.matches.get(&dtop) {
// Skip over new matches for the same program that are worse
// than the one we already have.
if ma_old > &ma {
return;
}
}
self.matches.insert(dtop, ma);
}
}
fn matches(&self) -> Vec<Desktop> {
let mut m = self
.matches
.iter()
.map(|(key, ma)| (*ma, key.clone()))
.collect::<Vec<(i64, Desktop)>>();
m.sort_by(|(ma1, d1), (ma2, d2)| {
if ma1 > ma2 {
Ordering::Less
} else if ma1 < ma2 {
Ordering::Greater
} else {
d1.cmp(d2)
}
});
m.into_iter().map(|(_, x)| x).collect()
}
}
enum PromptMode {
Normal,
Shell,
Calc,
}
struct Prompt {
input: String,
mode: PromptMode,
cursor: usize,
}
impl Prompt {
fn new() -> Prompt {
Prompt {
input: String::new(),
mode: PromptMode::Normal,
cursor: 0,
}
}
fn move_cursor(&mut self, distance: isize) {
let new_cursor = self.cursor as isize + distance;
if new_cursor < 0 {
self.cursor = 0;
return;
} else if new_cursor > self.input.len() as isize {
self.cursor = self.input.len()
} else {
self.cursor = new_cursor as usize;
}
}
fn set(&mut self, v: &str) {
self.input = v.to_string();
self.cursor = self.input.len();
}
fn append(&mut self, v: &str) {
if self.input.len() == 0 {
match v {
"!" => {
self.mode = PromptMode::Shell;
return;
}
"=" => {
self.mode = PromptMode::Calc;
return;
}
_ => (),
}
}
let indices: Vec<(usize, &str)> = self.input.grapheme_indices(true).collect();
if self.cursor == indices.len() {
self.input += &v;
} else {
let index_at = indices[self.cursor].0;
self.input.insert_str(index_at, &v);
}
self.cursor += 1;
}
fn backspace(&mut self) {
let mut indices: Vec<(usize, &str)> = self.input.grapheme_indices(true).collect();
if indices.is_empty() {
self.mode = PromptMode::Normal;
return;
}
if self.cursor == 0 {
return;
}
self.cursor -= 1;
indices.remove(self.cursor);
self.input = indices.iter().fold("".into(), |acc, el| acc + el.1);
}
fn delete(&mut self) {
let mut indices: Vec<(usize, &str)> = self.input.grapheme_indices(true).collect();
if indices.is_empty() {
self.mode = PromptMode::Normal;
return;
}
if self.cursor >= indices.len() {
return;
}
indices.remove(self.cursor);
self.input = indices.iter().fold("".into(), |acc, el| acc + el.1);
}
fn clear_right(&mut self) {
let indices: Vec<(usize, &str)> = self.input.grapheme_indices(true).collect();
if !indices.is_empty() {
self.input = indices[0..self.cursor]
.iter()
.fold("".into(), |acc, el| acc + el.1);
} else {
self.mode = PromptMode::Normal;
}
}
fn clear_left(&mut self) {
let indices: Vec<(usize, &str)> = self.input.grapheme_indices(true).collect();
if !indices.is_empty() {
self.input = indices[self.cursor..indices.len()]
.iter()
.fold("".into(), |acc, el| acc + el.1);
self.cursor = 0;
} else {
self.mode = PromptMode::Normal;
}
}
fn home(&mut self) {
self.cursor = 0;
}
fn end(&mut self) {
self.cursor = self.input.len();
}
}
trait InterfaceWidget {
fn trigger(&mut self, intf: &mut InnerInterface);
fn draw(
&mut self,
intf: &InnerInterface,
fonts: &mut FontMap,
view: &mut BufferView,
) -> Geometry;
fn update(&mut self, intf: &InnerInterface);
}
struct Launcher {
next_token: Option<String>,
options: Arc<Mutex<Vec<Desktop>>>,
matches: Vec<Desktop>,
launch_cmd: Option<String>,
}
impl Launcher {
fn new(events: Arc<Mutex<Events>>, launch_cmd: Option<String>) -> Launcher {
let options = Arc::new(Mutex::new(Vec::new()));
{
let options = Arc::clone(&options);
thread::Builder::new()
.name("desktopini".to_string())
.spawn(move || {
let mut options = options.lock().unwrap();
*options = match load_desktop_cache() {
Ok(v) => v,
Err(_) => {
let v = load_desktop_files();
write_desktop_cache(&v).unwrap();
v
}
};
drop(options);
let mut events = events.lock().unwrap();
events.add_event(Event::LauncherUpdate);
})
.unwrap();
}
Launcher {
next_token: None,
options: options,
matches: Vec::new(),
launch_cmd,
}
}
fn exec(&self, cmdline: &str) {
let mut cmd = Command::new("/bin/sh");
if let Some(token) = &self.next_token {
cmd.env("XDG_ACTIVATION_TOKEN", token);
}
cmd.arg("-c");
if let Some(l) = &self.launch_cmd {
cmd.arg(format!("{} {}", l, cmdline));
} else {
cmd.arg(cmdline);
}
cmd.spawn().unwrap();
exit(0);
}
}
impl InterfaceWidget for Launcher {
fn trigger(&mut self, intf: &mut InnerInterface) {
if self.matches.len() > intf.selection {
let d = &self.matches[intf.selection];
if let Some(exec) = &d.exec {
let exec = exec
.replace("%f", "")
.replace("%F", "")
.replace("%u", "")
.replace("%U", "");
self.exec(&exec);
}
}
}
fn update(&mut self, intf: &InnerInterface) {
let mut matcher = Matcher::new();
let options = self.options.lock().unwrap();
for desktop in options.iter() {
matcher.try_match(
desktop.clone(),
&desktop.name.to_lowercase(),
&intf.prompt.input.to_lowercase(),
1.0,
);
for keyword in desktop.keywords.iter() {
matcher.try_match(
desktop.clone(),
&keyword.to_lowercase(),
&intf.prompt.input.to_lowercase(),
0.5,
);
}
}
self.matches = matcher.matches();
}
fn draw(
&mut self,
intf: &InnerInterface,
fonts: &mut FontMap,
view: &mut BufferView,
) -> Geometry {
let fg = Color::WHITE;
let line_height = intf.size.ceil() as u32;
// Draw line
let mut prompt_offset = intf.geometry.height - line_height;
let mut prompt_line = view.offset((0, prompt_offset));
let font = fonts.get_font(intf.font, intf.size);
let mut x_max = font
.auto_draw_text_with_cursor(
&mut prompt_line,
fg,
&format!(" {}", &intf.prompt.input),
intf.prompt.cursor + 3,
)
.unwrap();
font.auto_draw_text(&mut prompt_line, fg, ">").unwrap();
// Draw entries
let dimfg = Color::GREY50;
prompt_offset -= 8;
for (idx, m) in self.matches.iter().enumerate() {
if prompt_offset < line_height {
break;
}
prompt_offset -= line_height;
let mut line = view.offset((0, prompt_offset));
if idx == intf.selection {
let fuzzy_matcher = SkimMatcherV2::default();
let (_, indices) = fuzzy_matcher
.fuzzy_indices(&m.name.to_lowercase(), &intf.prompt.input.to_lowercase())
.unwrap_or((0, vec![]));
let mut colors = Vec::with_capacity(m.name.len());
for pos in 0..m.name.len() {
if indices.contains(&pos) {
colors.push(Color::LIGHTORANGE);
} else {
colors.push(Color::GREY75);
}
}
x_max = max(
x_max,
font.auto_draw_text_individual_colors(&mut line, &colors, &m.name)
.unwrap(),
);
} else {
x_max = max(
x_max,
font.auto_draw_text(&mut line, dimfg, &m.name).unwrap(),
);
}
}
let content_height = min(
intf.geometry.height,
(self.matches.len() + 1) as u32 * line_height + 8,
);
let content_width = min(intf.geometry.width, x_max.0 + 1);
Geometry {
x: intf.geometry.x,
y: intf.geometry.y + intf.geometry.height - content_height,
width: content_width,
height: content_height,
}
}
}
struct Shell {
next_token: Option<String>,
}
impl Shell {
fn new() -> Shell {
Shell { next_token: None }
}
fn exec(&self, args: Vec<String>) {
let mut cmd = Command::new(args[0].clone());
if let Some(token) = &self.next_token {
cmd.env("XDG_ACTIVATION_TOKEN", token);
}
cmd.args(&args[1..]).spawn().unwrap();
exit(0);
}
}
impl InterfaceWidget for Shell {
fn trigger(&mut self, intf: &mut InnerInterface) {
let args = vec![
"/bin/sh".to_string(),
"-c".to_string(),
intf.prompt.input.clone(),
];
self.exec(args);
}
fn update(&mut self, _intf: &InnerInterface) {}
fn draw(
&mut self,
intf: &InnerInterface,
fonts: &mut FontMap,
view: &mut BufferView,
) -> Geometry {
let fg = Color::WHITE;
let line_height = intf.size.ceil() as u32;
// Draw line
let prompt_offset = intf.geometry.height - line_height;
let mut prompt_line = view.offset((0, prompt_offset));
// Draw prompt
let font = fonts.get_font(intf.font, intf.size);
let x_max = font
.auto_draw_text_with_cursor(
&mut prompt_line,
fg,
&format!(" {}", &intf.prompt.input),
intf.prompt.cursor + 3,
)
.unwrap();
font.auto_draw_text(&mut prompt_line, Color::BUFF, "!")
.unwrap();
Geometry {
x: intf.geometry.x,
y: intf.geometry.y + intf.geometry.height - line_height,
width: x_max.0 + 1,
height: line_height,
}
}
}
struct Calc {
old: Arc<Mutex<Vec<(String, String)>>>,
result: Option<String>,
}
impl Calc {
fn new() -> Calc {
let old: Arc<Mutex<Vec<(String, String)>>> = Arc::new(Mutex::new(Vec::new()));
let old_local = old.clone();
thread::Builder::new()
.name("calc".to_string())
.spawn(move || {
let s = match read_to_string(format!("{}/wldash/calc", xdg::cache_folder())) {
Ok(s) => s,
_ => return,
};
let mut old = old_local.lock().unwrap();
for line in s.lines() {
let pos = match line.find("=") {
Some(v) => v,
_ => continue,
};
let (input, res) = line.split_at(pos);
let (input, res) = (input.trim(), res[1..].trim());
old.push((input.to_string(), res.to_string()));
}
})
.unwrap();
Calc { old, result: None }
}
fn sync(&self) {
let mut f = match File::create(format!("{}/wldash/calc", xdg::cache_folder())) {
Ok(f) => f,
_ => return,
};
let old = self.old.lock().unwrap();
for (input, res) in old.iter() {
write!(f, "{}={}\n", input, res).unwrap();
}
f.sync_data().unwrap();
}
}
impl InterfaceWidget for Calc {
fn trigger(&mut self, intf: &mut InnerInterface) {
let mut old = self.old.lock().unwrap();
if intf.selection == 0 {
if let Some(res) = &self.result {
old.push((intf.prompt.input.to_string(), res.to_string()));
while old.len() > 32 {
old.remove(0);
}
drop(old);
self.sync();
}
} else if old.len() >= intf.selection {
let (input, res) = &old[old.len() - intf.selection];
self.result = Some(res.to_string());
intf.prompt.set(input);
intf.selection = 0;
}
}
fn update(&mut self, intf: &InnerInterface) {
let res =
rcalc_lib::parse::eval(&intf.prompt.input, &mut rcalc_lib::parse::CalcState::new())
.map(|x| format!("{}", x))
.map_err(|x| format!("{}", x));
self.result = match res {
Ok(v) => Some(v),
Err(_) => None,
};
}
fn draw(
&mut self,
intf: &InnerInterface,
fonts: &mut FontMap,
view: &mut BufferView,
) -> Geometry {
let old = self.old.lock().unwrap();
let fg = Color::WHITE;
let line_height = intf.size.ceil() as u32;
// Draw line
let mut prompt_offset = intf.geometry.height - (line_height);
let mut prompt_line = view.offset((0, prompt_offset));
// Draw prompt
let font = fonts.get_font(intf.font, intf.size);
font.auto_draw_text_with_cursor(
&mut prompt_line,
fg,
&format!(" {} ", &intf.prompt.input),
intf.prompt.cursor + 3,
)
.unwrap();
font.auto_draw_text(&mut prompt_line, Color::BUFF, "=")
.unwrap();
prompt_offset -= 8;
prompt_offset -= line_height;
if let Some(res) = &self.result {
let c = if intf.selection == 0 {
Color::LIGHTORANGE
} else {
Color::GREY50
};
let mut result_line = view.offset((0, prompt_offset));
font.auto_draw_text(&mut result_line, c, res).unwrap();
}
for (idx, (input, res)) in old.iter().rev().enumerate() {
if prompt_offset < line_height {
break;
}
let c = if idx + 1 == intf.selection {
Color::GREY75
} else {
Color::GREY50
};
prompt_offset -= line_height;
let mut result_line = view.offset((0, prompt_offset));
font.auto_draw_text(&mut result_line, c, &format!("{} = {}", input, res))
.unwrap();
}
let content_height = min(
intf.geometry.height,
(old.len() + 2) as u32 * line_height + 8,
);
Geometry {
x: intf.geometry.x,
y: intf.geometry.y + intf.geometry.height - content_height,
width: intf.geometry.width,
height: content_height,
}
}
}
struct InnerInterface {
font: &'static str,
size: f32,
dirty: bool,
geometry: Geometry,
selection: usize,
prompt: Prompt,
}
pub struct Interface {
launcher: Launcher,
shell: Shell,
calc: Calc,
inner: InnerInterface,
}
impl Interface {
pub fn new(
events: Arc<Mutex<Events>>,
fm: &mut FontMap,
font: &'static str,
size: f32,
launch_cmd: Option<String>,
) -> Interface {
fm.queue_font(
font,
size,
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 >=!,.-/()",
);
Interface {
launcher: Launcher::new(events, launch_cmd),
shell: Shell::new(),
calc: Calc::new(),
inner: InnerInterface {
font,
size,
dirty: false,
geometry: Default::default(),
selection: 0,
prompt: Prompt::new(),
},
}
}
fn pointer_input(&mut self, event: &PointerEvent) {
if let PointerButton::Left = event.button {
let line_height = self.inner.size.ceil() as u32;
let height = self.inner.geometry.height - line_height - 8;
let lines = height / line_height;
let offset = height % line_height;
let pos = if event.pos.1 >= offset {
event.pos.1 - offset
} else {
return;
};
self.inner.selection = (lines - pos / line_height - 1) as usize;
self.inner.dirty = true;
}
}
fn exit(&mut self) {
if self.inner.prompt.input.len() == 0 {
std::process::exit(0);
}
if let Ok(mut f) = File::create(format!("{}/wldash/prompt", xdg::cache_folder())) {
write!(f, "{}", self.inner.prompt.input).unwrap();
f.sync_data().unwrap();
}
std::process::exit(0);
}
fn keyboard_input(&mut self, event: &KeyEvent) {
if event.state != WEnum::Value(wl_keyboard::KeyState::Pressed) {
return;
}
self.inner.dirty = true;
let widget = match self.inner.prompt.mode {
PromptMode::Shell => &mut self.shell as &mut dyn InterfaceWidget,
PromptMode::Normal => &mut self.launcher as &mut dyn InterfaceWidget,
PromptMode::Calc => &mut self.calc as &mut dyn InterfaceWidget,
};
match event.keysym {
keysyms::KEY_a if event.modifiers.ctrl => self.inner.prompt.home(),
keysyms::KEY_e if event.modifiers.ctrl => self.inner.prompt.end(),
keysyms::KEY_u if event.modifiers.ctrl => {
self.inner.prompt.clear_left();
self.inner.selection = 0;
widget.update(&self.inner);
}
keysyms::KEY_k if event.modifiers.ctrl => {
self.inner.prompt.clear_right();
self.inner.selection = 0;
widget.update(&self.inner);
}
keysyms::KEY_r if event.modifiers.ctrl => {
if let Ok(s) = read_to_string(format!("{}/wldash/prompt", xdg::cache_folder())) {
self.inner.prompt.set(&s);
}
}
keysyms::KEY_Home => self.inner.prompt.home(),
keysyms::KEY_End => self.inner.prompt.end(),
keysyms::KEY_BackSpace => {
self.inner.prompt.backspace();
self.inner.selection = 0;
widget.update(&self.inner);
}
keysyms::KEY_Delete => {
self.inner.prompt.delete();
self.inner.selection = 0;
widget.update(&self.inner);
}
keysyms::KEY_Escape => self.exit(),
keysyms::KEY_Return => widget.trigger(&mut self.inner),
keysyms::KEY_Left => self.inner.prompt.move_cursor(-1),
keysyms::KEY_Right => self.inner.prompt.move_cursor(1),
keysyms::KEY_Up => {
self.inner.selection += 1;
}
keysyms::KEY_Down => {
if self.inner.selection > 0 {
self.inner.selection -= 1;
}
}
_ => {
if let Some(utf8) = &event.utf8 {
self.inner.prompt.append(&utf8);
self.inner.selection = 0;
widget.update(&self.inner);
} else {
self.inner.dirty = false;
}
}
}
}
}
impl Widget for Interface {
fn get_dirty(&self) -> bool {
self.inner.dirty
}
fn geometry(&self) -> Geometry {
self.inner.geometry
}
fn draw(&mut self, fonts: &mut FontMap, view: &mut BufferView) -> Geometry {
self.inner.dirty = false;
match self.inner.prompt.mode {
PromptMode::Shell => self.shell.draw(&self.inner, fonts, view),
PromptMode::Normal => self.launcher.draw(&self.inner, fonts, view),
PromptMode::Calc => self.calc.draw(&self.inner, fonts, view),
}
}
fn geometry_update(&mut self, _fonts: &mut FontMap, geometry: &Geometry) -> Geometry {
self.inner.geometry = geometry.clone();
self.inner.geometry
}
fn minimum_size(&mut self, _fonts: &mut FontMap) -> Geometry {
Geometry {
x: 0,
y: 0,
width: 256,
height: (self.inner.size.ceil() as u32) * 4 + 8,
}
}
fn event(&mut self, event: &Event) {
match event {
Event::KeyEvent(e) => self.keyboard_input(e),
Event::PointerEvent(e) => self.pointer_input(e),
Event::FocusLost => self.exit(),
Event::LauncherUpdate => {
self.inner.dirty = true;
self.launcher.update(&self.inner);
}
Event::TokenUpdate(t) => {
self.launcher.next_token = Some(t.to_string());
self.shell.next_token = Some(t.to_string());
}
_ => (),
}
}
}
+283
View File
@@ -0,0 +1,283 @@
use std::cmp::max;
use crate::{fonts::FontMap, state::State, widgets::Geometry};
pub trait Layout {
fn geometry_update(
&self,
fonts: &mut FontMap,
geometry: &Geometry,
state: &mut State,
) -> Geometry;
fn minimum_size(&self, fonts: &mut FontMap, state: &mut State) -> Geometry;
}
pub struct HorizontalLayout {
pub widgets: Vec<Box<dyn Layout>>,
}
impl HorizontalLayout {
pub fn new(widgets: Vec<Box<dyn Layout>>) -> Box<dyn Layout> {
Box::new(HorizontalLayout { widgets })
}
}
impl Layout for HorizontalLayout {
fn geometry_update(
&self,
fonts: &mut FontMap,
geometry: &Geometry,
state: &mut State,
) -> Geometry {
let mut geo = geometry.clone();
let mut max_width = 0;
let mut max_height = 0;
for w in self.widgets.iter() {
let result = w.geometry_update(fonts, &geo, state);
geo.x = result.x + result.width;
geo.width -= result.width;
max_width += result.width;
max_height = max(result.height, max_height);
}
geo.width = max_width;
geo.height = max_height;
geo
}
fn minimum_size(&self, fonts: &mut FontMap, state: &mut State) -> Geometry {
let mut max_width = 0;
let mut max_height = 0;
for w in self.widgets.iter() {
let result = w.minimum_size(fonts, state);
max_width += result.x + result.width;
max_height = max(result.y + result.height, max_height);
}
Geometry {
width: max_width,
height: max_height,
x: 0,
y: 0,
}
}
}
pub struct VerticalLayout {
pub widgets: Vec<Box<dyn Layout>>,
}
impl VerticalLayout {
pub fn new(widgets: Vec<Box<dyn Layout>>) -> Box<dyn Layout> {
Box::new(VerticalLayout { widgets })
}
}
impl Layout for VerticalLayout {
fn geometry_update(
&self,
fonts: &mut FontMap,
geometry: &Geometry,
state: &mut State,
) -> Geometry {
let mut geo = geometry.clone();
let mut max_width = 0;
let mut max_height = 0;
for w in self.widgets.iter() {
let result = w.geometry_update(fonts, &geo, state);
geo.y = result.y + result.height;
geo.height -= result.height;
max_width = max(result.width, max_width);
max_height += result.height;
}
geo.width = max_width;
geo.height = max_height;
geo
}
fn minimum_size(&self, fonts: &mut FontMap, state: &mut State) -> Geometry {
let mut max_width = 0;
let mut max_height = 0;
for w in self.widgets.iter() {
let result = w.minimum_size(fonts, state);
max_width = max(result.x + result.width, max_width);
max_height += result.y + result.height;
}
Geometry {
width: max_width,
height: max_height,
x: 0,
y: 0,
}
}
}
pub trait WidgetUpdater {
fn geometry_update(&mut self, idx: usize, fonts: &mut FontMap, geometry: &Geometry)
-> Geometry;
fn minimum_size(&mut self, idx: usize, fonts: &mut FontMap) -> Geometry;
}
pub struct IndexedLayout {
pub widget_idx: usize,
}
impl IndexedLayout {
pub fn new(widget_idx: usize) -> Box<dyn Layout> {
Box::new(IndexedLayout { widget_idx })
}
}
impl Layout for IndexedLayout {
fn geometry_update(
&self,
fonts: &mut FontMap,
geometry: &Geometry,
state: &mut State,
) -> Geometry {
state.geometry_update(self.widget_idx, fonts, geometry)
}
fn minimum_size(&self, fonts: &mut FontMap, state: &mut State) -> Geometry {
state.minimum_size(self.widget_idx, fonts)
}
}
pub struct InvertedHorizontalLayout {
pub widgets: Vec<Box<dyn Layout>>,
}
impl InvertedHorizontalLayout {
pub fn new(widgets: Vec<Box<dyn Layout>>) -> Box<dyn Layout> {
Box::new(InvertedHorizontalLayout { widgets })
}
}
impl Layout for InvertedHorizontalLayout {
fn geometry_update(
&self,
fonts: &mut FontMap,
geometry: &Geometry,
state: &mut State,
) -> Geometry {
let mut geo = geometry.clone();
let mut max_height = 0;
for w in self.widgets.iter() {
let mut temp_geo = geo.clone();
let temp_result = w.geometry_update(fonts, &temp_geo, state);
temp_geo.x = geo.x + (geo.width - temp_result.width);
let result = w.geometry_update(fonts, &temp_geo, state);
geo.width -= result.width;
max_height = max(result.height, max_height);
}
geo.height = max_height;
geo
}
fn minimum_size(&self, fonts: &mut FontMap, state: &mut State) -> Geometry {
let mut max_width = 0;
let mut max_height = 0;
for w in self.widgets.iter() {
let result = w.minimum_size(fonts, state);
max_width += result.x + result.width;
max_height = max(result.y + result.height, max_height);
}
Geometry {
width: max_width,
height: max_height,
x: 0,
y: 0,
}
}
}
pub struct InvertedVerticalLayout {
pub widgets: Vec<Box<dyn Layout>>,
}
impl InvertedVerticalLayout {
pub fn new(widgets: Vec<Box<dyn Layout>>) -> Box<dyn Layout> {
Box::new(InvertedVerticalLayout { widgets })
}
}
impl Layout for InvertedVerticalLayout {
fn geometry_update(
&self,
fonts: &mut FontMap,
geometry: &Geometry,
state: &mut State,
) -> Geometry {
let mut geo = geometry.clone();
let mut max_width = 0;
for w in self.widgets.iter() {
let mut temp_geo = geo.clone();
let temp_result = w.geometry_update(fonts, &temp_geo, state);
temp_geo.y = geo.y + (geo.height - temp_result.height);
let result = w.geometry_update(fonts, &temp_geo, state);
geo.height -= result.height;
max_width = max(result.width, max_width);
}
geo.width = max_width;
geo
}
fn minimum_size(&self, fonts: &mut FontMap, state: &mut State) -> Geometry {
let mut max_width = 0;
let mut max_height = 0;
for w in self.widgets.iter() {
let result = w.minimum_size(fonts, state);
max_width = max(result.x + result.width, max_width);
max_height += result.y + result.height;
}
Geometry {
width: max_width,
height: max_height,
x: 0,
y: 0,
}
}
}
pub struct Margin {
pub widget: Box<dyn Layout>,
pub margin: (u32, u32, u32, u32),
}
impl Margin {
pub fn new(widget: Box<dyn Layout>, margin: (u32, u32, u32, u32)) -> Box<dyn Layout> {
Box::new(Margin { widget, margin })
}
}
impl Layout for Margin {
fn geometry_update(
&self,
fonts: &mut FontMap,
geometry: &Geometry,
state: &mut State,
) -> Geometry {
let geo = Geometry {
x: geometry.x + self.margin.0,
y: geometry.y + self.margin.1,
width: geometry.width - self.margin.0 - self.margin.2,
height: geometry.height - self.margin.1 - self.margin.3,
};
let out = self.widget.geometry_update(fonts, &geo, state);
Geometry {
x: out.x - self.margin.0,
y: out.y - self.margin.1,
width: out.width + self.margin.0 + self.margin.2,
height: out.height + self.margin.1 + self.margin.3,
}
}
fn minimum_size(&self, fonts: &mut FontMap, state: &mut State) -> Geometry {
let size = self.widget.minimum_size(fonts, state);
Geometry {
width: size.x + size.width + self.margin.0 + self.margin.2,
height: size.y + size.height + self.margin.1 + self.margin.3,
x: 0,
y: 0,
}
}
}
+62
View File
@@ -0,0 +1,62 @@
use std::default::Default;
use crate::{
buffer::BufferView,
color::Color,
fonts::FontMap,
widgets::{Geometry, Widget},
};
pub struct Line {
geometry: Geometry,
thickness: u32,
vertical: bool,
}
impl Line {
pub fn new(thickness: u32, vertical: bool) -> Line {
Line {
geometry: Default::default(),
thickness,
vertical,
}
}
}
impl Widget for Line {
fn geometry(&self) -> Geometry {
self.geometry
}
fn draw(&mut self, _fonts: &mut FontMap, view: &mut BufferView) -> Geometry {
view.memset(Color::WHITE);
self.geometry
}
fn geometry_update(&mut self, _fonts: &mut FontMap, geometry: &Geometry) -> Geometry {
self.geometry = Geometry {
x: geometry.x,
y: geometry.y,
width: if self.vertical {
self.thickness
} else {
geometry.width
},
height: if self.vertical {
geometry.height
} else {
self.thickness
},
};
self.geometry
}
fn minimum_size(&mut self, _fonts: &mut FontMap) -> Geometry {
Geometry {
x: 0,
y: 0,
width: if self.vertical { self.thickness } else { 1 },
height: if self.vertical { 1 } else { self.thickness },
}
}
}
+27
View File
@@ -0,0 +1,27 @@
//mod alsaaudio;
mod backlight;
mod bar_widget;
mod battery;
mod calendar;
mod clock;
mod date;
mod launcher;
mod layout;
mod line;
mod pulseaudio;
mod widget;
//pub use alsaaudio::AlsaAudio;
pub use backlight::Backlight;
pub use battery::Battery;
pub use calendar::Calendar;
pub use clock::Clock;
pub use date::Date;
pub use launcher::Interface;
pub use layout::{
HorizontalLayout, IndexedLayout, InvertedHorizontalLayout, InvertedVerticalLayout, Layout,
Margin, VerticalLayout, WidgetUpdater,
};
pub use line::Line;
pub use pulseaudio::PulseAudio;
pub use widget::{Geometry, Widget};
+243
View File
@@ -0,0 +1,243 @@
use std::{
cell::RefCell,
error::Error,
os::fd::RawFd,
rc::Rc,
sync::{Arc, Mutex},
thread,
};
use nix::unistd::{pipe, read, write};
use crate::{
color::Color,
event::{Event, Events, PointerButton},
fonts::FontMap,
widgets::bar_widget::{BarWidget, BarWidgetImpl},
};
use libpulse_binding::volume::ChannelVolumes;
fn monitor(
events: Arc<Mutex<Events>>,
inner: Arc<Mutex<InnerAudio>>,
pipe: RawFd,
) -> Result<(), Box<dyn Error>> {
use libpulse_binding::{
callbacks::ListResult,
context::{
subscribe::{Facility, InterestMaskSet},
Context, FlagSet, State,
},
mainloop::{
self, api::Mainloop, events::io::FlagSet as IoFlagSet, standard::IterateResult,
},
proplist::{properties, Proplist},
volume::Volume,
};
let mut proplist = Proplist::new().unwrap();
proplist
.set_str(properties::APPLICATION_NAME, "wldash")
.unwrap();
let mut mainloop = mainloop::standard::Mainloop::new().unwrap();
let context = Rc::new(RefCell::new(
Context::new_with_proplist(&mainloop, "wldash_context", &proplist).unwrap(),
));
context.borrow_mut().connect(None, FlagSet::NOFLAGS, None)?;
loop {
mainloop.iterate(false);
match context.borrow().get_state() {
State::Ready => break,
State::Failed | State::Terminated => panic!("damn"),
_ => (),
}
}
let local_context = context.clone();
let local_inner = inner.clone();
let local_events = events.clone();
context.borrow_mut().set_subscribe_callback(Some(Box::new(
move |facility, _operation, index| match facility {
Some(Facility::Sink) => {
let introspector = local_context.borrow_mut().introspect();
let inner = local_inner.clone();
let events = local_events.clone();
introspector.get_sink_info_by_index(index, move |res| match res {
ListResult::End | ListResult::Error => (),
ListResult::Item(sink_info) => {
if let Some(_) = &sink_info.name {
let avg = sink_info.volume.avg().0 as f32 / Volume::NORMAL.0 as f32;
let mut inner = inner.lock().unwrap();
inner.volume = avg;
inner.mute = sink_info.mute;
inner.dirty = true;
drop(inner);
let mut events = events.lock().unwrap();
events.add_event(Event::AudioUpdate);
}
}
});
}
_ => (),
},
)));
context
.borrow_mut()
.subscribe(InterestMaskSet::SINK, |_| {});
let introspector = context.borrow_mut().introspect();
let local_inner = inner.clone();
introspector.get_sink_info_by_name("@DEFAULT_SINK@", move |res| match res {
ListResult::End | ListResult::Error => (),
ListResult::Item(sink_info) => {
if let Some(_) = &sink_info.name {
let avg = sink_info.volume.avg().0 as f32 / Volume::NORMAL.0 as f32;
let mut inner = local_inner.lock().unwrap();
inner.volume = avg;
inner.channel_volume = Some(sink_info.volume);
inner.mute = sink_info.mute;
inner.dirty = true;
drop(inner);
let mut events = events.lock().unwrap();
events.add_event(Event::AudioUpdate);
}
}
});
drop(introspector);
let local_context = context.clone();
let local_inner = inner.clone();
let event_source = mainloop.new_io_event(
pipe as i32,
IoFlagSet::INPUT,
Box::new(move |_, _, _| {
let mut buf = [0; 8];
_ = read(pipe, &mut buf);
let mut inner = local_inner.lock().unwrap();
let mut introspector = local_context.borrow_mut().introspect();
match inner.last_click.take() {
Some(Change::Volume(volume)) => {
// do something
let mut vol = inner.channel_volume.unwrap();
vol.scale(Volume((volume * Volume::NORMAL.0 as f32).round() as u32));
introspector.set_sink_volume_by_name("@DEFAULT_SINK@", &vol, None);
}
Some(Change::VolumeInc(value)) => {
let mut vol = inner.channel_volume.unwrap();
// apply step to volumes
let step = (value * Volume::NORMAL.0 as f32).round() as i32;
if step > 0 {
vol.inc_clamp(Volume(step as u32), Volume::NORMAL);
} else {
vol.decrease(Volume(-step as u32));
}
// HACK: It would be better to only update the volume from feedback, but axis
// events fire fast and require the last set volume immediately for reference.
inner.channel_volume = Some(vol);
introspector.set_sink_volume_by_name("@DEFAULT_SINK@", &vol, None);
}
Some(Change::ToggleMute) => {
introspector.set_sink_mute_by_name("@DEFAULT_SINK@", !inner.mute, None);
}
None => (),
}
}),
);
loop {
match mainloop.iterate(true) {
IterateResult::Quit(_) | IterateResult::Err(_) => break,
_ => (),
}
}
// Need to keep the event source alive
_ = event_source;
Ok(())
}
fn start_monitor(events: Arc<Mutex<Events>>, inner: Arc<Mutex<InnerAudio>>, pipe: RawFd) {
thread::Builder::new()
.name("audiomon".to_string())
.spawn(move || monitor(events, inner, pipe).unwrap())
.unwrap();
}
enum Change {
Volume(f32),
VolumeInc(f32),
ToggleMute,
}
struct InnerAudio {
volume: f32,
channel_volume: Option<ChannelVolumes>,
mute: bool,
dirty: bool,
last_click: Option<Change>,
pipe: RawFd,
}
pub struct PulseAudio {
inner: Arc<Mutex<InnerAudio>>,
}
impl PulseAudio {
pub fn new(
events: Arc<Mutex<Events>>,
fm: &mut FontMap,
font: &'static str,
size: f32,
) -> BarWidget {
let (a, b) = pipe().unwrap();
let audio = PulseAudio {
inner: Arc::new(Mutex::new(InnerAudio {
volume: 0.0,
channel_volume: None,
mute: false,
dirty: false,
last_click: None,
pipe: b,
})),
};
start_monitor(events, audio.inner.clone(), a);
BarWidget::new(Box::new(audio), fm, font, size)
}
}
impl BarWidgetImpl for PulseAudio {
fn get_dirty(&self) -> bool {
self.inner.lock().unwrap().dirty
}
fn name(&self) -> &'static str {
"volume"
}
fn value(&mut self) -> f32 {
let mut inner = self.inner.lock().unwrap();
inner.dirty = false;
inner.volume
}
fn color(&self) -> Color {
match self.inner.lock().unwrap().mute {
true => Color::YELLOW,
false => Color::WHITE,
}
}
fn click(&mut self, pos: f32, btn: PointerButton) {
let mut inner = self.inner.lock().unwrap();
inner.last_click = match btn {
PointerButton::Left => Some(Change::Volume(pos)),
PointerButton::Right => Some(Change::ToggleMute),
PointerButton::ScrollVertical(val) => Some(Change::VolumeInc((val / 512.) as f32)),
PointerButton::ScrollHorizontal(val) => Some(Change::VolumeInc((val / 100.) as f32)),
_ => None,
};
_ = write(inner.pipe, &[0]);
}
}
+66
View File
@@ -0,0 +1,66 @@
use std::{
cmp::{max, min},
fmt,
};
use crate::{buffer::BufferView, event::Event, fonts::FontMap};
#[derive(Debug, Default, Clone, Copy)]
pub struct Geometry {
pub x: u32,
pub y: u32,
pub width: u32,
pub height: u32,
}
impl fmt::Display for Geometry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"(x: {}, y: {}, width: {}, height: {})",
self.x, self.y, self.width, self.height
)
}
}
impl Geometry {
pub fn new() -> Geometry {
Geometry {
x: 0,
y: 0,
width: 0,
height: 0,
}
}
pub fn expand(&self, other: Geometry) -> Geometry {
let x = min(self.x, other.x);
let y = min(self.y, other.y);
Geometry {
x,
y,
width: max(self.width + self.x, other.width + other.x) - x,
height: max(self.height + self.y, other.height + other.height) - y,
}
}
pub fn contains(&self, position: (u32, u32)) -> bool {
position.0 >= self.x
&& position.0 < self.x + self.width
&& position.1 >= self.y
&& position.1 < self.y + self.height
}
}
pub trait Widget {
fn get_dirty(&self) -> bool {
false
}
fn geometry(&self) -> Geometry;
fn geometry_update(&mut self, fonts: &mut FontMap, geometry: &Geometry) -> Geometry;
fn minimum_size(&mut self, _fonts: &mut FontMap) -> Geometry {
Default::default()
}
fn draw(&mut self, fonts: &mut FontMap, view: &mut BufferView) -> Geometry;
fn event(&mut self, _event: &Event) {}
}