Yoda 0.6.1

Yoda - 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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
mod content;
mod database;
mod input;
mod meta;
mod navigation;
mod widget;

use content::Content;
use database::Database;
use input::Input;
use navigation::Navigation;
use widget::Widget;

use meta::{Meta, Status};

use gtk::{
    gdk_pixbuf::Pixbuf,
    gio::{
        Cancellable, SimpleAction, SocketClient, SocketClientEvent, SocketProtocol,
        TlsCertificateFlags,
    },
    glib::{
        gformat, uuid_string_random, Bytes, GString, Priority, Regex, RegexCompileFlags,
        RegexMatchFlags, Uri, UriFlags,
    },
    prelude::{
        ActionExt, IOStreamExt, OutputStreamExt, SocketClientExt, StaticVariantType, ToVariant,
    },
    Box,
};
use sqlite::Transaction;
use std::{cell::RefCell, sync::Arc};

pub struct Page {
    id: GString,
    // Actions
    action_page_open: SimpleAction,
    action_tab_page_navigation_reload: SimpleAction,
    action_update: SimpleAction,
    // Components
    navigation: Arc<Navigation>,
    content: Arc<Content>,
    input: Arc<Input>,
    // Extras
    meta: Arc<RefCell<Meta>>,
    // GTK
    widget: Arc<Widget>,
}

impl Page {
    // Construct
    pub fn new_arc(
        id: GString,
        action_tab_open: SimpleAction,
        action_tab_page_navigation_base: SimpleAction,
        action_tab_page_navigation_history_back: SimpleAction,
        action_tab_page_navigation_history_forward: SimpleAction,
        action_tab_page_navigation_reload: SimpleAction,
        action_update: SimpleAction,
    ) -> Arc<Self> {
        // Init local actions
        let action_page_open =
            SimpleAction::new(&uuid_string_random(), Some(&String::static_variant_type()));

        // Init components
        let content = Arc::new(Content::new(
            action_tab_open.clone(),
            action_page_open.clone(),
        ));

        let navigation = Navigation::new_arc(
            action_tab_page_navigation_base.clone(),
            action_tab_page_navigation_history_back.clone(),
            action_tab_page_navigation_history_forward.clone(),
            action_tab_page_navigation_reload.clone(),
            action_update.clone(),
        );

        let input = Input::new_arc();

        let widget = Widget::new_arc(
            &id,
            action_page_open.clone(),
            navigation.gobject(),
            content.gobject(),
            input.gobject(),
        );

        // Init async mutable Meta object
        let meta = Arc::new(RefCell::new(Meta::new()));

        // Init events
        action_page_open.connect_activate({
            let navigation = navigation.clone();
            let action_tab_page_navigation_reload = action_tab_page_navigation_reload.clone();
            move |_, request| {
                // Update request
                navigation.set_request_text(
                    request
                        .expect("Parameter required for `page.open` action")
                        .get::<String>()
                        .expect("Parameter does not match `String`")
                        .as_str(),
                );

                // Reload page
                action_tab_page_navigation_reload.activate(None);
            }
        });

        // Return activated structure
        Arc::new(Self {
            id,
            // Actions
            action_page_open,
            action_tab_page_navigation_reload,
            action_update,
            // Components
            content,
            navigation,
            input,
            // Extras
            meta,
            // GTK
            widget,
        })
    }

    // Actions
    pub fn navigation_request_grab_focus(&self) {
        self.navigation.request_grab_focus();
    }

    pub fn navigation_base(&self) {
        if let Some(url) = self.navigation.base_url() {
            // Update with history record
            self.action_page_open.activate(Some(&url.to_variant()));
        }
    }

    pub fn navigation_history_back(&self) {
        if let Some(request) = self.navigation.history_back(true) {
            // Update
            self.navigation.set_request_text(&request);

            // Reload page
            self.action_tab_page_navigation_reload.activate(None);
        }
    }

    pub fn navigation_history_forward(&self) {
        if let Some(request) = self.navigation.history_forward(true) {
            // Update
            self.navigation.set_request_text(&request);

            // Reload page
            self.action_tab_page_navigation_reload.activate(None);
        }
    }

