File size: 11,157 Bytes
2d8be8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use super::{SectionItem, Status};
#[cfg(windows)]
use crate::error::Context;
use colored::Colorize;
#[cfg(windows)]
use serde::Deserialize;
use std::process::Command;

#[cfg(windows)]
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct VsInstanceInfo {
  display_name: String,
}

#[cfg(windows)]
const VSWHERE: &[u8] = include_bytes!("../../scripts/vswhere.exe");

#[cfg(windows)]
fn build_tools_version() -> crate::Result<Vec<String>> {
  let mut vswhere = std::env::temp_dir();
  vswhere.push("vswhere.exe");

  if !vswhere.exists() {
    if let Ok(mut file) = std::fs::File::create(&vswhere) {
      use std::io::Write;
      let _ = file.write_all(VSWHERE);
    }
  }

  // Check if there are Visual Studio installations that have the "MSVC - C++ Buildtools" and "Windows SDK" components.
  // Both the Windows 10 and Windows 11 SDKs work so we need to query it twice.
  let output_sdk10 = Command::new(&vswhere)
    .args([
      "-prerelease",
      "-products",
      "*",
      "-requires",
      "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
      "-requires",
      "Microsoft.VisualStudio.Component.Windows10SDK.*",
      "-format",
      "json",
      "-utf8",
    ])
    .output()
    .map_err(|error| crate::error::Error::CommandFailed {
      command: "vswhere -prerelease -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -requires Microsoft.VisualStudio.Component.Windows10SDK.* -format json -utf8".to_string(),
      error,
    })?;

  let output_sdk11 = Command::new(vswhere)
    .args([
      "-prerelease",
      "-products",
      "*",
      "-requires",
      "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
      "-requires",
      "Microsoft.VisualStudio.Component.Windows11SDK.*",
      "-format",
      "json",
      "-utf8",
    ])
    .output()
    .map_err(|error| crate::error::Error::CommandFailed {
      command: "vswhere -prerelease -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -requires Microsoft.VisualStudio.Component.Windows11SDK.* -format json -utf8".to_string(),
      error,
    })?;

  let mut instances: Vec<VsInstanceInfo> = Vec::new();

  if output_sdk10.status.success() {
    let stdout = String::from_utf8_lossy(&output_sdk10.stdout);
    let found: Vec<VsInstanceInfo> =
      serde_json::from_str(&stdout).context("failed to parse vswhere output")?;
    instances.extend(found);
  }

  if output_sdk11.status.success() {
    let stdout = String::from_utf8_lossy(&output_sdk11.stdout);
    let found: Vec<VsInstanceInfo> =
      serde_json::from_str(&stdout).context("failed to parse vswhere output")?;
    instances.extend(found);
  }

  let mut instances: Vec<String> = instances
    .iter()
    .map(|i| i.display_name.clone())
    .collect::<Vec<String>>();

  instances.sort_unstable();
  instances.dedup();

  Ok(instances)
}

#[cfg(windows)]
fn webview2_version() -> crate::Result<Option<String>> {
  let powershell_path = std::env::var("SYSTEMROOT").map_or_else(
    |_| "powershell.exe".to_string(),
    |p| format!("{p}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"),
  );
  // check 64bit machine-wide installation
  let output = Command::new(&powershell_path)
      .args(["-NoProfile", "-Command"])
      .arg("Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}")
      .output()
      .map_err(|error| crate::error::Error::CommandFailed {
        command: "Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}".to_string(),
        error,
      })?;
  if output.status.success() {
    return Ok(Some(
      String::from_utf8_lossy(&output.stdout).replace('\n', ""),
    ));
  }
  // check 32bit machine-wide installation
  let output = Command::new(&powershell_path)
        .args(["-NoProfile", "-Command"])
        .arg("Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}")
        .output()
        .map_err(|error| crate::error::Error::CommandFailed {
          command: "Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}".to_string(),
          error,
        })?;
  if output.status.success() {
    return Ok(Some(
      String::from_utf8_lossy(&output.stdout).replace('\n', ""),
    ));
  }
  // check user-wide installation
  let output = Command::new(&powershell_path)
      .args(["-NoProfile", "-Command"])
      .arg("Get-ItemProperty -Path 'HKCU:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}")
      .output()
      .map_err(|error| crate::error::Error::CommandFailed {
        command: "Get-ItemProperty -Path 'HKCU:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}".to_string(),
        error,
      })?;
  if output.status.success() {
    return Ok(Some(
      String::from_utf8_lossy(&output.stdout).replace('\n', ""),
    ));
  }

  Ok(None)
}

#[cfg(any(
  target_os = "linux",
  target_os = "dragonfly",
  target_os = "freebsd",
  target_os = "openbsd",
  target_os = "netbsd"
))]
fn pkg_conf_version(package: &str) -> Option<String> {
  Command::new("pkg-config")
    .args([package, "--print-provides"])
    .output()
    .map(|o| {
      String::from_utf8_lossy(&o.stdout)
        .split('=')
        .nth(1)
        .map(|s| s.trim().to_string())
    })
    .unwrap_or(None)
}
#[cfg(any(
  target_os = "linux",
  target_os = "dragonfly",
  target_os = "freebsd",
  target_os = "openbsd",
  target_os = "netbsd"
))]
fn webkit2gtk_ver() -> Option<String> {
  pkg_conf_version("webkit2gtk-4.1")
}
#[cfg(any(
  target_os = "linux",
  target_os = "dragonfly",
  target_os = "freebsd",
  target_os = "openbsd",
  target_os = "netbsd"
))]
fn rsvg2_ver() -> Option<String> {
  pkg_conf_version("librsvg-2.0")
}

