summaryrefslogtreecommitdiffstats
path: root/src/ui/ui.rs
blob: fcf42580afbbdbf46123da4585726febeb59ea75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use gdk;
use glib;
use gtk;
use gtk::prelude::*;

use log::{debug, error};
use rmpv::Value;

use crate::nvim_bridge::{Message, Request};
use crate::nvim_gio::GioNeovim;
use crate::ui::cmdline::Cmdline;
use crate::ui::color::{Highlight, HlDefs};
use crate::ui::common::spawn_local;
#[cfg(feature = "libwebkit2gtk")]
use crate::ui::cursor_tooltip::CursorTooltip;
use crate::ui::font::Font;
use crate::ui::grid::Grid;
use crate::ui::popupmenu::Popupmenu;
use crate::ui::state::{attach_grid_events, UIState, Windows};
use crate::ui::tabline::Tabline;
use crate::ui::window::MsgWindow;

/// Main UI structure.
pub struct UI {
    /// Main window.
    win: gtk::ApplicationWindow,
    /// Neovim instance.
    nvim: GioNeovim,
    /// Channel to receive event from nvim.
    rx: glib::Receiver<Message>,
    /// Our internal state, containing basically everything we manipulate
    /// when we receive an event from nvim.
    state: Rc<RefCell<UIState>>,
}

