28 Commits

Author SHA1 Message Date
Ultradesu
d9b5643ae5 Fixed mem_load_bar and cpu_load_bar to new sysinfo crate 2025-07-16 16:09:55 +03:00
Ultradesu
eb3577979c Improved styling 2025-04-07 19:08:24 +01:00
Ultradesu
c082c328f5 Improved styling 2025-04-07 19:07:57 +01:00
Ultradesu
c9a7c33356 Drop PKGBUILD action 2025-04-03 13:44:50 +01:00
Ultradesu
a910ea39f4 Drop PKGBUILDaction 2025-04-03 13:38:14 +01:00
Ultradesu
337949a792 Drop PKGBUILDaction 2025-04-03 13:33:15 +01:00
Ultradesu
d09629794f Drop PKGBUILDaction 2025-04-03 13:32:19 +01:00
Ultradesu
59240601fe Bump PKGBUILD action 2025-04-03 13:31:06 +01:00
Ultradesu
00b0b5f3ef Bump PKGBUILD action 2025-04-03 13:28:06 +01:00
Ultradesu
60c014347c Bump PKGBUILD action 2025-04-03 13:25:20 +01:00
Ultradesu
e0ff50a7fa Bump PKGBUILD action 2025-04-03 13:21:26 +01:00
Ultradesu
df1ccc4054 Bump upload action 2025-04-03 13:20:10 +01:00
Ultradesu
86596eed29 Bump version 2025-04-03 13:18:40 +01:00
Ultradesu
4af53996a7 Added macos build 2025-04-03 13:17:50 +01:00
Ultradesu
25fe327294 Bump rust and libs 2025-03-31 16:18:21 +01:00
House of Vanity
6340565c27 Update build.yml 2020-09-23 19:20:43 +03:00
Alexandr
e9c59a6733 Improve player MPRIS line. 2020-09-22 15:52:55 +03:00
Alexandr Bogomyakov
5d37a86d09 Dummy commit. 2020-07-10 14:11:50 +03:00
AB
573cb35b52 Linting and minor style changes 2020-07-07 09:23:00 +03:00
AB
b1015ada2f Update readme 2020-05-20 12:29:22 +03:00
AB
e7ac12974f Fix player printing. 2020-05-15 13:07:49 +03:00
AB
6e08864d99 Fix duration format. 2020-05-14 23:39:40 +03:00
AB
6a9a871006 Fix duration format. 2020-05-14 23:32:05 +03:00
AB
bab994fc41 Fix duration format. 2020-05-14 22:13:22 +03:00
AB
fc1c2f539d Aupdate image 2020-05-14 22:00:02 +03:00
AB
0f5a1aaaed Hotfix 2020-05-14 21:53:47 +03:00
AB
1030e69932 Hotfix 2020-05-14 21:53:41 +03:00
AB
474d48d15c Add mpd. Rewrite. 2020-05-14 21:18:37 +03:00
8 changed files with 651 additions and 339 deletions

BIN
.github/prev.png vendored

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -1,7 +1,7 @@
# Maintainer: Alexandr Bogomyakov (ultradesu) <ab@hexor.ru> # Maintainer: Alexandr Bogomyakov (ultradesu) <ab@hexor.ru>
pkgname=tmux-helper pkgname=tmux-helper
pkgver=0.2.1 pkgver=0.3.4
pkgrel=1 pkgrel=1
pkgdesc="Tmux helper" pkgdesc="Tmux helper"
url="https://github.com/house-of-vanity/tmux-helper.git" url="https://github.com/house-of-vanity/tmux-helper.git"

View File

