makepad_code_editor/
code_view.rs

1
2use {
3    crate::{
4        {CodeDocument, decoration::{DecorationSet}, CodeSession},
5        makepad_widgets::*,
6        CodeEditor,
7        code_editor::KeepCursorInView,
8    },
9    std::{
10        env,
11    },
12};
13
14live_design!{
15    use crate::code_editor::CodeEditor;
16        
17    pub CodeView = {{CodeView}}{
18        editor: <CodeEditor>{
19            pad_left_top: vec2(0.0,-0.0)
20            height:Fit
21            empty_page_at_end: false,
22            read_only: true,
23            show_gutter: false
24        }
25    }
26} 
27
28
29#[derive(Live, LiveHook, Widget)] 
30pub struct CodeView{
31    #[wrap] #[live] pub editor: CodeEditor,
32    // alright we have to have a session and a document.
33     #[rust] pub session: Option<CodeSession>,
34     #[live(false)] keep_cursor_at_end: bool,
35     
36    #[live] text: ArcStringMut,
37}
38
39impl CodeView{
40    pub fn lazy_init_session(&mut self){
41        if self.session.is_none(){
42            let dec = DecorationSet::new();
43            let doc = CodeDocument::new(self.text.as_ref().into(), dec);
44            self.session = Some(CodeSession::new(doc));
45            self.session.as_mut().unwrap().handle_changes();
46            if self.keep_cursor_at_end{
47                self.session.as_mut().unwrap().set_cursor_at_file_end();
48                self.editor.keep_cursor_in_view = KeepCursorInView::Once
49            }
50        }
51    }
52}
53
54impl Widget for CodeView {
55    fn draw_walk(&mut self, cx: &mut Cx2d, _scope:&mut Scope, walk:Walk)->DrawStep{
56        // alright so. 
57        self.lazy_init_session();
58        // alright we have a scope, and an id, so now we can properly draw the editor.
59        let session = self.session.as_mut().unwrap();
60        
61        self.editor.draw_walk_editor(cx, session, walk);
62        
63        DrawStep::done()
64    }
65        
66    fn handle_event(&mut self, cx: &mut Cx, event: &Event, _scope: &mut Scope){
67        self.lazy_init_session();
68        let session = self.session.as_mut().unwrap();
69        for _action in self.editor.handle_event(cx, event, &mut Scope::empty(), session){
70            //cx.widget_action(uid, &scope.path, action);
71            session.handle_changes();
72        }
73    }
74    
75    fn text(&self)->String{
76        self.text.as_ref().to_string()
77    }
78        
79    fn set_text(&mut self, cx:&mut Cx, v:&str){
80        if self.text.as_ref() != v{
81            self.text.as_mut_empty().push_str(v);
82            self.session = None;
83            self.redraw(cx);
84        }
85    }
86}