Compare commits

...

12 Commits

Author SHA1 Message Date
0f72c41b42 listen to output events from the wlr protocol 2025-01-04 15:44:06 +00:00
5718d8d772 docs 2025-01-02 00:44:43 +00:00
778392f729 better error handling using Result instead of panic 2025-01-02 00:42:54 +00:00
6004c1a2d3 panic if trying to enable a closed monitor 2025-01-01 18:24:26 +00:00
818df0f7e8 support monitor lid option to disable closed monitors 2025-01-01 18:02:56 +00:00
20ec42d126 code format 2024-12-31 02:51:58 +00:00
c5f35ebf06 Use HashSet for available layout names to avoid monitor-layout dup 2024-12-31 02:46:35 +00:00
2ce2631bbc Add support for --automatic. 2024-12-31 02:41:53 +00:00
3c9324b63a KDL 6.1.0 2024-12-30 03:41:58 +00:00
6d859b8b9b separate sway module 2024-12-30 03:36:05 +00:00
bec2bdc8f9 separate config module 2024-12-30 03:30:08 +00:00
b8c38da85b separate to bin and lib 2024-12-30 03:26:20 +00:00
9 changed files with 1201 additions and 357 deletions

382
Cargo.lock generated
View File

@@ -2,6 +2,58 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "bitflags"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
[[package]]
name = "cc"
version = "1.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7"
dependencies = [
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "dlib"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412"
dependencies = [
"libloading",
]
[[package]]
name = "downcast-rs"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
[[package]]
name = "errno"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "itoa"
version = "1.0.14"
@@ -10,15 +62,44 @@ checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674"
[[package]]
name = "kdl"
version = "4.7.1"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e03e2e96c5926fe761088d66c8c2aee3a4352a2573f4eaca50043ad130af9117"
checksum = "a927c788db5413fbaced8fc5ac08a4a341c50766cba1d363ba3e25f3db343af0"
dependencies = [
"miette",
"nom",
"num",
"thiserror",
"winnow",
]
[[package]]
name = "libc"
version = "0.2.169"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
[[package]]
name = "libloading"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"
dependencies = [
"cfg-if",
"windows-targets",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
[[package]]
name = "log"
version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
[[package]]
name = "memchr"
version = "2.7.4"
@@ -27,21 +108,21 @@ checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "miette"
version = "5.10.0"
version = "7.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59bb584eaeeab6bd0226ccf3509a69d7936d148cf3d036ad350abe35e8c6856e"
checksum = "317f146e2eb7021892722af37cf1b971f0a70c8406f487e24952667616192c64"
dependencies = [
"cfg-if",
"miette-derive",
"once_cell",
"thiserror",
"unicode-width",
]
[[package]]
name = "miette-derive"
version = "5.10.0"
version = "7.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49e7bc1560b95a3c4a25d03de42fe76ca718ab92d1a22a55b9b4cf67b3ae635c"
checksum = "23c9b935fbe1d6cbd1dac857b54a688145e2d93f48db36010514d0f612d0ad67"
dependencies = [
"proc-macro2",
"quote",
@@ -49,26 +130,83 @@ dependencies = [
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
name = "num"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
dependencies = [
"memchr",
"minimal-lexical",
"num-bigint",
"num-complex",
"num-integer",
"num-iter",
"num-rational",
"num-traits",
]
[[package]]
name = "once_cell"
version = "1.20.2"
name = "num-bigint"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775"
checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "pkg-config"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2"
[[package]]
name = "proc-macro2"
@@ -79,6 +217,15 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "quick-xml"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7649a7b4df05aed9ea7ec6f628c67c9953a43869b8bc50929569b2999d443fe"
dependencies = [
"memchr",
]
[[package]]
name = "quote"
version = "1.0.37"
@@ -88,12 +235,31 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "rustix"
version = "0.38.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "ryu"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
[[package]]
name = "scoped-tls"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
[[package]]
name = "serde"
version = "1.0.216"
@@ -126,13 +292,28 @@ dependencies = [
"serde",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "smallvec"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
name = "swayout"
version = "1.0.0"
version = "1.2.2"
dependencies = [
"kdl",
"serde",
"serde_json",
"wayland-client",
"wayland-protocols",
"wayland-protocols-wlr",
"xdg",
]
@@ -179,6 +360,161 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]]
name = "wayland-backend"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "056535ced7a150d45159d3a8dc30f91a2e2d588ca0b23f70e56033622b8016f6"
dependencies = [
"cc",
"downcast-rs",
"rustix",
"scoped-tls",
"smallvec",
"wayland-sys",
]
[[package]]
name = "wayland-client"
version = "0.31.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66249d3fc69f76fd74c82cc319300faa554e9d865dab1f7cd66cc20db10b280"
dependencies = [
"bitflags",
"rustix",
"wayland-backend",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols"
version = "0.32.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd0ade57c4e6e9a8952741325c30bf82f4246885dca8bf561898b86d0c1f58e"
dependencies = [
"bitflags",
"wayland-backend",
"wayland-client",
"wayland-scanner",
]
[[package]]
name = "wayland-protocols-wlr"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "782e12f6cd923c3c316130d56205ebab53f55d6666b7faddfad36cecaeeb4022"
dependencies = [
"bitflags",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-scanner",
]
[[package]]
name = "wayland-scanner"
version = "0.31.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597f2001b2e5fc1121e3d5b9791d3e78f05ba6bfa4641053846248e3a13661c3"
dependencies = [
"proc-macro2",
"quick-xml",
"quote",
]
[[package]]
name = "wayland-sys"
version = "0.31.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efa8ac0d8e8ed3e3b5c9fc92c7881406a268e11555abe36493efabe649a29e09"
dependencies = [
"dlib",
"log",
"pkg-config",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.6.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b"
dependencies = [
"memchr",
]
[[package]]
name = "xdg"
version = "2.5.2"

View File

@@ -1,6 +1,6 @@
[package]
name = "swayout"
version = "1.0.0"
version = "1.2.2"
edition = "2021"
description = "A tool to configure sway outputs"
authors = ["Stephen Byrne"]
@@ -13,6 +13,10 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.133"
# for config file
kdl = "4.7.1"
kdl = "6.1.0"
xdg = "2.5.2"
xdg = "2.5.2"
wayland-client = "0.31.7"
wayland-protocols = { version = "0.32.5" , features = ["client", "unstable"] }
wayland-protocols-wlr = { version = "0.3.5", features = ["client"] }

View File

@@ -12,7 +12,7 @@ Example `config.kdl`:
```kdl
// This is my laptop's built-in screen.
monitor "laptop" make="Unknown" model="0x403D" serial="0x00000000"
monitor "laptop" make="Unknown" model="0x403D" serial="0x00000000" lid="LID"
// I usually have it hooked up to this monitor, which is the top one on my desk.
monitor "top" make="Dell Inc." model="DELL U2415" serial="CFV9N99T0Y0U"
@@ -23,7 +23,7 @@ monitor "left" make="Goldstar Company Ltd" model="LG HDR 4K" serial="0x0000B9C0"
monitor "right" make="Goldstar Company Ltd" model="LG HDR 4K" serial="0x0000B9BF"
// When I have "left" and "right" hooked up, I want this layout.
layout "two4k" {
layout "two4k" automatic=#true {
output "left" mode="3840x2160" scale="1.5" x=0 y=0 transform="270"
output "right" mode="3840x2160" scale="1.5" x=1440 y=1120 transform="normal"
}
@@ -35,6 +35,9 @@ Printed layouts include:
* All layouts defined in `config.kdl` for which the monitors are currently available. E.g.: `two4k`.
* All monitors defined in `config.kdl` that are currently available. E.g.: `laptop`, `left`, `right`.
* All available outputs that are not matched by a configured monitor. E.g.: `HDMI-2`.
If a monitor has its `lid` property is set to the name of a directory in `/proc/acpi/button/lid/`, if the `state` file
in that directory indicates that the lid is closed, the monitor will not be considered available.
If you pass a layout name (or monitor name, or output name) as a command line argument to `swayout`,
it calls `swaymsg` to configure that layout.
@@ -48,16 +51,12 @@ set $select_layout swayout | tofi | xargs swayout
bindsym $mod+Shift+m exec $select_layout
```
## TODO
Things I might do someday:
### Automatic
Add a `automatic` option to layouts and an `--automatic` flag to `swayout`, and have it automatically enable the
first layout with `automatic=true` for which all outputs are available.
If `swayout` is called with the `--automatic` switch, the first layout with `automatic=#true` for which all outputs
are available is enabled. If no automatic layouts are available, `swayout` exits with code 2.
This could be run by `bindswitch lid:toggle exec swayout --automatic`.
## TODO
How to call when an output is connected or disconnected?
Wayland events via [wayland_client](https://docs.rs/wayland-client/latest/wayland_client/index.html)?

119
src/config.rs Normal file
View File

@@ -0,0 +1,119 @@
use kdl::KdlDocument;
use std::collections::HashMap;
use std::fs;
/// Configuration for swayout.
pub struct Config {
/// Monitor name is independent of output name. It can be anything.
pub monitors: Vec<Monitor>,
/// Definition of layouts: a map of the layout name to the outputs.
/// The outputs is a map of the monitor name (in `monitors`) to the configuration
/// of that monitor for this layout.
/// Available outputs that do not match a monitor in the map are disabled.
pub layouts: Vec<Layout>,
}
/// A configured layout
pub struct Layout {
/// Layout name
pub name: String,
/// If true, automatically enableable
pub automatic: bool,
/// Map of monitor name to OutputConfig
pub outputs: HashMap<String, OutputConfig>,
}
/// Defines a monitor by make, model, and serial.
pub struct Monitor {
pub name: String,
pub make: String,
pub model: String,
pub serial: String,
pub lid: Option<String>,
}
/// Configuration for an enabled output.
pub struct OutputConfig {
/// mode. See man 5 sway-output
pub mode: String,
/// scale. See man 5 sway-output
pub scale: String,
/// x value for position. See man 5 sway-output
pub x: u16,
/// y value for position. See man 5 sway-output
pub y: u16,
/// transform. See man 5 sway-output
pub transform: String,
}
/// Get a `Config` from ~/.config/swayout/config.kdl.
/// (It really uses XDG config dirs.)
pub fn get_config() -> Config {
let xdg_dirs = xdg::BaseDirectories::with_prefix("swayout").unwrap();
if let Some(path) = xdg_dirs.find_config_file("config.kdl") {
let kdl = fs::read_to_string(path).expect("error reading file");
parse_config(kdl)
} else {
// no config files, use an empty rules
Config {
monitors: Vec::new(),
layouts: Vec::new(),
}
}
}
fn parse_config(kdl: String) -> Config {
let doc: KdlDocument = kdl.parse().expect("failed to parse config KDL");
let monitors: Vec<Monitor> = doc
.nodes()
.iter()
.filter(|node| node.name().value() == "monitor")
.map(|monitor_node| Monitor {
name: String::from(monitor_node[0].as_string().unwrap()),
make: String::from(monitor_node["make"].as_string().unwrap()),
model: String::from(monitor_node["model"].as_string().unwrap()),
serial: String::from(monitor_node["serial"].as_string().unwrap()),
lid: if let Some(lid) = monitor_node.get("lid") {
Some(String::from(lid.as_string().unwrap()))
} else {
None
},
})
.collect();
let layouts: Vec<Layout> = doc
.nodes()
.iter()
.filter(|node| node.name().value() == "layout")
.map(|layout_node| {
let name = String::from(layout_node[0].as_string().unwrap());
let automatic = layout_node
.get("automatic")
.is_some_and(|v| v.as_bool().is_some_and(|a| a));
let outputs: HashMap<String, OutputConfig> = layout_node
.children()
.unwrap()
.nodes()
.iter()
.map(|output_node| {
let output = String::from(output_node[0].as_string().unwrap());
let output_config = OutputConfig {
mode: String::from(output_node["mode"].as_string().unwrap()),
scale: String::from(output_node["scale"].as_string().unwrap()),
transform: String::from(output_node["transform"].as_string().unwrap()),
x: output_node["x"].as_integer().unwrap() as u16,
y: output_node["y"].as_integer().unwrap() as u16,
};
(output, output_config)
})
.collect();
Layout {
name,
automatic,
outputs,
}
})
.collect();
Config { monitors, layouts }
}

248
src/lib.rs Normal file
View File

@@ -0,0 +1,248 @@
use std::collections::{HashMap, HashSet};
mod config;
use crate::config::{get_config, Config, Layout, Monitor, OutputConfig};
mod lid;
use crate::lid::is_lid_closed;
mod sway;
use crate::sway::{apply_outputs, get_outputs, Output};
mod listen;
/// Determine the available layout names.
/// Return one layout for each layout defined in the configuration file
/// for which all outputs are available (and lids are not closed),
/// one for each monitor defined in the configuration file (for using just that monitor) if the lid is not closed,
/// and one for each available output that is not a configured monitor (for using just that output).
fn get_layouts() -> HashSet<String> {
let outputs = get_outputs();
let config = get_config();
let monitor_states = get_monitor_states(&config, &outputs);
let mut layout_names: HashSet<String> = HashSet::new();
// Add each layout defined in the config file for which all outputs are available
get_available_layouts(&config, &monitor_states)
.iter()
.for_each(|layout| {
layout_names.insert(String::from(&layout.name));
});
// add each individual output (by monitor name if the monitor is defined, else by output name)
outputs.iter().for_each(|output| {
// if there is a monitor for the output, use the monitor name, else use the output name
if let Some(monitor_state) = get_monitor_state_for_output(&monitor_states, &output) {
// do not include it if the lid is closed
if !monitor_state.is_lid_closed {
layout_names.insert(String::from(&monitor_state.monitor.name));
}
} else {
layout_names.insert(String::from(&output.name));
}
});
layout_names
}
/// Monitor and lid state. Created for available monitors.
struct MonitorState<'a> {
monitor: &'a Monitor,
is_lid_closed: bool,
}
/// Get a MonitorState for each monitor that is available (matches an output).
fn get_monitor_states<'a, 'b>(
config: &'a Config,
outputs: &'b Vec<Output>,
) -> Vec<MonitorState<'a>> {
config
.monitors
.iter()
.filter(|monitor| {
outputs
.iter()
.any(|output| monitor_matches_output(&monitor, &output))
})
.map(|monitor| MonitorState {
monitor,
is_lid_closed: is_lid_closed(&monitor),
})
.collect()
}
/// Find a monitor state that matches the supplied output.
fn get_monitor_state_for_output<'a, 'b>(
monitor_states: &'a Vec<MonitorState<'a>>,
output: &'b &Output,
) -> Option<&'a MonitorState<'a>> {
monitor_states
.iter()
.find(|monitor_state| monitor_matches_output(monitor_state.monitor, output))
}
/// Determine if the specified monitor matches the specified output (by make/model/serial).
fn monitor_matches_output(monitor: &Monitor, output: &Output) -> bool {
monitor.make == output.make && monitor.model == output.model && monitor.serial == output.serial
}
/// Find a monitor state by monitor name.
fn get_monitor_state_by_name<'a, 'b>(
monitor_states: &'a Vec<MonitorState<'a>>,
monitor_name: &'b String,
) -> Option<&'a MonitorState<'a>> {
monitor_states
.iter()
.find(|monitor_state| &monitor_state.monitor.name == monitor_name)
}
/// Determine if the specified monitor name is available:
/// if it is one of the known monitors and the lid is not closed.
fn is_monitor_available<'a, 'b>(
monitor_states: &'a Vec<MonitorState<'a>>,
monitor_name: &'b String,
) -> bool {
if let Some(monitor_state) = get_monitor_state_by_name(&monitor_states, monitor_name) {
!monitor_state.is_lid_closed
} else {
false
}
}
/// Get the layouts for which all monitors are available and lids are not closed.
fn get_available_layouts<'a, 'b, 'c>(
config: &'a Config,
monitor_states: &'a Vec<MonitorState<'a>>,
) -> Vec<&'a Layout> {
config
.layouts
.iter()
.filter(|layout| {
layout.outputs.iter().all(|(monitor_name, _output_config)| {
is_monitor_available(monitor_states, monitor_name)
})
})
.collect()
}
/// Print the name of each layout to standard out, one per line
pub fn print_layout_names() {
get_layouts().iter().for_each(|layout| println!("{layout}"))
}
/// Apply the specified layout.
/// layout_name may be the name of a layout in the config, the name of a monitor,
/// or the name of an output.
/// Return true of any outputs were enabled.
/// Return false if there were no outputs to enable and thus nothing was done.
pub fn apply_layout(layout_name: &String) -> Result<(), String> {
let config = get_config();
let outputs = get_outputs();
let monitor_states = get_monitor_states(&config, &outputs);
// Map of output name to config for all outputs to enable.
// (All outputs not in this map will be disabled.)
let mut output_config_map: HashMap<&String, &OutputConfig> = HashMap::new();
// First check if the layout is defined in the rules
if let Some(layout) = config
.layouts
.iter()
.find(|layout| &layout.name == layout_name)
{
// The layout is defined in the config.
for (monitor_name, output_config) in &layout.outputs {
// there is probably a syntactic sugar for this?
let monitor_state = if let Some(monitor_state) =
get_monitor_state_by_name(&monitor_states, &monitor_name)
{
monitor_state
} else {
return Err(format!(
"Cannot find monitor '{}' for layout '{}'",
monitor_name, layout_name
));
};
if monitor_state.is_lid_closed {
return Err(format!("Monitor '{}' is closed.", monitor_name));
}
// find the output for the monitor to get the output name.
let output_opt = outputs
.iter()
.find(|output| monitor_matches_output(monitor_state.monitor, output));
if let Some(output) = output_opt {
output_config_map.insert(&output.name, &output_config);
} else {
return Err(format!("Missing output for monitor '{}'.", monitor_name));
}
}
} else {
// The layout is not defined in the rules.
// See if it is a monitor name...
if let Some(monitor_state) = get_monitor_state_by_name(&monitor_states, &layout_name) {
if monitor_state.is_lid_closed {
return Err(format!(
"Monitor '{}' is closed.",
&monitor_state.monitor.name
));
}
// It is a monitor name. Find the matching output...
if let Some(output) = outputs
.iter()
.find(|output| monitor_matches_output(monitor_state.monitor, output))
{
output_config_map.insert(&output.name, &output.output_config);
} else {
return Err(format!(
"Could not find output for monitor '{}'.",
layout_name
));
}
} else {
// See if it is an output name...
if let Some(output) = outputs.iter().find(|output| &output.name == layout_name) {
output_config_map.insert(&output.name, &output.output_config);
} else {
return Err(format!(
"Could not find layout, monitor, or output '{}.'",
layout_name
));
}
}
}
if output_config_map.is_empty() {
return Err("No outputs would be enabled. Do nothing.".to_string());
}
apply_outputs(&outputs, &output_config_map)
}
/// Apply the first automatic layout for which all outputs are available.
/// Return the name of the layout applied or None if no automatic layout was available.
pub fn apply_automatic() -> Result<String,String> {
let outputs = get_outputs();
let config = get_config();
let monitor_states = get_monitor_states(&config, &outputs);
if let Some(layout) = get_available_layouts(&config, &monitor_states)
.iter()
.find(|layout| layout.automatic)
{
apply_layout(&layout.name)?;
Ok(String::from(&layout.name))
} else {
Err("No automatic layouts available.".to_string())
}
}
pub fn listen() {
listen::listen()
}

48
src/lid.rs Normal file
View File

@@ -0,0 +1,48 @@
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use crate::config::Monitor;
// Determine if the lid id closed.
// Returns true if the lid is known to be closed.
// Returns false if the lid is known to be open, or if the lid state is not known.
pub fn is_lid_closed(monitor: &Monitor) -> bool {
if let Some(lid) = &monitor.lid {
is_acpi_closed(lid)
} else {
false
}
}
/// Determine if the lid is closed.
/// lid is the name of a directory in /proc/acpi/button/lid/.
fn is_acpi_closed(lid: &String) -> bool {
let mut path_buf = PathBuf::from("/proc/acpi/button/lid");
path_buf.push(&lid);
path_buf.push("state");
if let Ok(ok) = path_buf.try_exists() {
if ok {
File::open(path_buf).is_ok_and(|mut file| {
let mut str = String::new();
if let Ok(_size) = file.read_to_string(&mut str) {
is_state_closed(str)
} else {
// error reading file
false
}
})
} else {
// no file
false
}
} else {
// error checking for file
false
}
}
/// Parse a /proc/acpi/button/lid/*/state file and return true if the lid is closed
fn is_state_closed(str:String) -> bool {
str.contains("closed")
}

261
src/listen.rs Normal file
View File

@@ -0,0 +1,261 @@
use wayland_client::{event_created_child, protocol::wl_registry, Connection, Dispatch, QueueHandle};
use wayland_client::protocol::wl_output::Transform;
use wayland_protocols_wlr::output_management::v1::client::zwlr_output_head_v1::{AdaptiveSyncState, ZwlrOutputHeadV1};
use wayland_protocols_wlr::output_management::v1::client::zwlr_output_manager_v1;
use wayland_protocols_wlr::output_management::v1::client::zwlr_output_manager_v1::ZwlrOutputManagerV1;
use wayland_protocols_wlr::output_management::v1::client::zwlr_output_head_v1::Event as HeadEvent;
use wayland_protocols_wlr::output_management::v1::client::zwlr_output_mode_v1::Event as ModeEvent;
use wayland_protocols_wlr::output_management::v1::client::zwlr_output_mode_v1::ZwlrOutputModeV1;
// The state of this app.
struct AppState {
output_names: Vec<String>,
}
impl AppState {
fn reset(&mut self) {
self.output_names.clear()
}
fn add_output(&mut self, output_name:String) {
self.output_names.push(output_name)
}
}
// When we get the global registry event, use the registry to bind the ZwlrOutputManagerV1 to get output events
impl Dispatch<wl_registry::WlRegistry, ()> for AppState {
fn event(
_state: &mut Self,
registry: &wl_registry::WlRegistry,
event: wl_registry::Event,
_data: &(),
_conn: &Connection,
qh: &QueueHandle<AppState>,
) {
// When receiving events from the wl_registry, we are only interested in the
// `global` event, which signals a new available global.
// When receiving this event, we just print its characteristics in this example.
if let wl_registry::Event::Global { name, interface, version } = event {
//println!("[{}] {} (v{})", name, interface, version);
match interface.as_str() {
"zwlr_output_manager_v1" => {
println!("found output manager");
registry.bind::<ZwlrOutputManagerV1, _, _>(name, version, qh, ());
}
_ => {}
}
}
}
}
// Handle ZwlrOutputManagerV1 events
impl Dispatch<ZwlrOutputManagerV1, ()> for AppState {
event_created_child!(AppState, ZwlrOutputManagerV1, [
0 => (ZwlrOutputHeadV1, ()) // How did I know that 0 was for ZwlrOutputHeadV1?
]);
fn event(
state: &mut Self,
_: &ZwlrOutputManagerV1,
event: zwlr_output_manager_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<AppState>,
) {
match event {
zwlr_output_manager_v1::Event::Head { head } => {
println!("-=-= Head")
}
zwlr_output_manager_v1::Event::Finished => {
println!("-=-= Finished")
}
zwlr_output_manager_v1::Event::Done { serial } => {
print!("-=-= Done. Output names({}): ", &state.output_names.len());
for output_name in &state.output_names {
print!("{},", output_name);
}
println!(".");
}
_ => {}
}
}
}
impl Dispatch<ZwlrOutputHeadV1, ()> for AppState {
event_created_child!(AppState, ZwlrOutputManagerV1, [
3 => (ZwlrOutputModeV1, ()) // How did I know that 3 is ZwlrOutputModeV1?
]);
fn event(
state: &mut Self,
_: &ZwlrOutputHeadV1,
event: HeadEvent,
_: &(),
_: &Connection,
_: &QueueHandle<AppState>,
) {
//println!("headv1 op:{}", event.opcode());
match event {
HeadEvent::Name { name } => {
println!("name: {}", &name);
state.add_output(name);
}
HeadEvent::Description { description} => {
// HeadEvent.Description is "<make> <model> <serial> (<name>)"
println!("description: {}", description)
}
HeadEvent::PhysicalSize { width, height } => {
println!("size: {}x{}", width, height)
}
HeadEvent::Mode { mode } => {
//println!("mode")
}
HeadEvent::Enabled { enabled} => {
println!("enabled: {}", enabled)
}
HeadEvent::CurrentMode { mode } => {
println!("mode...");
}
HeadEvent::Position { x, y } => {
println!("position: {},{}", x, y)
}
HeadEvent::Transform { transform } => {
let mut s = String::new();
match transform.into_result() {
Ok(t) => {
s.push_str(
match t {
Transform::Normal => { "normal" }
Transform::_90 => { "90" }
Transform::_180 => { "180" }
Transform::_270 => { "270" }
Transform::Flipped => { "flipped" }
Transform::Flipped90 => { "flipped90" }
Transform::Flipped180 => { "flipped180" }
Transform::Flipped270 => { "flipped270" }
_ => { "wat?" }
}
)
}
Err(e) => {
s.push_str(e.to_string().as_str())
}
};
println!("transform: {}", s)
}
HeadEvent::Scale { scale } => {
println!("scale: {}", scale)
}
HeadEvent::Finished => {
// This happens when something is disconnected
println!("finished")
}
// I never get Make
HeadEvent::Make { make } => {
println!("make: {}", make)
}
// I never get Model
HeadEvent::Model { model } => {
println!("model: {}", model)
}
// I never get SerialNumber
HeadEvent::SerialNumber { serial_number } => {
println!("serial: {}", serial_number)
}
HeadEvent::AdaptiveSync { state } => {
let mut s = String::new();
match state.into_result() {
Ok(st) => {
s.push_str(
match st {
AdaptiveSyncState::Disabled => { "disabled" }
AdaptiveSyncState::Enabled => { "enabled" }
_ => { "wat?" }
}
)
}
Err(e) => {
s.push_str(e.to_string().as_str())
}
};
println!("adaptive sync: {}", s)
}
_ => {
println!("head unhandled {}", event.opcode())
}
}
}
}
impl Dispatch<ZwlrOutputModeV1, ()> for AppState {
fn event(
_state: &mut Self,
_: &ZwlrOutputModeV1,
event: ModeEvent,
_: &(),
_: &Connection,
_: &QueueHandle<AppState>,
) {
match event {
ModeEvent::Size { width, height } => {
//println!("mode size: {}x{}", width, height)
}
ModeEvent::Refresh { refresh } => {
//println!("mode refresh: {}", refresh)
}
ModeEvent::Preferred => {
//println!("mode preferred")
}
ModeEvent::Finished => {
//println!("mode finished")
}
_ => {
println!("mode unhandled {}", event.opcode())
}
}
}
}
// The main function of our program
pub fn listen() {
// Create a Wayland connection by connecting to the server through the
// environment-provided configuration.
let conn = Connection::connect_to_env().unwrap();
// Retrieve the WlDisplay Wayland object from the connection. This object is
// the starting point of any Wayland program, from which all other objects will
// be created.
let display = conn.display();
// Create an event queue for our event processing
let mut event_queue = conn.new_event_queue();
// And get its handle to associate new objects to it
let qh = event_queue.handle();
// Create a wl_registry object by sending the wl_display.get_registry request.
// This method takes two arguments: a handle to the queue that the newly created
// wl_registry will be assigned to, and the user-data that should be associated
// with this registry (here it is () as we don't need user-data).
let _registry = display.get_registry(&qh, ());
// At this point everything is ready, and we just need to wait to receive the events
// from the wl_registry. Our callback will print the advertised globals.
println!("Advertised globals:");
// To actually receive the events, we invoke the `roundtrip` method. This method
// is special and you will generally only invoke it during the setup of your program:
// it will block until the server has received and processed all the messages you've
// sent up to now.
//
// In our case, that means it'll block until the server has received our
// wl_display.get_registry request, and as a reaction has sent us a batch of
// wl_registry.global events.
//
// `roundtrip` will then empty the internal buffer of the queue it has been invoked
// on, and thus invoke our `Dispatch` implementation that prints the list of advertised
// globals.
let mut state = AppState { output_names : Vec::new() };
event_queue.roundtrip(&mut state).unwrap();
loop {
event_queue.blocking_dispatch(&mut state).unwrap();
}
}

View File

@@ -1,332 +1,36 @@
use kdl::KdlDocument;
use serde_json::{from_str, Value};
use std::collections::HashMap;
use std::env;
use std::process::Command;
use std::{fs, str};
/// Configuration for swayout.
struct Config {
/// Monitor name is independent of output name. It can be anything.
monitors: HashMap<String, Monitor>,
/// Definition of layouts: a map of the layout name to the outputs.
/// The outputs is a map of the monitor name (in `monitors`) to the configuration
/// of that monitor for this layout.
/// Available outputs that do not match a monitor in the map are disabled.
layouts: HashMap<String, HashMap<String, OutputConfig>>,
}
/// Defines a monitor by make, model, and serial.
struct Monitor {
make: String,
model: String,
serial: String,
}
/// Configuration for an enabled output.
struct OutputConfig {
/// mode. See man 5 sway-output
mode: String,
/// scale. See man 5 sway-output
scale: String,
/// x value for position. See man 5 sway-output
x: u16,
/// y value for position. See man 5 sway-output
y: u16,
/// transform. See man 5 sway-output
transform: String,
}
/// An output, as returned by `swaymsg -t get_outputs`.
struct Output {
/// output name, according to sway
name: String,
make: String,
model: String,
serial: String,
output_config: OutputConfig,
}
use std::{env, process};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() == 1 {
// first arg is executable
print_layout_names();
swayout::print_layout_names();
} else if args.len() == 2 {
apply_layout(&args[1]);
} else {
panic!("Usage: {} [layout]", args[0].as_str());
}
}
/// Get all outputs currently available, according to `swaymsg -t get_outputs`.
fn get_outputs() -> Vec<Output> {
let output = Command::new("swaymsg")
.arg("-t")
.arg("get_outputs")
.output()
.expect("swaymsg -t get_outputs failed");
let json_string = str::from_utf8(&output.stdout).unwrap();
let json = from_str(json_string).unwrap();
if let Value::Array(outputs) = json {
outputs
.iter()
.map(|output_json| Output {
name: String::from(output_json["name"].as_str().unwrap()),
make: String::from(output_json["make"].as_str().unwrap()),
model: String::from(output_json["model"].as_str().unwrap()),
serial: String::from(output_json["serial"].as_str().unwrap()),
output_config: OutputConfig {
mode: get_mode(output_json),
scale: String::from("1.0"),
x: 0,
y: 0,
transform: String::from("normal"),
},
})
.collect()
} else {
panic!("outputs json was not an array");
}
}
/// Parse the mode from the output JSON into a string suitable for the mode param for sway-output.
/// This will go into `OutputConfig.mode`.
fn get_mode(output: &Value) -> String {
if let Value::Array(modes) = &output["modes"] {
if let Some(mode) = modes.first() {
let width = mode["width"].as_i64().unwrap().to_string();
let height = mode["height"].as_i64().unwrap().to_string();
let mut out: String = String::new();
out.push_str(&width);
out.push_str("x");
out.push_str(&height);
out
} else {
panic!("no modes")
}
} else {
panic!("modes not an array")
}
}
/// Get a `Config` from ~/.config/swayout/config.kdl.
/// (It really uses XDG config dirs.)
fn get_config() -> Config {
let xdg_dirs = xdg::BaseDirectories::with_prefix("swayout").unwrap();
if let Some(path) = xdg_dirs.find_config_file("config.kdl") {
let kdl = fs::read_to_string(path).expect("error reading file");
parse_config(kdl)
} else {
// no config files, use an empty rules
Config {
monitors: HashMap::new(),
layouts: HashMap::new(),
}
}
}
fn parse_config(kdl:String) -> Config {
let doc:KdlDocument = kdl.parse().expect("failed to parse config KDL");
let monitors:HashMap<String,Monitor> = doc.nodes().iter()
.filter(|node| node.name().value() == "monitor")
.map(|monitor_node| {
let name = String::from(monitor_node[0].as_string().unwrap());
let monitor = Monitor {
make : String::from(monitor_node["make"].as_string().unwrap()),
model : String::from(monitor_node["model"].as_string().unwrap()),
serial : String::from(monitor_node["serial"].as_string().unwrap()),
};
(name, monitor)
})
.collect();
let layouts:HashMap<String,HashMap<String,OutputConfig>> = doc.nodes().iter()
.filter(|node| node.name().value() == "layout")
.map(|layout_node| {
let layout_name = String::from(layout_node[0].as_string().unwrap());
let monitor_name_to_output_config:HashMap<String,OutputConfig> = layout_node
.children().unwrap().nodes().iter()
.map(|output_node| {
let output = String::from(output_node[0].as_string().unwrap());
let output_config = OutputConfig {
mode : String::from(output_node["mode"].as_string().unwrap()),
scale : String::from(output_node["scale"].as_string().unwrap()),
transform : String::from(output_node["transform"].as_string().unwrap()),
x : output_node["x"].as_i64().unwrap() as u16,
y : output_node["y"].as_i64().unwrap() as u16,
};
(output, output_config)
})
.collect();
(layout_name,monitor_name_to_output_config)
})
.collect();
Config { monitors, layouts }
}
/// Determine the available layout names.
/// Return one layout for each layout defined in the configuration file
/// for which all outputs are available,
/// one for each monitor defined in the configuration file (for using just that monitor),
/// and one for each available output that is not a configured monitor (for using just that output).
fn get_layouts() -> Vec<String> {
let available_outputs = get_outputs();
let config = get_config();
// Get the names of monitors that are available (that match an available output)
let available_monitor_names:Vec<&String> = config.monitors.iter()
.filter(|(_monitor_name,monitor)|
available_outputs.iter().any(|output|
monitor.make == output.make
&& monitor.model == output.model
&& output.serial == monitor.serial
)
)
.map(|(monitor_name,_monitor)| monitor_name)
.collect();
let mut layout_names: Vec<String> = Vec::new();
// Add each layout defined in the config file for which all outputs are available
config.layouts.iter().for_each(|(layout_name, layout)| {
if layout
.iter()
.all(|(output_name, _output)| available_monitor_names.contains(&output_name))
{
layout_names.push(String::from(layout_name))
}
});
// add each individual output (by monitor name if the monitor is defined, else by output name)
available_outputs.iter().for_each(|output| {
// if there is a monitor for the output, use the monitor name, else use the output name
let monitor_opt = config.monitors.iter()
.find(|(_monitor_name, monitor)| {
monitor.make == output.make
&& monitor.model == output.model
&& monitor.serial == output.serial
});
if let Some((monitor_name, _monitor)) = monitor_opt {
layout_names.push(String::from(monitor_name));
} else {
layout_names.push(String::from(&output.name));
}
});
layout_names
}
/// Print the name of each layout to standard out, one per line
fn print_layout_names() {
get_layouts().iter().for_each(|layout| println!("{layout}"))
}
/// Apply the specified layout.
/// layout_name may be the name of a layout in the config, the name of a monitor,
/// or the name of an output.
fn apply_layout(layout_name: &String) {
let rules = get_config();
let outputs = get_outputs();
// Map of output name to config for all outputs to enable.
// (All outputs not in this map will be disabled.)
let mut output_config_map: HashMap<&String, &OutputConfig> = HashMap::new();
// First check if the layout is defined in the rules
let opt_layout = rules.layouts.get(layout_name);
if let Some(layout) = opt_layout {
// The layout is defined in the rules.
layout.iter().for_each(|(monitor_name, output_config)| {
let monitor = &rules.monitors[monitor_name];
// find the output for the monitor to get the output name.
let output_opt = outputs.iter().find(|output| {
output.make == monitor.make
&& output.model == monitor.model
&& output.serial == monitor.serial
});
if let Some(output) = output_opt {
output_config_map.insert(&output.name, &output_config);
} else {
panic!("Missing output for monitor {monitor_name}");
let arg = args[1].as_str();
match arg {
"--automatic" => {
match swayout::apply_automatic() {
Ok(layout_name) => {
println!("{}", layout_name);
}
Err(e) => {
eprintln!("{}", e);
process::exit(2)
}
}
},
"--listen" => {
swayout::listen()
}
});
} else {
// The layout is not defined in the rules.
// See if it is a monitor name...
if let Some(monitor) = rules.monitors.get(layout_name) {
// It is a monitor name. Find the matching output...
if let Some(output) = outputs.iter().find(|output| {
output.make == monitor.make && output.model == monitor.model
&& output.serial == monitor.serial
}) {
output_config_map.insert(&output.name, &output.output_config);
} else {
panic!("could not find output for monitor {layout_name}")
}
} else {
// See if it is an output name...
if let Some(output) = outputs.iter()
.find(|output| &output.name == layout_name) {
output_config_map.insert(&output.name, &output.output_config);
} else {
panic!("could not find layout, monitor, or output {layout_name}")
_ => {
if let Err(e) = swayout::apply_layout(&args[1]) {
eprintln!("{}", e);
process::exit(3)
}
}
}
} else {
eprintln!("Usage: {} [layout]", args[0].as_str());
process::exit(1)
}
apply_outputs(&outputs, &output_config_map);
}
/// Apply the specified outputs. Enable all outputs in [outputs], disable others.
fn apply_outputs(all_outputs: &Vec<Output>, outputs: &HashMap<&String, &OutputConfig>) {
// set enabled outputs first, then set disabled outputs.
// That way if some work before an error, you have at least one output enabled.
// for outputs to be enabled: map of output name to config
let mut enabled: HashMap<&String,&OutputConfig> = HashMap::new();
// for outputs to be disabled: output names
let mut disabled: Vec<&String> = Vec::new();
all_outputs.iter().for_each(|output| {
if let Some(output_config) = outputs.get(&output.name) {
enabled.insert(&output.name, &output_config);
} else {
disabled.push(&output.name);
}
});
let mut cmd = Command::new("swaymsg");
enabled.iter().for_each(|(output_name,output_config)| {
cmd.arg("output");
cmd.arg(&output_name);
cmd.arg("enable");
cmd.arg("mode");
cmd.arg(&output_config.mode);
cmd.arg("scale");
cmd.arg(&output_config.scale);
cmd.arg("pos");
cmd.arg(&output_config.x.to_string());
cmd.arg(&output_config.y.to_string());
cmd.arg("transform");
cmd.arg(&output_config.transform);
cmd.arg(",");
});
disabled.iter().for_each(|output_name| {
cmd.arg("output");
cmd.arg(&output_name);
cmd.arg("disable");
cmd.arg(",");
});
// print what we are about to do.
cmd.get_args()
.for_each(|arg| print!("{} ", arg.to_str().unwrap()));
cmd.output().expect("swaymsg output failed");
}

125
src/sway.rs Normal file
View File

@@ -0,0 +1,125 @@
use crate::config::OutputConfig;
use serde_json::{from_str, Value};
use std::collections::HashMap;
use std::process::Command;
use std::str::from_utf8;
/// An output, as returned by `swaymsg -t get_outputs`.
pub struct Output {
/// output name, according to sway
pub name: String,
pub make: String,
pub model: String,
pub serial: String,
pub output_config: OutputConfig,
}
/// Get all outputs currently available, according to `swaymsg -t get_outputs`.
pub fn get_outputs() -> Vec<Output> {
let output = Command::new("swaymsg")
.arg("-t")
.arg("get_outputs")
.output()
.expect("swaymsg -t get_outputs failed");
let json_string = from_utf8(&output.stdout).unwrap();
let json = from_str(json_string).unwrap();
if let Value::Array(outputs) = json {
outputs
.iter()
.map(|output_json| Output {
name: String::from(output_json["name"].as_str().unwrap()),
make: String::from(output_json["make"].as_str().unwrap()),
model: String::from(output_json["model"].as_str().unwrap()),
serial: String::from(output_json["serial"].as_str().unwrap()),
output_config: OutputConfig {
mode: get_mode(output_json),
scale: String::from("1.0"),
x: 0,
y: 0,
transform: String::from("normal"),
},
})
.collect()
} else {
panic!("outputs json was not an array");
}
}
/// Parse the mode from the output JSON into a string suitable for the mode param for sway-output.
/// This will go into `OutputConfig.mode`.
fn get_mode(output: &Value) -> String {
if let Value::Array(modes) = &output["modes"] {
if let Some(mode) = modes.first() {
let width = mode["width"].as_i64().unwrap().to_string();
let height = mode["height"].as_i64().unwrap().to_string();
let mut out: String = String::new();
out.push_str(&width);
out.push_str("x");
out.push_str(&height);
out
} else {
panic!("no modes")
}
} else {
panic!("modes not an array")
}
}
/// Apply the specified outputs. Enable all outputs in [outputs], disable others.
pub fn apply_outputs(
all_outputs: &Vec<Output>,
outputs: &HashMap<&String, &OutputConfig>,
) -> Result<(), String> {
// set enabled outputs first, then set disabled outputs.
// That way if some work before an error, you have at least one output enabled.
// for outputs to be enabled: map of output name to config
let mut enabled: HashMap<&String, &OutputConfig> = HashMap::new();
// for outputs to be disabled: output names
let mut disabled: Vec<&String> = Vec::new();
all_outputs.iter().for_each(|output| {
if let Some(output_config) = outputs.get(&output.name) {
enabled.insert(&output.name, &output_config);
} else {
disabled.push(&output.name);
}
});
if enabled.is_empty() {
return Err("No enabled outputs!".to_string());
}
let mut cmd = Command::new("swaymsg");
enabled.iter().for_each(|(output_name, output_config)| {
cmd.arg("output");
cmd.arg(&output_name);
cmd.arg("enable");
cmd.arg("mode");
cmd.arg(&output_config.mode);
cmd.arg("scale");
cmd.arg(&output_config.scale);
cmd.arg("pos");
cmd.arg(&output_config.x.to_string());
cmd.arg(&output_config.y.to_string());
cmd.arg("transform");
cmd.arg(&output_config.transform);
cmd.arg(",");
});
disabled.iter().for_each(|output_name| {
cmd.arg("output");
cmd.arg(&output_name);
cmd.arg("disable");
cmd.arg(",");
});
// print what we are about to do.
cmd.get_args()
.for_each(|arg| print!("{} ", arg.to_str().unwrap()));
cmd.output().expect("swaymsg output failed");
Ok(())
}