summaryrefslogtreecommitdiff
path: root/support/texlab/src/build.rs
blob: fe4597c0d74d8f5d82e9e1a4bc0dfff4e304747c (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
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
use crate::{
    feature::{FeatureProvider, FeatureRequest},
    protocol::{
        BuildParams, BuildResult, BuildStatus, ClientCapabilitiesExt, LatexOptions,
        LogMessageParams, LspClient, MessageType, ProgressParams, ProgressParamsValue,
        ProgressToken, Uri, WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressCreateParams,
        WorkDoneProgressEnd,
    },
};
use async_trait::async_trait;
use chashmap::CHashMap;
use futures::{
    future::{AbortHandle, Abortable, Aborted},
    lock::Mutex,
    prelude::*,
    stream,
};
use log::error;
use std::{collections::HashMap, io, path::Path, process::Stdio, sync::Arc};
use tokio::{
    io::{AsyncBufReadExt, BufReader},
    process::Command,
};
use uuid::Uuid;

pub struct BuildProvider<C> {
    client: Arc<C>,
    handles_by_token: Mutex<HashMap<ProgressToken, AbortHandle>>,
    current_docs: CHashMap<Uri, ()>,
}

impl<C> BuildProvider<C> {
    pub fn new(client: Arc<C>) -> Self {
        Self {
            client,
            handles_by_token: Mutex::new(HashMap::new()),
            current_docs: CHashMap::new(),
        }
    }

    pub fn is_building(&self) -> bool {
        self.current_docs.len() > 0
    }

    pub async fn cancel(&self, token: ProgressToken) {
        let handles_by_token = self.handles_by_token.lock().await;
        if let Some(handle) = handles_by_token.get(&token) {
            handle.abort();
        } else if let ProgressToken::String(id) = token {
            if id == "texlab-build-*" {
                handles_by_token.values().for_each(|handle| handle.abort());
            }
        }
    }
}

#[async_trait]
impl<C> FeatureProvider for BuildProvider<C>
where
    C: LspClient + Send + Sync + 'static,
{
    type Params = BuildParams;
    type Output = BuildResult;

    async fn execute<'a>(&'a self, req: &'a FeatureRequest<BuildParams>) -> BuildResult {
        let token = ProgressToken::String(format!("texlab-build-{}", Uuid::new_v4()));
        let (handle, reg) = AbortHandle::new_pair();
        {
            let mut handles_by_token = self.handles_by_token.lock().await;
            handles_by_token.insert(token.clone(), handle);
        }

        let doc = req
            .snapshot()
            .parent(&req.current().uri, &req.options, &req.current_dir)
            .unwrap_or_else(|| Arc::clone(&req.view.current));

        if !doc.is_file() {
            error!("Unable to build the document {}: wrong URI scheme", doc.uri);
            return BuildResult {
                status: BuildStatus::Failure,
            };
        }

        if self.current_docs.get(&doc.uri).is_some() {
            return BuildResult {
                status: BuildStatus::Success,
            };
        }
        self.current_docs.insert(doc.uri.clone(), ());

        let status = match doc.uri.to_file_path() {
            Ok(path) => {
                if req.client_capabilities.has_work_done_progress_support() {
                    let params = WorkDoneProgressCreateParams {
                        token: token.clone(),
                    };
                    self.client.work_done_progress_create(params).await.unwrap();

                    let title = path.file_name().unwrap().to_string_lossy().into_owned();
                    let params = ProgressParams {
                        token: token.clone(),
                        value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(
                            WorkDoneProgressBegin {
                                title,
                                cancellable: Some(true),
                                message: Some("Building".into()),
                                percentage: None,
                            },
                        )),
                    };
                    self.client.progress(params).await;
                }

                let latex_options = req.options.latex.clone().unwrap_or_default();
                let client = Arc::clone(&self.client);
                match Abortable::new(build(&path, &latex_options, client), reg).await {
                    Ok(Ok(true)) => BuildStatus::Success,
                    Ok(Ok(false)) => BuildStatus::Error,
                    Ok(Err(why)) => {
                        error!("Unable to build the document {}: {}", doc.uri, why);
                        BuildStatus::Failure
                    }
                    Err(Aborted) => BuildStatus::Cancelled,
                }
            }
            Err(()) => {
                error!("Unable to build the document {}: invalid URI", doc.uri);
                BuildStatus::Failure
            }
        };

        if req.client_capabilities.has_work_done_progress_support() {
            let params = ProgressParams {
                token: token.clone(),
                value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(WorkDoneProgressEnd {
                    message: None,
                })),
            };
            self.client.progress(params).await;
        }
        {
            let mut handles_by_token = self.handles_by_token.lock().await;
            handles_by_token.remove(&token);
        }

        self.current_docs.remove(&doc.uri);
        BuildResult { status }
    }
}

async fn build<C>(path: &Path, options: &LatexOptions, client: Arc<C>) -> io::Result<bool>
where
    C: LspClient + Send + Sync + 'static,
{
    let build_options = options.build.as_ref().cloned().unwrap_or_default();
    let build_dir = options
        .root_directory
        .as_ref()
        .map(AsRef::as_ref)
        .or_else(|| path.parent())
        .unwrap();

    let args: Vec<_> = build_options
        .args()
        .into_iter()
        .map(|arg| replace_placeholder(arg, path))
        .collect();

    let mut process = Command::new(build_options.executable())
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .current_dir(build_dir)
        .kill_on_drop(true)
        .spawn()?;

    let stdout = BufReader::new(process.stdout.take().unwrap()).lines();
    let stderr = BufReader::new(process.stderr.take().unwrap()).lines();
    let mut output = stream::select(stdout, stderr);

    tokio::spawn(async move {
        while let Some(Ok(line)) = output.next().await {
            let params = LogMessageParams {
                typ: MessageType::Log,
                message: line,
            };

            client.log_message(params).await;
        }
    });

    Ok(process.await?.success())
}

fn replace_placeholder(arg: String, file: &Path) -> String {
    if arg.starts_with('"') || arg.ends_with('"') {
        arg
    } else {
        arg.replace("%f", &file.to_string_lossy())
    }
}