Yoda 0.12.9

Browser for Gemini Protocol
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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
mod gutter;
mod tags;

use super::{ItemAction, WindowAction};
use crate::app::browser::window::{action::Position, tab::item::page::Page};
use gtk::{
    EventControllerMotion, GestureClick, PopoverMenu, TextBuffer, TextTag, TextTagTable, TextView,
    TextWindowType, UriLauncher, Window, WrapMode,
    gdk::{BUTTON_MIDDLE, BUTTON_PRIMARY, BUTTON_SECONDARY, Display, RGBA},
    gio::{Cancellable, Menu, SimpleAction, SimpleActionGroup},
    glib::{ControlFlow, GString, Uri, idle_add_local, uuid_string_random},
    prelude::{EditableExt, PopoverExt, TextBufferExt, TextTagExt, TextViewExt, WidgetExt},
};
use gutter::Gutter;
use regex::Regex;
use sourceview::prelude::{ActionExt, ActionMapExt, DisplayExt, ToVariant};
use std::{cell::Cell, collections::HashMap, rc::Rc};
use strip_tags::*;
use tags::Tags;

pub struct Markdown {
    pub title: Option<String>,
    pub text_view: TextView,
}

impl Markdown {
    // Constructors

    /// Build new `Self`
    pub fn build(
        (window_action, item_action): (&Rc<WindowAction>, &Rc<ItemAction>),
        page: &Rc<Page>,
        base: &Uri,
        markdown: &str,
    ) -> Self {
        // Init HashMap storage (for event controllers)
        let mut links: HashMap<TextTag, Uri> = HashMap::new();
        let mut headers: HashMap<TextTag, (String, Uri)> = HashMap::new();

        // Init hovered tag storage for `links`
        // * maybe less expensive than update entire HashMap by iter
        let hover: Rc<Cell<Option<TextTag>>> = Rc::new(Cell::new(None));

        // Init colors
        // @TODO use accent colors in adw 1.6 / ubuntu 24.10+
        let link_color = (
            RGBA::new(0.208, 0.518, 0.894, 1.0),
            RGBA::new(0.208, 0.518, 0.894, 0.9),
        );

        // Init tags
        let mut tags = Tags::new();

        // Init new text buffer
        let buffer = TextBuffer::new(Some(&TextTagTable::new()));
        buffer.set_text(
            Regex::new(r"\n{3,}")
                .unwrap()
                .replace_all(&strip_tags(markdown), "\n\n")
                .trim(),
        ); // @TODO extract `<img>` tags?

        // Init main widget
        let text_view = {
            const MARGIN: i32 = 8;
            TextView::builder()
                .bottom_margin(MARGIN)
                .buffer(&buffer)
                .cursor_visible(false)
                .editable(false)
                .left_margin(MARGIN)
                .right_margin(MARGIN)
                .top_margin(MARGIN)
                .vexpand(true)
                .wrap_mode(WrapMode::Word)
                .build()
        };

        // Init gutter widget (the tooltip on URL tags hover)
        let gutter = Gutter::build(&text_view);

        // Render markdown tags
        let title = tags.render(&text_view, base, &link_color.0, &mut links, &mut headers);

        // Headers context menu (fragment capture)
        let action_header_copy_url =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_header_copy_url.connect_activate(|this, _| {
            Display::default()
                .unwrap()
                .clipboard()
                .set_text(&this.state().unwrap().get::<String>().unwrap())
        });
        let action_header_copy_text =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_header_copy_text.connect_activate(|this, _| {
            Display::default()
                .unwrap()
                .clipboard()
                .set_text(&this.state().unwrap().get::<String>().unwrap())
        });
        let action_header_copy_text_selected =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_header_copy_text_selected.connect_activate(|this, _| {
            Display::default()
                .unwrap()
                .clipboard()
                .set_text(&this.state().unwrap().get::<String>().unwrap())
        });
        let header_context_group_id = uuid_string_random();
        text_view.insert_action_group(
            &header_context_group_id,
            Some(&{
                let g = SimpleActionGroup::new();
                g.add_action(&action_header_copy_url);
                g.add_action(&action_header_copy_text);
                g.add_action(&action_header_copy_text_selected);
                g
            }),
        );
        let header_context = PopoverMenu::from_model(Some(&{
            let m = Menu::new();
            m.append(
                Some("Copy Header Link"),
                Some(&format!(
                    "{header_context_group_id}.{}",
                    action_header_copy_url.name()
                )),
            );
            m.append(
                Some("Copy Header Text"),
                Some(&format!(
                    "{header_context_group_id}.{}",
                    action_header_copy_text.name()
                )),
            );
            m.append(
                Some("Copy Text Selected"),
                Some(&format!(
                    "{header_context_group_id}.{}",
                    action_header_copy_text_selected.name()
                )),
            );
            m
        }));
        header_context.set_parent(&text_view);

        // Link context menu
        let action_link_tab =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_link_tab.connect_activate({
            let window_action = window_action.clone();
            move |this, _| {
                open_link_in_new_tab(
                    &this.state().unwrap().get::<String>().unwrap(),
                    &window_action,
                )
            }
        });
        let action_link_copy_url =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_link_copy_url.connect_activate(|this, _| {
            Display::default()
                .unwrap()
                .clipboard()
                .set_text(&this.state().unwrap().get::<String>().unwrap())
        });
        let action_link_copy_text =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_link_copy_text.connect_activate(|this, _| {
            Display::default()
                .unwrap()
                .clipboard()
                .set_text(&this.state().unwrap().get::<String>().unwrap())
        });
        let action_link_copy_text_selected =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_link_copy_text_selected.connect_activate(|this, _| {
            Display::default()
                .unwrap()
                .clipboard()
                .set_text(&this.state().unwrap().get::<String>().unwrap())
        });
        let action_link_bookmark =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_link_bookmark.connect_activate({
            let p = page.profile.clone();
            move |this, _| {
                let state = this.state().unwrap().get::<String>().unwrap();
                p.bookmark.toggle(&state, None).unwrap();
            }
        });
        let action_link_download =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_link_download.connect_activate({
            let window_action = window_action.clone();
            move |this, _| {
                open_link_in_new_tab(
                    &link_prefix(
                        this.state().unwrap().get::<String>().unwrap(),
                        LINK_PREFIX_DOWNLOAD,
                    ),
                    &window_action,
                )
            }
        });
        let action_link_source =
            SimpleAction::new_stateful(&uuid_string_random(), None, &String::new().to_variant());
        action_link_source.connect_activate({
            let window_action = window_action.clone();
            move |this, _| {
                open_link_in_new_tab(
                    &link_prefix(
                        this.state().unwrap().get::<String>().unwrap(),
                        LINK_PREFIX_SOURCE,
                    ),
                    &window_action,
                )
            }
        });
        let link_context_group_id = uuid_string_random();
        text_view.insert_action_group(
            &link_context_group_id,
            Some(&{
                let g = SimpleActionGroup::new();
                g.add_action(&action_link_tab);
                g.add_action(&action_link_copy_url);
                g.add_action(&action_link_copy_text);
                g.add_action(&action_link_copy_text_selected);
                g.add_action(&action_link_bookmark);
                g.add_action(&action_link_download);
                g.add_action(&action_link_source);
                g
            }),
        );
        let link_context = PopoverMenu::from_model(Some(&{
            let m = Menu::new();
            m.append(
                Some("Open Link in New Tab"),
                Some(&format!(
                    "{link_context_group_id}.{}",
                    action_link_tab.name()
                )),
            );
            m.append_section(None, &{
                let m_copy = Menu::new();
                m_copy.append(
                    Some("Copy Link URL"),
                    Some(&format!(
                        "{link_context_group_id}.{}",
                        action_link_copy_url.name()
                    )),
                );
                m_copy.append(
                    Some("Copy Link Text"),
                    Some(&format!(
                        "{link_context_group_id}.{}",
                        action_link_copy_text.name()
                    )),
                );
                m_copy.append(
                    Some("Copy Text Selected"),
                    Some(&format!(
                        "{link_context_group_id}.{}",
                        action_link_copy_text_selected.name()
                    )),
                );
                m_copy
            });
            m.append_section(None, &{
                let m_other = Menu::new();
                m_other.append(
                    Some("Bookmark Link"), // @TODO highlight state
                    Some(&format!(
                        "{link_context_group_id}.{}",
                        action_link_bookmark.name()
                    )),
                );
                m_other.append(
                    Some("Download Link"),
                    Some(&format!(
                        "{link_context_group_id}.{}",
                        action_link_download.name()
                    )),
                );
                m_other.append(
                    Some("View Link as Source"),
                    Some(&format!(
                        "{link_context_group_id}.{}",
                        action_link_source.name()
                    )),
                );
                m_other
            });
            m
        }));
        link_context.set_parent(&text_view);

        // Init additional controllers
        let middle_button_controller = GestureClick::builder().button(BUTTON_MIDDLE).build();
        let primary_button_controller = GestureClick::builder().button(BUTTON_PRIMARY).build();
        let secondary_button_controller = GestureClick::builder()
            .button(BUTTON_SECONDARY)
            .propagation_phase(gtk::PropagationPhase::Capture)
            .build();
        let motion_controller = EventControllerMotion::new();

        text_view.add_controller(middle_button_controller.clone());
        text_view.add_controller(motion_controller.clone());
        text_view.add_controller(primary_button_controller.clone());
        text_view.add_controller(secondary_button_controller.clone());

        // Init shared reference container for HashTable collected
        let links = Rc::new(links);
        let headers = Rc::new(headers);

        // Init events
        primary_button_controller.connect_released({
            let headers = headers.clone();
            let item_action = item_action.clone();
            let links = links.clone();
            let page = page.clone();
            let text_view = text_view.clone();
            move |_, _, window_x, window_y| {
                // Detect tag match current coords hovered
                let (buffer_x, buffer_y) = text_view.window_to_buffer_coords(
                    TextWindowType::Widget,
                    window_x as i32,
                    window_y as i32,
                );
                if let Some(iter) = text_view.iter_at_location(buffer_x, buffer_y) {
                    for tag in iter.tags() {
                        // Tag is link
                        if let Some(uri) = links.get(&tag) {
                            return if let Some(fragment) = uri.fragment() {
                                scroll_to_anchor(&page, &text_view, &headers, fragment);
                            } else {
                                open_link_in_current_tab(&uri.to_string(), &item_action);
                            };
                        }
                    }
                }
            }
        });

        secondary_button_controller.connect_pressed({
            let headers = headers.clone();
            let link_context = link_context.clone();
            let links = links.clone();
            let text_view = text_view.clone();
            move |_, _, window_x, window_y| {
                let x = window_x as i32;
                let y = window_y as i32;
                // Detect tag match current coords hovered
                let (buffer_x, buffer_y) =
                    text_view.window_to_buffer_coords(TextWindowType::Widget, x, y);
                if let Some(iter) = text_view.iter_at_location(buffer_x, buffer_y) {
                    for tag in iter.tags() {
                        // Tag is link
                        if let Some(uri) = links.get(&tag) {
                            let request_str = uri.to_str();
                            let request_var = request_str.to_variant();
                            let is_prefix_link = is_prefix_link(&request_str);

                            // Open in the new tab
                            action_link_tab.set_state(&request_var);
                            action_link_tab.set_enabled(!request_str.is_empty());

                            // Copy link to the clipboard
                            action_link_copy_url.set_state(&request_var);
                            action_link_copy_url.set_enabled(!request_str.is_empty());

                            // Copy link text
                            {
                                let mut start_iter = iter;
                                let mut end_iter = iter;
                                if !start_iter.starts_tag(Some(&tag)) {
                                    start_iter.backward_to_tag_toggle(Some(&tag));
                                }
                                if !end_iter.ends_tag(Some(&tag)) {
                                    end_iter.forward_to_tag_toggle(Some(&tag));
                                }
                                let tagged_text = text_view
                                    .buffer()
                                    .text(&start_iter, &end_iter, false)
                                    .replace(LINK_EXTERNAL_INDICATOR, "")
                                    .trim()
                                    .to_string();

                                action_link_copy_text.set_state(&tagged_text.to_variant());
                                action_link_copy_text.set_enabled(!tagged_text.is_empty());
                            }

                            // Copy link text (if) selected
                            action_link_copy_text_selected.set_enabled(
                                if let Some((start, end)) = buffer.selection_bounds() {
                                    let selected = buffer.text(&start, &end, false);
                                    action_link_copy_text_selected
                                        .set_state(&selected.to_variant());
                                    !selected.is_empty()
                                } else {
                                    false
                                },
                            );

                            // Bookmark
                            action_link_bookmark.set_state(&request_var);
                            action_link_bookmark.set_enabled(is_prefix_link);

                            // Download (new tab)
                            action_link_download.set_state(&request_var);
                            action_link_download.set_enabled(is_prefix_link);

                            // View as Source (new tab)
                            action_link_source.set_state(&request_var);
                            action_link_source.set_enabled(is_prefix_link);

                            // Toggle
                            link_context
                                .set_pointing_to(Some(&gtk::gdk::Rectangle::new(x, y, 1, 1)));
                            link_context.popup()
                        }
                        // Tag is header
                        if let Some((title, uri)) = headers.get(&tag) {
                            let request_str = uri.to_str();
                            let request_var = request_str.to_variant();

                            // Copy link to the clipboard
                            action_header_copy_url.set_state(&request_var);
                            action_header_copy_url.set_enabled(!request_str.is_empty());

                            // Copy header text
                            action_header_copy_text.set_state(&title.to_variant());
                            action_header_copy_text.set_enabled(!title.is_empty());

                            // Copy header text (if) selected
                            action_header_copy_text_selected.set_enabled(
                                if let Some((start, end)) = buffer.selection_bounds() {
                                    let selected = buffer.text(&start, &end, false);
                                    action_header_copy_text_selected
                                        .set_state(&selected.to_variant());
                                    !selected.is_empty()
                                } else {
                                    false
                                },
                            );

                            // Toggle
                            header_context
                                .set_pointing_to(Some(&gtk::gdk::Rectangle::new(x, y, 1, 1)));
                            header_context.popup()
                        }
                    }
                }
            }
        });

        middle_button_controller.connect_pressed({
            let links = links.clone();
            let text_view = text_view.clone();
            let window_action = window_action.clone();
            move |_, _, window_x, window_y| {
                // Detect tag match current coords hovered
                let (buffer_x, buffer_y) = text_view.window_to_buffer_coords(
                    TextWindowType::Widget,
                    window_x as i32,
                    window_y as i32,
                );
                if let Some(iter) = text_view.iter_at_location(buffer_x, buffer_y) {
                    for tag in iter.tags() {
                        // Tag is link
                        if let Some(uri) = links.get(&tag) {
                            return open_link_in_new_tab(&uri.to_string(), &window_action);
                        }
                    }
                }
            }
        }); // for a note: this action sensitive to focus out

        motion_controller.connect_motion({
            let text_view = text_view.clone();
            let links = links.clone();
            let hover = hover.clone();
            move |_, window_x, window_y| {
                // Detect tag match current coords hovered
                let (buffer_x, buffer_y) = text_view.window_to_buffer_coords(
                    TextWindowType::Widget,
                    window_x as i32,
                    window_y as i32,
                );
                // Reset link colors to default
                if let Some(tag) = hover.replace(None) {
                    tag.set_foreground_rgba(Some(&link_color.0));
                }
                // Apply hover effect
                if let Some(iter) = text_view.iter_at_location(buffer_x, buffer_y) {
                    for tag in iter.tags() {
                        // Tag is link
                        if let Some(uri) = links.get(&tag) {
                            // Toggle color
                            tag.set_foreground_rgba(Some(&link_color.1));
                            // Keep hovered tag in memory
                            hover.replace(Some(tag.clone()));
                            // Show tooltip
                            gutter.set_uri(Some(uri));
                            // Toggle cursor
                            text_view.set_cursor_from_name(Some("pointer"));
                            // Redraw required to apply changes immediately
                            text_view.queue_draw();
                            return;
                        }
                    }
                }
                // Restore defaults
                gutter.set_uri(None);
                text_view.set_cursor_from_name(Some("text"));
                text_view.queue_draw();
            }
        }); // @TODO may be expensive for CPU, add timeout?

        // Anchor auto-scroll behavior
        idle_add_local({
            let base = base.clone();
            let page = page.clone();
            let text_view = text_view.clone();
            move || {
                if let Some(fragment) = base.fragment() {
                    scroll_to_anchor(&page, &text_view, &headers, fragment);
                }
                ControlFlow::Break
            }
        });

        Self { text_view, title }
    }
}

