autocomplete.rs 20.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
extern crate gtk;
extern crate pango;
extern crate gdk;

use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use std::cell::RefCell;
use std::rc::Rc;

use glib;
use self::gtk::prelude::*;
use self::pango::LayoutExt;

use types::Member;
//use types::Room;
//use types::RoomList;

use widgets;
19
use appop::AppOp;
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

pub struct Autocomplete {
    entry: gtk::Entry,
    listbox: gtk::ListBox,
    popover: gtk::Popover,
    window: gtk::Window,
    highlighted_entry: Vec<String>,
    popover_position: Option<i32>,
    popover_search: Option<String>,
    popover_closing: bool,
    op: Arc<Mutex<AppOp>>,
}

impl Autocomplete {
    pub fn new(op: Arc<Mutex<AppOp>>, window: gtk::Window, msg_entry: gtk::Entry, popover: gtk::Popover, listbox: gtk::ListBox) -> Autocomplete {
        Autocomplete {
            entry: msg_entry,
            listbox: listbox,
            popover: popover,
            window: window,
            highlighted_entry: vec![],
            popover_position: None,
            popover_search: None,
            popover_closing: false,
            op: op,
        }
    }

    pub fn connect(self) {
        let this: Rc<RefCell<Autocomplete>> = Rc::new(RefCell::new(self));

        let own = this.clone();
        this.borrow().window.connect_button_press_event(move |_, _| {
            if own.borrow().popover_position.is_some() {
                own.borrow_mut().autocomplete_enter();
                return Inhibit(true)
            }
            else {
                return Inhibit(false);
            }
        });

        let own = this.clone();
        this.borrow().entry.connect_property_cursor_position_notify(move |w| {
            if let Ok(item) = own.try_borrow() {
65 66 67 68 69
                if let Some(input) = w.get_text() {
                    if let Some(attr) = item.add_highlight(input) {
                        w.set_attributes(&attr);
                    }
                }
70 71 72 73 74 75
            }
        });

        let own = this.clone();
        this.borrow().entry.connect_property_selection_bound_notify(move |w| {
            if let Ok(item) = own.try_borrow() {
76 77 78 79 80
                if let Some(input) = w.get_text() {
                    if let Some(attr) = item.add_highlight(input) {
                        w.set_attributes(&attr);
                    }
                }
81 82 83 84 85 86
            }
        });

        let own = this.clone();
        this.borrow().entry.connect_changed(move |w| {
            if let Ok(item) = own.try_borrow() {
87 88 89 90 91
                if let Some(input) = w.get_text() {
                    if let Some(attr) = item.add_highlight(input) {
                        w.set_attributes(&attr);
                    }
                }
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
            }
        });

        let own = this.clone();
        this.borrow().entry.connect_delete_text(move |_, start, end| {
            if let Ok(mut item) = own.try_borrow_mut() {
                if let Some(pos) = item.popover_position {
                    if end <= pos + 1 || (start <= pos && end > pos){
                        item.autocomplete_enter();
                    }
                }
            }
        });

        let own = this.clone();
        this.borrow().entry.connect_key_release_event(move |_, k| {
            match k.get_keyval() {
                gdk::enums::key::Escape => {
                    if own.borrow().popover_position.is_some() {
                        own.borrow_mut().autocomplete_enter();
                        return Inhibit(true)
                    }
                }
                _ => {}
            }
            Inhibit(false)
        });

        let own = this.clone();
        this.borrow().entry.connect_key_press_event(move |w, ev| {
            match ev.get_keyval() {
                gdk::enums::key::BackSpace => {
124 125 126 127 128 129
                    match w.get_text() {
                        Some(ref t) if t == "" => { own.borrow_mut().autocomplete_enter(); }
                        None => { own.borrow_mut().autocomplete_enter(); }
                        _ => { }
                    };

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
                    return glib::signal::Inhibit(false);
                },
                /* Tab and Enter key */
                gdk::enums::key::Tab | gdk::enums::key::Return => {
                    if own.borrow().popover_position.is_some() {
                        let widget = {
                            own.borrow_mut().popover_closing = true;
                            own.borrow_mut().autocomplete_arrow(0)
                        };
                        if let Some(w) = widget {
                            let ev: &gdk::Event = ev;
                            let _ = w.emit("button-press-event", &[ev]);
                        }
                    }
                    else {
                        if ev.get_keyval() != gdk::enums::key::Tab {
                            return glib::signal::Inhibit(false);
                        }
                    }
                },
                /* Arrow key */
                gdk::enums::key::Up => {
                    let widget = {
                        own.borrow_mut().autocomplete_arrow(-1)
                    };
                    if let Some(w) = widget {
                        let ev: &gdk::Event = ev;
                        let _ = w.emit("button-press-event", &[ev]);
                    }
                },
                /* Arrow key */
                gdk::enums::key::Down => {
                    let widget = {
                        own.borrow_mut().autocomplete_arrow(1)
                    };

                    if let Some(w) = widget {
                        let ev: &gdk::Event = ev;
                        let _ = w.emit("button-press-event", &[ev]);
                    }
                }
                _ => return glib::signal::Inhibit(false),
            }
            return glib::signal::Inhibit(true);
        });

        let own = this.clone();
        this.borrow().entry.connect_key_release_event(move |e, ev| {
            let is_tab = ev.get_keyval() == gdk::enums::key::Tab;
            let text = e.get_text();
            /* when closing popover with tab */
            {
                if own.borrow().popover_closing {
                    own.borrow_mut().popover_closing = false;
                    return Inhibit(false);
                }
            }
187
            /* allow popover opening with tab
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
             * don't update popover when the input didn't change */
            if !is_tab {
                if let Some(ref text) = text {
                    if let Some(ref old) = own.borrow().popover_search {
                        if text == old {
                            return Inhibit(false);
                        }
                    }
                }
            }
            /* update the popover when closed and tab is released
             * don't update the popover the arrow keys are pressed */
            if (is_tab && own.borrow().popover_position.is_none()) ||
                (ev.get_keyval() != gdk::enums::key::Up && ev.get_keyval() != gdk::enums::key::Down) {
                    own.borrow_mut().popover_search = text.clone();
                    let pos = e.get_position();
                    if let Some(text) = text.clone() {
205
                        let graphs = text.chars().collect::<Vec<char>>();
206 207 208 209 210

                        if pos as usize > graphs.len() {
                            return Inhibit(false);
                        }

211
                        let (p1, _) = graphs.split_at(pos as usize);
212
                        let first = p1.into_iter().collect::<String>();
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
                        if own.borrow().popover_position.is_none() {
                            if !is_tab {
                                if let Some(at_pos) = first.rfind("@") {
                                    own.borrow_mut().popover_position = Some(at_pos as i32);
                                }
                            }
                            else {
                                if let Some(space_pos) = first.rfind(" ") {
                                    own.borrow_mut().popover_position = Some(space_pos as i32 + 1);
                                }
                                else {
                                    own.borrow_mut().popover_position = Some(0);
                                }
                            }
                        }
                    }

                    if own.borrow().popover_position.is_some() {
                        let list = {
                            own.borrow().autocomplete(text, e.get_position())
                        };
                        let widget_list = {
                            own.borrow_mut().autocomplete_show_popover(list)
                        };
                        for (alias, widget) in widget_list.iter() {
                            widget.connect_button_press_event(clone!(own, alias => move |_, ev| {
                                own.borrow_mut().autocomplete_insert(alias.clone());
                                if ev.is::<gdk::EventKey>() {
                                    let ev = {
                                        let ev: &gdk::Event = ev;
                                        ev.clone().downcast::<gdk::EventKey>().unwrap()
                                    };
                                    /* Submit on enter */
                                    if ev.get_keyval() == gdk::enums::key::Return || ev.get_keyval() == gdk::enums::key::Tab  {
                                        own.borrow_mut().autocomplete_enter();
                                    }
                                }
                                else if ev.is::<gdk::EventButton>() {
                                    own.borrow_mut().autocomplete_enter();
                                }
                                Inhibit(true)
                            }));
                        }
                        /*for element in op.lock().unwrap().highlighted_entry.iter() {
                          println!("Saved aliases {}", element);
                          }
                          */
                    }
                }
            Inhibit(false)
        });
    }

