summaryrefslogtreecommitdiffstats
path: root/src/ui/wildmenu.rs
blob: a865f8a1a4f86fab7ce7d26e07ae5734cfdc1a07 (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
use gtk;
use gtk::prelude::*;
use std::cell::RefCell;
use std::rc::Rc;

use crate::nvim_bridge;
use crate::nvim_gio::GioNeovim;
use crate::ui::color::{Color, HlDefs, HlGroup};
use crate::ui::common::spawn_local;

const MAX_HEIGHT: i32 = 500;

#[derive(Default)]
struct State {
    /// Currently selected row in wildmenu.
    selected: i32,
}

pub struct Wildmenu {
    css_provider: gtk::CssProvider,
    frame: gtk::Frame,
    list: gtk::ListBox,

    state: Rc<RefCell<State>>,
}

impl Wildmenu {
    pub fn new(nvim: GioNeovim) -> Self {
        let css_provider = gtk::CssProvider::new();

        let frame = gtk::Frame::new(None);

        let list = gtk::ListBox::new();
        list.set_selection_mode(gtk::SelectionMode::Single);

        let scrolledwindow = gtk::ScrolledWindow::new(
            None::<&gtk::Adjustment>,
            None::<&gtk::Adjustment>,
        );
        scrolledwindow
            .set_policy(gtk::PolicyType::Automatic, gtk::PolicyType::Automatic);
        scrolledwindow.add(&list);

        frame.add(&scrolledwindow);

        let frame_weak = frame.downgrade();
        // Make sure our container grows to certain height.
        list.connect_size_allocate(clone!(frame_weak => move |list, _| {
            let frame = upgrade_weak!(frame_weak);
            // Calculate height based on shown rows.
            let count = list.get_children().len() as i32;
            let row_height = if let Some(item) = list.get_children().get(0) {
                item.get_preferred_height().0
            } else {
                16
            };

            let h = (row_height * count).min(MAX_HEIGHT);

            frame.set_size_request(-1, h);
        }));

        let state = Rc::new(RefCell::new(State::default()));

        // If user selects some row with a mouse, notify nvim about it.
        list.connect_row_activated(clone!(state => move |_, row| {
            let prev = state.borrow().selected;
            let new = row.get_index();

            let op = if new > prev { "<Tab>" } else { "<S-Tab>" };

            for _ in 0..(new - prev).abs() {
                // NOTE(ville): nvim doesn't like single input with many
                //              tabs in it, so we'll have to send each
                //              individually.
                let nvim = nvim.clone();
                spawn_local(async move {
                    nvim.input(&op)
                        .await
                        .unwrap();
                })
            }
        }));

        add_css_provider!(&css_provider, list, frame);

        Wildmenu {
            css_provider,
            list,
            frame,

            state,
        }
    }

    pub fn widget(&self) -> gtk::Widget {
        self.frame.clone().upcast()
    }

    pub fn show(&self) {
        self.frame.show_all();
    }

    pub fn hide(&self) {
        self.frame.hide();
    }

    pub fn clear(&mut self) {
        let mut children = self.list.get_children();
        while let Some(item) = children.pop() {
            item.destroy();
        }
    }

    pub fn set_items(&mut self, items: &Vec<nvim_bridge::CompletionItem>) {
        self.clear();

        for item in items {
            let label = gtk::Label::new(Some(item.word.as_str()));
            label.set_halign(gtk::Align::Start);

            let row = gtk::ListBoxRow::new();
            row.add(&label);

            add_css_provider!(&self.css_provider, row, label);

            self.list.add(&row);
        }

        self.list.show_all();
    }

    pub fn select(&mut self, item_num: i32) {
        self.state.borrow_mut().selected = item_num;

        if item_num < 0 {
            self.list.unselect_all();
        } else {
            if let Some(row) = self.list.get_row_at_index(item_num) {
                self.list.select_row(Some(&row));
                row.grab_focus();
            }
        }
    }

    pub fn set_colors(&self, hl_defs: &HlDefs) {
        let color = hl_defs.get_hl_group(&HlGroup::Wildmenu);
        let color_sel = hl_defs.get_hl_group(&HlGroup::WildmenuSel);
        let fg = color
            .and_then(|hl| hl.foreground)
            .unwrap_or(hl_defs.default_fg);
        let bg = color
            .and_then(|hl| hl.background)
            .unwrap_or(hl_defs.default_bg);
        let sel_fg = color_sel
            .and_then(|hl| hl.foreground)
            .unwrap_or(hl_defs.default_fg);
        let sel_bg = color_sel
            .and_then(|hl| hl.background)
            .unwrap_or(hl_defs.default_bg);

        if gtk::get_minor_version() < 20 {
            self.set_colors_pre20(fg, bg, sel_fg, sel_bg);
        } else {
            self.set_colors_post20(fg, bg, sel_fg, sel_bg);
        }
    }

    fn set_colors_pre20(
        &self,
        fg: Color,
        bg: Color,
        sel_fg: Color,
        sel_bg: Color,
    ) {
        let css = format!(
            "GtkFrame {{
                border: none;
            }}

            GtkListBoxRow {{
                padding: 6px;
                color: #{fg};
                background-color: #{bg};
                outline: none;
            }}

            GtkListBoxRow:selected, GtkListBoxRow:selected > GtkLabel {{
                color: #{sel_fg};
                background: #{sel_bg};
            }}",
            fg = fg.to_hex(),
            bg = bg.to_hex(),
            sel_fg = sel_fg.to_hex(),
            sel_bg = sel_bg.to_hex(),
        );
        CssProviderExt::load_from_data(&self.css_provider, css.as_bytes())
            .unwrap();
    }

    fn set_colors_post20(
        &self,
        fg: Color,
        bg: Color,
        sel_fg: Color,
        sel_bg: Color,
    ) {
        let css = format!(
            "frame > border {{
                border: none;
            }}

            row {{
                padding: 6px;
                color: #{fg};
                background-color: #{bg};
                outline: none;
            }}

            row:selected, row:selected > label {{
                color: #{sel_fg};
                background: #{sel_bg};
            }}",
            fg = fg.to_hex(),
            bg = bg.to_hex(),
            sel_fg = sel_fg.to_hex(),
            sel_bg = sel_bg.to_hex(),
        );
        CssProviderExt::load_from_data(&self.css_provider, css.as_bytes())
            .unwrap();
    }
}