Fix(treewide): Update codebase to new lua_macros api

This commit is contained in:
Benedikt Peetz 2023-07-20 21:49:23 +02:00
parent c243c90cab
commit 20c751fd7f
Signed by: bpeetz
GPG Key ID: A5E94010C3A642AD
7 changed files with 108 additions and 69 deletions

View File

@ -18,4 +18,4 @@ tokio-util = "0.7"
serde = "1.0" serde = "1.0"
cli-log = "2.0" cli-log = "2.0"
indexmap = "2.0.0" indexmap = "2.0.0"
mlua = { version = "0.8.9", features = ["lua54", "async"] } mlua = { version = "0.8.9", features = ["lua54", "async", "send"] }

View File

@ -1,9 +1,11 @@
// FIXME: This file needs documentation with examples of how the proc macros work. // FIXME: This file needs documentation with examples of how the proc macros work.
// for now use `cargo expand app::command_interface` for an overview // for now use `cargo expand app::command_interface` for an overview
use lua_macros::{ci_command, turn_struct_to_ci_commands};
use super::events::event_types::Event; use std::{io::{Error, ErrorKind}, sync::Arc};
use lua_macros::{ci_command, turn_struct_to_ci_command_enum};
use crate::app::event_types::Event;
/// This struct is here to guarantee, that all functions actually end up in the lua context. /// This struct is here to guarantee, that all functions actually end up in the lua context.
/// I.e. Rust should throw a compile error, when one field is added, but not a matching function. /// I.e. Rust should throw a compile error, when one field is added, but not a matching function.
/// ///
@ -20,41 +22,28 @@ use super::events::event_types::Event;
/// ``` /// ```
/// where $return_type is the type returned by the function (the only supported ones are right now /// where $return_type is the type returned by the function (the only supported ones are right now
/// `String` and `()`). /// `String` and `()`).
#[turn_struct_to_ci_commands]
#[turn_struct_to_ci_command_enum]
struct Commands { struct Commands {
/// Greets the user /// Greets the user
greet: fn(usize) -> String, greet: fn(String) -> String,
/// Closes the application /// Closes the application
#[gen_default_lua_function] //#[expose(lua)]
exit: fn(), exit: fn(),
/// Shows the command line /// Shows the command line
#[gen_default_lua_function]
command_line_show: fn(), command_line_show: fn(),
/// Hides the command line /// Hides the command line
#[gen_default_lua_function]
command_line_hide: fn(), command_line_hide: fn(),
/// Go to the next plane /// Go to the next plane
#[gen_default_lua_function]
cycle_planes: fn(), cycle_planes: fn(),
/// Go to the previous plane /// Go to the previous plane
#[gen_default_lua_function]
cycle_planes_rev: fn(), cycle_planes_rev: fn(),
/// Send a message to the current room /// Send a message to the current room
/// The send message is interpreted literally. /// The send message is interpreted literally.
room_message_send: fn(String) -> String, room_message_send: fn(String) -> String,
} }
#[ci_command]
async fn greet(lua: &mlua::Lua, input_str: String) -> Result<String, mlua::Error> {
Ok(format!("Name is {}", input_str))
}
#[ci_command]
async fn room_message_send(lua: &mlua::Lua, input_str: String) -> Result<String, mlua::Error> {
Ok(format!("Sent message: {}", input_str))
}

View File

@ -2,39 +2,65 @@ use crate::app::{command_interface::Command, events::event_types::EventStatus, A
use anyhow::Result; use anyhow::Result;
use cli_log::info; use cli_log::info;
pub async fn handle(app: &mut App<'_>, command: &Command) -> Result<EventStatus> { pub async fn handle(
app: &mut App<'_>,
command: &Command,
send_output: bool,
) -> Result<(EventStatus, String)> {
macro_rules! set_status_output {
($str:expr) => {
if send_output {
app.ui.set_command_output($str);
}
};
($str:expr, $($args:ident),+) => {
if send_output {
app.ui.set_command_output(&format!($str, $($args),+));
}
};
}
info!("Handling command: {:#?}", command); info!("Handling command: {:#?}", command);
Ok(match command { Ok(match command {
Command::Exit => EventStatus::Terminate, Command::Exit => (
EventStatus::Terminate,
"Terminated the application".to_owned(),
),
Command::CommandLineShow => { Command::CommandLineShow => {
app.ui.cli_enable(); app.ui.cli_enable();
EventStatus::Ok set_status_output!("CLI online");
(EventStatus::Ok, "".to_owned())
} }
Command::CommandLineHide => { Command::CommandLineHide => {
app.ui.cli_disable(); app.ui.cli_disable();
EventStatus::Ok set_status_output!("CLI offline");
(EventStatus::Ok, "".to_owned())
} }
Command::CyclePlanes => { Command::CyclePlanes => {
app.ui.cycle_main_input_position(); app.ui.cycle_main_input_position();
EventStatus::Ok set_status_output!("Switched main input position");
(EventStatus::Ok, "".to_owned())
} }
Command::CyclePlanesRev => { Command::CyclePlanesRev => {
app.ui.cycle_main_input_position_rev(); app.ui.cycle_main_input_position_rev();
EventStatus::Ok set_status_output!("Switched main input position; reversed");
(EventStatus::Ok, "".to_owned())
} }
Command::RoomMessageSend(msg) => { Command::RoomMessageSend(msg) => {
if let Some(room) = app.status.room_mut() { if let Some(room) = app.status.room_mut() {
room.send(msg.clone()).await?; room.send(msg.clone()).await?;
} }
EventStatus::Ok set_status_output!("Send message: `{}`", msg);
(EventStatus::Ok, "".to_owned())
} }
Command::Greet(name) => { Command::Greet(name) => {
info!("Greated {}", name); info!("Greated {}", name);
EventStatus::Ok set_status_output!("Hi, {}!", name);
(EventStatus::Ok, "".to_owned())
} }
Command::Help(_) => todo!(),
}) })
} }

