summary refs log tree commit diff
path: root/src/cue_view.rs
blob: c03172027b3baa058ce3f36945b585f008101352 (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
use std::ops::Range;
use std::str::FromStr;

use gtk::gdk;
use gtk::glib;
use gtk::{pango, prelude::*};
use relm4::prelude::*;
use relm4::{ComponentParts, SimpleComponent};
use unicode_segmentation::UnicodeSegmentation;

use crate::util::OptionTracker;

pub struct CueView {
    text: OptionTracker<String>,
    // byte ranges for the words in `text`
    word_ranges: Vec<Range<usize>>,
}

#[derive(Debug)]
pub enum CueViewMsg {
    // messages from the app
    SetText(Option<String>),
    // messages from UI
    MouseMotion,
}

#[derive(Debug)]
pub enum CueViewOutput {
    MouseEnter,
    MouseLeave,
}

#[relm4::component(pub)]
impl SimpleComponent for CueView {
    type Init = ();
    type Input = CueViewMsg;
    type Output = CueViewOutput;

    view! {
        #[root]
        #[name(label)]
        gtk::Label {
            add_controller: event_controller.clone(),
            set_use_markup: true,
            set_visible: false,
            set_justify: gtk::Justification::Center,
            add_css_class: "cue-view",
        },

        #[name(event_controller)]
        gtk::EventControllerMotion {
            connect_enter[sender] => move |_, _, _| { sender.output(CueViewOutput::MouseEnter).unwrap() },
            connect_motion[sender] => move |_, _, _| { sender.input(CueViewMsg::MouseMotion) },
            connect_leave[sender] => move |_| { sender.output(CueViewOutput::MouseLeave).unwrap() },
        },

        #[name(popover)]
        gtk::Popover {
            set_parent: &root,
            set_position: gtk::PositionType::Top,
            set_autohide: false,

            #[name(popover_label)]
            gtk::Label { }
        }
    }

    fn init(
        _init: Self::Init,
        root: Self::Root,
        sender: relm4::ComponentSender<Self>,
    ) -> relm4::ComponentParts<Self> {
        let model = Self {
            text: OptionTracker::new(None),
            word_ranges: Vec::new(),
        };

        let widgets = view_output!();

        ComponentParts { model, widgets }
    }

    fn update(&mut self, message: Self::Input, _sender: relm4::ComponentSender<Self>) {
        match message {
            CueViewMsg::SetText(text) => {
                self.text.set(text);

                if let Some(text) = self.text.get() {
                    self.word_ranges = UnicodeSegmentation::unicode_word_indices(text.as_str())
                        .map(|(offset, slice)| Range {
                            start: offset,
                            end: offset + slice.len(),
                        })
                        .collect();
                } else {
                    self.word_ranges = Vec::new();
                }
            }
            CueViewMsg::MouseMotion => {
                // only used to update popover in view
            }
        }
    }

    fn post_view() {
        if self.text.is_dirty() {
            if let Some(text) = self.text.get() {
                let mut markup = String::new();

                let mut it = self.word_ranges.iter().enumerate().peekable();
                if let Some((_, first_word_range)) = it.peek() {
                    markup.push_str(
                        glib::markup_escape_text(&text[..first_word_range.start]).as_str(),
                    );
                }
                while let Some((word_ix, word_range)) = it.next() {
                    markup.push_str(&format!(
                        "<a href=\"{}\">{}</a>",
                        word_ix,
                        glib::markup_escape_text(&text[word_range.clone()])
                    ));
                    let next_gap_range = if let Some((_, next_word_range)) = it.peek() {
                        word_range.end..next_word_range.start
                    } else {
                        word_range.end..text.len()
                    };
                    markup.push_str(glib::markup_escape_text(&text[next_gap_range]).as_str());
                }

                widgets.label.set_markup(markup.as_str());
                widgets.label.set_visible(true);
            } else {
                widgets.label.set_visible(false);
            }
        }

        if let Some(word_ix_str) = widgets.label.current_uri() {
            let range = self
                .word_ranges
                .get(usize::from_str(word_ix_str.as_str()).unwrap())
                .unwrap();
            widgets
                .popover_label
                .set_text(&self.text.get().as_ref().unwrap()[range.clone()]);
            widgets
                .popover
                .set_pointing_to(Some(&Self::get_rect_of_byte_range(&widgets.label, &range)));
            widgets.popover.popup();
        } else {
            widgets.popover.popdown();
        }
    }

    fn shutdown(&mut self, widgets: &mut Self::Widgets, _output: relm4::Sender<Self::Output>) {
        widgets.popover.unparent();
    }
}

impl CueView {
    fn get_rect_of_byte_range(label: &gtk::Label, range: &Range<usize>) -> gdk::Rectangle {
        let layout = label.layout();
        let (offset_x, offset_y) = label.layout_offsets();

        let start_pos = layout.index_to_pos(range.start as i32);
        let end_pos = layout.index_to_pos(range.end as i32);
        let (x, width) = if start_pos.x() <= end_pos.x() {
            (start_pos.x(), end_pos.x() - start_pos.x())
        } else {
            (end_pos.x(), start_pos.x() - end_pos.x())
        };

        gdk::Rectangle::new(
            x / pango::SCALE + offset_x,
            start_pos.y() / pango::SCALE + offset_y,
            width / pango::SCALE,
            start_pos.height() / pango::SCALE,
        )
    }
}