Compare commits

..

No commits in common. "2a2c173683b4992942cb7dfdf40ca159fd1445c0" and "c3a2b2d56658dfef8829c0d34eee7de387a3d4b9" have entirely different histories.

16 changed files with 111 additions and 89 deletions

View File

@ -88,7 +88,7 @@ fn append_tx_send_code(input: &mut syn::ItemFn) -> &mut syn::ItemFn {
.expect("This is valid.");
return_type_as_return_type
} else {
// There is only mlua::Error left
// There is only rlua
ReturnType::Default
}
}
@ -108,22 +108,23 @@ fn append_tx_send_code(input: &mut syn::ItemFn) -> &mut syn::ItemFn {
ReturnType::Type(_, _) => {
quote! {
{
Event::CommandEvent(Command::#function_name_pascal(input_str.clone()))
Event::CommandEvent(Command::#function_name_pascal(input_str))
}
}
}
};
quote! {
{
let tx:
core::cell::Ref<
tokio::sync::mpsc::Sender<crate::app::events::event_types::Event>
> =
let tx: std::sync::Arc<std::sync::Mutex<tokio::sync::mpsc::Sender<crate::app::events::event_types::Event>>> =
lua
.app_data_ref()
.named_registry_value("sender_for_ci_commands")
.expect("This exists, it was set before");
(*tx)
tx
// FIXME: This is sync code, it needs to be run in a blocking allowed
// executor
.lock()
.expect("This should work, as only one function is executed. It wil however fail, when concurrency is added");
.send(#send_data)
.await
.expect("This should work, as the reciever is not dropped");

View File

@ -44,7 +44,7 @@ pub fn generate_generate_ci_function(input: &syn::DeriveInput) -> TokenStream2 {
lua: &mut mlua::Lua,
tx: tokio::sync::mpsc::Sender<crate::app::events::event_types::Event>)
{
lua.set_app_data(tx);
lua.set_named_registry_value("sender_for_ci_commands", std::sync::Arc::new(std::sync::Mutex::new(tx))).expect("This should always work, as the value is added before all else");
let globals = lua.globals();
#input_tokens
}

View File

@ -1,6 +1,7 @@
// FIXME: This file needs documentation with examples of how the proc macros work.
// for now use `cargo expand app::command_interface` for an overview
use lua_macros::{ci_command, turn_struct_to_ci_commands};
use rlua::Context;
use super::events::event_types::Event;
@ -22,30 +23,22 @@ use super::events::event_types::Event;
/// `String` and `()`).
#[turn_struct_to_ci_commands]
struct Commands {
/// Greets the user
greet: fn(usize) -> String,
/// Closes the application
// Closes the application
#[gen_default_lua_function]
exit: fn(),
/// Shows the command line
#[gen_default_lua_function]
command_line_show: fn(),
/// Hides the command line
#[gen_default_lua_function]
command_line_hide: fn(),
/// Go to the next plane
#[gen_default_lua_function]
cycle_planes: fn(),
/// Go to the previous plane
#[gen_default_lua_function]
cycle_planes_rev: fn(),
/// Send a message to the current room
/// The send message is interpreted literally.
//// sends a message to the current room
room_message_send: fn(String) -> String,
}

View File

@ -1,4 +1,4 @@
use crate::app::{command_interface::Command, events::event_types::EventStatus, App};
use crate::app::{events::event_types::EventStatus, App, command_interface::Command};
use anyhow::Result;
use cli_log::info;
@ -32,9 +32,5 @@ pub async fn handle(app: &mut App<'_>, command: &Command) -> Result<EventStatus>
}
EventStatus::Ok
}
Command::Greet(name) => {
info!("Greated {}", name);
EventStatus::Ok
}
})
}

View File

@ -18,7 +18,7 @@ pub async fn handle(app: &mut App<'_>, command: &str) -> Result<EventStatus> {
.with_context(|| format!("Failed to execute: `{command}`"))?;
info!("Function evaluated to: `{output}`");
app.tx.send(Event::CiOutput(output)).await.context("Failed to send ci output to internal event stream")?;
app.transmitter.send(Event::CiOutput(output));
Ok(EventStatus::Ok)
}

View File

@ -1,4 +1,4 @@
use anyhow::{Context, Result};
use anyhow::Result;
use crossterm::event::{Event as CrosstermEvent, KeyCode, KeyEvent, KeyModifiers};
use crate::{
@ -15,14 +15,14 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
CrosstermEvent::Key(KeyEvent {
code: KeyCode::Esc, ..
}) => {
app.tx
app.transmitter
.send(Event::CommandEvent(Command::Exit))
.await?;
}
CrosstermEvent::Key(KeyEvent {
code: KeyCode::Tab, ..
}) => {
app.tx
app.transmitter
.send(Event::CommandEvent(Command::CyclePlanes))
.await?;
}
@ -30,7 +30,7 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
code: KeyCode::BackTab,
..
}) => {
app.tx
app.transmitter
.send(Event::CommandEvent(Command::CyclePlanesRev))
.await?;
}
@ -39,7 +39,7 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
modifiers: KeyModifiers::CONTROL,
..
}) => {
app.tx
app.transmitter
.send(Event::CommandEvent(Command::CommandLineShow))
.await?;
}
@ -51,7 +51,7 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
modifiers: KeyModifiers::ALT,
..
}) => {
app.tx
app.transmitter
.send(Event::CommandEvent(Command::RoomMessageSend(
app.ui.message_compose.lines().join("\n"),
)))
@ -155,7 +155,7 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
code: KeyCode::Enter,
..
}) => {
let ci_event = app.ui
let cli_event = app.ui
.cli
.as_mut()
.expect("This is already checked")
@ -165,10 +165,16 @@ pub async fn handle(app: &mut App<'_>, input_event: &CrosstermEvent) -> Result<E
"There can only be one line in the buffer, as we collect it on enter being inputted"
)
.to_owned();
app.tx
.send(Event::LuaCommand(ci_event))
.await
.context("Failed to send lua command to internal event stream")?;
let output = app.handle_ci_event(&cli_event).await?;
// delete the old text:
// We can use a mutable borrow now, as we should only need one
let cli = app.ui.cli.as_mut().expect("Checked above");
cli.move_cursor(tui_textarea::CursorMove::Jump(0, 0));
cli.delete_str(0, cli_event.chars().count());
assert!(cli.is_empty());
cli.insert_str(output);
}
_ => {
app.ui

View File

@ -1,11 +1,4 @@
// input events
pub mod setup;
pub mod main;
// matrix
pub mod matrix;
// ci
pub mod ci_output;
pub mod command;
pub mod lua_command;
pub mod main;
pub mod matrix;
pub mod setup;

View File

@ -3,9 +3,9 @@ mod handlers;
use anyhow::{Context, Result};
use crossterm::event::Event as CrosstermEvent;
use crate::app::{command_interface::Command, status::State, App};
use crate::app::{status::State, App, command_interface::Command};
use self::handlers::{ci_output, command, lua_command, main, matrix, setup};
use self::handlers::{command, main, matrix, setup};
use super::EventStatus;
@ -14,8 +14,6 @@ pub enum Event {
InputEvent(CrosstermEvent),
MatrixEvent(matrix_sdk::deserialized_responses::SyncResponse),
CommandEvent(Command),
CiOutput(String),
LuaCommand(String),
}
impl Event {
@ -28,14 +26,6 @@ impl Event {
Event::CommandEvent(event) => command::handle(app, event)
.await
.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)
}),
Event::LuaCommand(lua_code) => {
lua_command::handle(app, lua_code).await.with_context(|| {
format!("Failed to handle lua code: `{:#?}`", lua_code)
})
}
Event::InputEvent(event) => match app.status.state() {
State::None => Ok(EventStatus::Ok),

View File

@ -1,10 +1,11 @@
pub mod command_interface;
pub mod events;
pub mod status;
pub mod transmitter;
use std::path::Path;
use anyhow::{Error, Result, Context};
use anyhow::{Context, Error, Result};
use cli_log::info;
use matrix_sdk::Client;
use mlua::Lua;
@ -18,16 +19,14 @@ use crate::{
ui::{central, setup},
};
use self::events::event_types;
use self::{events::event_types, transmitter::Transmitter};
pub struct App<'ui> {
ui: central::UI<'ui>,
accounts_manager: AccountsManager,
status: Status,
tx: mpsc::Sender<Event>,
rx: mpsc::Receiver<Event>,
transmitter: Transmitter,
input_listener_killer: CancellationToken,
matrix_listener_killer: CancellationToken,
@ -37,7 +36,7 @@ pub struct App<'ui> {
impl App<'_> {
pub fn new() -> Result<Self> {
fn set_up_lua(tx: mpsc::Sender<Event>) -> Lua {
let mut lua = Lua::new();
let lua = Lua::new();
generate_ci_functions(&mut lua, tx);
lua
@ -51,25 +50,39 @@ impl App<'_> {
None
};
let (tx, rx) = mpsc::channel(256);
let transmitter = Transmitter::new();
Ok(Self {
ui: central::UI::new()?,
accounts_manager: AccountsManager::new(config)?,
status: Status::new(None),
tx: tx.clone(),
rx,
transmitter,
input_listener_killer: CancellationToken::new(),
matrix_listener_killer: CancellationToken::new(),
lua: set_up_lua(tx),
lua: set_up_lua(transmitter.tx()),
})
}
pub async fn handle_ci_event(&self, event: &str) -> Result<String> {
info!("Recieved ci event: `{event}`; executing..");
// TODO: Should the ci support more than strings?
let output = self.lua.context(|context| -> Result<String> {
let output = context
.load(&event)
.eval::<String>()
.with_context(|| format!("Failed to execute: `{event}`"))?;
info!("Function evaluated to: `{output}`");
Ok(output)
})?;
Ok(output)
}
pub async fn run(&mut self) -> Result<()> {
// Spawn input event listener
tokio::task::spawn(events::poll_input_events(
self.tx.clone(),
self.transmitter.tx(),
self.input_listener_killer.clone(),
));
@ -85,7 +98,11 @@ impl App<'_> {
self.status.set_state(State::Main);
self.ui.update(&self.status).await?;
let event = self.rx.recv().await.context("Failed to get next event")?;
let event = self
.transmitter
.recv()
.await
.context("Failed to get next event")?;
match event.handle(self).await? {
event_types::EventStatus::Ok => (),
@ -105,7 +122,11 @@ impl App<'_> {
self.status.set_state(State::Setup);
self.ui.update_setup().await?;
let event = self.rx.recv().await.context("Failed to get next event")?;
let event = self
.transmitter
.recv()
.await
.context("Failed to get next event")?;
match event.handle(self).await? {
event_types::EventStatus::Ok => (),
@ -129,7 +150,7 @@ impl App<'_> {
// Spawn Matrix Event Listener
tokio::task::spawn(events::poll_matrix_events(
self.tx.clone(),
self.transmitter.tx(),
self.matrix_listener_killer.clone(),
client.clone(),
));

View File

@ -1,5 +1,5 @@
use anyhow::{Error, Result};
use cli_log::warn;
use cli_log::{warn, info};
use indexmap::IndexMap;
use matrix_sdk::{
room::MessagesOptions,

32
src/app/transmitter.rs Normal file
View File

@ -0,0 +1,32 @@
use anyhow::{bail, Context, Result};
use tokio::sync::mpsc;
use super::events::event_types::Event;
pub struct Transmitter {
tx: mpsc::Sender<Event>,
rx: mpsc::Receiver<Event>,
}
impl Transmitter {
pub fn new() -> Transmitter {
let (tx, rx) = mpsc::channel(256);
Transmitter {
tx,
rx,
}
}
pub fn tx(&self) -> mpsc::Sender<Event> {
self.tx.to_owned()
}
pub async fn recv(&mut self) -> Result<Event> {
match self.rx.recv().await {
Some(event) => Ok(event),
None => bail!("Event channel has no senders"),
}
}
pub async fn send(&mut self, event: Event) -> Result<()> {
self.tx.send(event).await.context("Failed to send event")
}
}

View File

@ -2,8 +2,8 @@ pub mod update;
use std::io::Stdout;
use anyhow::{bail, Context, Result};
use cli_log::{info, warn};
use anyhow::{bail, Result, Context};
use cli_log::info;
use crossterm::{
event::DisableMouseCapture,
execute,
@ -125,16 +125,6 @@ impl UI<'_> {
);
}
pub fn set_command_output(&mut self, output: &str) {
info!("Setting output to: `{}`", output);
if let Some(_) = self.cli {
let cli = Some(TextArea::from([output]));
self.cli = cli;
} else {
warn!("Failed to set output");
}
}
pub fn cli_enable(&mut self) {
self.input_position = InputPosition::CLI;
if self.cli.is_some() {

View File

@ -9,7 +9,7 @@ use tui::{
use crate::{app::status::Room, ui::central::InputPosition};
pub fn init<'a>(room: Option<&'a Room>, colors: &Vec<Color>) -> Result<(List<'a>, ListState)> {
pub fn init<'a>(room: Option<&Room>, colors: &Vec<Color>) -> Result<(List<'a>, ListState)> {
let content = match room {
Some(room) => get_content_from_room(room).context("Failed to get content from room")?,
None => vec![ListItem::new(Text::styled(

View File

@ -6,7 +6,7 @@ use tui::{
use crate::{app::status::Room, ui::central::InputPosition};
pub fn init<'a>(room: Option<&'a Room>, colors: &Vec<Color>) -> Paragraph<'a> {
pub fn init<'a>(room: Option<&Room>, colors: &Vec<Color>) -> Paragraph<'a> {
let mut room_info_content = Text::default();
if let Some(room) = room {
room_info_content.extend(Text::styled(room.name(), Style::default().fg(Color::Cyan)));

View File

@ -6,7 +6,7 @@ use tui::{
use crate::{app::status::Status, ui::central::InputPosition};
pub fn init<'a>(status: &'a Status, colors: &Vec<Color>) -> List<'a> {
pub fn init<'a>(status: &Status, colors: &Vec<Color>) -> List<'a> {
let rooms_content: Vec<_> = status
.rooms()
.iter()

View File

@ -7,7 +7,7 @@ use tui::{
use crate::{app::status::Status, ui::central::InputPosition};
pub fn init<'a>(status: &'a Status, colors: &Vec<Color>) -> Paragraph<'a> {
pub fn init<'a>(status: &Status, colors: &Vec<Color>) -> Paragraph<'a> {
let mut status_content = Text::styled(
status.account_name(),
Style::default().add_modifier(Modifier::BOLD),