    pub fn autocomplete_insert(&mut self, alias: String) {
        if let Some(start_pos) = self.popover_position {
            let mut start_pos = start_pos as i32;
            let end_pos = self.entry.get_position();
            self.entry.delete_text(start_pos, end_pos);
            self.entry.insert_text(&alias, &mut start_pos);
            self.entry.set_position(start_pos);

            /* highlight member inside the entry */
            /* we need to set the highlight here the first time
             * because the ui changes from others are blocked as long we hold the look */
            if let Some(input) = self.entry.get_text() {
                self.highlighted_entry.push(alias);
279 280 281
                if let Some(attr) = self.add_highlight(input) {
                    self.entry.set_attributes(&attr);
                }
282 283 284 285 286 287
            }
        }
    }

    pub fn autocomplete_enter(&mut self) -> bool {
        if let Some(input) = self.entry.get_text() {
288 289 290
            if let Some(attr) = self.add_highlight(input) {
                self.entry.set_attributes(&attr);
            }
291 292 293 294 295
        }
        self.popover_position = None;
        self.popover_search = None;
        let visible = self.popover.is_visible();
        self.popover.popdown();
296
        self.op.lock().unwrap().inhibit_escape = false;
297 298

        visible
299 300
    }

301
    pub fn add_highlight(&self, input: String) -> Option<pango::AttrList> {
302
        fn contains((start, end): (i32, i32), item: i32) -> bool {
303 304 305
            match start <= end {
                true => start <= item && end > item,
                false => start <= item || end > item,
306 307
            }
        }
308

309 310
        let input = input.to_lowercase();
        let bounds = self.entry.get_selection_bounds();
311 312
        let context = gtk::Widget::get_style_context (&self.entry.clone().upcast::<gtk::Widget>())?;
        let fg  = gtk::StyleContext::lookup_color (&context, "theme_selected_bg_color")?;
313 314 315
        let red = fg.red * 65535. + 0.5;
        let green = fg.green * 65535. + 0.5;
        let blue = fg.blue * 65535. + 0.5;
316
        let color = pango::Attribute::new_foreground(red as u16, green as u16, blue as u16)?;
317 318 319 320 321 322 323 324 325

        let attr = pango::AttrList::new();
        for (_, alias) in self.highlighted_entry.iter().enumerate() {
            let mut input = input.clone();
            let alias = &alias.to_lowercase();
            let mut removed_char = 0;
            let mut found = false;
            while input.contains(alias) {
                let pos = {
326
                    let start = input.find(alias)? as i32;
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
                    (start, start + alias.len() as i32)
                };
                let mut color = color.clone();
                let mark_start = removed_char as i32 + pos.0;
                let mark_end = removed_char as i32 + pos.1;
                let mut final_pos = Some((mark_start, mark_end));
                /* exclude selected text */
                if let Some((bounds_start, bounds_end)) = bounds {
                    /* If the selection is within the alias */
                    if contains((mark_start, mark_end), bounds_start) &&
                        contains((mark_start, mark_end), bounds_end) {
                            final_pos = Some((mark_start, bounds_start));
                            /* Add blue color after a selection */
                            let mut color = color.clone();
                            color.set_start_index(bounds_end as u32);
                            color.set_end_index(mark_end as u32);
                            attr.insert(color);
                        } else {
                            /* The alias starts inside a selection */
346 347
                            if contains(bounds?, mark_start) {
                                final_pos = Some((bounds_end, final_pos?.1));
348 349
                            }
                            /* The alias ends inside a selection */
350 351
                            if contains(bounds?, mark_end - 1) {
                                final_pos = Some((final_pos?.0, bounds_start));
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
                            }
                        }
                }

                if let Some((start, end)) = final_pos {
                    color.set_start_index(start as u32);
                    color.set_end_index(end as u32);
                    attr.insert(color);
                }
                {
                    let end = pos.1 as usize;
                    input.drain(0..end);
                }
                removed_char = removed_char + pos.1 as u32;
                found = true;
            }
            if !found {
                //guard.highlighted_entry.remove(i);
                //println!("Should remove {} form store", alias);
            }
        }

374
        Some(attr)
375 376 377 378 379 380 381 382 383 384 385 386
    }

