file tree with better prompts and callbacks

pull/8675/merge^2
mattwparas 1 year ago
parent e063c58d30
commit 76181da53a

@ -791,7 +791,6 @@ fn call_indent_hook(
let mut cursor = line_before; let mut cursor = line_before;
let mut depth = 0; let mut depth = 0;
// for line in text_up_to_cursor.lines().reversed() {
loop { loop {
let line = text_up_to_cursor.line(cursor); let line = text_up_to_cursor.line(cursor);
@ -864,7 +863,12 @@ fn call_indent_hook(
// return Some(" ".repeat(offset + 1)); // return Some(" ".repeat(offset + 1));
// } // }
if line.slice(offset..offset + end).as_str().map(|x| LISP_WORDS.contains(x)).unwrap_or_default() { if line
.slice(offset..offset + end)
.as_str()
.map(|x| LISP_WORDS.contains(x))
.unwrap_or_default()
{
return Some(" ".repeat(offset + 1)); return Some(" ".repeat(offset + 1));
} }
@ -1021,16 +1025,21 @@ pub fn custom_indent_for_newline(
} }
// TODO: Don't unwrap here, we don't want that // TODO: Don't unwrap here, we don't want that
if LISP_WORDS.contains( // if LISP_WORDS.contains(
line.slice(offset..offset + end).as_str().unwrap(), // line.slice(offset..offset + end).as_str().unwrap(),
) { // ) {
return Some(" ".repeat(offset + 1));
}
// if line.slice(offset..offset + end).as_str().map(|x| LISP_WORDS.contains(x)).unwrap_or_default() {
// return Some(" ".repeat(offset + 1)); // return Some(" ".repeat(offset + 1));
// } // }
if line
.slice(offset..offset + end)
.as_str()
.map(|x| LISP_WORDS.contains(x))
.unwrap_or_default()
{
return Some(" ".repeat(offset + 1));
}
for _ in char_iter_from_paren for _ in char_iter_from_paren
.take_while(|(_, x)| x.is_whitespace()) .take_while(|(_, x)| x.is_whitespace())
{ {

@ -343,6 +343,10 @@ impl Application {
self.jobs.handle_callback(&mut self.editor, &mut self.compositor, callback); self.jobs.handle_callback(&mut self.editor, &mut self.compositor, callback);
self.render().await; self.render().await;
} }
Some(callback) = self.jobs.local_futures.next() => {
self.jobs.handle_local_callback(&mut self.editor, &mut self.compositor, callback);
self.render().await;
}
event = self.editor.wait_event() => { event = self.editor.wait_event() => {
let _idle_handled = self.handle_editor_event(event).await; let _idle_handled = self.handle_editor_event(event).await;

@ -1,10 +1,12 @@
use fuzzy_matcher::FuzzyMatcher; use fuzzy_matcher::FuzzyMatcher;
use helix_core::{graphemes, Tendril, Selection}; use helix_core::{graphemes, Selection, Tendril};
use helix_view::{document::Mode, Document, DocumentId, Editor, editor::Action, extension::document_id_to_usize}; use helix_view::{
document::Mode, editor::Action, extension::document_id_to_usize, Document, DocumentId, Editor,
};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use steel::{ use steel::{
gc::unsafe_erased_pointers::CustomReference, gc::unsafe_erased_pointers::CustomReference,
rvals::{FromSteelVal, IntoSteelVal, SteelString}, rvals::{AsRefMutSteelValFromRef, FromSteelVal, IntoSteelVal},
steel_vm::{engine::Engine, register_fn::RegisterFn}, steel_vm::{engine::Engine, register_fn::RegisterFn},
SteelErr, SteelVal, SteelErr, SteelVal,
}; };
@ -25,7 +27,7 @@ use crate::{
compositor::{self, Component, Compositor}, compositor::{self, Component, Compositor},
job::{self, Callback}, job::{self, Callback},
keymap::{merge_keys, Keymap}, keymap::{merge_keys, Keymap},
ui::{self, menu::Item, overlay::overlaid, Popup, PromptEvent}, ui::{self, menu::Item, overlay::overlaid, Popup, Prompt, PromptEvent},
}; };
use self::components::SteelDynamicComponent; use self::components::SteelDynamicComponent;
@ -418,6 +420,11 @@ fn configure_engine() -> std::rc::Rc<std::cell::RefCell<steel::steel_vm::engine:
engine.register_fn("enqueue-callback!", CallbackQueue::enqueue); engine.register_fn("enqueue-callback!", CallbackQueue::enqueue);
// Find the workspace
engine.register_fn("helix-find-workspace", || {
helix_core::find_workspace().0.to_str().unwrap().to_string()
});
// Get the current OS // Get the current OS
engine.register_fn("current-os!", || std::env::consts::OS); engine.register_fn("current-os!", || std::env::consts::OS);
engine.register_fn("new-component!", SteelDynamicComponent::new_dyn); engine.register_fn("new-component!", SteelDynamicComponent::new_dyn);
@ -477,6 +484,52 @@ fn configure_engine() -> std::rc::Rc<std::cell::RefCell<steel::steel_vm::engine:
}, },
); );
engine.register_fn(
"Prompt::new",
|prompt: String, callback_fn: SteelVal| -> WrappedDynComponent {
let prompt = Prompt::new(
prompt.into(),
None,
|_, _| Vec::new(),
move |cx, input, prompt_event| {
log::info!("Calling dynamic prompt callback");
if prompt_event != PromptEvent::Validate {
return;
}
let mut ctx = Context {
register: None,
count: None,
editor: cx.editor,
callback: None,
on_next_key_callback: None,
jobs: cx.jobs,
};
let cloned_func = callback_fn.clone();
ENGINE
.with(|x| {
x.borrow_mut()
.with_mut_reference::<Context, Context>(&mut ctx)
.consume(move |engine, mut args| {
// Add the string as an argument to the callback
args.push(input.into_steelval().unwrap());
engine.call_function_with_args(cloned_func.clone(), args)
})
})
.unwrap();
},
);
WrappedDynComponent {
inner: Some(Box::new(prompt)),
}
},
);
engine.register_fn("Picker::new", |values: Vec<String>| todo!()); engine.register_fn("Picker::new", |values: Vec<String>| todo!());
// engine.register_fn( // engine.register_fn(
@ -583,6 +636,8 @@ fn configure_engine() -> std::rc::Rc<std::cell::RefCell<steel::steel_vm::engine:
// Check if the doc exists first // Check if the doc exists first
engine.register_fn("editor-doc-exists?", document_exists); engine.register_fn("editor-doc-exists?", document_exists);
engine.register_fn("Document-path", document_path); engine.register_fn("Document-path", document_path);
engine.register_fn("helix.context?", is_context);
engine.register_type::<DocumentId>("DocumentId?");
// RegisterFn::< // RegisterFn::<
// _, // _,
@ -618,6 +673,10 @@ fn configure_engine() -> std::rc::Rc<std::cell::RefCell<steel::steel_vm::engine:
"PromptEvent::Validate", "PromptEvent::Validate",
PromptEvent::Validate.into_steelval().unwrap(), PromptEvent::Validate.into_steelval().unwrap(),
); );
module.register_value(
"PromptEvent::Update",
PromptEvent::Update.into_steelval().unwrap(),
);
// Register everything in the typable command list. Now these are all available // Register everything in the typable command list. Now these are all available
for command in TYPABLE_COMMAND_LIST { for command in TYPABLE_COMMAND_LIST {
@ -718,11 +777,9 @@ fn configure_engine() -> std::rc::Rc<std::cell::RefCell<steel::steel_vm::engine:
module.register_fn("current-highlighted-text!", get_highlighted_text); module.register_fn("current-highlighted-text!", get_highlighted_text);
module.register_fn("get-current-line-number", current_line_number); module.register_fn("get-current-line-number", current_line_number);
module.register_fn("current-selection-object", current_selection); module.register_fn("current-selection-object", current_selection);
module.register_fn("set-current-selection-object!", set_selection); module.register_fn("set-current-selection-object!", set_selection);
module.register_fn("run-in-engine!", run_in_engine); module.register_fn("run-in-engine!", run_in_engine);
module.register_fn("get-helix-scm-path", get_helix_scm_path); module.register_fn("get-helix-scm-path", get_helix_scm_path);
module.register_fn("get-init-scm-path", get_init_scm_path); module.register_fn("get-init-scm-path", get_init_scm_path);
@ -733,6 +790,7 @@ fn configure_engine() -> std::rc::Rc<std::cell::RefCell<steel::steel_vm::engine:
engine.register_module(module); engine.register_module(module);
engine.register_fn("push-component!", push_component); engine.register_fn("push-component!", push_component);
engine.register_fn("enqueue-thread-local-callback", enqueue_command);
let helix_module_path = helix_loader::helix_module_file(); let helix_module_path = helix_loader::helix_module_file();
@ -857,12 +915,12 @@ fn set_selection(cx: &mut Context, selection: Selection) {
fn current_line_number(cx: &mut Context) -> usize { fn current_line_number(cx: &mut Context) -> usize {
let (view, doc) = current_ref!(cx.editor); let (view, doc) = current_ref!(cx.editor);
helix_core::coords_at_pos( helix_core::coords_at_pos(
doc.text().slice(..), doc.text().slice(..),
doc doc.selection(view.id)
.selection(view.id)
.primary() .primary()
.cursor(doc.text().slice(..)), .cursor(doc.text().slice(..)),
).row )
.row
} }
fn get_selection(cx: &mut Context) -> String { fn get_selection(cx: &mut Context) -> String {
@ -970,15 +1028,17 @@ fn get_document_id(editor: &mut Editor, view_id: helix_view::ViewId) -> Document
editor.tree.get(view_id).doc editor.tree.get(view_id).doc
} }
// Get the document from the document id - TODO: Add result type here // Get the document from the document id - TODO: Add result type here
fn get_document(editor: &mut Editor, doc_id: DocumentId) -> &Document { fn get_document(editor: &mut Editor, doc_id: DocumentId) -> &Document {
editor.documents.get(&doc_id).unwrap() editor.documents.get(&doc_id).unwrap()
} }
fn is_document_in_view(editor: &mut Editor, doc_id: DocumentId) -> Option<helix_view::ViewId> { fn is_document_in_view(editor: &mut Editor, doc_id: DocumentId) -> Option<helix_view::ViewId> {
editor.tree.traverse().find(|(_, v)| v.doc == doc_id).map(|(id, _)| id) editor
.tree
.traverse()
.find(|(_, v)| v.doc == doc_id)
.map(|(id, _)| id)
} }
fn document_exists(editor: &mut Editor, doc_id: DocumentId) -> bool { fn document_exists(editor: &mut Editor, doc_id: DocumentId) -> bool {
@ -1035,45 +1095,59 @@ fn run_shell_command_text(
} }
} }
// Pin the value to _this_ thread? fn is_context(value: SteelVal) -> bool {
Context::as_mut_ref_from_ref(&value).is_ok()
}
// Overlay the dynamic component, see what happens? // Overlay the dynamic component, see what happens?
// Probably need to pin the values to this thread - wrap it in a shim which pins the value // Probably need to pin the values to this thread - wrap it in a shim which pins the value
// to this thread? - call methods on the thread local value? // to this thread? - call methods on the thread local value?
fn push_component(cx: &mut Context, component: &mut WrappedDynComponent) { fn push_component(cx: &mut Context, component: &mut WrappedDynComponent) {
// let component = crate::ui::Text::new("Hello world!".to_string());
log::info!("Pushing dynamic component!"); log::info!("Pushing dynamic component!");
// todo!(); let inner = component.inner.take().unwrap();
// let callback = async move {
// let call: job::Callback = Callback::EditorCompositor(Box::new(
// move |_editor: &mut Editor, compositor: &mut Compositor| {
// compositor.push(Box::new(component));
// },
// ));
// Ok(call)
// };
// cx.jobs.callback(callback);
// Why does this not work? - UPDATE: This does work when called in a static command context, but let callback = async move {
// in a typed command context, we do not have access to the real compositor. Thus, we need a callback let call: Box<dyn FnOnce(&mut Editor, &mut Compositor, &mut job::Jobs)> = Box::new(
// that then requires the values to be moved over threads. We'll need some message passing scheme move |_editor: &mut Editor, compositor: &mut Compositor, _| compositor.push(inner),
// to call values from the typed command context. );
cx.push_layer(component.inner.take().unwrap()); Ok(call)
};
// TODO: This _needs_ to go through a callback. Otherwise the new layer is just dropped. cx.jobs.local_callback(callback);
// Set up some sort of callback queue for dynamic components that we can pull from instead, so that }
// things stay thread local?
// let root = helix_core::find_workspace().0; fn enqueue_command(cx: &mut Context, callback_fn: SteelVal) {
// let picker = ui::file_picker(root, &cx.editor.config()); let callback = async move {
// cx.push_layer(Box::new(overlaid(picker))); let call: Box<dyn FnOnce(&mut Editor, &mut Compositor, &mut job::Jobs)> = Box::new(
move |editor: &mut Editor, _compositor: &mut Compositor, jobs: &mut job::Jobs| {
let mut ctx = Context {
register: None,
count: None,
editor,
callback: None,
on_next_key_callback: None,
jobs,
};
let cloned_func = callback_fn.clone();
ENGINE
.with(|x| {
x.borrow_mut()
.with_mut_reference::<Context, Context>(&mut ctx)
.consume(move |engine, args| {
engine.call_function_with_args(cloned_func.clone(), args)
})
})
.unwrap();
},
);
Ok(call)
};
cx.jobs.local_callback(callback);
} }
// fn push_component_raw(cx: &mut Context, component: Box<dyn Component>) { // fn enqueue_callback(cx: &mut Context, thunk: SteelVal) {
// cx.push_layer(component); // log::info!("Enqueueing callback!");
// } // }

