~julienxx/asuka

ref: 26daa0efca55c80a5f36fff08056ab245e6f39b8 asuka/src/main.rs -rw-r--r-- 12.1 KiB
26daa0ef — Arav K Add reload capability 2 months ago
                                                                                
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
#[macro_use]
extern crate lazy_static;

extern crate native_tls;
extern crate regex;

use cursive::align::HAlign;
use cursive::theme::{BaseColor, Color, Effect, PaletteColor, Style, Theme};
use cursive::traits::*;
use cursive::utils::markup::StyledString;
use cursive::view::Scrollable;
use cursive::views::{Dialog, EditView, Panel, SelectView};
use cursive::Cursive;

use json::object;

use std::str::FromStr;
use url::Url;

mod status;
use status::Status;

mod link;
use link::Link;

mod bookmarks;
mod content;
mod history;

const HELP: &str = "Welcome to Asuka Gemini browser!

  Press g to visit a URL
  Press b to go to the previous URL
  Press B to show bookmarks
  Press r to reload
  Press a to bookmark the current URL
  Press q to exit
";

fn main() {
    let mut siv = Cursive::default();

    let theme = custom_colors(&siv);
    siv.set_theme(theme);

    let mut select = SelectView::new();

    select.add_all_str(HELP.lines());
    select.set_on_submit(|s, line| {
        follow_line(s, line);
    });

    siv.add_fullscreen_layer(
        Dialog::around(Panel::new(
            select.with_id("main").scrollable().full_screen(),
        ))
        .title("Asuka Browser")
        .h_align(HAlign::Center)
        .button("Back (b)", |s| go_back(s))
        .button("Go To URL (g)", |s| prompt_for_url(s))
        .button("Bookmarks (B)", |s| show_bookmarks(s))
        .button("Reload (r)", |s| reload_page(s))
        .button("Quit (q)", |s| s.quit())
        .with_id("container"),
    );

    // We can quit by pressing q
    siv.add_global_callback('q', |s| s.quit());
    // pressing g prompt for an URL
    siv.add_global_callback('g', |s| prompt_for_url(s));
    // pressing a bookmarks current URL
    siv.add_global_callback('a', |s| add_bookmark(s));
    // pressing B shows/hides bookmarks
    siv.add_global_callback('B', |s| show_bookmarks(s));
    // pressing b goes to the previous URL if any
    siv.add_global_callback('b', |s| go_back(s));
    // pressing r reloads the current URL if any
    siv.add_global_callback('r', |s| reload_page(s));

    siv.run();
}

fn custom_colors(s: &Cursive) -> Theme {
    // We'll return the current theme with a small modification.
    let mut theme = s.current_theme().clone();
    theme.palette[PaletteColor::Highlight] = Color::Rgb(120, 120, 120);
    theme
}

fn prompt_for_url(s: &mut Cursive) {
    s.add_layer(
        Dialog::new()
            .title("Enter URL")
            // Padding is (left, right, top, bottom)
            .padding((1, 1, 1, 0))
            .content(EditView::new().on_submit(goto_url).fixed_width(20))
            .with_id("url_popup"),
    );
}

fn prompt_for_answer(s: &mut Cursive, url: Url, message: String) {
    s.add_layer(
        Dialog::new()
            .title(message)
            // Padding is (left, right, top, bottom)
            .padding((1, 1, 1, 0))
            .content(
                EditView::new()
                    .on_submit(move |s, response| {
                        let link = format!("{}?{}", url.to_string(), response);
                        s.pop_layer();
                        follow_link(s, &link);
                    })
                    .fixed_width(60),
            )
            .with_id("url_query"),
    );
}

fn goto_url(s: &mut Cursive, url: &str) {
    // Prepend gemini scheme if needed
    if url.starts_with("gemini://") {
        visit_url(s, &Url::parse(url).unwrap())
    } else {
        let url = format!("gemini://{}", url);
        visit_url(s, &Url::parse(&url).unwrap())
    };
}

fn go_back(s: &mut Cursive) {
    let previous = history::get_previous_url();
    if let Some(url) = previous {
        goto_url(s, &url.to_string())
    }
}

fn add_bookmark(s: &mut Cursive) {
    let current_url = history::get_current_url();
    if let Some(url) = current_url {
        bookmarks::add(&url.to_string());
        s.add_layer(Dialog::info("Bookmark added."));
    }
}

fn show_bookmarks(s: &mut Cursive) {
    // Hide popup when pressing B on an opened popup
    if s.find_id::<Dialog>("bookmarks_popup").is_some() {
        s.pop_layer();
        return;
    }

    let mut select = SelectView::new();

    for url in bookmarks::content().iter().rev() {
        let url_s = url.as_str();
        select.add_item_str(url_s);
    }

    select.set_on_submit(|s, link| {
        s.pop_layer();
        follow_link(s, link);
    });

    s.add_layer(
        Dialog::around(select.scrollable().fixed_size((50, 10)))
            .title("Bookmarks")
            .with_id("bookmarks_popup"),
    );
}

fn reload_page(s: &mut Cursive) {
    // Get current URL from history and revisit it without modifying history
    if let Some(url) = history::get_current_url() {
        match content::get_data(&url) {
            Ok((meta, new_content)) => {
                // handle meta header
                let response = handle_response_status(s, &url, meta, new_content);
                draw_content(s, &url, response);
            }
            Err(msg) => {
                s.add_layer(Dialog::info(msg));
            }
        }
    }
}