    pub fn navigation_reload(&self) {
        // Reset widgets
        self.input.unset();

        // Init shared objects to not spawn a lot
        let request_text = self.navigation.request_text();
        let id = self.id.to_variant();

        // Update
        self.meta.borrow_mut().status = Some(Status::Reload);
        self.meta.borrow_mut().title = Some(gformat!("Loading.."));
        self.meta.borrow_mut().description = None;

        self.action_update.activate(Some(&id));

        // Route by request
        match Uri::parse(&request_text, UriFlags::NONE) {
            Ok(uri) => {
                // Route by scheme
                match uri.scheme().as_str() {
                    "file" => todo!(),
                    "gemini" => self.load_gemini(uri), // @TODO
                    scheme => {
                        // Define common data
                        let status = Status::Failure;
                        let title = gformat!("Oops");
                        let description = gformat!("Protocol `{scheme}` not supported");

                        // Update widget
                        self.content
                            .set_status_failure(title.as_str(), description.as_str());

                        // Update meta
                        self.meta.borrow_mut().status = Some(status);
                        self.meta.borrow_mut().title = Some(title);
                        self.meta.borrow_mut().description = Some(description);

                        // Update window
                        self.action_update.activate(Some(&id));
                    }
                }
            }
            Err(_) => {
                // Try interpret URI manually
                if Regex::match_simple(
                    r"^[^\/\s]+\.[\w]{2,}",
                    request_text.clone(),
                    RegexCompileFlags::DEFAULT,
                    RegexMatchFlags::DEFAULT,
                ) {
                    // Seems request contain some host, try append default scheme
                    let request_text = gformat!("gemini://{request_text}");
                    // Make sure new request conversable to valid URI
                    match Uri::parse(&request_text, UriFlags::NONE) {
                        Ok(_) => {
                            // Update
                            self.navigation.set_request_text(&request_text);

                            // Reload page
                            self.action_tab_page_navigation_reload.activate(None);
                        }
                        Err(_) => {
                            // @TODO any action here?
                        }
                    }
                } else {
                    // Plain text given, make search request to default provider
                    let request_text = gformat!(
                        "gemini://tlgs.one/search?{}",
                        Uri::escape_string(&request_text, None, false)
                    );

                    // Update
                    self.navigation.set_request_text(&request_text);

                    // Reload page
                    self.action_tab_page_navigation_reload.activate(None);
                }
            }
        }; // Uri::parse
    }

    pub fn update(&self) {
        // Update components
        self.navigation.update(self.progress_fraction());
        // @TODO self.content.update();
    }

    pub fn clean(
        &self,
        transaction: &Transaction,
        app_browser_window_tab_item_id: &i64,
    ) -> Result<(), String> {
        match Database::records(transaction, app_browser_window_tab_item_id) {
            Ok(records) => {
                for record in records {
                    match Database::delete(transaction, &record.id) {
                        Ok(_) => {
                            // Delegate clean action to the item childs
                            self.navigation.clean(transaction, &record.id)?;
                        }
                        Err(e) => return Err(e.to_string()),
                    }
                }
            }
            Err(e) => return Err(e.to_string()),
        }

        Ok(())
    }

    pub fn restore(
        &self,
        transaction: &Transaction,
        app_browser_window_tab_item_id: &i64,
    ) -> Result<(), String> {
        match Database::records(transaction, app_browser_window_tab_item_id) {
            Ok(records) => {
                for record in records {
                    // Delegate restore action to the item childs
                    self.navigation.restore(transaction, &record.id)?;
                }
            }
            Err(e) => return Err(e.to_string()),
        }

        Ok(())
    }

    pub fn save(
        &self,
        transaction: &Transaction,
        app_browser_window_tab_item_id: &i64,
    ) -> Result<(), String> {
        match Database::add(transaction, app_browser_window_tab_item_id) {
            Ok(_) => {
                let id = Database::last_insert_id(transaction);

                // Delegate save action to childs
                self.navigation.save(transaction, &id)?;
            }
            Err(e) => return Err(e.to_string()),
        }

        Ok(())
    }

    // Setters
    pub fn set_navigation_request_text(&self, value: &str) {
        self.navigation.set_request_text(value);
    }

    // Getters
    pub fn progress_fraction(&self) -> Option<f64> {
        // Interpret status to progress fraction
        match self.meta.borrow().status {
            Some(Status::Reload) => Some(0.0),
            Some(Status::Resolving) => Some(0.1),
            Some(Status::Resolved) => Some(0.2),
            Some(Status::Connecting) => Some(0.3),
            Some(Status::Connected) => Some(0.4),
            Some(Status::ProxyNegotiating) => Some(0.5),
            Some(Status::ProxyNegotiated) => Some(0.6),
            Some(Status::TlsHandshaking) => Some(0.7),
            Some(Status::TlsHandshaked) => Some(0.8),
            Some(Status::Complete) => Some(0.9),
            Some(Status::Failure | Status::Redirect | Status::Success | Status::Input) => Some(1.0),
            _ => None,
        }
    }