@@ -1,95 +1,95 @@
name: Build and publish name: Build and publish
on: on:
push: push:
# Sequence of patterns matched against refs/tags
tags: tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10 - 'v*'
env:
BINARY_NAME: tmux-helper
jobs: jobs:
make_bin: build:
name: Build binary name: Build binaries
runs-on: ubuntu-latest runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
include:
- os: ubuntu-latest
platform_name: linux-amd64
- os: macos-latest
platform_name: macos-arm64
steps: steps:
- name: Checkout code - uses: actions/checkout@v4
uses: actions/checkout@v2
- name: Pre-build - name: Pre-build (Linux)
if: matrix.os == 'ubuntu-latest'
run: sudo apt install -y libdbus-1-dev pkg-config libdbus-1-3 libfuse-dev run: sudo apt install -y libdbus-1-dev pkg-config libdbus-1-3 libfuse-dev
- uses: actions/checkout@v2
- name: Pre-build (macOS)
if: matrix.os == 'macos-latest'
run: brew install dbus
- name: Build binary - name: Build binary
run: cargo build --release run: cargo build --release
- name: Upload binary
uses: actions/upload-artifact@v1
with:
name: tmux-helper
path: ./target/release/tmux-helper
make_arch:
name: Make Arch Linux package
runs-on: ubuntu-latest
container:
image: archlinux
options: --privileged
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup
steps:
- uses: actions/checkout@v2
- name: Build Arch Linux package
uses: FFY00/build-arch-package@master
with:
PKGBUILD: $GITHUB_WORKSPACE/.github/workflows/PKGBUILD
OUTDIR: $HOME/arch-packages
- run: mv $HOME/arch-packages/*pkg.tar.zst tmux-helper-x86_64.pkg.tar.zst
- name: Upload Arch Package
uses: actions/upload-artifact@v1
with:
name: arch_linux_tmux-helper-x86_64.pkg.tar.zst
path: ./tmux-helper-x86_64.pkg.tar.zst
publish: - name: Rename binary
name: Publish release
needs: [make_bin, make_arch]
runs-on: ubuntu-latest
steps:
- name: Get the version (git tag)
id: get_version
run: | run: |
echo ${GITHUB_REF/refs\/tags\/v/} mkdir -p ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\/v/} cp target/release/${{ env.BINARY_NAME }} ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}/${{ env.BINARY_NAME }}
echo ::set-output name=FULL_TAG::${GITHUB_REF/refs\/tags\//}
- name: Create Release - uses: actions/upload-artifact@v4
with:
name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
path: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
release:
name: Create Release Page
needs: build
runs-on: ubuntu-latest
permissions:
contents: write
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
steps:
- uses: actions/checkout@v4
- uses: ncipollo/release-action@v1
id: create_release id: create_release
uses: actions/create-release@v1
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
tag_name: ${{ github.ref }} allowUpdates: true
release_name: Release ${{ github.ref }} tag: ${{ github.ref_name }}
draft: false
prerelease: false
- name: Download binary
uses: actions/download-artifact@v1
with:
name: tmux-helper
path: ./
- name: Download Arch Package
uses: actions/download-artifact@v1
with:
name: arch_linux_tmux-helper-x86_64.pkg.tar.zst
path: ./
- name: Upload binary assets
run: |
wget https://github.com/aktau/github-release/releases/download/v0.7.2/linux-amd64-github-release.tar.bz2
tar xjf linux-amd64-github-release.tar.bz2
export GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }}
./bin/linux/amd64/github-release upload -u house-of-vanity -r tmux-helper --tag ${{ steps.get_version.outputs.FULL_TAG }} --name arch_linux_tmux-helper-${{ steps.get_version.outputs.VERSION }}-x86_64.pkg.tar.zst --file ./tmux-helper-x86_64.pkg.tar.zst
./bin/linux/amd64/github-release upload -u house-of-vanity -r tmux-helper --tag ${{ steps.get_version.outputs.FULL_TAG }} --name tmux-helper-${{ steps.get_version.outputs.VERSION }} --file ./tmux-helper
# SCP to arch repo upload:
- name: Copy package to repository name: Upload Release Assets
uses: appleboy/scp-action@master needs: release
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
include:
- os: ubuntu-latest
platform_name: linux-amd64
- os: macos-latest
platform_name: macos-arm64
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
name: Download ${{ matrix.platform_name }} artifact
with: with:
host: ${{ secrets.SSH_HOST }} name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
username: github_deploy path: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
port: 22
key: ${{ secrets.SSH_KEY }} - name: Upload Release Asset
source: "./tmux-helper-x86_64.pkg.tar.zst" uses: actions/upload-release-asset@v1
target: "/srv/arch-repo/" env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.release.outputs.upload_url }}
asset_path: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}/${{ env.BINARY_NAME }}
asset_name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
asset_content_type: application/octet-stream

View File

@@ -1,10 +1,14 @@
[package] [package]
name = "tmux-helper" name = "tmux-helper"
version = "0.2.2" version = "0.4.0"
description = "Utility for printing system info for tmux status line."
authors = ["Ultra Desu <ultradesu@hexor.ru>"] authors = ["Ultra Desu <ultradesu@hexor.ru>"]
edition = "2018" edition = "2021"
[dependencies] [dependencies]
sys-info = "*" sysinfo = "0.36.0"
dbus = "*" dbus = "0.9"
chrono = "*" chrono = "0.4"
mpd = "0.1"
clap = "4"
size_format = "1"

View File

@@ -3,14 +3,37 @@ Small app that perform system check and print TMUX friendly output.
![Preview](.github/prev.png) ![Preview](.github/prev.png)
### Features:
1. `tmux-helper -cb` print cpu load with bar.
2. `tmux-helper -mb` print memory usage with bar.
3. `tmux-helper -p` show current player status using d-bus.
### Building ### Building
`cargo build --release` `cargo build --release`
or get binary on release page or get binary on release page
### Customization ### Fetures
Colours are hardcoded but it's easy to change it. It defined as CONST in very beginning of main.rs file. ```shell
tmux-helper 0.3.2
Ultra Desu <ultradesu@hexor.ru>
Utility for printing system info for tmux status line.
USAGE:
tmux-helper [FLAGS] [OPTIONS]
FLAGS:
-c, --cpu Print cpu load bar.
-h, --help Prints help information
-m, --mem Print mem usage bar.
-d, --mpd Show mpd player using MPD native protocol.
-p, --mpris Show player info using MPRIS2 interface.
-V, --version Prints version information
OPTIONS:
--COLOR_END <COLOR_END> Default color using to terminate others.
--COLOR_HIGH <COLOR_HIGH> CPU and MEM bar color while high usage.
--COLOR_LOW <COLOR_LOW> CPU and MEM bar color while low usage.
--COLOR_MID <COLOR_MID> CPU and MEM bar color while mid usage.
--COLOR_TRACK_ARTIST <COLOR_TRACK_ARTIST> Color of artist name filed.
--COLOR_TRACK_NAME <COLOR_TRACK_NAME> Color of track name filed.
--COLOR_TRACK_TIME <COLOR_TRACK_TIME> Color of playing time field.
-l, --localtime <localtime> Local time
-a, --mpd-address <mpd_address> <ADDR>:<PORT> of MPD server.
-u, --utctime <utctime> UTC time
```

245
src/config.rs Normal file
View File

@@ -0,0 +1,245 @@
use clap::{Arg, Command};
#[derive(Debug)]
pub enum Action {
Mem,
Cpu,
Mpris,
Mpd,
Localtime,
Utctime,
}
impl Default for Action {
fn default() -> Action {
Action::Cpu
}
}
#[derive(Default, Debug)]
pub struct Config {
pub action: Action,
pub mpd_server: String,
pub lt_format: Option<String>,
pub ut_format: Option<String>,
pub bar_symbol: Option<String>,
pub bar_empty_symbol: Option<String>,
pub low_threshold: f32,
pub mid_threshold: f32,
pub color_low: String,
pub color_mid: String,
pub color_high: String,
pub color_track_name: String,
pub color_track_artist: String,
pub color_track_time: String,
pub color_end: String,
}
fn colorize(color: String) -> String {
format!("#[fg=colour{}]", color)
}
pub fn read() -> Config {
let cli_args = Command::new(env!("CARGO_PKG_NAME"))
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about(env!("CARGO_PKG_DESCRIPTION"))
.arg(
Arg::new("cpu")
.short('c')
.long("cpu")
.help("Print cpu load bar.")
.action(clap::ArgAction::SetTrue)
.conflicts_with_all(["mem", "mpris", "mpd", "localtime", "utctime"]),
)
.arg(
Arg::new("mem")
.short('m')
.long("mem")
.action(clap::ArgAction::SetTrue)
.help("Print mem usage bar."),
)
.arg(
Arg::new("low")
.long("low")
.help("Low threshold (0.0 - 1.0)")
.value_parser(clap::value_parser!(f32))
.default_value("0.7"),
)
.arg(
Arg::new("mid")
.long("mid")
.help("Mid threshold (0.0 - 1.0)")
.value_parser(clap::value_parser!(f32))
.default_value("0.9"),
)
.arg(
Arg::new("mpris")
.short('p')
.long("mpris")
.action(clap::ArgAction::SetTrue)
.help("Show player info using MPRIS2 interface."),
)
.arg(
Arg::new("mpd")
.short('d')
.long("mpd")
.action(clap::ArgAction::SetTrue)
.help("Show mpd player using MPD native protocol."),
)
.arg(
Arg::new("localtime")
.short('l')
.long("localtime")
.help("Local time")
.num_args(0..=1)
.default_missing_value("%H:%M"),
)
.arg(
Arg::new("utctime")
.short('u')
.long("utctime")
.help("UTC time")
.num_args(0..=1)
.default_missing_value("%H:%M"),
)
.arg(
Arg::new("bar_symbol")
.short('s')
.long("symbol")
.help("Symbol to build bar")
.num_args(0..=1)
.default_value(""),
)
.arg(
Arg::new("bar_empty_symbol")
.short('e')
.long("empty-symbol")
.help("Symbol to represent the empty part of the bar")
.num_args(0..=1)
.default_value(""),
)
.arg(
Arg::new("mpd_address")
.short('a')
.long("mpd-address")
.help("<ADDR>:<PORT> of MPD server.")
.default_value("127.0.0.1:6600"),
)
.arg(
Arg::new("COLOR_LOW")
.long("COLOR_LOW")
.help("CPU and MEM bar color while low usage.")
.default_value("119"),
)
.arg(
Arg::new("COLOR_MID")
.long("COLOR_MID")
.help("CPU and MEM bar color while mid usage.")
.default_value("220"),
)
.arg(
Arg::new("COLOR_HIGH")
.long("COLOR_HIGH")
.help("CPU and MEM bar color while high usage.")
.default_value("197"),
)
.arg(
Arg::new("COLOR_TRACK_NAME")
.long("COLOR_TRACK_NAME")
.help("Color of track name filed.")
.default_value("46"),
)
.arg(
Arg::new("COLOR_TRACK_ARTIST")
.long("COLOR_TRACK_ARTIST")
.help("Color of artist name filed.")
.default_value("46"),
)
.arg(
Arg::new("COLOR_TRACK_TIME")
.long("COLOR_TRACK_TIME")
.help("Color of playing time field.")
.default_value("153"),
)
.arg(
Arg::new("COLOR_END")
.long("COLOR_END")
.help("Default color using to terminate others.")
.default_value("153"),
)
.get_matches();
let lt_format = cli_args
.get_one::<String>("localtime")
.map(|s| s.to_string());
let ut_format = cli_args.get_one::<String>("utctime").map(|s| s.to_string());
let bar_symbol = cli_args
.get_one::<String>("bar_symbol")
.map(|s| s.to_string());
let bar_empty_symbol = cli_args
.get_one::<String>("bar_empty_symbol")
.map(|s| s.to_string());
let mut cfg = Config {
action: Action::Cpu,
mpd_server: cli_args
.get_one::<String>("mpd_address")
.unwrap()
.to_string(),
lt_format,
ut_format,
bar_symbol,
bar_empty_symbol,
low_threshold: *cli_args.get_one::<f32>("low").unwrap(),
mid_threshold: *cli_args.get_one::<f32>("mid").unwrap(),
color_low: colorize(cli_args.get_one::<String>("COLOR_LOW").unwrap().to_string()),
color_mid: colorize(cli_args.get_one::<String>("COLOR_MID").unwrap().to_string()),
color_high: colorize(
cli_args
.get_one::<String>("COLOR_HIGH")
.unwrap()
.to_string(),
),
color_track_name: colorize(
cli_args
.get_one::<String>("COLOR_TRACK_NAME")
.unwrap()
.to_string(),
),
color_track_artist: colorize(
cli_args
.get_one::<String>("COLOR_TRACK_ARTIST")
.unwrap()
.to_string(),
),
color_track_time: colorize(
cli_args
.get_one::<String>("COLOR_TRACK_TIME")
.unwrap()
.to_string(),
),
color_end: colorize(cli_args.get_one::<String>("COLOR_END").unwrap().to_string()),
};
if cli_args.get_flag("cpu") {
cfg.action = Action::Cpu;
}
if cli_args.get_flag("mem") {
cfg.action = Action::Mem;
}
if cli_args.contains_id("localtime") {
cfg.action = Action::Localtime;
}
if cli_args.contains_id("utctime") {
cfg.action = Action::Utctime;
}
if cli_args.get_flag("mpris") {
cfg.action = Action::Mpris;
}
if cli_args.get_flag("mpd") {
cfg.action = Action::Mpd;
}
cfg
}

View File

@@ -1,256 +1,24 @@
extern crate chrono; mod config;
extern crate dbus; mod utils;
use crate::dbus::blocking::stdintf::org_freedesktop_dbus::Properties;
use chrono::{DateTime, Local, Utc};
use dbus::{arg, blocking::Connection};
use std::{env, time::Duration};
use sys_info;
const LOW: &str = "#[fg=colour119]";
const MID: &str = "#[fg=colour220]";
const HIGH: &str = "#[fg=colour197]";
const END: &str = "#[fg=colour153]";
const TRACK_NAME: &str = "#[fg=colour46]";
const TRACK_ARTIST: &str = "#[fg=colour46]";
const TRACK_TIME: &str = "#[fg=colour153]";
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct TrackInfo { pub struct TrackInfo {
title: String, pub title: String,
artist: String, pub artist: String,
position: String, pub position: String,
duration: String, pub duration: String,
status: String, pub status: String,
}
fn to_bar(value: i32, max: i32, low: f32, mid: f32) {
let mut bar = "".to_string();
let bar_sym = "".to_string();
if (value as f32) / (max as f32) < low {
bar.push_str(LOW);
} else if (value as f32) / (max as f32) < mid {
bar.push_str(MID);
} else {
bar.push_str(HIGH);
}
for i in 0..max {
if i < value as i32 {
bar.push_str(&bar_sym);
} else {
bar.push_str(" ")
}
}
bar.push_str(END);
bar.push_str("|");
print!("{}", bar)
}
fn mem_load_bar(bar_len: i32) {
let memory;
match sys_info::mem_info() {
Err(w) => panic!("{:?}", w),
Ok(mem_data) => memory = mem_data,
}
let len =
((memory.total - memory.avail) as f32 / (memory.total as f32) * bar_len as f32) as i32;
to_bar(len, bar_len, 0.7, 0.9);
print!("{:.0} MiB#[default]", memory.avail / 1024);
}
fn cpu_load_bar(bar_len: i32) {
let cpu_count = match sys_info::cpu_num() {
Ok(c) => c,
Err(e) => panic!("{:?}", e),
};
let la_one: f32 = match sys_info::loadavg() {
Ok(l) => l.one as f32,
Err(e) => panic!("{:?}", e),
};
let len: f32 = la_one as f32 / cpu_count as f32 * bar_len as f32;
to_bar(len as i32, bar_len, 0.3, 0.7);
print!("{:.2} LA1#[default]", la_one);
}
fn get_player() -> Result<Vec<String>, Box<dyn std::error::Error>> {
let conn = Connection::new_session()?;
let proxy = conn.with_proxy("org.freedesktop.DBus", "/", Duration::from_millis(5000));
let (names,): (Vec<String>,) = proxy.method_call("org.freedesktop.DBus", "ListNames", ())?;
let mut players: Vec<String> = Vec::new();
for name in names {
if name.contains("org.mpris.MediaPlayer2") {
players.push(name);
}
}
Ok(players)
}
fn player_info(players: Vec<String>) -> Result<TrackInfo, Box<dyn std::error::Error>> {
let mut players_vec: Vec<TrackInfo> = Vec::new();
for player in players {
let mut track_info = TrackInfo {
artist: "".to_string(),
title: "".to_string(),
position: "".to_string(),
duration: "".to_string(),
status: "".to_string(),
};
let conn = Connection::new_session()?;
let proxy = conn.with_proxy(
player,
"/org/mpris/MediaPlayer2",
Duration::from_millis(5000),
);
let metadata: Box<dyn arg::RefArg> =
proxy.get("org.mpris.MediaPlayer2.Player", "Metadata")?;
let mut iter = metadata.as_iter().unwrap();
while let Some(key) = iter.next() {
if key.as_str() == Some("xesam:title") {
if let Some(title) = iter.next().unwrap().as_str() {
track_info.title = title.to_string();
}
}
if key.as_str() == Some("mpris:length") {
if let Some(length) = iter.next().unwrap().as_i64() {
track_info.duration = format_time(length / 1000000);
}
}
if key.as_str() == Some("xesam:artist") {
if let Some(mut artists) = iter.next().unwrap().as_iter() {
while let Some(artist) = artists.next() {
if let Some(mut line) = artist.as_iter() {
track_info.artist = line.next().unwrap().as_str().unwrap().to_string();
}
}
}
}
}
let position: Box<dyn arg::RefArg> =
proxy.get("org.mpris.MediaPlayer2.Player", "Position")?;
track_info.position = format_time(position.as_i64().unwrap() / 1000000);
// ugly
let _status_text_box: Box<dyn arg::RefArg> =
proxy.get("org.mpris.MediaPlayer2.Player", "PlaybackStatus")?;
let _status_text = _status_text_box.as_str().unwrap();
match _status_text.as_ref() {
"Playing" => track_info.status = "".to_string(),
"Paused" => track_info.status = "".to_string(),
_ => track_info.status = "".to_string(),
};
players_vec.push(track_info);
}
for player in &players_vec {
if player.status == "".to_string() {
return Ok(player.clone());
}
}
Ok(players_vec[players_vec.len() - 1].clone())
}
fn format_time(sec: i64) -> String {
let minutes = sec / 60;
let secondes = sec % 60;
let result = format!("{:02}:{:02}", minutes, secondes);
result.to_string()
}
fn get_time(utc: bool, mut format: &str) {
// Format reference: https://docs.rs/chrono/0.4.10/chrono/format/strftime/index.html
if format.len() == 0 {
format = "%H:%M";
}
if utc {
let local_time = Local::now();
let utc_time = DateTime::<Utc>::from_utc(local_time.naive_utc(), Utc);
println!("{}", utc_time.format(format));
} else {
let local_time = Local::now();
println!("{}", local_time.format(format));
}
} }
fn main() { fn main() {
let args: Vec<String> = env::args().collect(); let conf = config::read();
let help_text: &str = "Available commands -mb, -cb, -tl <TIME FORMAT>, -tu <TIME FORMAT>, -p";
match args.len() { match conf.action {
1 => { config::Action::Cpu => utils::cpu_load_bar(15, &conf),
panic!(help_text); config::Action::Mem => utils::mem_load_bar(15, &conf),
} config::Action::Mpris => utils::mpris(&conf),
2 => match args[1].as_ref() { config::Action::Utctime => utils::get_time(true, conf.ut_format),
"-cb" => cpu_load_bar(15), config::Action::Localtime => utils::get_time(false, conf.lt_format),
"-mb" => mem_load_bar(15), config::Action::Mpd => utils::mpd(&conf),
"-tl" => get_time(false, ""),
"-tu" => get_time(true, ""),
"-p" => match player_info(get_player().unwrap()) {
Ok(mut track_info) => {
let mut title_len = 30;
let mut artist_len = 30;
let mut separator: String = "".to_string();
let max_shift = 6;
if track_info.artist.chars().count() == 0 {
separator = "".to_string();
title_len += artist_len;
}
if artist_len + max_shift >= track_info.artist.chars().count() {
artist_len = track_info.artist.chars().count()
}
if track_info.artist.len() > artist_len {
let mut artist: String = String::new();
let mut counter = 0;
for ch in track_info.artist.chars() {
if counter == artist_len {
artist.push_str("..");
break;
}
artist.push(ch);
counter += 1;
}
track_info.artist = artist;
}
if title_len + max_shift >= track_info.title.chars().count() {
title_len = track_info.title.chars().count()
}
if track_info.title.len() > title_len {
let mut title: String = String::new();
let mut counter = 0;
for ch in track_info.title.chars() {
if counter == title_len {
title.push_str("..");
break;
}
title.push(ch);
counter += 1;
}
track_info.title = title;
}
println!(
"#[none]#[bold]{}{}{}#[none]{}{}{}{} {}[{}/{}] {} {}#[default]",
TRACK_NAME,
track_info.title,
END,
separator,
TRACK_ARTIST,
track_info.artist,
END,
TRACK_TIME,
track_info.position,
track_info.duration,
track_info.status,
END,
);
}
Err(_e) => println!("No music playing"),
},
_ => panic!(help_text),
},
3 => match args[1].as_ref() {
"-tl" => get_time(false, args[2].as_ref()),
"-tu" => get_time(true, args[2].as_ref()),
_ => panic!(help_text),
},
_ => {
panic!(help_text);
}
} }
} }

272
src/utils.rs Normal file
View File

@@ -0,0 +1,272 @@
use crate::config;
use chrono::{Local, Utc};
use dbus::arg::RefArg;
use dbus::blocking::stdintf::org_freedesktop_dbus::Properties;
use dbus::{arg, blocking::Connection};
use mpd::Client;
use size_format::SizeFormatterBinary;
use std::process;
use std::thread;
use std::time::Duration;
use sysinfo::System;
#[derive(Debug, Clone)]
pub struct TrackInfo {
pub title: String,
pub artist: String,
pub position: String,
pub duration: String,
pub status: String,
}
pub fn to_bar(value: i32, max: i32, low: f32, mid: f32, config: &config::Config) {
let mut bar = "".to_string();
let ratio = (value as f32) / (max as f32);
bar.push_str(if ratio < low {
&config.color_low
} else if ratio < mid {
&config.color_mid
} else {
&config.color_high
});
let symbol = config.bar_symbol.as_deref().unwrap_or("");
let empty = config.bar_empty_symbol.as_deref().unwrap_or(" ");
for i in 0..max {
bar.push_str(if i < value { symbol } else { empty });
}
bar.push_str(&config.color_end);
bar.push('|');
print!("{}", bar);
}
pub fn mem_load_bar(bar_len: i32, config: &config::Config) {
let mut sys = System::new_all();
sys.refresh_memory();
let total_memory = sys.total_memory();
let used_memory = sys.used_memory();
// On macOS sysinfo.used_memory() includes caches and compressed memory
// Try a more conservative estimate
// Usually real used memory is about 30-50% of what sysinfo shows
#[cfg(target_os = "macos")]
let actual_used = used_memory * 40 / 100; // Approximately 40% of sysinfo.used_memory
#[cfg(not(target_os = "macos"))]
let actual_used = used_memory;
let actual_free = total_memory - actual_used;
let used_ratio = actual_used as f32 / total_memory as f32;
let len = (used_ratio * bar_len as f32) as i32;
to_bar(
len,
bar_len,
config.low_threshold,
config.mid_threshold,
config,
);
// Show: used/free
print!(
"{}/{} #[default]",
SizeFormatterBinary::new(actual_used),
SizeFormatterBinary::new(actual_free)
);
}
pub fn cpu_load_bar(bar_len: i32, config: &config::Config) {
let mut sys = System::new_all();
// Update CPU information
sys.refresh_cpu_all();
// Wait a bit to get accurate CPU usage data
thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
sys.refresh_cpu_all();
let cpu_count = sys.cpus().len();
// Get average CPU usage
let cpu_usage: f32 = sys.cpus().iter().map(|cpu| cpu.cpu_usage()).sum::<f32>() / cpu_count as f32;
let cpu_load_ratio = cpu_usage / 100.0; // sysinfo returns percentages
let len = (cpu_load_ratio * bar_len as f32).round() as i32;
to_bar(
len,
bar_len,
config.low_threshold,
config.mid_threshold,
config,
);
print!("{:.1}% CPU#[default]", cpu_usage);
}
pub fn get_player() -> Result<Vec<String>, Box<dyn std::error::Error>> {
let conn = Connection::new_session()?;
let proxy = conn.with_proxy("org.freedesktop.DBus", "/", Duration::from_secs(5));
let (names,): (Vec<String>,) = proxy.method_call("org.freedesktop.DBus", "ListNames", ())?;
Ok(names
.into_iter()
.filter(|n| n.contains("org.mpris.MediaPlayer2"))
.collect())
}
pub fn player_info(players: Vec<String>) -> Result<TrackInfo, Box<dyn std::error::Error>> {
for player in players {
let conn = Connection::new_session()?;
let proxy = conn.with_proxy(player, "/org/mpris/MediaPlayer2", Duration::from_secs(5));
let metadata: arg::PropMap = proxy.get("org.mpris.MediaPlayer2.Player", "Metadata")?;
let title = metadata
.get("xesam:title")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let artist = metadata
.get("xesam:artist")
.and_then(|v| v.as_iter())
.and_then(|mut artists| artists.next().and_then(|a| a.as_str()))
.unwrap_or("")
.to_string();
let duration_us = metadata
.get("mpris:length")
.and_then(|v| v.as_i64())
.unwrap_or(0);
let position_us: i64 = proxy.get("org.mpris.MediaPlayer2.Player", "Position")?;
let status_text: String = proxy.get("org.mpris.MediaPlayer2.Player", "PlaybackStatus")?;
let status = match status_text.as_str() {
"Playing" => "",
"Paused" => "",
_ => "",
}
.to_string();
let track_info = TrackInfo {
title,
artist,
position: format_time(position_us / 1_000_000),
duration: format_time(duration_us / 1_000_000),
status,
};
if track_info.status == "" {
return Ok(track_info);
}
}
Err("No active player".into())
}
pub fn format_time(sec: i64) -> String {
format!("{:02}:{:02}", sec / 60, sec % 60)
}
pub fn get_time(utc: bool, format: Option<String>) {
let fmt = format.unwrap_or_else(|| "%H:%M".to_string());
let now = if utc {
Utc::now().format(&fmt)
} else {
Local::now().format(&fmt)
};
println!("{}", now);
}
fn shorten(line: &str, max_len: usize) -> String {
if line.chars().count() > max_len {
format!("{}..", line.chars().take(max_len).collect::<String>())
} else {
line.to_string()
}
}
fn format_player(track_info: TrackInfo, config: &config::Config) {
let separator = if track_info.artist.is_empty() {
""
} else {
""
};
let max_len = if track_info.artist.is_empty() { 60 } else { 30 };
let artist_line = shorten(&track_info.artist, max_len);
let title_line = shorten(&track_info.title, max_len);
if track_info.position == "00:00" || track_info.duration.is_empty() {
println!(
"#[bold]{}{}{}{}{}{} {}{} {}#[default]",
config.color_track_name,
title_line,
config.color_end,
separator,
config.color_track_artist,
artist_line,
config.color_end,
config.color_track_time,
track_info.status
);
} else {
println!(
"#[bold]{}{}{}{}{}{} {}[{}/{}] {}{}{}#[default]",
config.color_track_name,
title_line,
config.color_end,
separator,
config.color_track_artist,
artist_line,
config.color_end,
config.color_track_time,
track_info.position,
track_info.duration,
track_info.status,
config.color_end
);
}
}
pub fn mpris(config: &config::Config) {
match player_info(get_player().unwrap_or_default()) {
Ok(track_info) => format_player(track_info, config),
Err(_) => println!("No music playing"),
}
}
pub fn mpd(config: &config::Config) {
let mut conn = Client::connect(&config.mpd_server).unwrap_or_else(|e| {
println!("Can't connect to MPD server. {}", e);
process::exit(1);
});
let song = conn.currentsong().unwrap_or(None);
let status = conn.status().unwrap();
let artist = song
.as_ref()
.and_then(|s| s.tags.iter().find(|(k, _)| k == "Artist").map(|(_, v)| v))
.cloned()
.unwrap_or_default();
let title = song
.as_ref()
.and_then(|s| s.title.clone().or_else(|| s.name.clone()))
.unwrap_or_default();
let (position, duration) = status.time.unwrap_or_default();
let track_info = TrackInfo {
title,
artist,
position: format_time(position.as_secs() as i64),
duration: format_time(duration.as_secs() as i64),
status: match status.state {
mpd::State::Play => "",
mpd::State::Pause => "",
mpd::State::Stop => "",
}
.to_string(),
};
format_player(track_info, config);
}