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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! Build HTML messages.

use gettextrs::gettext;
use gtk::{pango, prelude::*};
use ruma::html::{
    matrix::{MatrixElement, OrderedListData},
    Children, NodeRef,
};
use sourceview::prelude::*;
use tracing::debug;

use super::{inline_html::InlineHtmlBuilder, SUPPORTED_BLOCK_ELEMENTS};
use crate::{
    components::{AtRoom, LabelWithWidgets},
    prelude::*,
    session::model::Room,
};

/// The immutable config fields to build a HTML widget tree.
#[derive(Debug, Clone, Copy)]
pub(super) struct HtmlWidgetConfig<'a> {
    pub(super) room: &'a Room,
    pub(super) detect_at_room: bool,
    pub(super) ellipsize: bool,
}

/// Construct a new label for displaying a message's content.
pub(super) fn new_message_label() -> gtk::Label {
    gtk::Label::builder()
        .wrap(true)
        .wrap_mode(pango::WrapMode::WordChar)
        .xalign(0.0)
        .valign(gtk::Align::Start)
        .use_markup(true)
        .build()
}

/// Create a widget for the given HTML nodes in the given room.
///
/// If `detect_at_room` is `true`, we will try to detect `@room` in the text.
///
/// If `ellipsize` is true, we will only render the first block.
///
/// If the sender name is set, it will be added as soon as possible.
///
/// Returns `None` if the widget would have been empty.
pub(super) fn widget_for_html_nodes<'a>(
    nodes: impl IntoIterator<Item = NodeRef<'a>>,
    config: HtmlWidgetConfig<'a>,
    add_ellipsis: bool,
    sender_name: &mut Option<&str>,
) -> Option<gtk::Widget> {
    let nodes = nodes.into_iter().collect::<Vec<_>>();

    if nodes.is_empty() {
        return None;
    }

    let groups = group_inline_nodes(nodes);
    let len = groups.len();

    let mut children = Vec::new();
    for (i, group) in groups.into_iter().enumerate() {
        let is_last = i == (len - 1);
        let add_ellipsis = add_ellipsis || (config.ellipsize && !is_last);

        match group {
            NodeGroup::Inline(inline_nodes) => {
                if let Some(widget) =
                    label_for_inline_html(inline_nodes, config, add_ellipsis, sender_name)
                {
                    children.push(widget);
                }
            }
            NodeGroup::Block(block_node) => {
                let Some(widget) =
                    widget_for_html_block(block_node, config, add_ellipsis, sender_name)
                else {
                    continue;
                };

                // Include sender name before, if the child widget did not handle it.
                if let Some(sender_name) = sender_name.take() {
                    let label = new_message_label();
                    let (text, _) = InlineHtmlBuilder::new(false, false)
                        .append_emote_with_name(&mut Some(sender_name))
                        .build();
                    label.set_label(&text);

                    children.push(label.upcast());
                }

                children.push(widget);
            }
        }

        if config.ellipsize {
            // Stop at the first constructed child.
            break;
        }
    }

    if children.is_empty() {
        return None;
    }
    if children.len() == 1 {
        return children.into_iter().next();
    }

    let grid = gtk::Grid::builder()
        .row_spacing(6)
        .accessible_role(gtk::AccessibleRole::Group)
        .build();

    for (row, child) in children.into_iter().enumerate() {
        grid.attach(&child, 0, row as i32, 1, 1);
    }

    Some(grid.upcast())
}