    pub fn autocomplete_arrow(&mut self, direction: i32) -> Option<gtk::Widget> {
        let mut result = None;
        if let Some(row) = self.listbox.get_selected_row() {
            let index = row.get_index() + direction;
            if index >= 0 {
                let row = self.listbox.get_row_at_index(row.get_index() + direction);
                match row {
                    None => {
                        if let Some(row) = self.listbox.get_row_at_index(0) {
                            self.listbox.select_row(&row);
387
                            result = Some(row.get_children().first()?.clone());
388 389 390 391
                        }
                    }
                    Some(row) => {
                        self.listbox.select_row(&row);
392
                        result = Some(row.get_children().first()?.clone());
393 394 395 396 397 398 399
                    }
                };
            }
            else {
                if let Some(row) = self.listbox.get_children().last() {
                    if let Ok(row) = row.clone().downcast::<gtk::ListBoxRow>() {
                        self.listbox.select_row(&row);
400
                        result = Some(row.get_children().first()?.clone());
401 402 403 404 405 406 407
                    }
                }
            }
        }
        else {
            if let Some(row) = self.listbox.get_row_at_index(0) {
                self.listbox.select_row(&row);
408
                result = Some(row.get_children().first()?.clone());
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
            }
        }
        return result;
    }

    pub fn autocomplete_show_popover(&mut self, list: Vec<Member>) -> HashMap<String, gtk::EventBox> {
        for ch in self.listbox.get_children().iter() {
            self.listbox.remove(ch);
        }

        let mut widget_list : HashMap<String, gtk::EventBox> = HashMap::new();

        if list.len() > 0 {
            for m in list.iter() {
                let alias = &m.alias.clone().unwrap_or_default().trim_right_matches(" (IRC)").to_owned();
                let widget;
                {
426
                    let guard = self.op.lock().unwrap();
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
                    let mb = widgets::MemberBox::new(&m, &guard);
                    widget = mb.widget(true);
                }

                let w = widget.clone();
                let a = alias.clone();
                widget_list.insert(a, w);
                self.listbox.add(&widget);
            }

            self.popover.set_relative_to(Some(&self.entry));
            self.popover.set_modal(false);
            /* calculate position for popover */

            if let Some(text_index) = self.popover_position {
                let offset = self.entry.get_layout_offsets().0;
443 444 445
                if let Some(layout) = self.entry.get_layout() {
                    let layout_index = self.entry.text_index_to_layout_index(text_index);
                    let (_, index) = layout.get_cursor_pos(layout_index);
446

447 448 449
                    pango::extents_to_pixels(Some(&index), None);
                    self.popover.set_pointing_to(&gdk::Rectangle{x: index.x + offset + 10, y: 0, width: 0, height: 0});
                }
450 451 452 453 454 455 456
            }

            if let Some(row) = self.listbox.get_row_at_index(0) {
                self.listbox.select_row(&row);
            }

            self.popover.popup();
457
            self.op.lock().unwrap().inhibit_escape = true;
458 459 460 461
        }
        else {
            self.autocomplete_enter();
        }
462

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
        return widget_list;
    }

