Convert (e)println to log macros

Add and configure env_logger
timeout_old
Aleksei Bavshin 3 years ago committed by Tassilo Horn
parent 69465b940f
commit c6f4631796
  1. 30
      Cargo.lock
  2. 2
      Cargo.toml
  3. 14
      README.md
  4. 3
      etc/swayrd.service
  5. 5
      src/bin/swayr.rs
  6. 4
      src/bin/swayrd.rs
  7. 22
      src/cmds.rs
  8. 40
      src/demon.rs
  9. 26
      src/layout.rs
  10. 14
      src/util.rs

30
Cargo.lock generated

@ -90,6 +90,19 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "env_logger"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3"
dependencies = [
"atty",
"humantime",
"log",
"regex",
"termcolor",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.2.4" version = "0.2.4"
@ -122,6 +135,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "1.8.0" version = "1.8.0"
@ -150,6 +169,15 @@ version = "0.2.117"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e74d72e0f9b65b5b4ca49a346af3976df0f9c61d550727f349ecd559f251a26c" checksum = "e74d72e0f9b65b5b4ca49a346af3976df0f9c61d550727f349ecd559f251a26c"
[[package]]
name = "log"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "memchr" name = "memchr"
version = "2.4.1" version = "2.4.1"
@ -370,7 +398,9 @@ version = "0.13.0"
dependencies = [ dependencies = [
"clap", "clap",
"directories", "directories",
"env_logger",
"lazy_static", "lazy_static",
"log",
"rand", "rand",
"regex", "regex",
"rt-format", "rt-format",

@ -20,3 +20,5 @@ regex = "1.5.4"
lazy_static = "1.4.0" lazy_static = "1.4.0"
rand = "0.8.4" rand = "0.8.4"
rt-format = "0.3.0" rt-format = "0.3.0"
log = "0.4"
env_logger = "0.9.0"

@ -166,14 +166,14 @@ You need to start the swayr demon `swayrd` in your sway config
(`~/.config/sway/config`) like so: (`~/.config/sway/config`) like so:
``` ```
exec env RUST_BACKTRACE=1 swayrd > /tmp/swayrd.log 2>&1 exec env RUST_BACKTRACE=1 RUST_LOG=swayr=debug swayrd > /tmp/swayrd.log 2>&1
``` ```
The setting of `RUST_BACKTRACE=1` and the redirection of the output to some The setting of `RUST_BACKTRACE=1`, `RUST_LOG=swayr=debug` and the redirection
logfile is optional but helps a lot when something doesn't work. Especially, of the output to some logfile is optional but helps a lot when something
if you encounter a crash in certain situations and you want to report a bug, it doesn't work. Especially, if you encounter a crash in certain situations and
would be utmost helpful if you could reproduce the issue with backtrace and you want to report a bug, it would be utmost helpful if you could reproduce
logging and attach that to your bug report. the issue with backtrace and logging and attach that to your bug report.
Next to starting the demon, you want to bind swayr commands to some keys like Next to starting the demon, you want to bind swayr commands to some keys like
so: so:
@ -183,7 +183,7 @@ bindsym $mod+Space exec env RUST_BACKTRACE=1 \
swayr switch-window >> /tmp/swayr.log 2>&1 swayr switch-window >> /tmp/swayr.log 2>&1
bindsym $mod+Delete exec env RUST_BACKTRACE=1 \ bindsym $mod+Delete exec env RUST_BACKTRACE=1 \
swayr quit-window > /tmp/swayr.log 2>&1 swayr quit-window >> /tmp/swayr.log 2>&1
bindsym $mod+Tab exec env RUST_BACKTRACE=1 \ bindsym $mod+Tab exec env RUST_BACKTRACE=1 \
swayr switch-to-urgent-or-lru-window >> /tmp/swayr.log 2>&1 swayr switch-to-urgent-or-lru-window >> /tmp/swayr.log 2>&1

@ -7,10 +7,9 @@ After=sway-session.target
[Service] [Service]
Type=simple Type=simple
Environment=RUST_BACKTRACE=1 Environment=RUST_BACKTRACE=1
# Environment=RUST_LOG=swayr=debug
ExecStart=/usr/bin/swayrd ExecStart=/usr/bin/swayrd
Restart=on-failure Restart=on-failure
# Remove or override this to send debug output to the journal
StandardOutput=null
[Install] [Install]
WantedBy=sway-session.target WantedBy=sway-session.target

@ -16,6 +16,7 @@
//! The `swayr` binary. //! The `swayr` binary.
use clap::Parser; use clap::Parser;
use env_logger::Env;
/// Windows are sorted urgent first, then windows in LRU order, focused window /// Windows are sorted urgent first, then windows in LRU order, focused window
/// last. Licensed under the GPLv3 (or later). /// last. Licensed under the GPLv3 (or later).
@ -27,8 +28,10 @@ struct Opts {
} }
fn main() { fn main() {
env_logger::Builder::from_env(Env::default().default_filter_or("warn"))
.init();
let opts: Opts = Opts::parse(); let opts: Opts = Opts::parse();
if let Err(err) = swayr::client::send_swayr_cmd(opts.command) { if let Err(err) = swayr::client::send_swayr_cmd(opts.command) {
eprintln!("Could not send command: {}", err); log::error!("Could not send command: {}", err);
} }
} }

@ -15,6 +15,10 @@
//! The `swayrd` binary. //! The `swayrd` binary.
use env_logger::Env;
fn main() { fn main() {
env_logger::Builder::from_env(Env::default().default_filter_or("warn"))
.init();
swayr::demon::run_demon(); swayr::demon::run_demon();
} }

@ -31,11 +31,11 @@ use std::sync::RwLock;
use swayipc as s; use swayipc as s;
pub fn run_sway_command_1(cmd: &str) { pub fn run_sway_command_1(cmd: &str) {
println!("Running sway command: {}", cmd); log::debug!("Running sway command: {}", cmd);
match s::Connection::new() { match s::Connection::new() {
Ok(mut con) => { Ok(mut con) => {
if let Err(err) = con.run_command(cmd) { if let Err(err) = con.run_command(cmd) {
eprintln!("Could not run sway command: {}", err) log::error!("Could not run sway command: {}", err)
} }
} }
Err(err) => panic!("{}", err), Err(err) => panic!("{}", err),
@ -482,7 +482,7 @@ pub fn switch_to_urgent_or_lru_window(
if let Some(win) = tree.get_windows().get(0) { if let Some(win) = tree.get_windows().get(0) {
focus_window_by_id(win.node.id) focus_window_by_id(win.node.id)
} else { } else {
println!("No window to switch to.") log::debug!("No window to switch to.")
} }
} }
@ -550,7 +550,7 @@ fn select_and_focus(prompt: &str, choices: &[t::DisplayNode]) {
focus_window_by_id(tn.node.id) focus_window_by_id(tn.node.id)
} }
t => { t => {
eprintln!("Cannot handle {:?} in select_and_focus", t) log::error!("Cannot handle {:?} in select_and_focus", t)
} }
}, },
Err(non_matching_input) => { Err(non_matching_input) => {
@ -613,10 +613,10 @@ fn kill_process_by_pid(pid: Option<i32>) {
.arg(format!("{}", pid)) .arg(format!("{}", pid))
.output() .output()
{ {
eprintln!("Error killing process {}: {}", pid, err) log::error!("Error killing process {}: {}", pid, err)
} }
} else { } else {
eprintln!("Cannot kill window with no pid."); log::error!("Cannot kill window with no pid.");
} }
} }
@ -638,7 +638,7 @@ fn select_and_quit(prompt: &str, choices: &[t::DisplayNode], kill: bool) {
} }
} }
t => { t => {
eprintln!("Cannot handle {:?} in quit_workspace_or_window", t) log::error!("Cannot handle {:?} in quit_workspace_or_window", t)
} }
} }
} }
@ -721,7 +721,7 @@ fn select_and_move_focused_to(prompt: &str, choices: &[t::DisplayNode]) {
t::Type::Container | t::Type::Window => { t::Type::Container | t::Type::Window => {
move_focused_to_container_or_window(tn.node.id) move_focused_to_container_or_window(tn.node.id)
} }
t => eprintln!("Cannot move focused to {:?}", t), t => log::error!("Cannot move focused to {:?}", t),
}, },
Err(input) => { Err(input) => {
let ws_name = chop_workspace_shortcut(&input); let ws_name = chop_workspace_shortcut(&input);
@ -765,7 +765,7 @@ pub fn swap_focused_with(extra_props: &HashMap<i64, t::ExtraProps>) {
&format!("{}", tn.node.id), &format!("{}", tn.node.id),
]) ])
} }
t => eprintln!("Cannot move focused to {:?}", t), t => log::error!("Cannot move focused to {:?}", t),
}, },
Err(input) => { Err(input) => {
let ws_name = chop_workspace_shortcut(&input); let ws_name = chop_workspace_shortcut(&input);
@ -914,7 +914,7 @@ fn tile_current_workspace(floating: &ConsiderFloating, shuffle: bool) {
}), }),
) { ) {
Ok(_) => (), Ok(_) => (),
Err(err) => eprintln!("Error retiling workspace: {:?}", err), Err(err) => log::error!("Error retiling workspace: {:?}", err),
} }
} }
@ -946,7 +946,7 @@ fn tab_current_workspace(floating: &ConsiderFloating) {
}), }),
) { ) {
Ok(_) => (), Ok(_) => (),
Err(err) => eprintln!("Error retiling workspace: {:?}", err), Err(err) => log::error!("Error retiling workspace: {:?}", err),
} }
} }