View File

@ -1,24 +1,38 @@
use std::{sync::Arc, time::Duration};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use cli_log::info; use cli_log::{debug, info};
use tokio::{task, time::timeout};
use crate::app::{ use crate::app::{events::event_types::EventStatus, App};
events::event_types::{Event, EventStatus},
App,
};
pub async fn handle(app: &mut App<'_>, command: &str) -> Result<EventStatus> { pub async fn handle(app: &mut App<'_>, command: String) -> Result<EventStatus> {
info!("Recieved ci command: `{command}`; executing.."); info!("Recieved ci command: `{command}`; executing..");
// TODO: Should the ci support more than strings? let local = task::LocalSet::new();
let output = app
.lua // Run the local task set.
.load(command) let output = local
.run_until(async move {
let lua = Arc::clone(&app.lua);
debug!("before_handle");
let c_handle = task::spawn_local(async move {
lua.load(&command)
// FIXME this assumes string output only
.eval_async::<String>() .eval_async::<String>()
.await .await
.with_context(|| format!("Failed to execute: `{command}`"))?; .with_context(|| format!("Failed to execute: `{command}`"))
info!("Function evaluated to: `{output}`"); });
debug!("after_handle");
c_handle
})
.await;
debug!("after_thread");
app.tx.send(Event::CiOutput(output)).await.context("Failed to send ci output to internal event stream")?; let output = timeout(Duration::from_secs(10), output)
.await
.context("Failed to join lua command executor")???;
info!("Command returned: `{}`", output);
Ok(EventStatus::Ok) Ok(EventStatus::Ok)
} }

View File

@ -16,14 +16,14 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
code: KeyCode::Esc, .. code: KeyCode::Esc, ..
}) => { }) => {
app.tx app.tx
.send(Event::CommandEvent(Command::Exit)) .send(Event::CommandEvent(Command::Exit, None))
.await?; .await?;
} }
CrosstermEvent::Key(KeyEvent { CrosstermEvent::Key(KeyEvent {
code: KeyCode::Tab, .. code: KeyCode::Tab, ..
}) => { }) => {
app.tx app.tx
.send(Event::CommandEvent(Command::CyclePlanes)) .send(Event::CommandEvent(Command::CyclePlanes, None))
.await?; .await?;
} }
CrosstermEvent::Key(KeyEvent { CrosstermEvent::Key(KeyEvent {
@ -31,7 +31,7 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
.. ..
}) => { }) => {
app.tx app.tx
.send(Event::CommandEvent(Command::CyclePlanesRev)) .send(Event::CommandEvent(Command::CyclePlanesRev, None))
.await?; .await?;
} }
CrosstermEvent::Key(KeyEvent { CrosstermEvent::Key(KeyEvent {
@ -40,7 +40,7 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
.. ..
}) => { }) => {
app.tx app.tx
.send(Event::CommandEvent(Command::CommandLineShow)) .send(Event::CommandEvent(Command::CommandLineShow, None))
.await?; .await?;
} }
input => match app.ui.input_position() { input => match app.ui.input_position() {
@ -52,9 +52,10 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
.. ..
}) => { }) => {
app.tx app.tx
.send(Event::CommandEvent(Command::RoomMessageSend( .send(Event::CommandEvent(
app.ui.message_compose.lines().join("\n"), Command::RoomMessageSend(app.ui.message_compose.lines().join("\n")),
))) None,
))
.await?; .await?;
app.ui.message_compose_clear(); app.ui.message_compose_clear();
} }