@ -10,7 +10,7 @@ use steel::{
use crate::{ use crate::{
commands::{engine::ENGINE, Context}, commands::{engine::ENGINE, Context},
compositor::{self, Component}, compositor::{self, Component},
ui::Popup, ui::{Popup, Prompt, PromptEvent},
}; };
pub fn helix_component_module() -> BuiltInModule { pub fn helix_component_module() -> BuiltInModule {
@ -72,6 +72,61 @@ pub fn helix_component_module() -> BuiltInModule {
} }
}, },
); );
// prompt: Cow<'static, str>,
// history_register: Option<char>,
// completion_fn: impl FnMut(&Editor, &str) -> Vec<Completion> + 'static,
// callback_fn: impl FnMut(&mut Context, &str, PromptEvent) + 'static,
module.register_fn(
"Prompt::new",
|prompt: String, callback_fn: SteelVal| -> WrappedDynComponent {
let prompt = Prompt::new(
prompt.into(),
None,
|_, _| Vec::new(),
move |cx, input, prompt_event| {
if prompt_event != PromptEvent::Validate {
return;
}
let mut ctx = Context {
register: None,
count: None,
editor: cx.editor,
callback: None,
on_next_key_callback: None,
jobs: cx.jobs,
};
let cloned_func = callback_fn.clone();
// let thunk = move |engine: &mut Engine, cx, input| {
// engine.call_function_with_args(
// cloned_func,
// vec![cx, input],
// )
// };
ENGINE
.with(|x| {
x.borrow_mut()
.with_mut_reference::<Context, Context>(&mut ctx)
.consume(move |engine, mut args| {
// Add the string as an argument to the callback
args.push(input.into_steelval().unwrap());
engine.call_function_with_args(cloned_func.clone(), args)
})
})
.unwrap();
},
);
WrappedDynComponent {
inner: Some(Box::new(prompt)),
}
},
);
module.register_fn("Picker::new", |values: Vec<String>| todo!()); module.register_fn("Picker::new", |values: Vec<String>| todo!());

