abacus/abacus-ui/src/app_delegate.rs

134 lines
4.3 KiB
Rust

use abacus_core::Engine;
use druid::{AppDelegate, Target};
use crate::{
commands,
data::{AppData, Block},
};
pub struct Delegate;
impl AppDelegate<AppData> for Delegate {
fn command(
&mut self,
ctx: &mut druid::DelegateCtx,
_target: druid::Target,
cmd: &druid::Command,
data: &mut AppData,
_env: &druid::Env,
) -> druid::Handled {
if let Some(file_info) = cmd.get(druid::commands::SAVE_FILE_AS) {
let filepath = file_info.path().as_os_str().to_str().unwrap().to_string();
data.filename = Some(filepath);
data.save();
return druid::Handled::Yes;
}
if let Some(file_info) = cmd.get(druid::commands::OPEN_FILE) {
let filepath = file_info.path().as_os_str().to_str().unwrap();
match abacus_core::SaveFile::open(filepath) {
Ok(save_file) => {
data.blocks = save_file
.blocks
.iter()
.enumerate()
.map(|(i, b)| Block::new_with_content(&b.name, i, &b.content))
.collect();
}
Err(e) => {
println!("{}", e);
}
}
data.filename = Some(filepath.to_string());
return druid::Handled::Yes;
}
if cmd.is(commands::PROCESS_WORKBOOK) {
let scripts = data
.blocks
.iter()
.enumerate()
.map(|(idx, b)| (idx, b.editor_data.content.to_string()))
.collect::<Vec<_>>();
let sink = ctx.get_external_handle();
std::thread::spawn(move || {
for (idx, script) in scripts.iter() {
let mut engine = Engine::default();
let output = engine.process_script(script);
let _ = sink.submit_command(
crate::commands::BLOCK_PROCESSED,
(*idx, output),
Target::Auto,
);
}
});
return druid::Handled::Yes;
}
if cmd.is(commands::PROCESS_BLOCK) {
if let Some(index) = cmd.get(commands::PROCESS_BLOCK) {
let index = *index;
let script = data
.blocks
.get(index)
.map(|b| b.editor_data.content.to_string());
if let Some(script) = script {
let sink = ctx.get_external_handle();
std::thread::spawn(move || {
let mut engine = Engine::default();
let output = engine.process_script(&script);
let _ = sink.submit_command(
crate::commands::BLOCK_PROCESSED,
(index, output),
Target::Auto,
);
});
}
return druid::Handled::Yes;
}
}
if cmd.is(commands::BLOCK_PROCESSED) {
if let Some((idx, output)) = cmd.get(commands::BLOCK_PROCESSED) {
if let Some(block) = data.blocks.get_mut(*idx) {
block.output = output.clone();
}
return druid::Handled::Yes;
}
}
if cmd.is(commands::DELETE_BLOCK) {
if let Some(index) = cmd.get(commands::DELETE_BLOCK) {
data.remove_block(*index);
return druid::Handled::Yes;
}
}
druid::Handled::No
}
fn event(
&mut self,
_ctx: &mut druid::DelegateCtx,
_window_id: druid::WindowId,
event: druid::Event,
data: &mut AppData,
_env: &druid::Env,
) -> Option<druid::Event> {
if let druid::Event::KeyDown(ref e) = event {
if druid::keyboard_types::Key::Character(String::from("n")) == e.key && e.mods.ctrl() {
data.blocks.push_back(Block::new(
&format!("Block #{}", data.blocks.len() + 1),
data.blocks.len(),
));
return None;
}
}
Some(event)
}
}