View File

@ -1,11 +1,13 @@
mod handlers; mod handlers;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use cli_log::{info, trace};
use crossterm::event::Event as CrosstermEvent; use crossterm::event::Event as CrosstermEvent;
use tokio::sync::mpsc::Sender;
use crate::app::{command_interface::Command, status::State, App}; use crate::app::{command_interface::Command, status::State, App};
use self::handlers::{ci_output, command, lua_command, main, matrix, setup}; use self::handlers::{command, lua_command, main, matrix, setup};
use super::EventStatus; use super::EventStatus;
@ -13,32 +15,39 @@ use super::EventStatus;
pub enum Event { pub enum Event {
InputEvent(CrosstermEvent), InputEvent(CrosstermEvent),
MatrixEvent(matrix_sdk::deserialized_responses::SyncResponse), MatrixEvent(matrix_sdk::deserialized_responses::SyncResponse),
CommandEvent(Command), CommandEvent(Command, Option<Sender<String>>),
CiOutput(String),
LuaCommand(String), LuaCommand(String),
} }
impl Event { impl Event {
pub async fn handle(&self, app: &mut App<'_>) -> Result<EventStatus> { pub async fn handle(&self, app: &mut App<'_>) -> Result<EventStatus> {
trace!("Recieved event to handle: `{:#?}`", &self);
match &self { match &self {
Event::MatrixEvent(event) => matrix::handle(app, event) Event::MatrixEvent(event) => matrix::handle(app, event)
.await .await
.with_context(|| format!("Failed to handle matrix event: `{:#?}`", event)), .with_context(|| format!("Failed to handle matrix event: `{:#?}`", event)),
Event::CommandEvent(event) => command::handle(app, event) Event::CommandEvent(event, callback_tx) => {
let (result, output) = command::handle(app, event, callback_tx.is_some())
.await .await
.with_context(|| format!("Failed to handle command event: `{:#?}`", event)), .with_context(|| format!("Failed to handle command event: `{:#?}`", event))?;
Event::CiOutput(output) => ci_output::handle(app, output).await.with_context(|| {
format!("Failed to handle command interface output: `{:#?}`", output) if let Some(callback_tx) = callback_tx {
}), callback_tx
Event::LuaCommand(lua_code) => { .send(output.clone())
lua_command::handle(app, lua_code).await.with_context(|| { .await
format!("Failed to handle lua code: `{:#?}`", lua_code) .with_context(|| format!("Failed to send command output: {}", output))?;
})
} }
Ok(result)
}
Event::LuaCommand(lua_code) => lua_command::handle(app, lua_code.to_owned())
.await
.with_context(|| format!("Failed to handle lua code: `{:#?}`", lua_code)),
Event::InputEvent(event) => match app.status.state() { Event::InputEvent(event) => match app.status.state() {
State::None => Ok(EventStatus::Ok), State::None => unreachable!(
"This state should not be available, when we are in the input handling"
),
State::Main => main::handle(app, event) State::Main => main::handle(app, event)
.await .await
.with_context(|| format!("Failed to handle input event: `{:#?}`", event)), .with_context(|| format!("Failed to handle input event: `{:#?}`", event)),

View File

@ -2,9 +2,9 @@ pub mod command_interface;
pub mod events; pub mod events;
pub mod status; pub mod status;
use std::path::Path; use std::{path::Path, sync::Arc};
use anyhow::{Error, Result, Context}; use anyhow::{Context, Error, Result};
use cli_log::info; use cli_log::info;
use matrix_sdk::Client; use matrix_sdk::Client;
use mlua::Lua; use mlua::Lua;
@ -31,16 +31,16 @@ pub struct App<'ui> {
input_listener_killer: CancellationToken, input_listener_killer: CancellationToken,
matrix_listener_killer: CancellationToken, matrix_listener_killer: CancellationToken,
lua: Lua, lua: Arc<Lua>,
} }
impl App<'_> { impl App<'_> {
pub fn new() -> Result<Self> { pub fn new() -> Result<Self> {
fn set_up_lua(tx: mpsc::Sender<Event>) -> Lua { fn set_up_lua(tx: mpsc::Sender<Event>) -> Arc<Lua> {
let mut lua = Lua::new(); let mut lua = Lua::new();
generate_ci_functions(&mut lua, tx); generate_ci_functions(&mut lua, tx);
lua Arc::new(lua)
} }
let path: &std::path::Path = Path::new("userdata/accounts.json"); let path: &std::path::Path = Path::new("userdata/accounts.json");