Skip to content

Commit

Permalink
Method calls! You can now do dbus method calls in the TUI!
Browse files Browse the repository at this point in the history
When hitting Enter on a method in the tree a popup will show.
You can then enter each argument in text fields in this popup
the arguments are then parsed into dbus types that are sent with the method call
The return value is then put into the output text box.

To do this a parser for a human readable format for dbus types was created
parsers are created for a given type signature, and the then input is validated against that
The parser is written using chumsky with subparsers for each dbus type.
  • Loading branch information
Troels51 committed Nov 11, 2024
1 parent 03687f4 commit eddd8e1
Show file tree
Hide file tree
Showing 10 changed files with 1,212 additions and 256 deletions.
518 changes: 308 additions & 210 deletions Cargo.lock

Large diffs are not rendered by default.

13 changes: 8 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ authors = ["Troels Hoffmeyer <troels.d.hoffmeyer@gmail.com>"]
description = "dBus TUI for introspecting your current dbus session/system"
license = "MIT"
repository = "https://github.com/Troels51/dtui"
rust-version = "1.56"
rust-version = "1.75"
keywords = ["tui", "dbus"]
categories = ["command-line-utilities"]
exclude = [
Expand All @@ -16,16 +16,19 @@ exclude = [
]

[dependencies]
tui-tree-widget = "0.19"
zbus = { version = "4.2", default-features = false, features = ["tokio"] }
tui-tree-widget = "0.21"
zbus = { git = "https://github.com/dbus2/zbus.git", branch = "main", default-features = false, features = ["tokio"] }
crossterm = "0.27"
tokio = { version = "1.32", features = ["full"] }
async-recursion = "1.1.1"
itertools = "0.11.0"
clap = { version = "4.4.1", features = ["derive"] }
ratatui = { version = "0.26.2", features = ["macros"] }
zbus_xml = "4.0.0"
ratatui = { version = "0.27", features = ["macros"] }
zbus_xml = { git = "https://github.com/dbus2/zbus.git", branch = "main", default-features = false }
tracing-error = "0.2.0"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "json", "fmt"] }
tracing-journald = "0.3.0"
tui-textarea = "0.5.1"
zbus_names = { git = "https://github.com/dbus2/zbus.git", branch = "main", default-features = false }
chumsky = "0.9.3"
216 changes: 201 additions & 15 deletions src/bin/dtui/app.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,72 @@
use std::time::{Duration, Instant};

use chumsky::Parser;
use crossterm::event::{self, Event, KeyCode};
use itertools::Itertools;
use ratatui::{backend::Backend, Terminal};
use tokio::sync::mpsc::Receiver;
use tracing::Level;
use zbus::names::OwnedBusName;
use tui_textarea::CursorMove;
use zbus::{
names::{OwnedBusName, OwnedInterfaceName, OwnedMemberName},
zvariant::OwnedObjectPath,
};

use crate::{
dbus_handler::DbusActorHandle, messages::AppMessage, stateful_list::StatefulList,
stateful_tree::StatefulTree, ui::ui,
dbus_handler::DbusActorHandle,
messages::AppMessage,
stateful_list::StatefulList,
stateful_tree::{MethodDescription, StatefulTree},
ui::ui,
};

pub struct MethodArgVisual {
pub text_area: tui_textarea::TextArea<'static>,
pub parser:
Box<dyn Parser<char, zbus::zvariant::Value<'static>, Error = chumsky::error::Simple<char>>>,
pub is_input: bool, // Is this Arg an input or output
}
pub struct MethodCallPopUp {
pub service: OwnedBusName,
pub object: OwnedObjectPath,
pub interface: OwnedInterfaceName,
pub method_description: MethodDescription,
pub method_arg_vis: Vec<MethodArgVisual>,
pub selected: usize,
pub called: bool,
}
impl MethodCallPopUp {
fn new(
service: OwnedBusName,
object: OwnedObjectPath,
interface: OwnedInterfaceName,
method_description: MethodDescription,
) -> Self {
Self {
service,
object,
interface,
method_description,
method_arg_vis: Vec::new(), // This gets filled on UI. Maybe there is a better way of doing this
selected: 0,
called: false,
}
}
}

impl PartialEq for MethodCallPopUp {
fn eq(&self, other: &Self) -> bool {
self.method_description == other.method_description
}
}

