Skip to content

Visual Studio Code, rebuilt in Rust

Rust
11.7 KB
Raw Blame
//! output.contribution.ts `registerAddCompoundLogAction` and `registerRemoveLogAction`: Add Compound Log... joins
//! log channels into one, Remove Output... removes the ones the user added. `registerSaveActiveOutputAsAction`,
//! `registerExportLogsAction` and `registerImportLogAction` save channels to a file and add a log file as a channel.

use std::path::{Path, PathBuf};

use gpui::{Context, Window};
use serde_json::Value;

use super::Workbench;
use super::output_actions::{OutputPick, OutputPicks};
use crate::commands::Outcome;
use crate::file_dialog::FileDialog;
use crate::main_thread_quick_open::Owner;
use crate::notifications::{Notification, Severity};
use crate::output::OutputChannel;
use crate::output::compound::Source;
use crate::quick_input::{Entry, Item, Kind, QuickInput};
use crate::uri::Uri;

const IMPORTED_LOG_ID_PREFIX: &str = "importedLog.";

impl Workbench {
    pub(super) fn register_output_compound_actions(&mut self) {
        self.commands.register("workbench.action.output.addCompoundLog", |workbench, _, window, cx| {
            workbench.show_add_compound_log(window, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.output.remove", |workbench, _, window, cx| {
            workbench.show_remove_output(window, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.saveActiveLogOutputAs", |workbench, _, window, cx| {
            if let Some(id) = workbench.output.active.clone() {
                workbench.save_output_as(None, vec![id], window, cx);
            }
            Outcome::done()
        });
        self.commands.register("workbench.action.exportLogs", |workbench, args, window, cx| {
            workbench.export_logs(args.first().unwrap_or(&Value::Null), window, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.importLog", |workbench, _, window, cx| {
            workbench.import_log(window, cx);
            Outcome::done()
        });
    }

    /// The log channels by label: the workbench's, "Extension Logs", then "User Logs". `arg.outputChannelIds` picks
    /// without the picker, `*` all of them; `arg.outputPath` saves without the save dialog.
    fn export_logs(&mut self, arg: &Value, window: &mut Window, cx: &mut Context<Self>) {
        let mut logs = Vec::new();
        let mut extension_logs = Vec::new();
        let mut user_logs = Vec::new();
        for channel in self.output.channels.iter().filter(|channel| channel.log) {
            match (channel.extension_id.is_some(), channel.user) {
                (true, _) => extension_logs.push(channel),
                (false, true) => user_logs.push(channel),
                (false, false) => logs.push(channel),
            }
        }
        for list in [&mut logs, &mut extension_logs, &mut user_logs] {
            list.sort_by(|a, b| crate::command_palette::locale_compare(&a.label, &b.label));
        }
        let output_path = Uri::from_json(&arg["outputPath"]).ok().map(|uri| PathBuf::from(uri.path));
        if let Some(requested) = arg["outputChannelIds"].as_array() {
            let requested: Vec<String> = requested.iter().filter_map(Value::as_str).map(|id| id.trim().to_lowercase()).collect();
            let all = requested.iter().any(|id| id == "*");
            let ids: Vec<String> = logs.iter().chain(&extension_logs).chain(&user_logs).filter(|channel| all || requested.contains(&channel.id.to_lowercase())).map(|channel| channel.id.clone()).collect();
            if !ids.is_empty() {
                self.save_output_as(output_path, ids, window, cx);
            }
            return;
        }
        let mut picks = OutputPicks::default();
        for channel in &logs {
            picks.push(Item { label: channel.label.clone(), ..Item::default() }, OutputPick::Export(channel.id.clone()));
        }
        if !extension_logs.is_empty() && !logs.is_empty() {
            picks.entries.push(Entry::Separator(Some("Extension Logs".into())));
        }
        for channel in &extension_logs {
            picks.push(Item { label: channel.label.clone(), ..Item::default() }, OutputPick::Export(channel.id.clone()));
        }
        if !user_logs.is_empty() && (!extension_logs.is_empty() || !logs.is_empty()) {
            picks.entries.push(Entry::Separator(Some("User Logs".into())));
        }
        for channel in &user_logs {
            picks.push(Item { label: channel.label.clone(), ..Item::default() }, OutputPick::Export(channel.id.clone()));
        }
        self.show_many_output_picker(picks, window, cx);
    }

    /// outputServices.ts `saveOutputAs`: the channel's text, several channels as one compound log, written to
    /// `<label>.log` (`output.log` for several) at the default file path unless `output_path` names the file.
    pub(super) fn save_output_as(&mut self, output_path: Option<PathBuf>, ids: Vec<String>, window: &mut Window, cx: &mut Context<Self>) {
        let Some(first) = self.output.channel(&ids[0]) else { return };
        let name = if ids.len() > 1 { "output".to_owned() } else { first.label.clone() };
        let picked = output_path.is_none().then(|| {
            let dialog = FileDialog { title: Some("Save Output As".into()), filters: vec![(name.clone(), vec!["log".into()])], default_path: Some(self.default_file_path().join(format!("{name}.log"))), ..FileDialog::default() };
            self.show_save_dialog(dialog, cx)
        });
        cx.spawn_in(window, async move |workbench, cx| {
            let path = match picked {
                None => output_path,
                Some(picked) => picked.await.ok().flatten(),
            };
            let _ = workbench.update_in(cx, |workbench, window, cx| {
                let text = workbench.output_text(&ids, window, cx);
                let Some(path) = path else { return };
                if let Err(error) = std::fs::write(&path, text) {
                    workbench.notify_error(format!("Unable to write file '{}' ({error})", path.display()));
                    cx.notify();
                }
            });
        })
        .detach();
    }

    /// The text of one channel's model, or of the compound log of several, which is registered for the read only.
    fn output_text(&mut self, ids: &[String], window: &mut Window, cx: &mut Context<Self>) -> String {
        if ids.len() == 1 {
            return self.output.channel(&ids[0]).map(|channel| channel.clone().read_all()).unwrap_or_default();
        }
        let id = self.output.register_compound_channel(ids);
        let text = self.output.channel(&id).expect("registered above").clone().read_all();
        self.output.remove_channel(&id);
        self.output_channels_changed(window, cx);
        text
    }

    /// The picked `.log` files as one user log channel, a compound one for several, shown.
    fn import_log(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let dialog = FileDialog { title: Some("Import Log File".into()), filters: vec![("Log Files".into(), vec!["log".into()])], files: true, multiple: true, ..FileDialog::default() };
        let picked = self.show_open_dialog(dialog, cx);
        cx.spawn_in(window, async move |workbench, cx| {
            let Ok(files) = picked.await else { return };
            let _ = workbench.update_in(cx, |workbench, window, cx| workbench.add_imported_log(files, window, cx));
        })
        .detach();
    }

    pub(super) fn add_imported_log(&mut self, files: Vec<PathBuf>, window: &mut Window, cx: &mut Context<Self>) {
        let Some(first) = files.first() else { return };
        let millis = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_millis());
        let id = format!("{IMPORTED_LOG_ID_PREFIX}{millis}");
        let file_name = |path: &Path| path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
        let mut channel = OutputChannel::new(id.clone(), file_name(first), first.clone(), true);
        channel.user = true;
        if files.len() > 1 {
            channel.file = PathBuf::new();
            for file in &files {
                let name = file_name(file).split('.').next().unwrap_or_default().to_owned();
                channel.sources.push(Source { reader: OutputChannel::new(String::new(), String::new(), file.clone(), true), name });
            }
        }
        self.output.register_channel(channel);
        self.output_channels_changed(window, cx);
        self.show_output_channel(&id, false, window, cx);
    }

    /// The log channels the user did not add, the workbench's by label, then "Extension Logs".
    fn show_add_compound_log(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let (mut extension_logs, mut logs): (Vec<_>, Vec<_>) = self.output.channels.iter().filter(|channel| channel.log && !channel.user).partition(|channel| channel.extension_id.is_some());
        logs.sort_by(|a, b| crate::command_palette::locale_compare(&a.label, &b.label));
        extension_logs.sort_by(|a, b| crate::command_palette::locale_compare(&a.label, &b.label));
        let mut picks = OutputPicks::default();
        for channel in &logs {
            picks.push(Item { label: channel.label.clone(), ..Item::default() }, OutputPick::AddToCompound(channel.id.clone()));
        }
        if !extension_logs.is_empty() && !logs.is_empty() {
            picks.entries.push(Entry::Separator(Some("Extension Logs".into())));
        }
        for channel in &extension_logs {
            picks.push(Item { label: channel.label.clone(), ..Item::default() }, OutputPick::AddToCompound(channel.id.clone()));
        }
        self.show_many_output_picker(picks, window, cx);
    }

    fn show_remove_output(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let mut picks = OutputPicks::default();
        for channel in self.output.channels.iter().filter(|channel| channel.user) {
            picks.push(Item { label: channel.label.clone(), ..Item::default() }, OutputPick::Remove(channel.id.clone()));
        }
        if picks.picks.is_empty() {
            self.notify(Notification::new(Severity::Info, "No custom outputs to remove."));
            cx.notify();
            return;
        }
        self.show_many_output_picker(picks, window, cx);
    }

    fn show_many_output_picker(&mut self, picks: OutputPicks, window: &mut Window, cx: &mut Context<Self>) {
        let mut input = QuickInput::new(0, Kind::QuickPick);
        input.placeholder = Some("Select Log".into());
        input.can_select_many = true;
        input.set_items(picks.entries);
        let id = self.quick_inputs.add(input, Owner::Output(picks.picks));
        self.show_quick_input(id, window, cx);
        self.flush_quick_input_events(window, cx);
    }

    /// What a many-select output picker accepted: a compound log of the picked channels, shown, or the picked
    /// user channels removed.
    pub(super) fn accept_many_output_picks(&mut self, picks: Vec<OutputPick>, window: &mut Window, cx: &mut Context<Self>) {
        let mut compound = Vec::new();
        let mut exported = Vec::new();
        for pick in picks {
            match pick {
                OutputPick::AddToCompound(id) => compound.push(id),
                OutputPick::Export(id) => exported.push(id),
                OutputPick::Remove(id) => drop(self.output.remove_channel(&id)),
                _ => {}
            }
        }
        if !exported.is_empty() {
            self.save_output_as(None, exported, window, cx);
            return;
        }
        if !compound.is_empty() {
            let id = self.output.register_compound_channel(&compound);
            self.output_channels_changed(window, cx);
            self.show_output_channel(&id, false, window, cx);
            return;
        }
        self.output_channels_changed(window, cx);
    }
}