use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use gtk::prelude::*;
use gtk::{gdk, glib, pango};
use prism_core::{Color, NodeId, OBJECT_CHAR, Style, TextRun, TextTransform, UiEvent, decode_runs};
use prism_native::text::{StyledRun, StyledText};
thread_local! {
static RICH: RefCell<HashMap<NodeId, Rich>> = RefCell::new(HashMap::new());
}
struct Rich {
view: gtk::TextView,
runs: String,
style: Option<Style>,
tags: Vec<gtk::TextTag>,
chips: Vec<Chip>,
}
struct Chip {
anchor: gtk::TextChildAnchor,
widget: gtk::Box,
icon: gtk::Label,
label: gtk::Label,
css: gtk::CssProvider,
link: Rc<Cell<Option<u64>>>,
copied: String,
}
pub(crate) fn setup(id: NodeId, view: >k::TextView) {
RICH.with(|r| {
r.borrow_mut().insert(
id,
Rich {
view: view.clone(),
runs: String::new(),
style: None,
tags: Vec::new(),
chips: Vec::new(),
},
)
});
}
pub(crate) fn forget(id: NodeId) {
RICH.with(|r| r.borrow_mut().remove(&id));
}
pub(crate) fn is_rich(id: NodeId) -> bool {
RICH.with(|r| r.borrow().contains_key(&id))
}
pub(crate) fn set_runs(id: NodeId, runs: &str) {
RICH.with(|r| {
if let Some(rich) = r.borrow_mut().get_mut(&id) {
rich.runs = runs.to_string();
show(rich);
}
});
}
pub(crate) fn set_style(id: NodeId, style: &Style) {
RICH.with(|r| {
if let Some(rich) = r.borrow_mut().get_mut(&id) {
rich.style = Some(style.clone());
show(rich);
}
});
}
pub(crate) fn restyle_all() {
RICH.with(|r| r.borrow_mut().values_mut().for_each(show));
}
pub(crate) fn slice(b: >k::TextBuffer) -> String {
b.slice(&b.start_iter(), &b.end_iter(), false).to_string()
}
fn show(rich: &mut Rich) {
let Some(style) = rich.style.clone() else {
return;
};
let style = Style {
text_transform: TextTransform::None,
..style
};
let runs = decode_runs(&rich.runs);
let text: String = runs.iter().map(|r| r.text.as_str()).collect();
let b = rich.view.buffer();
if slice(&b) != text {
return;
}
let styled = StyledText::from_runs(&text, &runs, &style);
let dark = crate::imp::dark();
let table = b.tag_table();
for tag in rich.tags.drain(..) {
table.remove(&tag);
}
let mut at = 0;
for (s, run) in styled.runs.iter().zip(&runs) {
let (start, len) = (at, run.text.chars().count() as i32);
at += len;
if len == 0 {
continue;
}
if run.is_object() && len == 1 && b.iter_at_offset(start).char() == OBJECT_CHAR {
chip_at(rich, &b, start, run, s, &style, dark);
continue;
}
if let Some(tag) = tag(s, &style, dark) {
table.add(&tag);
b.apply_tag(&tag, &b.iter_at_offset(start), &b.iter_at_offset(at));
rich.tags.push(tag);
}
}
rich.chips.retain(|c| !c.anchor.is_deleted());
}
fn tag(s: &StyledRun, style: &Style, dark: bool) -> Option<gtk::TextTag> {
let tag = gtk::TextTag::new(None);
let mut any = false;
if s.font.family != style.font_family
&& let Some(name) = crate::text::family_name(&s.font.family)
{
tag.set_family(Some(&name));
any = true;
}
if s.font.weight != style.font_weight {
tag.set_weight(s.font.weight.css() as i32);
any = true;
}
if s.font.italic && !style.italic {
tag.set_style(pango::Style::Italic);
any = true;
}
if s.font.size != style.font_size && style.font_size > 0. {
tag.set_scale((s.font.size / style.font_size) as f64);
any = true;
}
if let Some(c) = s
.color
.filter(|_| s.color != style.text_color || s.link.is_some())
{
tag.set_foreground_rgba(Some(&rgba(c, dark)));
any = true;
}
if let Some(c) = s.background {
tag.set_background_rgba(Some(&rgba(c, dark)));
any = true;
}
if s.underline {
tag.set_underline(crate::text::underline(s.underline_style));
if let Some(c) = s.underline_color {
tag.set_underline_rgba(Some(&rgba(c, dark)));
}
any = true;
}
if s.strikethrough {
tag.set_strikethrough(true);
any = true;
}
any.then_some(tag)
}
fn rgba(c: Color, dark: bool) -> gdk::RGBA {
let c = if dark {
c.dark_variant()
} else {
c.light_variant()
};
gdk::RGBA::new(c.r, c.g, c.b, c.a)
}
fn chip_at(
rich: &mut Rich,
b: >k::TextBuffer,
at: i32,
run: &TextRun,
s: &StyledRun,
style: &Style,
dark: bool,
) {
let anchor = match b.iter_at_offset(at).child_anchor() {
Some(a) => a,
None => {
b.begin_irreversible_action();
let (mut from, mut to) = (b.iter_at_offset(at), b.iter_at_offset(at + 1));
b.delete(&mut from, &mut to);
let a = b.create_child_anchor(&mut b.iter_at_offset(at));
b.end_irreversible_action();
a
}
};
let i = match rich.chips.iter().position(|c| c.anchor == anchor) {
Some(i) => i,
None => {
let c = new_chip(anchor);
rich.view.add_child_at_anchor(&c.widget, &c.anchor);
rich.chips.push(c);
rich.chips.len() - 1
}
};
configure(&rich.chips[i], run, s, style, dark);
rich.chips[i].copied = copied(run).to_string();
}
fn parts(run: &TextRun) -> (Option<&'static str>, &str, bool) {
match &run.chip {
Some(_) => (
run.chip_icon.as_deref().map(prism_core::glyphs::glyph),
run.chip_label.as_deref().unwrap_or(""),
true,
),
None => (
None,
run.icon.as_deref().map_or("", prism_core::glyphs::glyph),
false,
),
}
}
fn copied(run: &TextRun) -> &str {
match (&run.chip, &run.chip_label) {
(Some(_), Some(label)) => label,
_ => "",
}
}
fn new_chip(anchor: gtk::TextChildAnchor) -> Chip {
let widget = gtk::Box::new(gtk::Orientation::Horizontal, 0);
widget.add_css_class("prism-chip");
widget.set_focusable(false);
widget.set_can_focus(false);
let icon = gtk::Label::new(None);
let label = gtk::Label::new(None);
widget.append(&icon);
widget.append(&label);
let css = gtk::CssProvider::new();
#[allow(deprecated)]
widget
.style_context()
.add_provider(&css, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION + 2);
let link = Rc::new(Cell::new(None));
let click = gtk::GestureClick::new();
let l = link.clone();
click.connect_released(move |g, _, _, _| {
if let Some(link) = l.get() {
g.set_state(gtk::EventSequenceState::Claimed);
crate::imp::dispatch(UiEvent::MenuSelect(link));
}
});
widget.add_controller(click);
Chip {
anchor,
widget,
icon,
label,
css,
link,
copied: String::new(),
}
}
fn configure(chip: &Chip, run: &TextRun, s: &StyledRun, style: &Style, dark: bool) {
let (icon, label, boxed) = parts(run);
let attrs = pango::AttrList::new();
if let Some(name) = crate::text::family_name(&s.font.family) {
attrs.insert(pango::AttrString::new_family(&name));
}
let w: pango::Weight = unsafe { glib::translate::from_glib(s.font.weight.css() as i32) };
attrs.insert(pango::AttrInt::new_weight(w));
if s.font.italic {
attrs.insert(pango::AttrInt::new_style(pango::Style::Italic));
}
attrs.insert(pango::AttrSize::new_size_absolute(
crate::text::pango_units(s.font.size),
));
for l in [&chip.icon, &chip.label] {
l.set_attributes(Some(&attrs));
}
chip.icon.set_text(icon.unwrap_or(""));
chip.icon.set_visible(icon.is_some());
chip.label.set_text(label);
chip.label.set_visible(!label.is_empty());
let em = s.font.size.max(1.);
let gap = if icon.is_some() && !label.is_empty() {
(em * 0.25).round()
} else {
0.
};
chip.widget.set_spacing(gap as i32);
let probe = if label.is_empty() {
&chip.icon
} else {
&chip.label
};
let (_, height, _, baseline) = probe.measure(gtk::Orientation::Vertical, -1);
let descent = if baseline >= 0 { height - baseline } else { 0 };
let mut css = format!("box{{margin-bottom:-{descent}px;");
if boxed {
let bg = s.background.map_or_else(
|| "alpha(#8e8e93,0.18)".to_string(),
|c| crate::decor::color(c, dark),
);
css += &format!(
"padding:0 {}px;border-radius:4px;background-color:{bg};",
(em * 0.35).round()
);
}
if let Some(c) = s.color.filter(|_| s.color != style.text_color) {
css += &format!("color:{};", crate::decor::color(c, dark));
}
css.push('}');
#[allow(deprecated)]
chip.css.load_from_data(&css);
chip.link.set(run.link);
chip.widget
.set_cursor_from_name(run.link.map(|_| "pointer"));
}
pub(crate) fn labelled(id: NodeId, b: >k::TextBuffer, start: i32, end: i32) -> String {
RICH.with(|r| {
let r = r.borrow();
let chips = r.get(&id).map(|r| &r.chips[..]).unwrap_or_default();
let mut out = String::new();
let mut it = b.iter_at_offset(start);
while it.offset() < end && !it.is_end() {
match it.child_anchor() {
Some(a) => {
if let Some(c) = chips.iter().find(|c| c.anchor == a) {
out += &c.copied;
}
}
None if it.char() == OBJECT_CHAR => {}
None => out.push(it.char()),
}
it.forward_char();
}
out
})
}
pub(crate) fn attributes(id: NodeId) -> Option<pango::AttrList> {
RICH.with(|r| {
let r = r.borrow();
let rich = r.get(&id)?;
let style = rich.style.clone()?;
let style = Style {
text_transform: TextTransform::None,
..style
};
let runs = decode_runs(&rich.runs);
let text: String = runs.iter().map(|r| r.text.as_str()).collect();
let b = rich.view.buffer();
if slice(&b) != text {
return None;
}
let styled = StyledText::from_runs(&text, &runs, &style);
let attrs = pango::AttrList::new();
for s in &styled.runs {
let (start, end) = (s.byte_start as u32, (s.byte_start + s.text.len()) as u32);
let add = |mut a: pango::Attribute| {
a.set_start_index(start);
a.set_end_index(end);
attrs.insert(a);
};
let char_at = text[..s.byte_start].chars().count() as i32;
let anchor = b.iter_at_offset(char_at).child_anchor();
if let Some(chip) = anchor.and_then(|a| rich.chips.iter().find(|c| c.anchor == a)) {
let (w, _, _, _) = chip.widget.measure(gtk::Orientation::Horizontal, -1);
let (h, _, _, _) = chip.widget.measure(gtk::Orientation::Vertical, w);
let rect =
pango::Rectangle::new(0, -h * pango::SCALE, w * pango::SCALE, h * pango::SCALE);
add(pango::AttrShape::new(&rect, &rect).upcast());
continue;
}
if let Some(name) = crate::text::family_name(&s.font.family) {
add(pango::AttrString::new_family(&name).upcast());
}
if s.font.size != style.font_size && style.font_size > 0. {
add(pango::AttrFloat::new_scale((s.font.size / style.font_size) as f64).upcast());
}
if s.font.weight != style.font_weight {
let w: pango::Weight =
unsafe { glib::translate::from_glib(s.font.weight.css() as i32) };
add(pango::AttrInt::new_weight(w).upcast());
}
}
Some(attrs)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_chip_shows_its_symbol_and_label_and_copies_its_label() {
let runs = decode_runs(&prism_core::encode_runs(&[
TextRun {
text: "See ".into(),
..TextRun::default()
},
TextRun {
text: OBJECT_CHAR.to_string(),
chip: Some("page:1".into()),
chip_label: Some("Roadmap".into()),
chip_icon: Some("doc.text".into()),
link: Some(7),
..TextRun::default()
},
TextRun {
text: OBJECT_CHAR.to_string(),
icon: Some("star.fill".into()),
..TextRun::default()
},
]));
let (icon, label, boxed) = parts(&runs[1]);
assert!(boxed);
assert_eq!(label, "Roadmap");
assert_eq!(icon, Some(prism_core::glyphs::glyph("doc.text")));
assert_eq!(copied(&runs[1]), "Roadmap");
assert_eq!(runs[1].link, Some(7));
let (icon, label, boxed) = parts(&runs[2]);
assert!(!boxed);
assert_eq!(icon, None);
assert_eq!(label, prism_core::glyphs::glyph("star.fill"));
assert_eq!(copied(&runs[2]), "");
let text: String = runs.iter().map(|r| r.text.as_str()).collect();
assert_eq!(text.chars().count(), 6);
}
}