@ -62,10 +62,10 @@ pub fn monitor_sway_events(
} }
resets += 1; resets += 1;
println!("Connecting to sway for subscribing to events..."); log::debug!("Connecting to sway for subscribing to events...");
match connect_and_subscribe() { match connect_and_subscribe() {
Err(err) => { Err(err) => {
eprintln!("Could not connect and subscribe: {}", err); log::warn!("Could not connect and subscribe: {}", err);
std::thread::sleep(std::time::Duration::from_secs(3)); std::thread::sleep(std::time::Duration::from_secs(3));
} }
Ok(iter) => { Ok(iter) => {
@ -94,7 +94,7 @@ pub fn monitor_sway_events(
); );
} }
s::Event::Shutdown(sd_ev) => { s::Event::Shutdown(sd_ev) => {
println!( log::debug!(
"Sway shuts down with reason '{:?}'.", "Sway shuts down with reason '{:?}'.",
sd_ev.change sd_ev.change
); );
@ -103,16 +103,16 @@ pub fn monitor_sway_events(
_ => show_extra_props_state = false, _ => show_extra_props_state = false,
}, },
Err(e) => { Err(e) => {
eprintln!("Error while receiving events: {}", e); log::warn!("Error while receiving events: {}", e);
std::thread::sleep(std::time::Duration::from_secs( std::thread::sleep(std::time::Duration::from_secs(
3, 3,
)); ));
show_extra_props_state = false; show_extra_props_state = false;
eprintln!("Resetting!"); log::warn!("Resetting!");
} }
} }
if show_extra_props_state { if show_extra_props_state {
println!( log::debug!(
"New extra_props state:\n{:#?}", "New extra_props state:\n{:#?}",
*extra_props.read().unwrap() *extra_props.read().unwrap()
); );
@ -121,7 +121,7 @@ pub fn monitor_sway_events(
} }
} }
} }
println!("Swayr demon shutting down.") log::debug!("Swayr demon shutting down.")
} }
fn handle_window_event( fn handle_window_event(
@ -137,28 +137,28 @@ fn handle_window_event(
s::WindowChange::Focus => { s::WindowChange::Focus => {
layout::maybe_auto_tile(config); layout::maybe_auto_tile(config);
update_last_focus_tick(container.id, extra_props, focus_val); update_last_focus_tick(container.id, extra_props, focus_val);
println!("Handled window event type {:?}", change); log::debug!("Handled window event type {:?}", change);
true true
} }
s::WindowChange::New => { s::WindowChange::New => {
layout::maybe_auto_tile(config); layout::maybe_auto_tile(config);
update_last_focus_tick(container.id, extra_props, focus_val); update_last_focus_tick(container.id, extra_props, focus_val);
println!("Handled window event type {:?}", change); log::debug!("Handled window event type {:?}", change);
true true
} }
s::WindowChange::Close => { s::WindowChange::Close => {
remove_extra_props(container.id, extra_props); remove_extra_props(container.id, extra_props);
layout::maybe_auto_tile(config); layout::maybe_auto_tile(config);
println!("Handled window event type {:?}", change); log::debug!("Handled window event type {:?}", change);
true true
} }
s::WindowChange::Move | s::WindowChange::Floating => { s::WindowChange::Move | s::WindowChange::Floating => {
layout::maybe_auto_tile(config); layout::maybe_auto_tile(config);
println!("Handled window event type {:?}", change); log::debug!("Handled window event type {:?}", change);
false // We don't affect the extra_props state here. false // We don't affect the extra_props state here.
} }
_ => { _ => {
println!("Unhandled window event type {:?}", change); log::debug!("Unhandled window event type {:?}", change);
false false
} }
} }
@ -184,7 +184,7 @@ fn handle_workspace_event(
extra_props, extra_props,
focus_val, focus_val,
); );
println!("Handled workspace event type {:?}", change); log::debug!("Handled workspace event type {:?}", change);
true true
} }
s::WorkspaceChange::Empty => { s::WorkspaceChange::Empty => {
@ -192,7 +192,7 @@ fn handle_workspace_event(
current.expect("No current in Empty workspace event").id, current.expect("No current in Empty workspace event").id,
extra_props, extra_props,
); );
println!("Handled workspace event type {:?}", change); log::debug!("Handled workspace event type {:?}", change);
true true
} }
_ => false, _ => false,
@ -229,8 +229,8 @@ pub fn serve_client_requests(
extra_props: Arc<RwLock<HashMap<i64, t::ExtraProps>>>, extra_props: Arc<RwLock<HashMap<i64, t::ExtraProps>>>,
) { ) {
match std::fs::remove_file(util::get_swayr_socket_path()) { match std::fs::remove_file(util::get_swayr_socket_path()) {
Ok(()) => println!("Deleted stale socket from previous run."), Ok(()) => log::debug!("Deleted stale socket from previous run."),
Err(e) => eprintln!("Could not delete socket:\n{:?}", e), Err(e) => log::error!("Could not delete socket:\n{:?}", e),
} }
match UnixListener::bind(util::get_swayr_socket_path()) { match UnixListener::bind(util::get_swayr_socket_path()) {
@ -241,14 +241,14 @@ pub fn serve_client_requests(
handle_client_request(stream, extra_props.clone()); handle_client_request(stream, extra_props.clone());
} }
Err(err) => { Err(err) => {
eprintln!("Error handling client request: {}", err); log::error!("Error handling client request: {}", err);
break; break;
} }
} }
} }
} }
Err(err) => { Err(err) => {
eprintln!("Could not bind socket: {}", err) log::error!("Could not bind socket: {}", err)
} }
} }
} }
@ -265,12 +265,12 @@ fn handle_client_request(
extra_props, extra_props,
}); });
} else { } else {
eprintln!( log::error!(
"Could not serialize following string to SwayrCommand.\n{}", "Could not serialize following string to SwayrCommand.\n{}",
cmd_str cmd_str
); );
} }
} else { } else {
eprintln!("Could not read command from client."); log::error!("Could not read command from client.");
} }
} }