impl UI {
    /// Creates new UI.
    ///
    /// * `app` - GTK application for the UI.
    /// * `rx` - Channel to receive nvim UI events.
    /// * `nvim` - Neovim instance to use. Should be the same that is the source
    ///            of `rx` events.
    pub fn init(
        app: &gtk::Application,
        rx: glib::Receiver<Message>,
        window_size: (i32, i32),
        nvim: GioNeovim,
    ) -> Self {
        // Create the main window.
        let window = gtk::ApplicationWindow::new(app);
        window.set_title("Neovim");
        window.set_default_size(window_size.0, window_size.1);

        // Realize window resources.
        window.realize();

        // Top level widget.
        let b = gtk::Box::new(gtk::Orientation::Vertical, 0);
        window.add(&b);

        let tabline = Tabline::new(nvim.clone());
        b.pack_start(&tabline.get_widget(), false, false, 0);

        // Our root widget for all grids/windows.
        let overlay = gtk::Overlay::new();
        b.pack_start(&overlay, true, true, 0);

        // Create hl defs and initialize 0th element because we'll need to have
        // something that is accessible for the default grid that we're gonna
        // make next.
        let mut hl_defs = HlDefs::default();
        hl_defs.insert(0, Highlight::default());

        let font = Font::from_guifont("Monospace:h12").unwrap();
        let line_space = 0;

        // Create default grid.
        let mut grid = Grid::new(
            1,
            &window.get_window().unwrap(),
            font.clone(),
            line_space,
            80,
            30,
            &hl_defs,
            true,
        );
        // Mark the default grid as active at the beginning.
        grid.set_active(true);
        overlay.add(&grid.widget());

        let windows_container = gtk::Fixed::new();
        windows_container.set_widget_name("windows-contianer");
        let windows_float_container = gtk::Fixed::new();
        windows_float_container.set_widget_name("windows-contianer-float");
        let msg_window_container = gtk::Fixed::new();
        msg_window_container.set_widget_name("message-grid-contianer");
        overlay.add_overlay(&windows_container);
        overlay.add_overlay(&msg_window_container);
        overlay.add_overlay(&windows_float_container);

        let css_provider = gtk::CssProvider::new();
        let msg_window =
            MsgWindow::new(msg_window_container.clone(), css_provider.clone());

        overlay.set_overlay_pass_through(&windows_container, true);
        overlay.set_overlay_pass_through(&windows_float_container, true);
        overlay.set_overlay_pass_through(&msg_window_container, true);

        // When resizing our window (main grid), we'll have to tell neovim to
        // resize it self also. The notify to nvim is send with a small delay,
        // so we don't spam it multiple times a second. source_id is used to
        // track the function timeout. This timeout might be canceled in
        // redraw even handler if we receive a message that changes the size
        // of the main grid.
        let source_id = Rc::new(RefCell::new(None));
        grid.connect_da_resize(clone!(nvim, source_id => move |rows, cols| {

            // Set timeout to notify nvim about the new size.
            let new = gtk::timeout_add(30, clone!(nvim, source_id => move || {
                let nvim = nvim.clone();
                spawn_local(async move {
                    match nvim.ui_try_resize(cols as i64, rows as i64).await {
                        Err(err) => error!("Error: failed to resize nvim when grid size changed ({:?})", err),
                        Ok(_) => {},
                    }
                });

                // Set the source_id to none, so we don't accidentally remove
                // it since it used at this point.
                source_id.borrow_mut().take();

                Continue(false)
            }));

            let mut source_id = source_id.borrow_mut();
            // If we have earlier timeout, remove it.
            if let Some(old) = source_id.take() {
                glib::source::source_remove(old);
            }

            *source_id = Some(new);

            false
        }));

        attach_grid_events(&grid, nvim.clone());

        // IMMulticontext is used to handle most of the inputs.
        let im_context = gtk::IMMulticontext::new();
        im_context.set_use_preedit(false);
        im_context.connect_commit(clone!(nvim => move |_, input| {
            // "<" needs to be escaped for nvim.input()
            let nvim_input = input.replace("<", "<lt>");

            let nvim = nvim.clone();
            spawn_local(async move {
                nvim.input(&nvim_input).await.expect("Couldn't send input");
            });
        }));

        window.connect_key_press_event(clone!(nvim, im_context => move |_, e| {
            if im_context.filter_keypress(e) {
                Inhibit(true)
            } else {
                if let Some(input) = event_to_nvim_input(e) {
                    let nvim = nvim.clone();
                    spawn_local(async move {
                        nvim.input(input.as_str()).await.expect("Couldn't send input");
                    });
                    return Inhibit(true);
                } else {
                    debug!(
                        "Failed to turn input event into nvim key (keyval: {})",
                        e.get_keyval()
                    )
                }

                Inhibit(false)
            }
        }));

        window.connect_key_release_event(clone!(im_context => move |_, e| {
            im_context.filter_keypress(e);
            Inhibit(false)
        }));

        window.connect_focus_in_event(clone!(im_context => move |_, _| {
            im_context.focus_in();
            Inhibit(false)
        }));

        window.connect_focus_out_event(clone!(im_context => move |_, _| {
            im_context.focus_out();
            Inhibit(false)
        }));

        let cmdline = Cmdline::new(&overlay, nvim.clone());
        #[cfg(feature = "libwebkit2gtk")]
        let cursor_tooltip = CursorTooltip::new(&overlay);

        window.show_all();

        grid.set_im_context(&im_context);

        cmdline.hide();
        #[cfg(feature = "libwebkit2gtk")]
        cursor_tooltip.hide();

        let mut grids = HashMap::new();
        grids.insert(1, grid);

        add_css_provider!(&css_provider, window);

        UI {
            win: window,
            rx,
            state: Rc::new(RefCell::new(UIState {
                css_provider,
                windows: Windows::new(),
                windows_container,
                msg_window_container,
                msg_window,
                windows_float_container,
                grids,
                mode_infos: vec![],
                current_grid: 1,
                wildmenu_shown: false,
                popupmenu: Popupmenu::new(&overlay, nvim.clone()),
                cmdline,
                overlay,
                tabline,
                #[cfg(feature = "libwebkit2gtk")]
                cursor_tooltip,
                resize_source_id: source_id,
                hl_defs,
                resize_on_flush: None,
                hl_changed: false,
                font,
                line_space,
                current_mode: None,
                enable_cursor_animations: true,
            })),
            nvim,
        }
    }

    /// Starts to listen events from `rx` (e.g. from nvim) and processing those.
    /// Think this as the "main" function of the UI.
    pub fn start(self) {
        let UI {
            rx,
            state,
            win,
            nvim,
        } = self;

        rx.attach(None, move |message| {
            match message