noctiluca 0.0.3

A terminal web browser: page text as terminal text, media as media
Documentation
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
//! `noctiluca`: a terminal web browser. See `noctiluca --help` and
//! `docs/design/browser.md`.

use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;

use noctiluca::actions::{self, ACTIONS};
use noctiluca::args::{Args, Run, USAGE, parse_args};
use noctiluca::bookmarks::{self, Bookmarks};
use noctiluca::cdp::{ChromeBackend, ChromeOptions};
use noctiluca::config::{Config, View, data_dir};
use noctiluca::engine::Engine;
use noctiluca::file_url;

/// How long the way out waits for the tabs to stop their browsers.
const STOP: Duration = Duration::from_secs(5);

/// The control socket this session listens on, closed on every way out.
static CONTROL: std::sync::Mutex<Option<noctiluca::control::ControlLink>> =
    std::sync::Mutex::new(None);

fn main() -> ExitCode {
    // Every way out stops the tabs, so each browser stops and its
    // temporary profile is removed: the end of `main` below, a panic, and
    // SIGTERM, SIGHUP or SIGQUIT (which end the process without
    // unwinding). Ctrl+C is a key in the app, and quits it.
    let panic = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        panic(info);
        stop_browsers();
    }));
    rich_intuituive::interact::session::on_terminate(stop_browsers);
    let args: Vec<String> = std::env::args().skip(1).collect();
    let result = run(&args);
    stop_browsers();
    match result {
        Ok(code) => code,
        Err(error) => {
            eprintln!("noctiluca: {error}");
            ExitCode::FAILURE
        }
    }
}

/// Stop each tab, which drops its engine (its browser stops, its temporary
/// profile goes), then end any browser still running: the raster view's,
/// or a tab's that did not stop in time.
fn stop_browsers() {
    if let Some(link) = CONTROL.lock().unwrap_or_else(|e| e.into_inner()).take() {
        link.close();
    }
    noctiluca::tab::stop_all(STOP);
    rich_embed::ChromeEngine::end_all();
}

fn run(args: &[String]) -> std::io::Result<ExitCode> {
    let result = match parse_args(args) {
        Ok(Run::Help) => {
            println!("{USAGE}");
            Ok(())
        }
        Ok(Run::Version) => {
            println!("noctiluca {}", env!("CARGO_PKG_VERSION"));
            Ok(())
        }
        Ok(Run::Keys { site, config }) => keys(site.as_deref(), config.as_deref()),
        Ok(Run::ControlHelp) => {
            println!("{}", noctiluca::control::ACTION_USAGE);
            Ok(())
        }
        Ok(Run::Ls { json }) => ls(json),
        Ok(Run::Action(action)) => return Ok(control_action(&action)),
        Ok(Run::Browse(parsed)) if parsed.split.is_some() => split(&parsed, args),
        Ok(Run::Browse(args)) => browse(args),
        Err(error) => {
            eprintln!("noctiluca: {error}\n\n{USAGE}");
            return Ok(ExitCode::from(2));
        }
    };
    result.map(|()| ExitCode::SUCCESS)
}

/// `noctiluca ls`.
#[cfg(unix)]
fn ls(json: bool) -> std::io::Result<()> {
    println!("{}", noctiluca::control::ls(json)?);
    Ok(())
}

#[cfg(not(unix))]
fn ls(_json: bool) -> std::io::Result<()> {
    Err(noctiluca::control::unix_only())
}

/// `noctiluca action …`: its reply on stdout; a refusal on stderr, and
/// exit status 1.
#[cfg(unix)]
fn control_action(action: &noctiluca::control::ActionArgs) -> ExitCode {
    match noctiluca::control::action(action) {
        Ok(out) => {
            println!("{out}");
            ExitCode::SUCCESS
        }
        Err(error) => {
            eprintln!("noctiluca: {error}");
            ExitCode::FAILURE
        }
    }
}

#[cfg(not(unix))]
fn control_action(_action: &noctiluca::control::ActionArgs) -> ExitCode {
    eprintln!("noctiluca: {}", noctiluca::control::unix_only());
    ExitCode::FAILURE
}

/// `--control`, `--read-only` or `[agent] control`: listen on the control
/// socket, kept for the way out to close.
fn listen(
    args: &Args,
    config: &Config,
) -> std::io::Result<Option<noctiluca::control::ControlLink>> {
    if !(args.control || args.read_only || config.agent.control) {
        return Ok(None);
    }
    let read_only = args.read_only || config.agent.read_only;
    // With a kept profile an agent acts signed in, and what pages say
    // reaches it: say so (`--read-only` lets it read only).
    if !read_only && (args.profile.is_some() || config.profile.is_some()) {
        eprintln!(
            "noctiluca: note: --control with a kept profile lets scripts act on your signed-in \
             sites; --read-only lets them read only"
        );
    }
    let link = noctiluca::control::ControlLink::bind(read_only)
        .map_err(|e| std::io::Error::new(e.kind(), format!("--control: {e}")))?;
    *CONTROL.lock().unwrap_or_else(|e| e.into_inner()) = Some(link.clone());
    Ok(Some(link))
}

