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
mod ansi;
pub mod error;
mod gutter;
mod icon;
mod syntax;
mod tag;
pub use error::Error;
use gutter::Gutter;
use icon::Icon;
use syntax::Syntax;
use tag::Tag;
use super::{ItemAction, WindowAction};
use crate::app::browser::window::action::Position;
use ggemtext::line::{
code::{Inline, Multiline},
header::{Header, Level},
link::Link,
list::List,
quote::Quote,
};
use gtk::{
gdk::{BUTTON_MIDDLE, BUTTON_PRIMARY, RGBA},
gio::Cancellable,
glib::{TimeZone, Uri},
prelude::{TextBufferExt, TextBufferExtManual, TextTagExt, TextViewExt, WidgetExt},
EventControllerMotion, GestureClick, TextBuffer, TextTag, TextView, TextWindowType,
UriLauncher, Window, WrapMode,
};
use std::{cell::Cell, collections::HashMap, rc::Rc};
pub const DATE_FORMAT: &str = "%Y-%m-%d";
pub const EXTERNAL_LINK_INDICATOR: &str = "⇖";
pub const LIST_ITEM: &str = "•";
pub const NEW_LINE: &str = "\n";
pub struct Gemini {
pub title: Option<String>,
pub text_view: TextView,
}
impl Gemini {
// Constructors
/// Build new `Self`
pub fn build(
(window_action, item_action): (&Rc<WindowAction>, &Rc<ItemAction>),
base: &Uri,
gemtext: &str,
) -> Result<Self, Error> {
// Init default values
let mut title = None;
// Init HashMap storage (for event controllers)
let mut links: HashMap<TextTag, 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 multiline code builder features
let mut multiline = None;
// Init quote icon feature
let mut is_line_after_quote = false;
// 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 syntect highlight features
let syntax = Syntax::new();
// Init icons
let icon = Icon::new();
// Init tags
let tag = Tag::new();
// Init new text buffer
let buffer = TextBuffer::new(Some(&tag.text_tag_table));
// 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);
// Parse gemtext lines
for line in gemtext.lines() {
// Is inline code
if let Some(code) = Inline::from(line) {
// Try auto-detect code syntax for given `value` @TODO optional
match syntax.highlight(&code.value, None) {
Ok(highlight) => {
for (syntax_tag, entity) in highlight {
// Register new tag
if !tag.text_tag_table.add(&syntax_tag) {
todo!()
}
// Append tag to buffer
buffer.insert_with_tags(
&mut buffer.end_iter(),
&entity,
&[&syntax_tag],
);
}
}
Err(_) => {
// Try ANSI/SGR format (terminal emulation) @TODO optional
for (ansi_tag, entity) in ansi::format(&code.value) {
// Register new tag
if !tag.text_tag_table.add(&ansi_tag) {
todo!()
}
// Append tag to buffer
buffer.insert_with_tags(&mut buffer.end_iter(), &entity, &[&ansi_tag]);
}
} // @TODO handle
}
// Append new line
buffer.insert(&mut buffer.end_iter(), NEW_LINE);
// Skip other actions for this line
continue;
}
// Is multiline code
match multiline {
None => {
// Open tag found
if let Some(code) = Multiline::begin_from(line) {
// Begin next lines collection into the code buffer
multiline = Some(code);
// Skip other actions for this line
continue;
}
}
Some(ref mut this) => {
match Multiline::continue_from(this, line) {
Ok(()) => {
// Close tag found:
if this.completed {
// Is alt provided
let alt = match this.alt {
Some(ref alt) => {
// Insert alt value to the main buffer
buffer.insert_with_tags(
&mut buffer.end_iter(),
alt.as_str(),
&[&tag.title],
);
// Append new line after alt text
buffer.insert(&mut buffer.end_iter(), NEW_LINE);
// Return value as wanted also for syntax highlight detection
Some(alt)
}
None => None,
};
// Begin code block construction
// Try auto-detect code syntax for given `value` and `alt` @TODO optional
match syntax.highlight(&this.value, alt) {
Ok(highlight) => {
for (syntax_tag, entity) in highlight {
// Register new tag
if !tag.text_tag_table.add(&syntax_tag) {
todo!()
}
// Append tag to buffer
buffer.insert_with_tags(
&mut buffer.end_iter(),
&entity,
&[&syntax_tag],
);
}
}
Err(_) => {
// Try ANSI/SGR format (terminal emulation) @TODO optional
for (syntax_tag, entity) in ansi::format(&this.value) {
// Register new tag
if !tag.text_tag_table.add(&syntax_tag) {
todo!()
}
// Append tag to buffer
buffer.insert_with_tags(
&mut buffer.end_iter(),
&entity,
&[&syntax_tag],
);
}
} // @TODO handle
}
// Reset
multiline = None;
}
// Skip other actions for this line
continue;
}
Err(e) => return Err(Error::Gemtext(e.to_string())),
}
}
};
// Is header
if let Some(header) = Header::from(line) {
// Append value to buffer
buffer.insert_with_tags(
&mut buffer.end_iter(),
&header.value,
&[match header.level {
Level::H1 => &tag.h1,
Level::H2 => &tag.h2,
Level::H3 => &tag.h3,
}],
);
buffer.insert(&mut buffer.end_iter(), NEW_LINE);
// Update reader title using first gemtext header match
if title.is_none() {
title = Some(header.value.clone());
}
// Skip other actions for this line
continue;
}
// Is link
if let Some(link) = Link::from(line, Some(base), Some(&TimeZone::local())) {
// Create vector for alt values
let mut alt = Vec::new();
// Append external indicator on exist
if let Some(is_external) = link.is_external {
if is_external {
alt.push(EXTERNAL_LINK_INDICATOR.to_string());
}
}
// Append date on exist
if let Some(timestamp) = link.timestamp {
// https://docs.gtk.org/glib/method.DateTime.format.html
if let Ok(value) = timestamp.format(DATE_FORMAT) {
alt.push(value.to_string())
}
}
// Append alt value on exist or use URL
alt.push(match link.alt {
Some(alt) => alt.to_string(),
None => link.uri.to_string(),
});
// Create new tag for new link
let a = TextTag::builder()
.foreground_rgba(&link_color.0)
// .foreground_rgba(&adw::StyleManager::default().accent_color_rgba()) @TODO adw 1.6 / ubuntu 24.10+
.sentence(true)
.wrap_mode(WrapMode::Word)
.build();
// Register new tag
if !tag.text_tag_table.add(&a) {
todo!()
}
// Append alt vector values to buffer
buffer.insert_with_tags(&mut buffer.end_iter(), &alt.join(" "), &[&a]);
buffer.insert(&mut buffer.end_iter(), NEW_LINE);
// Append tag to HashMap storage
links.insert(a, link.uri.clone());
// Skip other actions for this line
continue;
}
// Is list
if let Some(list) = List::from(line) {
// Append value to buffer
buffer.insert_with_tags(
&mut buffer.end_iter(),
format!("{LIST_ITEM} {}", list.value).as_str(),
&[&tag.list],
);
buffer.insert(&mut buffer.end_iter(), NEW_LINE);
// Skip other actions for this line
continue;
}
// Is quote
if let Some(quote) = Quote::from(line) {
// Show quote indicator if last line is not quote (to prevent duplicates)
if !is_line_after_quote {
// Show only if the icons resolved for default `Display`
if let Some(ref icon) = icon {
buffer.insert_paintable(&mut buffer.end_iter(), &icon.quote);
buffer.insert(&mut buffer.end_iter(), NEW_LINE);
}
}
is_line_after_quote = true;
// Append value to buffer
buffer.insert_with_tags(&mut buffer.end_iter(), "e.value, &[&tag.quote]);
buffer.insert(&mut buffer.end_iter(), NEW_LINE);
// Skip other actions for this line
continue;
} else {
is_line_after_quote = false;
}
// Nothing match custom tags above,
// just append plain text covered in empty tag (to handle controller events properly)
buffer.insert_with_tags(&mut buffer.end_iter(), line, &[&tag.plain]);
buffer.insert(&mut buffer.end_iter(), NEW_LINE);
}
// Init additional controllers
let primary_button_controller = GestureClick::builder().button(BUTTON_PRIMARY).build();
let middle_button_controller = GestureClick::builder().button(BUTTON_MIDDLE).build();
let motion_controller = EventControllerMotion::new();
text_view.add_controller(primary_button_controller.clone());
text_view.add_controller(middle_button_controller.clone());
text_view.add_controller(motion_controller.clone());
// Init shared reference container for HashTable collected
let links = Rc::new(links);
// Init events
primary_button_controller.connect_released({
let item_action = item_action.clone();
let links = links.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) {
// Select link handler by scheme
return match uri.scheme().as_str() {
"gemini" | "titan" => {
// Open new page in browser
item_action.load.activate(Some(&uri.to_str()), true);
}
// Scheme not supported, delegate
_ => UriLauncher::new(&uri.to_str()).launch(
Window::NONE,
Cancellable::NONE,
|result| {
if let Err(e) = result {
println!("{e}")
}
},
),
}; // @TODO common handler?
}
}
}
}
});
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) {
// Select link handler by scheme
return match uri.scheme().as_str() {
"gemini" | "titan" => {
// Open new page in browser
window_action.append.activate_stateful_once(
Position::After,
Some(uri.to_string()),
false,
false,
true,
true,
);
}
// Scheme not supported, delegate
_ => UriLauncher::new(&uri.to_str()).launch(
Window::NONE,
Cancellable::NONE,
|result| {
if let Err(e) = result {
println!("{e}")
}
},
),
}; // @TODO common handler?
}
}
}
}
}); // 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?
// Result
Ok(Self { text_view, title })
}
}