@ -26,7 +26,7 @@ pub fn auto_tile(res_to_min_width: &HashMap<i32, i32>) {
if let Ok(mut con) = s::Connection::new() { if let Ok(mut con) = s::Connection::new() {
if let Ok(tree) = con.get_tree() { if let Ok(tree) = con.get_tree() {
for output in &tree.nodes { for output in &tree.nodes {
println!("output: {:?}", output.name); log::debug!("output: {:?}", output.name);
// Assert our assumption that all children of the tree's root // Assert our assumption that all children of the tree's root
// must be outputs. // must be outputs.
@ -46,10 +46,10 @@ pub fn auto_tile(res_to_min_width: &HashMap<i32, i32>) {
t == t::Type::Workspace || t == t::Type::Container t == t::Type::Workspace || t == t::Type::Container
}) { }) {
if container.is_scratchpad() { if container.is_scratchpad() {
println!(" Skipping scratchpad"); log::debug!(" Skipping scratchpad");
continue; continue;
} }
println!( log::debug!(
" container: {:?}, layout {:?}, {} nodes", " container: {:?}, layout {:?}, {} nodes",
container.node_type, container.node_type,
container.layout, container.layout,
@ -63,7 +63,7 @@ pub fn auto_tile(res_to_min_width: &HashMap<i32, i32>) {
// Width if we'd split once more. // Width if we'd split once more.
let estimated_width = let estimated_width =
child_win.rect.width as f32 / 2.0; child_win.rect.width as f32 / 2.0;
println!( log::debug!(
" child_win: {:?}, estimated width after splith {} px", " child_win: {:?}, estimated width after splith {} px",
child_win.app_id, estimated_width child_win.app_id, estimated_width
); );
@ -81,7 +81,7 @@ pub fn auto_tile(res_to_min_width: &HashMap<i32, i32>) {
}; };
if let Some(split) = split { if let Some(split) = split {
println!( log::debug!(
"Auto-tiling performing {} on window {} \ "Auto-tiling performing {} on window {} \
because estimated width after another \ because estimated width after another \
split is {} and the minimum window width \ split is {} and the minimum window width \
@ -96,36 +96,38 @@ pub fn auto_tile(res_to_min_width: &HashMap<i32, i32>) {
child_win.id, split child_win.id, split
)) { )) {
Ok(_) => (), Ok(_) => (),
Err(e) => eprintln!( Err(e) => log::error!(
"Couldn't set {} on con {}: {:?}", "Couldn't set {} on con {}: {:?}",
split, child_win.id, e split,
child_win.id,
e
), ),
} }
} }
} }
} }
} else { } else {
eprintln!("No layout.auto_tile_min_window_width_per_output_width \ log::error!("No layout.auto_tile_min_window_width_per_output_width \
setting for output_width {}", output_width); setting for output_width {}", output_width);
} }
} }
} else { } else {
eprintln!("Couldn't call get_tree during auto_tile."); log::error!("Couldn't call get_tree during auto_tile.");
} }
} else { } else {
eprintln!("Couldn't get connection for auto_tile"); log::error!("Couldn't get connection for auto_tile");
} }
} }
pub fn maybe_auto_tile(config: &config::Config) { pub fn maybe_auto_tile(config: &config::Config) {
if config.is_layout_auto_tile() { if config.is_layout_auto_tile() {
println!("\nauto_tile: start"); log::debug!("\nauto_tile: start");
auto_tile( auto_tile(
&config &config
.get_layout_auto_tile_min_window_width_per_output_width_as_map( .get_layout_auto_tile_min_window_width_per_output_width_as_map(
), ),
); );
println!("auto_tile: end\n"); log::debug!("auto_tile: end\n");
} }
} }