/// `--split DIR`: the same command line, less `--split`, in a new pane of
/// the terminal beside this one; this process returns at once.
fn split(args: &Args, line: &[String]) -> std::io::Result<()> {
    use rich_interact::host::{Split, detect};
    let direction = args.split.expect("--split");
    let host = detect().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "--split needs a terminal that can split: tmux, WezTerm, kitty (with remote \
             control on), zellij, or one with terminal-browser's socket",
        )
    })?;
    let mut command = vec![std::env::current_exe()?.display().to_string()];
    command.extend(noctiluca::args::without_split(line));
    let pane = host
        .split(&Split::new(direction, command))
        .map_err(|e| std::io::Error::other(format!("--split: {e} ({})", host.name())))?;
    if pane.id.is_empty() {
        eprintln!("noctiluca: opened {} in {}", direction.name(), host.name());
    } else {
        eprintln!(
            "noctiluca: opened {} in {} (pane {})",
            direction.name(),
            host.name(),
            pane.id
        );
    }
    Ok(())
}

/// `noctiluca keys`: every action's keys, and a site's own.
fn keys(site: Option<&str>, path: Option<&Path>) -> std::io::Result<()> {
    let config = Config::load(path)?;
    for warning in &config.warnings {
        eprintln!("noctiluca: config: {warning}");
    }
    let (keymap, warnings) = actions::keymap(config.preset, &config.keys);
    for warning in warnings {
        eprintln!("noctiluca: config: {warning}");
    }
    match site {
        None => {
            for action in ACTIONS {
                println!(
                    "{:>16}  {:<16}  {}",
                    actions::keys_label(&keymap, action.id),
                    action.id,
                    action.label
                );
            }
            for site in &config.sites {
                for key in &site.keys {
                    println!(
                        "{:>16}  {}  [site {}]",
                        key.keys,
                        key.target.describe(),
                        site.pattern
                    );
                }
            }
        }
        Some(host) => {
            let url = if host.contains("://") {
                host.to_string()
            } else {
                format!("https://{host}/")
            };
            let matching: Vec<_> = config
                .sites
                .iter()
                .filter(|s| noctiluca::config::site_match(&s.pattern, &url).is_some())
                .collect();
            if matching.is_empty() {
                println!("No site keys for {host}.");
            }
            for site in matching {
                for key in &site.keys {
                    println!(
                        "{:>16}  {}  [site {}]",
                        key.keys,
                        key.target.describe(),
                        site.pattern
                    );
                }
            }
        }
    }
    Ok(())
}

/// What the words on the command line open.
fn start_url(args: &Args, config: &Config, marks: &Bookmarks) -> Option<String> {
    if args.target.is_empty() {
        return None;
    }
    if let [one] = args.target.as_slice() {
        let path = Path::new(one);
        if path.exists() && !one.contains("://") {
            return file_url(path).ok();
        }
    }
    let typed = args.target.join(" ");
    Some(
        config
            .destination(&typed, "about:blank", &marks.items)
            .url()
            .to_string(),
    )
}

/// The engine: Chrome; or, built with the test-only `fake-engine`
/// feature, a test's saved snapshots when `NOCTILUCA_FAKE_ENGINE` names
/// their directory (the end-to-end test and the docs tape run the binary
/// so, with no browser). A release build ignores the variable.
fn engine(args: &Args, config: &Config, switches: &[String]) -> std::io::Result<Box<dyn Engine>> {
    #[cfg(feature = "fake-engine")]
    if let Some(dir) = std::env::var_os("NOCTILUCA_FAKE_ENGINE") {
        // Videos play from Chrome's recorded frames, when there are some.
        let frames = Path::new(&dir).join("frames");
        let engine = noctiluca::testing::FakeEngine::from_dir(Path::new(&dir))?;
        return Ok(Box::new(if frames.is_dir() {
            engine.replaying(&frames)
        } else {
            engine
        }));
    }
    let profile = args
        .profile
        .clone()
        .or_else(|| config.profile.clone())
        .map(|name| {
            data_dir()
                .unwrap_or_else(std::env::temp_dir)
                .join("profiles")
                .join(name)
        });
    let binary = args
        .chrome
        .clone()
        .or_else(|| std::env::var_os("RICH_EMBED_CHROME").map(PathBuf::from));
    let (columns, rows) = terminal_size();
    let backend = ChromeBackend::start(ChromeOptions {
        binary,
        audio: args.audio || config.audio,
        profile,
        quarantine: None,
        no_js: args.no_js,
        transparent: args.transparent || config.transparent,
        switches: switches.to_vec(),
        columns,
        rows,
    })
    .map_err(|e| {
        let root = std::env::var("USER").is_ok_and(|u| u == "root");
        if root {
            std::io::Error::new(
                e.kind(),
                format!(
                    "{e} (Chrome cannot run its sandbox as root: run Noctiluca as a normal user)"
                ),
            )
        } else {
            e
        }
    })?;
    Ok(Box::new(backend))
}