    pub fn autocomplete(&self, text: Option<String>, pos : i32) -> Vec<Member> {
        let mut list: Vec<Member> = vec![];
        let guard = self.op.lock().unwrap();
        let rooms = &guard.rooms;
        match text {
            None => {},
            Some(txt) => {
                if let Some(at_pos) = self.popover_position {
                    let last = {
                        let start = at_pos as usize;
                        let end = pos as usize;
                        txt.get(start..end)
                    };
                    if let Some(last) = last {
                        println!("Matching string '{}'", last);
                        /*remove @ from string*/
                        let w = if last.starts_with("@") {
                            last[1..].to_lowercase()
                        }
                        else {
                            last.to_lowercase()
                        };

                        /* Search for the 5 most recent active users */
                        if let Some(aroom) = guard.active_room.clone() {
                            if let Some(r) = rooms.get(&aroom) {
                                let mut count = 0;
                                for (_, m) in r.members.iter() {
                                    let alias = &m.alias.clone().unwrap_or_default().to_lowercase();
                                    let uid = &m.uid.clone().to_lowercase()[1..];
                                    if alias.starts_with(&w) || uid.starts_with(&w) {
                                        list.push(m.clone());
                                        count = count + 1;
                                        /* Search only for 5 matching users */
                                        if count > 4 {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        };
        return list;
    }
}