@ -34,14 +34,14 @@ pub fn get_swayr_socket_path() -> String {
match xdg_runtime_dir { match xdg_runtime_dir {
Ok(val) => val, Ok(val) => val,
Err(_e) => { Err(_e) => {
eprintln!("Couldn't get XDG_RUNTIME_DIR!"); log::error!("Couldn't get XDG_RUNTIME_DIR!");
String::from("/tmp") String::from("/tmp")
} }
}, },
match wayland_display { match wayland_display {
Ok(val) => val, Ok(val) => val,
Err(_e) => { Err(_e) => {
eprintln!("Couldn't get WAYLAND_DISPLAY!"); log::error!("Couldn't get WAYLAND_DISPLAY!");
String::from("unknown") String::from("unknown")
} }
} }
@ -96,7 +96,7 @@ fn desktop_entries() -> Vec<Box<p::Path>> {
fn find_icon(icon_name: &str, icon_dirs: &[String]) -> Option<Box<p::Path>> { fn find_icon(icon_name: &str, icon_dirs: &[String]) -> Option<Box<p::Path>> {
let p = p::Path::new(icon_name); let p = p::Path::new(icon_name);
if p.is_file() { if p.is_file() {
println!("(1) Icon name '{}' -> {}", icon_name, p.display()); log::debug!("(1) Icon name '{}' -> {}", icon_name, p.display());
return Some(p.to_path_buf().into_boxed_path()); return Some(p.to_path_buf().into_boxed_path());
} }
@ -106,7 +106,7 @@ fn find_icon(icon_name: &str, icon_dirs: &[String]) -> Option<Box<p::Path>> {
pb.push(icon_name.to_owned() + "." + ext); pb.push(icon_name.to_owned() + "." + ext);
let icon_file = pb.as_path(); let icon_file = pb.as_path();
if icon_file.is_file() { if icon_file.is_file() {
println!( log::debug!(
"(2) Icon name '{}' -> {}", "(2) Icon name '{}' -> {}",
icon_name, icon_name,
icon_file.display() icon_file.display()
@ -116,7 +116,7 @@ fn find_icon(icon_name: &str, icon_dirs: &[String]) -> Option<Box<p::Path>> {
} }
} }
println!("(3) No icon for name {}", icon_name); log::debug!("(3) No icon for name {}", icon_name);
None None
} }
@ -187,7 +187,7 @@ fn get_app_id_to_icon_map(
} }
} }
println!( log::debug!(
"Desktop entries to icon files ({} entries):\n{:#?}", "Desktop entries to icon files ({} entries):\n{:#?}",
map.len(), map.len(),
map map
@ -278,7 +278,7 @@ where
.as_mut() .as_mut()
.expect("Failed to open the menu program's stdin"); .expect("Failed to open the menu program's stdin");
let input = strs.join("\n"); let input = strs.join("\n");
//println!("Menu program {} input:\n{}", menu_exec, input); //log::debug!("Menu program {} input:\n{}", menu_exec, input);
stdin stdin
.write_all(input.as_bytes()) .write_all(input.as_bytes())
.expect("Failed to write to the menu program's stdin"); .expect("Failed to write to the menu program's stdin");

Loading…
Cancel
Save