@ -2933,17 +2933,18 @@ pub(super) fn command_mode(cx: &mut Context) {
); );
let mut guard = x.borrow_mut(); let mut guard = x.borrow_mut();
// let mut maybe_callback = None;
let res = {
let mut cx = Context {
register: None,
count: std::num::NonZeroUsize::new(1),
editor: cx.editor,
callback: None,
on_next_key_callback: None,
jobs: cx.jobs,
};
let mut cx = Context {
register: None,
count: std::num::NonZeroUsize::new(1),
editor: cx.editor,
callback: None,
on_next_key_callback: None,
jobs: cx.jobs,
};
{
guard guard
.register_value("_helix_args", steel::rvals::SteelVal::ListV(args)); .register_value("_helix_args", steel::rvals::SteelVal::ListV(args));
@ -2955,8 +2956,22 @@ pub(super) fn command_mode(cx: &mut Context) {
guard.register_value("_helix_args", steel::rvals::SteelVal::Void); guard.register_value("_helix_args", steel::rvals::SteelVal::Void);
// if let Some(callback) = cx.callback.take() {
// panic!("Found a callback!");
// maybe_callback = Some(callback);
// }
res res
} };
// TODO: Recursively (or otherwise) keep retrying until we're back
// into the engine context, executing a function. We might need to set up
// some sort of fuel or something
// if let Some(callback) = maybe_callback {
// (callback)(_, cx);
// }
res
}) { }) {
compositor_present_error(cx, e) compositor_present_error(cx, e)
}; };