fn visit_url(s: &mut Cursive, url: &Url) {
    // Close URL popup if any
    if s.find_id::<Dialog>("url_popup").is_some() {
        s.pop_layer();
    }

    match content::get_data(&url) {
        Ok((meta, new_content)) => {
            history::append(url.as_str());
            // handle meta header
            let response = handle_response_status(s, &url, meta, new_content);
            draw_content(s, &url, response);
        }
        Err(msg) => {
            s.add_layer(Dialog::info(msg));
        }
    }
}

fn handle_response_status(
    s: &mut Cursive,
    url: &Url,
    meta: Vec<u8>,
    content: Vec<u8>,
) -> Option<Vec<u8>> {
    let url_copy = url.clone();
    let meta_str = String::from_utf8_lossy(&meta).to_string();

    if let Ok(status) = Status::from_str(&meta_str) {
        match status {
            Status::Success(meta) => {
                if meta.starts_with("text/") {
                    // display text files.
                    Some(content)
                } else {
                    // download and try to open the rest.
                    content::download(content);
                    None
                }
            }
            Status::Gone(_meta) => {
                s.add_layer(Dialog::info("Sorry page is gone."));
                None
            }
            Status::RedirectTemporary(new_url) | Status::RedirectPermanent(new_url) => {
                follow_link(s, &new_url);
                None
            }
            Status::TransientCertificateRequired(_meta)
            | Status::AuthorisedCertificatedRequired(_meta) => {
                s.add_layer(Dialog::info(
                    "You need a valid certificate to access this page.",
                ));
                None
            }
            Status::Input(message) => {
                prompt_for_answer(s, url_copy, message);
                None
            }
            other_status => {
                s.add_layer(Dialog::info(format!("ERROR: {:?}", other_status)));
                None
            }
        }
    } else {
        None
    }
}

fn draw_content(s: &mut Cursive, url: &Url, content: Option<Vec<u8>>) {
    if let Some(data) = content {
        let mut main_view = match s.find_id::<SelectView>("main") {
            Some(view) => view,
            None => panic!("Can't find main view."),
        };

        // set title and clear old content
        set_title(s, url.as_str());
        main_view.clear();
        let screen_size = s.screen_size();

        let content_str = String::from_utf8_lossy(&data).to_string();
        let mut preformatted = false;

        // draw new content lines
        for line in content_str.lines() {
            if line.starts_with("```") {
                preformatted = !preformatted;
                continue;
            } else if preformatted {
                main_view.add_item(line, String::from("0"));
                continue;
            }

            match Link::from_str(line) {
                Ok(link) => {
                    match link {
                        Link::Http(url, label) => {
                            let mut formatted = StyledString::new();
                            let www_label = format!("{} [WWW]", label);
                            formatted.append(StyledString::styled(
                                www_label,
                                Style::from(Color::Dark(BaseColor::Green)).combine(Effect::Bold),
                            ));

                            let data = object! {
                                "type" => "www",
                                "url" => url.to_string()
                            };
                            main_view.add_item(formatted, json::stringify(data))
                        }
                        Link::Gopher(url, label) => {
                            let mut formatted = StyledString::new();
                            let gopher_label = format!("{} [Gopher]", label);
                            formatted.append(StyledString::styled(
                                gopher_label,
                                Style::from(Color::Light(BaseColor::Magenta)).combine(Effect::Bold),
                            ));

                            let data = object! {
                                "type" => "gopher",
                                "url" => url.to_string()
                            };
                            main_view.add_item(formatted, json::stringify(data))
                        }
                        Link::Gemini(url, label) => {
                            let mut formatted = StyledString::new();
                            formatted.append(StyledString::styled(
                                label,
                                Style::from(Color::Light(BaseColor::Blue)).combine(Effect::Bold),
                            ));

                            let data = object! {
                                "type" => "gemini",
                                "url" => url.to_string()
                            };
                            main_view.add_item(formatted, json::stringify(data))
                        }
                        Link::Relative(url, label) => {
                            let mut formatted = StyledString::new();
                            formatted.append(StyledString::styled(
                                label,
                                Style::from(Color::Light(BaseColor::Blue)).combine(Effect::Bold),
                            ));

                            let data = object! {
                                "type" => "gemini",
                                "url" => url.to_string()
                            };
                            main_view.add_item(formatted, json::stringify(data))
                        }
                        Link::Unknown(_, _) => (),
                    }
                    continue;
                }
                Err(_) => {}
            }

            let line = str::replace(line, "\t", "    ");
            let max_size = screen_size.x - 10;
            if line.len() > max_size {
                let lines = textwrap::fill(&line, max_size);
                for l in lines.lines() {
                    main_view.add_item(l, String::from("0"));
                }
            } else {
                main_view.add_item(line, String::from("0"));
            }
        }
    }
}

fn set_title(s: &mut Cursive, text: &str) {
    let mut container = match s.find_id::<Dialog>("container") {
        Some(view) => view,
        None => panic!("Can't find container view."),
    };
    container.set_title(text);
}

fn follow_line(s: &mut Cursive, line: &str) {
    let parsed = json::parse(line);

    if let Ok(data) = parsed {
        if link::is_gemini(&data) {
            let current_url = history::get_current_url().unwrap();
            let next_url = current_url.join(&data["url"].to_string()).expect("Not a URL");
            visit_url(s, &next_url)
        } else {
            open::that(data["url"].to_string()).unwrap();
        }
    }
}

fn follow_link(s: &mut Cursive, link: &str) {
    let current_url = history::get_current_url().unwrap();
    let next_url = current_url.join(link).expect("Not a URL");
    visit_url(s, &next_url)
}