#[derive(PartialEq)]
pub enum WorkingArea {
Services,
Objects,
MethodCallPopUp(MethodCallPopUp),
}

// TODO: maybe we should use Components instead, Objects/Services/PopUp would be a componenet, and they would have their own input/render functions
pub struct App {
dbus_rx: Receiver<AppMessage>,
dbus_handle: DbusActorHandle,
Expand Down Expand Up @@ -58,6 +108,26 @@ pub async fn run_app<B: Backend>(
AppMessage::Services(names) => {
app.services = StatefulList::with_items(names);
}
AppMessage::MethodCallResponse(_method, message) => {
if let WorkingArea::MethodCallPopUp(ref mut popup) = app.working_area {
popup.called = true;
if let Ok(value) = message.body().deserialize::<zbus::zvariant::Structure>()
{
for (index, output_field) in popup
.method_arg_vis
.iter_mut()
.filter(|field| !field.is_input)
.enumerate()
{
output_field.text_area.move_cursor(CursorMove::Head);
output_field.text_area.delete_line_by_end(); // The way to clear a text area
output_field
.text_area
.insert_str(format!("{}", value.fields()[index]));
}
}
}
}
},
_error => (),
};
Expand All @@ -67,39 +137,117 @@ pub async fn run_app<B: Backend>(
if crossterm::event::poll(timeout)? {
if let Event::Key(key) = event::read()? {
match key.code {
KeyCode::Char('q') => return Ok(()),
KeyCode::Enter => match app.working_area {
WorkingArea::Services => {
if let Some(selected_index) = app.services.state.selected() {
let item = app.services.items[selected_index].clone();
app.dbus_handle.request_objects_from(item).await;
KeyCode::Char('q') => match app.working_area {
WorkingArea::Services => return Ok(()),
WorkingArea::Objects => return Ok(()),
WorkingArea::MethodCallPopUp(_) => (),
},
KeyCode::Enter => {
match app.working_area {
WorkingArea::Services => {
if let Some(selected_index) = app.services.state.selected() {
let item = app.services.items[selected_index].clone();
app.dbus_handle.request_objects_from(item).await;
}
}
WorkingArea::Objects => {
if let Some(full_description) =
extract_description(app.objects.state.selected())
{
app.working_area =
WorkingArea::MethodCallPopUp(MethodCallPopUp::new(
app.services.items
[app.services.state.selected().unwrap()]
.clone(),
full_description.0,
full_description.1,
full_description.2,
));
}
}
WorkingArea::MethodCallPopUp(ref popup) =>
// Call method
{
let parses = popup
.method_arg_vis
.iter()
.filter(|input| input.is_input)
.map(|input| {
input.parser.parse(input.text_area.lines()[0].clone())
});
if parses.clone().all(
|result: Result<
zbus::zvariant::Value<'static>,
Vec<chumsky::error::Simple<char>>,
>| Result::is_ok(&result),
) {
let values: Vec<zbus::zvariant::OwnedValue> = parses
.map(|value| {
// We know that they are all Ok, so unwrap is fine here
zbus::zvariant::OwnedValue::try_from(value.unwrap())
.unwrap()
})
.collect();
app.dbus_handle
.call_method(
popup.service.clone(),
popup.object.clone(),
popup.interface.clone(),
OwnedMemberName::from(
popup.method_description.0.name(),
),
values,
)
.await;
} else {
// Alert user that call cannot be made if arguments cannot be parsed
}
}
}
WorkingArea::Objects => {
//TOTO
}
},
}
KeyCode::Left => match app.working_area {
WorkingArea::Services => app.services.unselect(),
WorkingArea::Objects => app.objects.left(),
WorkingArea::MethodCallPopUp(ref mut popup) => {
popup.method_arg_vis[0].text_area.input(key);
}
},
KeyCode::Down => match app.working_area {
WorkingArea::Services => app.services.next(),
WorkingArea::Objects => app.objects.down(),
WorkingArea::MethodCallPopUp(ref mut popup) => {
popup.selected =
std::cmp::min(popup.selected + 1, popup.method_arg_vis.len());
}
},
KeyCode::Up => match app.working_area {
WorkingArea::Services => app.services.previous(),
WorkingArea::Objects => app.objects.up(),
WorkingArea::MethodCallPopUp(ref mut popup) => {
popup.selected = popup.selected.saturating_sub(1);
}
},
KeyCode::Right => match app.working_area {
WorkingArea::Services => {}
WorkingArea::Objects => app.objects.right(),
WorkingArea::MethodCallPopUp(ref mut popup) => {
popup.method_arg_vis[0].text_area.input(key);
}
},
KeyCode::Tab => match app.working_area {
WorkingArea::Services => app.working_area = WorkingArea::Objects,
WorkingArea::Objects => app.working_area = WorkingArea::Services,
WorkingArea::MethodCallPopUp(ref _method) => {}
},
KeyCode::Esc => {
app.working_area = WorkingArea::Objects;
}
_ => match app.working_area {
WorkingArea::MethodCallPopUp(ref mut popup) => {
popup.method_arg_vis[popup.selected].text_area.input(key);
}
_ => (),
},
_ => (),
}
tracing::event!(
Level::DEBUG,
Expand All @@ -114,3 +262,41 @@ pub async fn run_app<B: Backend>(
}
}
}

/// Takes a stateful_tree::DbusIdentifier, which is an identifier for where a node is in the UI tree
/// and if the selection is a method, it will extract the path, interface name and method description
/// Otherwise it returns None
fn extract_description(
selected: &[crate::stateful_tree::DbusIdentifier],
) -> Option<(OwnedObjectPath, OwnedInterfaceName, MethodDescription)> {
let object_path = selected
.iter()
.filter_map(|identifier| match identifier {
crate::stateful_tree::DbusIdentifier::Object(o) => Some(o),
_ => None,
})
.next();
let interface_name = selected
.iter()
.filter_map(|identifier| match identifier {
crate::stateful_tree::DbusIdentifier::Interface(i) => Some(i),
_ => None,
})
.next();
let member_name = selected
.iter()
.filter_map(|identifier| match identifier {
crate::stateful_tree::DbusIdentifier::Method(m) => Some(m),
_ => None,
})
.next();
if object_path.is_some() && interface_name.is_some() && member_name.is_some() {
Some((
OwnedObjectPath::try_from(object_path.unwrap().clone()).unwrap(),
OwnedInterfaceName::try_from(interface_name.unwrap().clone()).unwrap(),
member_name.unwrap().clone(),
))
} else {
None
}
}
55 changes: 54 additions & 1 deletion src/bin/dtui/dbus_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ use std::{collections::HashMap, error::Error, io::BufReader};

use async_recursion::async_recursion;
use tokio::sync::mpsc::{self, Receiver, Sender};
use zbus::{names::OwnedBusName, zvariant::ObjectPath, Connection};
use zbus::{
names::{OwnedBusName, OwnedInterfaceName, OwnedMemberName},
zvariant::{ObjectPath, OwnedValue, StructureBuilder},
Connection,
};
use zbus_xml::Node;

use crate::messages::{AppMessage, DbusMessage};
Expand Down Expand Up @@ -85,6 +89,43 @@ impl DbusActor {
let _ = self.app_sender.send(AppMessage::Services(names)).await;
}
}
DbusMessage::MethodCallRequest(service, object_path, interface, method, values) => {
let mut body = StructureBuilder::new();
let is_empty = values.is_empty();
for v in values {
body.push_value(v.into());
}
let method_call_response = if !is_empty {
self.connection
.call_method(
Some(service),
object_path,
Some(interface),
method.clone(),
&body.build().unwrap(),
)
.await
} else {
self.connection
.call_method(
Some(service),
object_path,
Some(interface),
method.clone(),
&(),
)
.await
};
match method_call_response {
Ok(message) => {
let _ = self
.app_sender
.send(AppMessage::MethodCallResponse(method, message))
.await;
}
Err(e) => tracing::debug!("Method call error {}", e),
};
}
}
}
}
Expand Down Expand Up @@ -118,4 +159,16 @@ impl DbusActorHandle {
let msg = DbusMessage::ServiceRequest();
let _ = self.sender.send(msg).await;
}

pub async fn call_method(
&self,
service: OwnedBusName,
object: zbus::zvariant::OwnedObjectPath,
interface: OwnedInterfaceName,
method: OwnedMemberName,
values: Vec<OwnedValue>,
) {
let msg = DbusMessage::MethodCallRequest(service, object, interface, method, values);
let _ = self.sender.send(msg).await;
}
}
Loading

0 comments on commit eddd8e1

Please sign in to comment.