@ -2,12 +2,15 @@ use helix_view::Editor;
use crate::compositor::Compositor; use crate::compositor::Compositor;
use futures_util::future::{BoxFuture, Future, FutureExt}; use futures_util::future::{BoxFuture, Future, FutureExt, LocalBoxFuture};
use futures_util::stream::{FuturesUnordered, StreamExt}; use futures_util::stream::{FuturesOrdered, FuturesUnordered, StreamExt};
pub type EditorCompositorCallback = Box<dyn FnOnce(&mut Editor, &mut Compositor) + Send>; pub type EditorCompositorCallback = Box<dyn FnOnce(&mut Editor, &mut Compositor) + Send>;
pub type EditorCallback = Box<dyn FnOnce(&mut Editor) + Send>; pub type EditorCallback = Box<dyn FnOnce(&mut Editor) + Send>;
pub type ThreadLocalEditorCompositorCallback =
Box<dyn FnOnce(&mut Editor, &mut Compositor, &mut Jobs)>;
pub enum Callback { pub enum Callback {
EditorCompositor(EditorCompositorCallback), EditorCompositor(EditorCompositorCallback),
Editor(EditorCallback), Editor(EditorCallback),
@ -21,11 +24,16 @@ pub struct Job {
pub wait: bool, pub wait: bool,
} }
pub type ThreadLocalJob =
LocalBoxFuture<'static, anyhow::Result<Option<ThreadLocalEditorCompositorCallback>>>;
#[derive(Default)] #[derive(Default)]
pub struct Jobs { pub struct Jobs {
pub futures: FuturesUnordered<JobFuture>, pub futures: FuturesUnordered<JobFuture>,
/// These are the ones that need to complete before we exit. /// These are the ones that need to complete before we exit.
pub wait_futures: FuturesUnordered<JobFuture>, pub wait_futures: FuturesUnordered<JobFuture>,
pub local_futures: FuturesUnordered<ThreadLocalJob>,
} }
impl Job { impl Job {
@ -67,6 +75,16 @@ impl Jobs {
self.add(Job::with_callback(f)); self.add(Job::with_callback(f));
} }
pub fn local_callback<
F: Future<Output = anyhow::Result<ThreadLocalEditorCompositorCallback>> + 'static,
>(
&mut self,
f: F,
) {
self.local_futures
.push(f.map(|r| r.map(Some)).boxed_local());
}
pub fn handle_callback( pub fn handle_callback(
&self, &self,
editor: &mut Editor, editor: &mut Editor,
@ -85,6 +103,21 @@ impl Jobs {
} }
} }
pub fn handle_local_callback(
&mut self,
editor: &mut Editor,
compositor: &mut Compositor,
call: anyhow::Result<Option<ThreadLocalEditorCompositorCallback>>,
) {
match call {
Ok(None) => {}
Ok(Some(call)) => call(editor, compositor, self),
Err(e) => {
editor.set_error(format!("Sync job failed: {}", e));
}
}
}
pub async fn next_job(&mut self) -> Option<anyhow::Result<Option<Callback>>> { pub async fn next_job(&mut self) -> Option<anyhow::Result<Option<Callback>>> {
tokio::select! { tokio::select! {
event = self.futures.next() => { event } event = self.futures.next() => { event }

@ -692,7 +692,7 @@ pub struct WhitespaceCharacters {
impl Default for WhitespaceCharacters { impl Default for WhitespaceCharacters {
fn default() -> Self { fn default() -> Self {
Self { Self {
space: '·', // U+00B7 space: '·', // U+00B7
nbsp: '', // U+237D nbsp: '', // U+237D
tab: '', // U+2192 tab: '', // U+2192
newline: '', // U+23CE newline: '', // U+23CE

Loading…
Cancel
Save