/// `--ssh HOST`'s tunnel, waited for (ssh may prompt meanwhile).
fn open_tunnel(host: &str, args: &Args) -> std::io::Result<noctiluca::ssh::TunnelLink> {
    let mut options = noctiluca::ssh::SshOptions::new(host);
    options.args = args.ssh_args.clone();
    if args.profile.is_some() {
        eprintln!(
            "noctiluca: note: with --ssh, the kept profile's cookies for localhost are \
             shared with the far side's localhost"
        );
    }
    eprintln!("noctiluca: connecting to {host} over SSH (Ctrl+C stops)…");
    let tunnel = noctiluca::ssh::Tunnel::open(options, Duration::from_secs(120))
        .map_err(|e| std::io::Error::new(e.kind(), format!("--ssh: {e}")))?;
    Ok(noctiluca::ssh::TunnelLink::new(tunnel))
}

fn terminal_size() -> (u16, u16) {
    let var = |name: &str| std::env::var(name).ok().and_then(|v| v.parse().ok());
    (var("COLUMNS").unwrap_or(100), var("LINES").unwrap_or(40))
}

fn browse(args: Args) -> std::io::Result<()> {
    let mut config = Config::load(args.config.as_deref())?;
    if let Some(fps) = args.fps {
        config.fps = fps;
    }
    config.audio |= args.audio;
    config.transparent |= args.transparent;
    config.adapt = noctiluca::args::adapt_of(&args, config.adapt)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
    let marks = bookmarks::default_path()
        .map(|p| Bookmarks::load(&p))
        .transpose()?
        .unwrap_or_default();
    let url = start_url(&args, &config, &marks);
    // `--ssh`: the tunnel first, while the terminal is still the shell's,
    // so ssh can ask for a password or a host key. It lives until the
    // browser ends; dropping it stops ssh.
    let tunnel = args
        .ssh
        .as_ref()
        .map(|host| open_tunnel(host, &args))
        .transpose()?;
    let switches = tunnel
        .as_ref()
        .map(|t| {
            t.0.lock()
                .unwrap_or_else(|e| e.into_inner())
                .chrome_switches()
        })
        .unwrap_or_default();
    if let Some(how) = args.dump {
        for warning in &config.warnings {
            eprintln!("noctiluca: config: {warning}");
        }
        let url = url.unwrap_or_default();
        let page = noctiluca::dump::read_page(
            engine(&args, &config, &switches)?,
            &url,
            Duration::from_secs(60),
        )?;
        println!("{}", noctiluca::dump::dump(&page, how));
        return Ok(());
    }
    if args.view.unwrap_or(config.view) == View::Raster {
        return raster(&args, url.unwrap_or_else(|| "about:blank".into()), switches);
    }
    let engine = engine(&args, &config, &switches)?;
    let control = listen(&args, &config)?;
    noctiluca::app::app(
        engine,
        noctiluca::app::Options {
            config,
            bookmarks: marks,
            url,
            view: args.view,
            images: args.images,
            tunnel,
            control,
        },
    )
    // `--no-mouse`: never captured; else captured full-screen, intuiTUIve's
    // rule (a drag over text still selects and copies it).
    .mouse(args.no_mouse.then_some(false))
    .run()
}

/// The raster view, for debugging: the page as Chrome paints it, in half
/// blocks, through rs-rich-embed's web view.
fn raster(args: &Args, url: String, switches: Vec<String>) -> std::io::Result<()> {
    use rich_intuituive::prelude::*;
    let binary = args.chrome.clone().or_else(noctiluca::cdp::find_chrome);
    let audio = args.audio;
    App::new(move || {
        let mut engine = rich_embed::ChromeEngine::new()
            .audio(audio)
            .args(switches.clone());
        if let Some(binary) = binary {
            engine = engine.binary(binary);
        }
        rich_embed::web_view_with(engine, url)
            .address_bar(true)
            .node()
            .on_key("ctrl+q", |cx| cx.quit())
    })
    .run()
}