Skip to main content

whisker_input_linux/
lib.rs

1//! Linux Host implementation for `whisker-input`: a `gtk::Text` field, or a `gtk::TextView` when multiline.
2
3#![cfg(target_os = "linux")]
4
5use std::cell::{Cell, RefCell};
6use std::rc::Rc;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use whisker::platform_module::WhiskerValue;
10use whisker_linux::gtk4::{self as gtk, gdk, glib, pango, prelude::*};
11use whisker_linux::{LinuxEventEmitter, LinuxModuleDefinition, LinuxView, LinuxViewDefinition};
12use whisker_protocol::{
13    AvailableSpace, MeasureFontFamily, MeasureFontStyle, MeasureLineHeight, MeasureTextAlignment,
14    MeasureTextDirection, MeasuredSize, ModuleMeasureRequest, PaintColor, TextStyleSnapshot,
15};
16
17const NAME: &str = "whisker-input:Input";
18
19#[derive(Clone)]
20enum Editor {
21    Line(gtk::Text),
22    Area(gtk::TextView),
23}
24
25impl Editor {
26    fn widget(&self) -> gtk::Widget {
27        match self {
28            Self::Line(text) => text.clone().upcast(),
29            Self::Area(view) => view.clone().upcast(),
30        }
31    }
32
33    fn text(&self) -> String {
34        match self {
35            Self::Line(text) => text.text().into(),
36            Self::Area(view) => {
37                let buffer = view.buffer();
38                let (start, end) = buffer.bounds();
39                buffer.text(&start, &end, false).into()
40            }
41        }
42    }
43
44    fn set_text(&self, value: &str) {
45        match self {
46            Self::Line(text) => text.set_text(value),
47            Self::Area(view) => view.buffer().set_text(value),
48        }
49    }
50}
51
52struct Settings {
53    placeholder: String,
54    placeholder_color: String,
55    caret_color: String,
56    selection_color: String,
57    multiline: bool,
58    secure: bool,
59    editable: bool,
60    auto_focus: bool,
61    max_length: i64,
62    keyboard_type: String,
63    auto_capitalize: String,
64    autocorrect: bool,
65    spell_check: bool,
66    style: Option<TextStyleSnapshot>,
67}
68
69impl Default for Settings {
70    fn default() -> Self {
71        Self {
72            placeholder: String::new(),
73            placeholder_color: String::new(),
74            caret_color: String::new(),
75            selection_color: String::new(),
76            multiline: false,
77            secure: false,
78            editable: true,
79            auto_focus: false,
80            max_length: 0,
81            keyboard_type: "default".into(),
82            auto_capitalize: "sentences".into(),
83            autocorrect: true,
84            spell_check: true,
85            style: None,
86        }
87    }
88}
89
90struct Inner {
91    root: gtk::Overlay,
92    hint: gtk::Label,
93    class: String,
94    css: gtk::CssProvider,
95    editor: RefCell<Editor>,
96    settings: RefCell<Settings>,
97    // Set while the Host writes the text, so the change is not echoed back as user input.
98    silent: Cell<bool>,
99    events: LinuxEventEmitter,
100}
101
102struct InputView(Rc<Inner>);
103
104impl LinuxView for InputView {
105    fn widget(&self) -> gtk::Widget {
106        self.0.root.clone().upcast()
107    }
108}
109
110impl Drop for InputView {
111    fn drop(&mut self) {
112        if let Some(display) = gdk::Display::default() {
113            gtk::style_context_remove_provider_for_display(&display, &self.0.css);
114        }
115    }
116}
117
118fn detail(value: &str) -> WhiskerValue {
119    WhiskerValue::map([("value", WhiskerValue::String(value.to_owned()))])
120}
121
122impl InputView {
123    fn new(events: LinuxEventEmitter) -> Self {
124        static NEXT: AtomicU64 = AtomicU64::new(0);
125        let class = format!("whisker-input-{}", NEXT.fetch_add(1, Ordering::Relaxed));
126        let css = gtk::CssProvider::new();
127        if let Some(display) = gdk::Display::default() {
128            gtk::style_context_add_provider_for_display(
129                &display,
130                &css,
131                gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
132            );
133        }
134        let root = gtk::Overlay::new();
135        let hint = gtk::Label::new(None);
136        hint.set_xalign(0.0);
137        hint.set_yalign(0.0);
138        hint.set_can_target(false);
139        hint.add_css_class(&format!("{class}-hint"));
140        root.add_overlay(&hint);
141        let inner = Rc::new(Inner {
142            root,
143            hint,
144            class,
145            css,
146            editor: RefCell::new(Editor::Line(gtk::Text::new())),
147            settings: RefCell::new(Settings::default()),
148            silent: Cell::new(false),
149            events,
150        });
151        let view = Self(inner);
152        view.rebuild();
153        let weak = Rc::downgrade(&view.0);
154        view.0.root.connect_map(move |_| {
155            if let Some(inner) = weak.upgrade()
156                && inner.settings.borrow().auto_focus
157            {
158                inner.editor.borrow().widget().grab_focus();
159            }
160        });
161        view
162    }
163
164    fn rebuild(&self) {
165        let inner = &self.0;
166        let value = inner.editor.borrow().text();
167        let editor = if inner.settings.borrow().multiline {
168            let view = gtk::TextView::new();
169            view.set_wrap_mode(gtk::WrapMode::WordChar);
170            view.set_accepts_tab(false);
171            Editor::Area(view)
172        } else {
173            Editor::Line(gtk::Text::new())
174        };
175        let widget = editor.widget();
176        widget.add_css_class(&inner.class);
177        widget.set_hexpand(true);
178        widget.set_vexpand(true);
179        inner.root.set_child(Some(&widget));
180        *inner.editor.borrow_mut() = editor.clone();
181        self.connect(&editor);
182        inner.silent.set(true);
183        editor.set_text(&value);
184        inner.silent.set(false);
185        self.apply();
186    }
187
188    fn connect(&self, editor: &Editor) {
189        let weak = Rc::downgrade(&self.0);
190        let changed = move || {
191            let Some(inner) = weak.upgrade() else { return };
192            inner.refresh_hint();
193            if inner.silent.get() {
194                return;
195            }
196            let mut value = inner.editor.borrow().text();
197            let limit = inner.settings.borrow().max_length;
198            if limit > 0 && value.chars().count() > limit as usize {
199                value = value.chars().take(limit as usize).collect();
200                inner.silent.set(true);
201                inner.editor.borrow().set_text(&value);
202                inner.silent.set(false);
203            }
204            inner.events.emit("input", detail(&value));
205        };
206        match editor {
207            Editor::Line(text) => {
208                text.connect_changed(move |_| changed());
209                let weak = Rc::downgrade(&self.0);
210                text.connect_activate(move |_| {
211                    if let Some(inner) = weak.upgrade() {
212                        inner.submit();
213                    }
214                });
215            }
216            Editor::Area(view) => {
217                view.buffer().connect_changed(move |_| changed());
218                let keys = gtk::EventControllerKey::new();
219                let weak = Rc::downgrade(&self.0);
220                keys.connect_key_pressed(move |_, key, _, state| {
221                    let submit = matches!(key, gdk::Key::Return | gdk::Key::KP_Enter)
222                        && state.contains(gdk::ModifierType::CONTROL_MASK);
223                    match weak.upgrade() {
224                        Some(inner) if submit => {
225                            inner.submit();
226                            glib::Propagation::Stop
227                        }
228                        _ => glib::Propagation::Proceed,
229                    }
230                });
231                view.add_controller(keys);
232            }
233        }
234        let focus = gtk::EventControllerFocus::new();
235        let weak = Rc::downgrade(&self.0);
236        focus.connect_enter(move |_| {
237            if let Some(inner) = weak.upgrade() {
238                inner
239                    .events
240                    .emit("focus", WhiskerValue::Map(Default::default()));
241            }
242        });
243        let weak = Rc::downgrade(&self.0);
244        focus.connect_leave(move |_| {
245            if let Some(inner) = weak.upgrade() {
246                let value = inner.editor.borrow().text();
247                inner
248                    .events
249                    .emit("blur", WhiskerValue::Map(Default::default()));
250                inner.events.emit("change", detail(&value));
251            }
252        });
253        editor.widget().add_controller(focus);
254    }
255
256    fn update(&self, change: impl FnOnce(&mut Settings)) {
257        let multiline = self.0.settings.borrow().multiline;
258        change(&mut self.0.settings.borrow_mut());
259        if multiline != self.0.settings.borrow().multiline {
260            self.rebuild();
261        } else {
262            self.apply();
263        }
264    }
265
266    fn apply(&self) {
267        let inner = &self.0;
268        let settings = inner.settings.borrow();
269        let editor = inner.editor.borrow();
270        let purpose = match settings.keyboard_type.as_str() {
271            "number" | "numeric" => gtk::InputPurpose::Number,
272            "decimal" => gtk::InputPurpose::Number,
273            "phone" => gtk::InputPurpose::Phone,
274            "email" => gtk::InputPurpose::Email,
275            "url" => gtk::InputPurpose::Url,
276            _ if settings.secure => gtk::InputPurpose::Password,
277            _ => gtk::InputPurpose::FreeForm,
278        };
279        let mut hints = match settings.auto_capitalize.as_str() {
280            "characters" => gtk::InputHints::UPPERCASE_CHARS,
281            "words" => gtk::InputHints::UPPERCASE_WORDS,
282            "none" => gtk::InputHints::LOWERCASE,
283            _ => gtk::InputHints::UPPERCASE_SENTENCES,
284        };
285        hints |= if settings.spell_check {
286            gtk::InputHints::SPELLCHECK
287        } else {
288            gtk::InputHints::NO_SPELLCHECK
289        };
290        if settings.autocorrect {
291            hints |= gtk::InputHints::WORD_COMPLETION;
292        }
293        let alignment = settings.style.as_ref().map(|style| style.alignment);
294        let rtl = settings
295            .style
296            .as_ref()
297            .is_some_and(|style| style.direction == MeasureTextDirection::RightToLeft);
298        let xalign = match alignment {
299            Some(MeasureTextAlignment::Center) => 0.5,
300            Some(MeasureTextAlignment::End) => (!rtl) as u8 as f32,
301            Some(MeasureTextAlignment::Right) => 1.0,
302            Some(MeasureTextAlignment::Start) => rtl as u8 as f32,
303            _ => 0.0,
304        };
305        match &*editor {
306            Editor::Line(text) => {
307                text.set_placeholder_text(Some(&settings.placeholder));
308                text.set_visibility(!settings.secure);
309                text.set_editable(settings.editable);
310                text.set_max_length(settings.max_length.clamp(0, i32::MAX as i64) as i32);
311                text.set_input_purpose(purpose);
312                text.set_input_hints(hints);
313                text.set_alignment(xalign);
314            }
315            Editor::Area(view) => {
316                view.set_editable(settings.editable);
317                view.set_cursor_visible(settings.editable);
318                view.set_input_purpose(purpose);
319                view.set_input_hints(hints);
320                view.set_justification(match xalign {
321                    0.5 => gtk::Justification::Center,
322                    1.0 => gtk::Justification::Right,
323                    _ => gtk::Justification::Left,
324                });
325            }
326        }
327        let direction = match settings.style.as_ref().map(|style| style.direction) {
328            Some(MeasureTextDirection::LeftToRight) => gtk::TextDirection::Ltr,
329            Some(MeasureTextDirection::RightToLeft) => gtk::TextDirection::Rtl,
330            _ => gtk::TextDirection::None,
331        };
332        editor.widget().set_direction(direction);
333        inner.hint.set_text(&settings.placeholder);
334        inner.hint.set_xalign(xalign);
335        inner
336            .css
337            .load_from_string(&stylesheet(&inner.class, &settings));
338        drop(settings);
339        drop(editor);
340        inner.refresh_hint();
341    }
342
343    fn set_value(&self, value: &str) {
344        let inner = &self.0;
345        if inner.editor.borrow().text() == value {
346            return;
347        }
348        inner.silent.set(true);
349        inner.editor.borrow().set_text(value);
350        inner.silent.set(false);
351        inner.refresh_hint();
352    }
353
354    fn blur(&self) {
355        let widget = self.0.editor.borrow().widget();
356        if widget.has_focus()
357            && let Some(window) = widget.root().and_downcast::<gtk::Window>()
358        {
359            GtkWindowExt::set_focus(&window, None::<&gtk::Widget>);
360        }
361    }
362}
363
364impl Inner {
365    fn refresh_hint(&self) {
366        let area = matches!(&*self.editor.borrow(), Editor::Area(_));
367        let empty = self.editor.borrow().text().is_empty();
368        self.hint.set_visible(area && empty);
369    }
370
371    fn submit(&self) {
372        let value = self.editor.borrow().text();
373        self.events.emit("submit", detail(&value));
374        self.events.emit("change", detail(&value));
375    }
376}
377
378fn css_color(color: &PaintColor) -> String {
379    match color {
380        PaintColor::Named(name) => name.clone(),
381        PaintColor::Srgba {
382            red,
383            green,
384            blue,
385            alpha,
386        } => format!("rgba({red},{green},{blue},{alpha})"),
387        #[allow(unreachable_patterns)]
388        _ => "currentColor".into(),
389    }
390}
391
392fn css_string(value: &str) -> String {
393    format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
394}
395
396fn stylesheet(class: &str, settings: &Settings) -> String {
397    let mut text = String::from(
398        "background: transparent; border: none; box-shadow: none; outline: none; \
399         padding: 0; margin: 0; min-height: 0;",
400    );
401    if let Some(style) = &settings.style {
402        let font = &style.style;
403        let family = font
404            .font_families
405            .iter()
406            .map(|family| match family {
407                MeasureFontFamily::System => "sans-serif".to_owned(),
408                MeasureFontFamily::Named(name) => css_string(name),
409            })
410            .collect::<Vec<_>>()
411            .join(", ");
412        if !family.is_empty() {
413            text.push_str(&format!(" font-family: {family};"));
414        }
415        text.push_str(&format!(
416            " font-size: {}px; font-weight: {}; font-style: {}; letter-spacing: {}px; color: {};",
417            font.font_size,
418            font.font_weight,
419            match font.font_style {
420                MeasureFontStyle::Normal => "normal",
421                MeasureFontStyle::Italic => "italic",
422                MeasureFontStyle::Oblique => "oblique",
423            },
424            font.letter_spacing,
425            css_color(&style.paint.foreground),
426        ));
427        if let MeasureLineHeight::LogicalPixels(height) = font.line_height {
428            text.push_str(&format!(" line-height: {height}px;"));
429        }
430    }
431    if !settings.caret_color.is_empty() {
432        text.push_str(&format!(" caret-color: {};", settings.caret_color));
433    }
434    let mut css = format!(
435        ".{class}, .{class} > text {{ {text} }}\n.{class}-hint {{ {text} opacity: 0.5; }}\n"
436    );
437    if !settings.selection_color.is_empty() {
438        css.push_str(&format!(
439            ".{class} selection, .{class} > text selection {{ background-color: {}; }}\n",
440            settings.selection_color
441        ));
442    }
443    if !settings.placeholder_color.is_empty() {
444        css.push_str(&format!(
445            ".{class} > placeholder, .{class}-hint {{ color: {}; opacity: 1; }}\n",
446            settings.placeholder_color
447        ));
448    }
449    css
450}
451
452thread_local! {
453    static MEASURER: gtk::Label = gtk::Label::new(None);
454}
455
456fn weight(value: i64) -> pango::Weight {
457    match value {
458        ..=150 => pango::Weight::Thin,
459        151..=250 => pango::Weight::Ultralight,
460        251..=350 => pango::Weight::Light,
461        351..=450 => pango::Weight::Normal,
462        451..=550 => pango::Weight::Medium,
463        551..=650 => pango::Weight::Semibold,
464        651..=750 => pango::Weight::Bold,
465        751..=850 => pango::Weight::Ultrabold,
466        _ => pango::Weight::Heavy,
467    }
468}
469
470fn measure(request: &ModuleMeasureRequest) -> Option<MeasuredSize> {
471    if request.payload_version != 1 {
472        return None;
473    }
474    let field = |name: &str| match &request.payload {
475        WhiskerValue::Map(entries) => entries.get(name),
476        _ => None,
477    };
478    let number = |name: &str| match field(name) {
479        Some(WhiskerValue::Float(value)) => Some(*value),
480        Some(WhiskerValue::Int(value)) => Some(*value as f64),
481        _ => None,
482    };
483    let Some(WhiskerValue::String(text)) = field("text") else {
484        return None;
485    };
486    let multiline = matches!(field("multiline"), Some(WhiskerValue::Bool(true)));
487    let italic = matches!(field("italic"), Some(WhiskerValue::Bool(true)));
488    let font_size = number("font_size")?;
489    let letter_spacing = number("letter_spacing").unwrap_or(0.0);
490    let line_height = number("line_height");
491    let text = if multiline {
492        text.clone()
493    } else {
494        text.replace('\n', " ")
495    };
496    MEASURER.with(|label| {
497        let layout = label.create_pango_layout(Some(&text));
498        let mut font = layout
499            .context()
500            .font_description()
501            .unwrap_or_else(pango::FontDescription::new);
502        if let Some(WhiskerValue::String(family)) = field("font_family") {
503            font.set_family(family);
504        }
505        font.set_absolute_size(font_size * f64::from(pango::SCALE));
506        font.set_weight(weight(number("font_weight").unwrap_or(400.0) as i64));
507        font.set_style(if italic {
508            pango::Style::Italic
509        } else {
510            pango::Style::Normal
511        });
512        layout.set_font_description(Some(&font));
513        let attributes = pango::AttrList::new();
514        attributes.insert(pango::AttrInt::new_letter_spacing(
515            (letter_spacing * f64::from(pango::SCALE)) as i32,
516        ));
517        layout.set_attributes(Some(&attributes));
518        let natural = layout.pixel_size().0 as f32;
519        let available = match request.available_space[0] {
520            AvailableSpace::Definite(width) => natural.min(width),
521            AvailableSpace::MinContent if multiline => 1.0,
522            AvailableSpace::MinContent | AvailableSpace::MaxContent => natural,
523        };
524        let width = request.known_dimensions[0].unwrap_or(available).max(1.0);
525        if multiline {
526            layout.set_wrap(pango::WrapMode::WordChar);
527            layout.set_width((width * pango::SCALE as f32) as i32);
528        }
529        let (used_width, used_height) = layout.pixel_size();
530        let height = match line_height {
531            Some(line) => line as f32 * layout.line_count().max(1) as f32,
532            None => used_height as f32,
533        };
534        Some(MeasuredSize::new(
535            request.known_dimensions[0].unwrap_or(used_width as f32),
536            request.known_dimensions[1].unwrap_or(height),
537        ))
538    })
539}
540
541fn string(value: &WhiskerValue) -> String {
542    match value {
543        WhiskerValue::String(value) => value.clone(),
544        _ => String::new(),
545    }
546}
547
548fn boolean(value: &WhiskerValue, default: bool) -> bool {
549    match value {
550        WhiskerValue::Bool(value) => *value,
551        _ => default,
552    }
553}
554
555fn int(value: &WhiskerValue) -> i64 {
556    match value {
557        WhiskerValue::Int(value) => *value,
558        _ => 0,
559    }
560}
561
562struct InputModule;
563
564#[whisker::WhiskerModule]
565impl whisker::WhiskerModule for InputModule {
566    type Definition = LinuxModuleDefinition;
567
568    fn definition() -> Self::Definition {
569        macro_rules! setting {
570            ($definition:expr, $prop:literal, |$settings:ident, $value:ident| $set:expr, $default:expr) => {
571                $definition.prop(
572                    $prop,
573                    |view: &InputView, $value| view.update(|$settings| $set),
574                    |view: &InputView| {
575                        let $value = &$default;
576                        view.update(|$settings| $set)
577                    },
578                )
579            };
580        }
581        let view = LinuxViewDefinition::new(NAME, InputView::new).prop(
582            "value",
583            |view, value| view.set_value(&string(value)),
584            |view| view.set_value(""),
585        );
586        let view = setting!(
587            view,
588            "placeholder",
589            |s, v| s.placeholder = string(v),
590            WhiskerValue::Null
591        );
592        let view = setting!(
593            view,
594            "placeholder-color",
595            |s, v| s.placeholder_color = string(v),
596            WhiskerValue::Null
597        );
598        let view = setting!(
599            view,
600            "caret-color",
601            |s, v| s.caret_color = string(v),
602            WhiskerValue::Null
603        );
604        let view = setting!(
605            view,
606            "selection-color",
607            |s, v| s.selection_color = string(v),
608            WhiskerValue::Null
609        );
610        let view = setting!(
611            view,
612            "multiline",
613            |s, v| s.multiline = boolean(v, false),
614            WhiskerValue::Null
615        );
616        let view = setting!(
617            view,
618            "secure",
619            |s, v| s.secure = boolean(v, false),
620            WhiskerValue::Null
621        );
622        let view = setting!(
623            view,
624            "editable",
625            |s, v| s.editable = boolean(v, true),
626            WhiskerValue::Null
627        );
628        let view = setting!(
629            view,
630            "auto-focus",
631            |s, v| s.auto_focus = boolean(v, false),
632            WhiskerValue::Null
633        );
634        let view = setting!(
635            view,
636            "max-length",
637            |s, v| s.max_length = int(v),
638            WhiskerValue::Null
639        );
640        let view = setting!(
641            view,
642            "keyboard-type",
643            |s, v| s.keyboard_type = string(v),
644            WhiskerValue::Null
645        );
646        let view = setting!(
647            view,
648            "auto-capitalize",
649            |s, v| s.auto_capitalize = string(v),
650            WhiskerValue::Null
651        );
652        let view = setting!(
653            view,
654            "autocorrect",
655            |s, v| s.autocorrect = boolean(v, true),
656            WhiskerValue::Null
657        );
658        let view = setting!(
659            view,
660            "spell-check",
661            |s, v| s.spell_check = boolean(v, true),
662            WhiskerValue::Null
663        );
664        let view = view
665            .prop("lines", |_, _| {}, |_| {})
666            .prop("return-key", |_, _| {}, |_| {})
667            .prop("auto-size", |_, _| {}, |_| {})
668            .text_style(|view, style| view.update(|settings| settings.style = Some(style.clone())))
669            .measure(measure)
670            .event("input")
671            .event("change")
672            .event("focus")
673            .event("blur")
674            .event("submit")
675            .command("focus", |view, _| {
676                view.0.editor.borrow().widget().grab_focus();
677            })
678            .command("blur", |view, _| view.blur())
679            .command("clear", |view, _| {
680                view.set_value("");
681                view.0.events.emit("input", detail(""));
682            })
683            .command("setValue", |view, value| {
684                if let WhiskerValue::Map(entries) = value
685                    && let Some(WhiskerValue::String(value)) = entries.get("value")
686                {
687                    view.set_value(value);
688                }
689            });
690        LinuxModuleDefinition::new().name(NAME).view(view)
691    }
692}