    pub fn is_loading(&self) -> bool {
        match self.progress_fraction() {
            Some(progress_fraction) => progress_fraction < 1.0,
            None => false,
        }
    }

    pub fn meta_title(&self) -> Option<GString> {
        self.meta.borrow().title.clone()
    }

    pub fn gobject(&self) -> &Box {
        &self.widget.gobject()
    }

    // Tools
    pub fn migrate(tx: &Transaction) -> Result<(), String> {
        // Migrate self components
        if let Err(e) = Database::init(tx) {
            return Err(e.to_string());
        }

        // Delegate migration to childs
        Navigation::migrate(tx)?;

        // Success
        Ok(())
    }

    // Private helpers @TODO
    fn load_gemini(&self, uri: Uri) {
        // Use local namespaces
        use gemini::client::response::{
            body::Error as BodyError,
            header::{Error as HeaderError, Mime as ClientMime, Status as ClientStatus},
            Body, Header,
        };

        // Init shared objects (async)
        let action_page_open = self.action_page_open.clone();
        let action_update = self.action_update.clone();
        let content = self.content.clone();
        let id = self.id.to_variant();
        let input = self.input.clone();
        let meta = self.meta.clone();
        let navigation = self.navigation.clone();
        let url = uri.clone().to_str();

        // Init socket
        let client = SocketClient::new();

        client.set_protocol(SocketProtocol::Tcp);
        client.set_tls_validation_flags(TlsCertificateFlags::INSECURE);
        client.set_tls(true);

        // Listen for connection status updates
        client.connect_event({
            let action_update = action_update.clone();
            let id = id.clone();
            let meta = meta.clone();
            move |_, event, _, _| {
                meta.borrow_mut().status = Some(match event {
                    SocketClientEvent::Resolving => Status::Resolving,
                    SocketClientEvent::Resolved => Status::Resolved,
                    SocketClientEvent::Connecting => Status::Connecting,
                    SocketClientEvent::Connected => Status::Connected,
                    SocketClientEvent::ProxyNegotiating => Status::ProxyNegotiating,
                    SocketClientEvent::ProxyNegotiated => Status::ProxyNegotiated,
                    SocketClientEvent::TlsHandshaking => Status::TlsHandshaking,
                    SocketClientEvent::TlsHandshaked => Status::TlsHandshaked,
                    SocketClientEvent::Complete => Status::Complete,
                    _ => todo!(), // notice on API change
                });
                action_update.activate(Some(&id));
            }
        });

        // Create connection
        client.clone().connect_to_uri_async(
            url.clone().as_str(),
            1965,
            None::<&Cancellable>,
            move |connect| match connect {
                Ok(connection) => {
                    // Send request
                    connection.output_stream().write_bytes_async(
                        &Bytes::from(gformat!("{url}\r\n").as_bytes()),
                        Priority::DEFAULT,
                        None::<&Cancellable>,
                        move |request| match request {
                            Ok(_) => {
                                // Read header from input stream
                                Header::from_socket_connection_async(
                                    connection.clone(),
                                    Some(Priority::DEFAULT),
                                    None::<Cancellable>,
                                    move |result| match result
                                    {
                                        Ok(header) => {
                                            // Route by status
                                            match header.status() {
                                                // https://geminiprotocol.net/docs/protocol-specification.gmi#input-expected
                                                ClientStatus::Input | ClientStatus::SensitiveInput => {
                                                    // Format response
                                                    let status = Status::Input;
                                                    let title = gformat!("Input expected");
                                                    let description = match header.meta() {
                                                        Some(meta) => match meta.to_gstring() {
                                                            Ok(value) => value,
                                                            Err(_) => title.clone(),
                                                        },
                                                        None => title.clone(),
                                                    };

                                                    // Make input form
                                                    match header.status() {
                                                        ClientStatus::SensitiveInput =>
                                                            input.set_new_sensitive(
                                                                action_page_open,
                                                                uri,
                                                                Some(&description),
                                                                Some(1024),
                                                            ),
                                                        _ =>
                                                            input.set_new_response(
                                                                action_page_open,
                                                                uri,
                                                                Some(&description),
                                                                Some(1024),
                                                            ),
                                                    }

                                                    // Update meta
                                                    meta.borrow_mut().status = Some(status);
                                                    meta.borrow_mut().description = Some(description);
                                                    meta.borrow_mut().title = Some(title);

                                                    // Update page
                                                    action_update.activate(Some(&id));
                                                },
                                                ClientStatus::Success => {
                                                    // Route by MIME
                                                    match header.mime() {
                                                        Some(ClientMime::TextGemini) => {
                                                            // Read entire input stream to buffer
                                                            Body::from_socket_connection_async(
                                                                connection,
                                                                move |result|{
                                                                    match result {
                                                                        Ok(buffer) => {
                                                                            // Update page meta
                                                                            meta.borrow_mut().status = Some(Status::Success);
                                                                            meta.borrow_mut().title = content.set_text_gemini(
                                                                                &uri,
                                                                                &match GString::from_utf8(buffer.to_utf8()) {
                                                                                    Ok(gemtext) => gemtext,
                                                                                    Err(_) => todo!()
                                                                                }
                                                                            );

                                                                            // Add new history record
                                                                            let request = uri.to_str();

                                                                            match navigation.history_current() {
                                                                                Some(current) => {
                                                                                    if current != request {
                                                                                        navigation.history_add(request);
                                                                                    }
                                                                                }
                                                                                None => navigation.history_add(request),
                                                                            }

                                                                            // Update window components
                                                                            action_update.activate(Some(&id));
                                                                        }
                                                                        Err((reason, message)) => {
                                                                            // Define common data
                                                                            let status = Status::Failure;
                                                                            let title = gformat!("Oops");
                                                                            let description = match reason {
                                                                                BodyError::InputStreamRead => match message {
                                                                                    Some(error) => gformat!("{error}"),
                                                                                    None => gformat!("Undefined connection error")
                                                                                } ,
                                                                                BodyError::BufferOverflow => gformat!("Buffer overflow"),
                                                                                BodyError::Decode => gformat!("Buffer decode error"),
                                                                            };

                                                                            // Update widget
                                                                            content.set_status_failure(
                                                                                title.as_str(),
                                                                                description.as_str(),
                                                                            );

                                                                            // Update meta
                                                                            meta.borrow_mut().status = Some(status);
                                                                            meta.borrow_mut().title = Some(title);
                                                                            meta.borrow_mut().description = Some(description);

                                                                            // Update window
                                                                            action_update.activate(Some(&id));
                                                                        },
                                                                    }
                                                                }
                                                            );
                                                        },
                                                        Some(
                                                            ClientMime::ImagePng  | ClientMime::ImageGif |
                                                            ClientMime::ImageJpeg | ClientMime::ImageWebp
                                                        ) => {
                                                            match Pixbuf::from_stream(
                                                                &connection.input_stream(),
                                                                None::<&Cancellable>,
                                                            ) {
                                                                Ok(buffer) => {
                                                                    // Update page meta
                                                                    meta.borrow_mut().status = Some(Status::Success);
                                                                    meta.borrow_mut().title = Some(gformat!("Image"));

                                                                    // Update page content
                                                                    content.set_image(&buffer);

                                                                    // Add history record
                                                                    let request = uri.to_str();
                                                                    match navigation.history_current() {
                                                                        Some(current) => {
                                                                            if current != request {
                                                                                navigation.history_add(request);
                                                                            }
                                                                        }
                                                                        None => navigation.history_add(request),
                                                                    }

                                                                    // Update window components
                                                                    action_update.activate(Some(&id));
                                                                }
                                                                Err(reason) => { // Pixbuf::from_stream
                                                                    // Define common data
                                                                    let status = Status::Failure;
                                                                    let title = gformat!("Oops");
                                                                    let description = gformat!("{}", reason.message());

                                                                    // Update widget
                                                                    content.set_status_failure(title.as_str(), description.as_str());

                                                                    // Update meta
                                                                    meta.borrow_mut().status = Some(status);
                                                                    meta.borrow_mut().title = Some(title);
                                                                    meta.borrow_mut().description = Some(description);
                                                                }
                                                            }
                                                        },
                                                        // @TODO stream extensions
                                                        _ => {
                                                            // Define common data
                                                            let status = Status::Failure;
                                                            let title = gformat!("Oops");
                                                            let description =
                                                                gformat!("Content type not supported");

                                                            // Update widget
                                                            content.set_status_failure(
                                                                title.as_str(),
                                                                description.as_str(),
                                                            );

                                                            // Update meta
                                                            meta.borrow_mut().status = Some(status);
                                                            meta.borrow_mut().title = Some(title);
                                                            meta.borrow_mut().description = Some(description);

                                                            // Update window
                                                            action_update.activate(Some(&id));
                                                        },
                                                    }
                                                },
                                                // https://geminiprotocol.net/docs/protocol-specification.gmi#redirection
                                                ClientStatus::Redirect | ClientStatus::PermanentRedirect => {

                                                    // @TODO ClientStatus::TemporaryRedirect

                                                    // Update meta
                                                    meta.borrow_mut().status = Some(Status::Redirect);
                                                    meta.borrow_mut().title = Some(gformat!("Redirect"));

                                                    // Build gemtext message for manual redirection @TODO use template?
                                                    match header.meta() {
                                                        Some(meta) => {
                                                            let _ = content.set_text_gemini(
                                                                &uri,
                                                                &match meta.to_gstring() {
                                                                    Ok(url) => gformat!(
                                                                        "# Redirect\n\nAuto-follow not implemented, click on link below to continue\n\n=> {url}"
                                                                    ),
                                                                    Err(_) => gformat!(
                                                                        "# Redirect\n\nProvider request redirect but not provided any target."
                                                                    )
                                                                }
                                                            );
                                                        },
                                                        None => content.set_status_failure(
                                                            &"Oops",
                                                            &"Could not parse redirect meta"
                                                        ),
                                                    }

                                                    action_update.activate(Some(&id));
                                                },
                                            }
                                        },
                                        Err((reason, message)) => {
                                            // Define common data
                                            let status = Status::Failure;
                                            let title = gformat!("Oops");
                                            let description = match reason {
                                                HeaderError::Buffer => match message {
                                                    Some(error) => gformat!("{error}"),
                                                    None => gformat!("Buffer error")
                                                },
                                                HeaderError::InputStream => match message {
                                                    Some(error) => gformat!("{error}"),
                                                    None => gformat!("Input stream reading error")
                                                },
                                                HeaderError::Protocol => match message {
                                                    Some(error) => gformat!("{error}"),
                                                    None => gformat!("Incorrect protocol")
                                                },
                                                HeaderError::StatusDecode => match message {
                                                    Some(error) => gformat!("{error}"),
                                                    None => gformat!("Could not detect status code")
                                                },
                                                HeaderError::StatusUndefined => match message {
                                                    Some(error) => gformat!("{error}"),
                                                    None => gformat!("Undefined status code")
                                                },
                                            };

                                            // Update widget
                                            content
                                                .set_status_failure(title.as_str(), description.as_str());

                                            // Update meta
                                            meta.borrow_mut().status = Some(status);
                                            meta.borrow_mut().title = Some(title);
                                            meta.borrow_mut().description = Some(description);

                                            // Update window
                                            action_update.activate(Some(&id));
                                        } // Header::from_socket_connection_async
                                    }
                                );
                            }
                            Err(reason) => {
                                // Define common data
                                let status = Status::Failure;
                                let title = gformat!("Oops");
                                let description = gformat!("Request error: {}", reason.message());

                                // Update widget
                                content
                                    .set_status_failure(title.as_str(), description.as_str());

                                // Update meta
                                meta.borrow_mut().status = Some(status);
                                meta.borrow_mut().title = Some(title);
                                meta.borrow_mut().description = Some(description);

                                // Update window
                                action_update.activate(Some(&id));
                            }, // OutputStream::write_bytes_async
                        },
                    );
                }
                Err(reason) => {
                    // Define common data
                    let status = Status::Failure;
                    let title = gformat!("Oops");
                    let description = gformat!("Connection error: {}", reason.message());

                    // Update widget
                    content
                        .set_status_failure(title.as_str(), description.as_str());

                    // Update meta
                    meta.borrow_mut().status = Some(status);
                    meta.borrow_mut().title = Some(title);
                    meta.borrow_mut().description = Some(description);

                    // Update window
                    action_update.activate(Some(&id));
                }, // SocketClient::connect_to_uri_async
            },
        );
    }
}