/// A group of nodes, representing the nodes contained in a single widget.
enum NodeGroup<'a> {
    /// A group of inline nodes.
    Inline(Vec<NodeRef<'a>>),
    /// A block node.
    Block(NodeRef<'a>),
}

/// Group subsequent nodes that are inline.
///
/// Allows to group nodes by widget that will need to be constructed.
fn group_inline_nodes(nodes: Vec<NodeRef<'_>>) -> Vec<NodeGroup<'_>> {
    let mut result = Vec::new();
    let mut inline_group = None;

    for node in nodes {
        let is_block = node
            .as_element()
            .is_some_and(|element| SUPPORTED_BLOCK_ELEMENTS.contains(&element.name.local.as_ref()));

        if is_block {
            if let Some(inline) = inline_group.take() {
                result.push(NodeGroup::Inline(inline));
            }

            result.push(NodeGroup::Block(node));
        } else {
            let inline = inline_group.get_or_insert_with(Vec::default);
            inline.push(node);
        }
    }

    if let Some(inline) = inline_group.take() {
        result.push(NodeGroup::Inline(inline));
    }

    result
}

/// Construct a `GtkLabel` for the given inline nodes.
///
/// Returns `None` if the label would have been empty.
fn label_for_inline_html<'a>(
    nodes: impl IntoIterator<Item = NodeRef<'a>>,
    config: HtmlWidgetConfig<'a>,
    add_ellipsis: bool,
    sender_name: &mut Option<&str>,
) -> Option<gtk::Widget> {
    let (text, widgets) = InlineHtmlBuilder::new(config.ellipsize, add_ellipsis)
        .detect_mentions(config.room, config.detect_at_room)
        .append_emote_with_name(sender_name)
        .build_with_nodes(nodes);

    if text.is_empty() {
        return None;
    }

    if let Some(widgets) = widgets {
        widgets.iter().for_each(|p| {
            if !p.source().is_some_and(|s| s.is::<AtRoom>()) {
                // Show the profile on click.
                p.set_activatable(true);
            }
        });
        let w = LabelWithWidgets::with_label_and_widgets(&text, widgets);
        w.set_use_markup(true);
        w.set_ellipsize(config.ellipsize);
        Some(w.upcast())
    } else {
        let w = new_message_label();
        w.set_markup(&text);
        w.set_ellipsize(if config.ellipsize {
            pango::EllipsizeMode::End
        } else {
            pango::EllipsizeMode::None
        });
        Some(w.upcast())
    }
}

/// Create a widget for the given HTML block node.
fn widget_for_html_block(
    node: NodeRef<'_>,
    config: HtmlWidgetConfig<'_>,
    add_ellipsis: bool,
    sender_name: &mut Option<&str>,
) -> Option<gtk::Widget> {
    let widget = match node.as_element()?.to_matrix().element {
        MatrixElement::H(heading) => {
            // Heading should only have inline elements as children.
            let w = label_for_inline_html(node.children(), config, add_ellipsis, sender_name)
                .unwrap_or_else(|| {
                    // We should show an empty title.
                    new_message_label().upcast()
                });
            w.add_css_class(&format!("h{}", heading.level.value()));
            w
        }
        MatrixElement::Blockquote => {
            let w = widget_for_html_nodes(node.children(), config, add_ellipsis, &mut None)?;
            w.add_css_class("quote");
            w
        }
        MatrixElement::P | MatrixElement::Div(_) | MatrixElement::Li | MatrixElement::Summary => {
            widget_for_html_nodes(node.children(), config, add_ellipsis, sender_name)?
        }
        MatrixElement::Ul => {
            widget_for_list(ListType::Unordered, node.children(), config, add_ellipsis)?
        }
        MatrixElement::Ol(list) => {
            widget_for_list(list.into(), node.children(), config, add_ellipsis)?
        }
        MatrixElement::Hr => gtk::Separator::new(gtk::Orientation::Horizontal).upcast(),
        MatrixElement::Pre => {
            widget_for_preformatted_text(node.children(), config.ellipsize, add_ellipsis)?
        }
        MatrixElement::Details => widget_for_details(node.children(), config, add_ellipsis)?,
        element => {
            debug!("Unexpected HTML block element: {element:?}");
            return None;
        }
    };

    Some(widget)
}

/// Create a widget for a list.
fn widget_for_list(
    list_type: ListType,
    list_items: Children<'_>,
    config: HtmlWidgetConfig<'_>,
    add_ellipsis: bool,
) -> Option<gtk::Widget> {
    let list_items = list_items
        // Lists are supposed to only have list items as children.
        .filter(|node| {
            node.as_element()
                .is_some_and(|element| element.name.local.as_ref() == "li")
        })
        .collect::<Vec<_>>();

    if list_items.is_empty() {
        return None;
    }

    let grid = gtk::Grid::builder()
        .row_spacing(6)
        .column_spacing(6)
        .margin_end(6)
        .margin_start(6)
        .build();

    let len = list_items.len();

    for (pos, li) in list_items.into_iter().enumerate() {
        let is_last = pos == (len - 1);
        let add_ellipsis = add_ellipsis || (config.ellipsize && !is_last);

        let w = widget_for_html_nodes(li.children(), config, add_ellipsis, &mut None)
            // We should show an empty list item.
            .unwrap_or_else(|| new_message_label().upcast());

        let bullet = list_type.bullet(pos);

        grid.attach(&bullet, 0, pos as i32, 1, 1);
        grid.attach(&w, 1, pos as i32, 1, 1);

        if config.ellipsize {
            break;
        }
    }

    Some(grid.upcast())
}

/// The type of bullet for a list.
#[derive(Debug, Clone, Copy)]
enum ListType {
    /// An unordered list.
    Unordered,
    /// An ordered list.
    Ordered {
        /// The number to start counting from.
        start: i64,
    },
}

impl ListType {
    /// Construct the widget for the bullet of the current type at the given
    /// position.
    fn bullet(&self, position: usize) -> gtk::Label {
        let bullet = gtk::Label::builder().valign(gtk::Align::Baseline).build();

        match self {
            ListType::Unordered => bullet.set_label("•"),
            ListType::Ordered { start } => {
                bullet.set_label(&format!("{}.", *start + position as i64))
            }
        }

        bullet
    }
}

impl From<OrderedListData> for ListType {
    fn from(value: OrderedListData) -> Self {
        Self::Ordered {
            start: value.start.unwrap_or(1),
        }
    }
}

/// Create a widget for preformatted text.
fn widget_for_preformatted_text(
    children: Children<'_>,
    ellipsize: bool,
    add_ellipsis: bool,
) -> Option<gtk::Widget> {
    let children = children.collect::<Vec<_>>();

    if children.is_empty() {
        return None;
    }

    let unique_code_child = (children.len() == 1)
        .then_some(&children[0])
        .and_then(|child| child.as_element())
        .and_then(|element| match element.to_matrix().element {
            MatrixElement::Code(code) => Some(code),
            _ => None,
        });

    let (children, code_language) = if let Some(code) = unique_code_child {
        let children = children[0].children().collect::<Vec<_>>();

        if children.is_empty() {
            return None;
        }

        (children, code.language)
    } else {
        (children, None)
    };

    let text = InlineHtmlBuilder::new(ellipsize, add_ellipsis).build_with_nodes_text(children);

    if ellipsize {
        // Present text as inline code.
        let text = format!("<tt>{}</tt>", text.escape_markup());

        let label = new_message_label();
        label.set_ellipsize(if ellipsize {
            pango::EllipsizeMode::End
        } else {
            pango::EllipsizeMode::None
        });
        label.set_label(&text);

        return Some(label.upcast());
    }

    let buffer = sourceview::Buffer::builder()
        .highlight_matching_brackets(false)
        .text(text)
        .build();
    crate::utils::sourceview::setup_style_scheme(&buffer);

    let language = code_language
        .and_then(|lang| sourceview::LanguageManager::default().language(lang.as_ref()));
    buffer.set_language(language.as_ref());

    let view = sourceview::View::builder()
        .buffer(&buffer)
        .editable(false)
        .css_classes(["codeview", "frame"])
        .hexpand(true)
        .build();

    let scrolled = gtk::ScrolledWindow::new();
    scrolled.set_policy(gtk::PolicyType::Automatic, gtk::PolicyType::Never);
    scrolled.set_child(Some(&view));
    Some(scrolled.upcast())
}

/// Create a widget for a details disclosure element.
fn widget_for_details(
    children: Children<'_>,
    config: HtmlWidgetConfig<'_>,
    add_ellipsis: bool,
) -> Option<gtk::Widget> {
    let (summary, other_children) = children.partition::<Vec<_>, _>(|node| {
        node.as_element()
            .is_some_and(|element| element.name.local.as_ref() == "summary")
    });

    let content = widget_for_html_nodes(other_children, config, add_ellipsis, &mut None);

    let summary = summary
        .into_iter()
        .next()
        .and_then(|node| widget_for_details_summary(node.children(), config, add_ellipsis));

    if let Some(content) = content {
        let summary = summary.unwrap_or_else(|| {
            let label = new_message_label();
            // Translators: this is the fallback title for an expander.
            label.set_label(&gettext("Details"));
            label.upcast()
        });

        let expander = gtk::Expander::builder()
            .label_widget(&summary)
            .child(&content)
            .build();
        Some(expander.upcast())
    } else {
        summary
    }
}

/// Create a widget for a details disclosure element's summary.
fn widget_for_details_summary(
    children: Children<'_>,
    config: HtmlWidgetConfig<'_>,
    add_ellipsis: bool,
) -> Option<gtk::Widget> {
    let children = children.collect::<Vec<_>>();

    if children.is_empty() {
        return None;
    }

    // Only inline elements or a single header element are allowed in summary.
    if children.len() == 1 {
        if let Some(node) = children.first().filter(|node| {
            node.as_element().is_some_and(|element| {
                matches!(
                    element.name.local.as_ref(),
                    "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
                )
            })
        }) {
            if let Some(widget) = widget_for_html_block(*node, config, add_ellipsis, &mut None) {
                return Some(widget);
            }
        }
    }

    label_for_inline_html(children, config, add_ellipsis, &mut None)
}