fn scroll_to_anchor(
    page: &Rc<Page>,
    text_view: &TextView,
    headers: &HashMap<TextTag, (String, Uri)>,
    fragment: GString,
) {
    if let Some((tag, (_, uri))) = headers.iter().find(|(_, (_, uri))| {
        uri.fragment()
            .is_some_and(|f| fragment == tags::format_header_fragment(&f))
    }) {
        let mut iter = text_view.buffer().start_iter();
        if iter.starts_tag(Some(tag)) || iter.forward_to_tag_toggle(Some(tag)) {
            text_view.scroll_to_iter(&mut iter, 0.0, true, 0.0, 0.0);
        }
        page.navigation.request.entry.set_text(&uri.to_string())
    }
}

fn is_internal_link(request: &str) -> bool {
    // schemes
    request.starts_with("gemini://")
        || request.starts_with("titan://")
        || request.starts_with("nex://")
        || request.starts_with("file://")
        // prefix
        || request.starts_with("download:")
        || request.starts_with("source:")
}

fn is_prefix_link(request: &str) -> bool {
    request.starts_with("gemini://")
        || request.starts_with("nex://")
        || request.starts_with("file://")
}

fn open_link_in_external_app(request: &str) {
    UriLauncher::new(request).launch(Window::NONE, Cancellable::NONE, |r| {
        if let Err(e) = r {
            println!("{e}") // @TODO use warn macro
        }
    })
}

fn open_link_in_current_tab(request: &str, item_action: &ItemAction) {
    if is_internal_link(request) {
        item_action.load.activate(Some(request), true, false)
    } else {
        open_link_in_external_app(request)
    }
}

fn open_link_in_new_tab(request: &str, window_action: &WindowAction) {
    if is_internal_link(request) {
        window_action.append.activate_stateful_once(
            Position::After,
            Some(request.into()),
            false,
            false,
            true,
            true,
        );
    } else {
        open_link_in_external_app(request)
    }
}

fn link_prefix(request: String, prefix: &str) -> String {
    format!("{prefix}{}", request.trim_start_matches(prefix))
}

const LINK_EXTERNAL_INDICATOR: &str = "";
const LINK_PREFIX_DOWNLOAD: &str = "download:";
const LINK_PREFIX_SOURCE: &str = "source:";