summaryrefslogtreecommitdiff
path: root/support/texlab/src/tex/mod.rs
blob: 6d60380e52658fcce8f478f69baa89c17e0ad3dc (plain)
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
mod compile;
mod kpsewhich;
mod miktex;
mod tectonic;
mod texlive;

pub use self::{
    compile::{Artifacts, CompileError, CompileParams, Format},
    kpsewhich::{KpsewhichError, Resolver},
};

use self::{compile::Compiler, miktex::Miktex, tectonic::Tectonic, texlive::Texlive};
use async_trait::async_trait;
use std::{fmt, process::Stdio, sync::Arc};
use tokio::process::Command;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum DistributionKind {
    Texlive,
    Miktex,
    Tectonic,
    Unknown,
}

impl fmt::Display for DistributionKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::Texlive => "TeXLive",
            Self::Miktex => "MikTeX",
            Self::Tectonic => "Tectonic",
            Self::Unknown => "Unknown",
        };
        write!(f, "{}", name)
    }
}

impl DistributionKind {
    pub async fn detect() -> Self {
        if Command::new("tectonic")
            .arg("--version")
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await
            .is_ok()
        {
            return Self::Tectonic;
        }

        match Command::new("latex").arg("--version").output().await {
            Ok(output) => {
                let stdout = String::from_utf8_lossy(&output.stdout);
                if stdout.contains("TeX Live") {
                    Self::Texlive
                } else if stdout.contains("MiKTeX") {
                    Self::Miktex
                } else {
                    Self::Unknown
                }
            }
            Err(_) => Self::Unknown,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Language {
    Latex,
    Bibtex,
}

impl Language {
    pub fn by_extension(extension: &str) -> Option<Self> {
        match extension.to_lowercase().as_str() {
            "tex" | "sty" | "cls" | "def" | "lco" | "aux" => Some(Language::Latex),
            "bib" | "bibtex" => Some(Language::Bibtex),
            _ => None,
        }
    }

    pub fn by_language_id(language_id: &str) -> Option<Self> {
        match language_id {
            "latex" | "tex" => Some(Language::Latex),
            "bibtex" | "bib" => Some(Language::Bibtex),
            _ => None,
        }
    }
}

#[async_trait]
pub trait Distribution: Send + Sync {
    fn kind(&self) -> DistributionKind;

    async fn compile<'a>(&'a self, params: CompileParams<'a>) -> Result<Artifacts, CompileError>;

    async fn load(&self) -> Result<(), KpsewhichError>;

    async fn resolver(&self) -> Arc<Resolver>;
}

impl dyn Distribution {
    pub async fn detect() -> Arc<dyn Distribution> {
        let kind = DistributionKind::detect().await;
        let distro: Arc<dyn Distribution + Send + Sync> = match kind {
            DistributionKind::Texlive => Arc::new(Texlive::default()),
            DistributionKind::Miktex => Arc::new(Miktex::default()),
            DistributionKind::Tectonic => Arc::new(Tectonic::default()),
            DistributionKind::Unknown => Arc::new(UnknownDistribution::default()),
        };
        distro
    }
}

impl fmt::Debug for dyn Distribution {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.kind())
    }
}

async fn compile(params: CompileParams<'_>) -> Result<Artifacts, CompileError> {
    let executable = params.format.executable();
    let args = &["--interaction=batchmode", "-shell-escape", params.file_name];
    let compiler = Compiler {
        executable,
        args,
        file_name: params.file_name,
        timeout: params.timeout,
    };
    compiler.compile(params.code).await
}

#[derive(Debug, Default)]
pub struct UnknownDistribution {
    resolver: Arc<Resolver>,
}

#[async_trait]
impl Distribution for UnknownDistribution {
    fn kind(&self) -> DistributionKind {
        DistributionKind::Unknown
    }

    async fn compile<'a>(&'a self, _params: CompileParams<'a>) -> Result<Artifacts, CompileError> {
        Err(CompileError::NotInstalled)
    }

    async fn load(&self) -> Result<(), KpsewhichError> {
        Ok(())
    }

    async fn resolver(&self) -> Arc<Resolver> {
        Arc::clone(&self.resolver)
    }
}