#[cfg(target_os = "macos")]
fn is_xcode_command_line_tools_installed() -> bool {
  Command::new("xcode-select")
    .arg("-p")
    .output()
    .map(|o| o.status.success())
    .unwrap_or(false)
}

#[cfg(target_os = "macos")]
pub fn xcode_version() -> Option<String> {
  Command::new("xcodebuild")
    .arg("-version")
    .output()
    .ok()
    .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
    .and_then(|s| {
      s.split('\n')
        .filter_map(|line| line.strip_prefix("Xcode "))
        .next()
        .map(ToString::to_string)
    })
}

fn de_and_session() -> String {
  #[cfg(any(
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd"
  ))]
  return {
    let de = std::env::var("XDG_SESSION_DESKTOP");
    let session = std::env::var("XDG_SESSION_TYPE");
    format!(
      " ({} on {})",
      de.as_deref().unwrap_or("Unknown DE"),
      session.as_deref().unwrap_or("Unknown Session")
    )
  };

  #[cfg(not(any(
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd"
  )))]
  String::new()
}

pub fn items() -> Vec<SectionItem> {
  vec![
    SectionItem::new().action(|| {
      let os_info = os_info::get();
      format!(
        "OS: {} {} {} ({:?}){}",
        os_info.os_type(),
        os_info.version(),
        os_info.architecture().unwrap_or("Unknown Architecture"),
        os_info.bitness(),
        de_and_session(),
      ).into()
    }),
    #[cfg(windows)]
    SectionItem::new().action(|| {
      let error = format!(
          "Webview2: {}\nVisit {}",
          "not installed!".red(),
          "https://developer.microsoft.com/en-us/microsoft-edge/webview2/".cyan()
        );
      webview2_version()
        .map(|v| {
          v.map(|v| (format!("WebView2: {v}"), Status::Success))
            .unwrap_or_else(|| (error.clone(), Status::Error))
        })
        .unwrap_or_else(|_| (error, Status::Error)).into()
    }),
    #[cfg(windows)]
    SectionItem::new().action(|| {
      let build_tools = build_tools_version().unwrap_or_default();
      if build_tools.is_empty() {
        (
            format!(
              "Couldn't detect any Visual Studio or VS Build Tools instance with MSVC and SDK components. Download from {}",
              "https://aka.ms/vs/17/release/vs_BuildTools.exe".cyan()
            ),
            Status::Error,
          ).into()
      } else {
        (
          format!(
            "MSVC: {}{}",
            if build_tools.len() > 1 {
              format!("\n  {} ", "-".cyan())
            } else {
              "".into()
            },
            build_tools.join(format!("\n  {} ", "-".cyan()).as_str()),
          ),
          Status::Success,
        ).into()
      }
    }),
    #[cfg(any(
      target_os = "linux",
      target_os = "dragonfly",
      target_os = "freebsd",
      target_os = "openbsd",
      target_os = "netbsd"
    ))]
    SectionItem::new().action(|| {
          webkit2gtk_ver()
            .map(|v| (format!("webkit2gtk-4.1: {v}"), Status::Success))
            .unwrap_or_else(|| {
              (
                format!(
                  "webkit2gtk-4.1: {}\nVisit {} to learn more about tauri prerequisites",
                  "not installed".red(),
                  "https://v2.tauri.app/start/prerequisites/".cyan()
                ),
                Status::Error,
              )
            }).into()
      },
    ),
    #[cfg(any(
      target_os = "linux",
      target_os = "dragonfly",
      target_os = "freebsd",
      target_os = "openbsd",
      target_os = "netbsd"
    ))]
    SectionItem::new().action(|| {
          rsvg2_ver()
            .map(|v| (format!("rsvg2: {v}"), Status::Success))
            .unwrap_or_else(|| {
              (
                format!(
                  "rsvg2: {}\nVisit {} to learn more about tauri prerequisites",
                  "not installed".red(),
                  "https://v2.tauri.app/start/prerequisites/".cyan()
                ),
                Status::Error,
              )
            }).into()
      },
    ),
    #[cfg(target_os = "macos")]
    SectionItem::new().action(|| {
        if is_xcode_command_line_tools_installed() {
          (
            "Xcode Command Line Tools: installed".into(),
            Status::Success,
          )
        } else {
          (
            format!(
              "Xcode Command Line Tools: {}\n Run `{}`",
              "not installed!".red(),
              "xcode-select --install".cyan()
            ),
            Status::Error,
          )
        }.into()
      },
    ),
    #[cfg(target_os = "macos")]
    SectionItem::new().action(|| {
      xcode_version().map(|v| (format!("Xcode: {v}"), Status::Success)).unwrap_or_else(|| {
          (format!("Xcode: {}", "not installed!".red()), Status::Error)
      }).into()
    }),
  ]
}